statanim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. statanim/__init__.py +0 -0
  2. statanim/animations/__init__.py +0 -0
  3. statanim/animations/clt_demo.py +1852 -0
  4. statanim/animations/flip_roll.py +1851 -0
  5. statanim/animations/sampling.py +2291 -0
  6. statanim/animations/transitions.py +1857 -0
  7. statanim/axes/__init__.py +0 -0
  8. statanim/axes/axes3d.py +1989 -0
  9. statanim/axes/grid3d.py +1127 -0
  10. statanim/axes/number_plane3d.py +1526 -0
  11. statanim/charts/__init__.py +0 -0
  12. statanim/charts/bar_chart3d.py +1572 -0
  13. statanim/charts/box_plot3d.py +1977 -0
  14. statanim/charts/heat_map3d.py +1639 -0
  15. statanim/charts/histogram3d.py +1019 -0
  16. statanim/charts/line_plot3d.py +1891 -0
  17. statanim/charts/scatter_plot3d.py +1469 -0
  18. statanim/charts/violin_plot3d.py +1567 -0
  19. statanim/core/__init__.py +0 -0
  20. statanim/core/base.py +1585 -0
  21. statanim/core/colors.py +1373 -0
  22. statanim/core/math_utils.py +2081 -0
  23. statanim/core/tex_utils.py +2111 -0
  24. statanim/distributions/__init__.py +0 -0
  25. statanim/distributions/base_dist.py +1936 -0
  26. statanim/distributions/cdf_viz.py +1773 -0
  27. statanim/distributions/continuous_dists.py +1769 -0
  28. statanim/distributions/discrete_dists.py +1734 -0
  29. statanim/distributions/normal3d.py +1877 -0
  30. statanim/distributions/pdf_viz.py +2247 -0
  31. statanim/distributions/pmf_viz.py +1936 -0
  32. statanim/inference/__init__.py +0 -0
  33. statanim/inference/confidence_interval.py +1693 -0
  34. statanim/inference/error_types.py +1825 -0
  35. statanim/inference/hypothesis.py +1821 -0
  36. statanim/inference/sampling_dist.py +1933 -0
  37. statanim/probability/__init__.py +0 -0
  38. statanim/probability/bayes.py +1682 -0
  39. statanim/probability/prob_tree.py +1478 -0
  40. statanim/probability/sample_space.py +1642 -0
  41. statanim/probability/venn3d.py +1857 -0
  42. statanim/props/__init__.py +0 -0
  43. statanim/props/card.py +2259 -0
  44. statanim/props/coin.py +1011 -0
  45. statanim/props/die.py +1391 -0
  46. statanim/props/spinner.py +1591 -0
  47. statanim/props/urn.py +1531 -0
  48. statanim/regression/__init__.py +0 -0
  49. statanim/regression/correlation.py +2805 -0
  50. statanim/regression/regression_plane.py +2286 -0
  51. statanim/regression/residuals.py +2599 -0
  52. statanim/scenes/__init__.py +0 -0
  53. statanim/scenes/demo_bayes.py +2056 -0
  54. statanim/scenes/demo_clt.py +1756 -0
  55. statanim/scenes/demo_distributions.py +1905 -0
  56. statanim/scenes/demo_hypothesis.py +1791 -0
  57. statanim/ui/__init__.py +0 -0
  58. statanim/ui/labels.py +1844 -0
  59. statanim/ui/panels.py +1937 -0
  60. statanim/ui/table3d.py +1745 -0
  61. statanim/ui/ticker.py +2007 -0
  62. statanim-0.1.0.dist-info/METADATA +463 -0
  63. statanim-0.1.0.dist-info/RECORD +66 -0
  64. statanim-0.1.0.dist-info/WHEEL +5 -0
  65. statanim-0.1.0.dist-info/licenses/LICENSE +21 -0
  66. statanim-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2805 @@
1
+ """
2
+ statanim/regression/correlation.py
3
+ ======================================
4
+ Correlation analysis, OLS regression fitting, diagnostic measures,
5
+ and Manim visualisation mobjects for the regression / correlation topic area.
6
+
7
+ Architecture
8
+ ------------
9
+ Layer A Pure-math computation — pearson, spearman, kendall, partial_r,
10
+ point_biserial, phi, cramers_v
11
+ Layer B Regression fitting — ols_fit, ridge_fit, robust_fit (IRLS)
12
+ Layer C Structured result classes — CorrelationResult, RegressionResult,
13
+ PartialCorrelationResult, InfluenceMeasures
14
+ Layer D Manim mobjects — CorrelationEllipse3D, CorrelationMatrix3D,
15
+ RegressionLine3D, ResidualArrows3D,
16
+ InfluenceMap3D, CIBand3D
17
+ Layer E Scene-level animations — build_scatter_to_line, morph_r_value,
18
+ reveal_residuals, animate_influence_removal
19
+ Layer F Formula registry bridge — CORR_FORMULAS, formula builders that
20
+ extend tex_utils.FORMULAS
21
+
22
+ Design notes
23
+ ------------
24
+ * Layers A–C are pure Python + NumPy/SciPy — usable in notebooks, scripts, or
25
+ tests without Manim installed.
26
+ * Every result dataclass has a ``.to_formula()`` method returning a TexFormula
27
+ (from core.tex_utils) so scenes can overlay the live equation alongside the
28
+ visualisation.
29
+ * Manim mobjects follow the ``VGroup`` sub-class pattern established in
30
+ Card3D: __init__ builds sub-mobjects, public methods return Animation objects.
31
+ * All colour constants are pulled from core.colors so every mobject respects
32
+ the active StatsTheme.
33
+ * SciPy is an optional dependency for p-value computation; if absent the
34
+ module falls back to NumPy-only implementations with a user warning.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import math
40
+ import warnings
41
+ from dataclasses import dataclass, field
42
+ from enum import Enum, auto
43
+ from typing import Dict, List, Optional, Sequence, Tuple, Union
44
+
45
+ import numpy as np
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Optional SciPy
49
+ # ---------------------------------------------------------------------------
50
+ try:
51
+ from scipy import stats as _sp
52
+ _SCIPY_AVAILABLE = True
53
+ except ImportError:
54
+ _SCIPY_AVAILABLE = False
55
+ _sp = None # type: ignore
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Graceful Manim import
59
+ # ---------------------------------------------------------------------------
60
+ try:
61
+ import manim as mn
62
+ from manim import (
63
+ VGroup, VMobject,
64
+ Axes, NumberPlane,
65
+ Line, Arrow, DashedLine,
66
+ Dot, Circle, Ellipse, Square, Rectangle, RoundedRectangle, Polygon,
67
+ Text, MathTex, Tex,
68
+ ManimColor, WHITE, BLACK, GRAY, DARK_GRAY,
69
+ RED, BLUE, GREEN, YELLOW, ORANGE, PURPLE,
70
+ UP, DOWN, LEFT, RIGHT, ORIGIN,
71
+ TAU, PI,
72
+ Write, Create, FadeIn, FadeOut, FadeToColor,
73
+ Transform, ReplacementTransform, TransformMatchingShapes,
74
+ Rotate, Flash, Indicate, Circumscribe,
75
+ AnimationGroup, Succession, LaggedStart,
76
+ rate_functions,
77
+ interpolate_color,
78
+ SurroundingRectangle,
79
+ )
80
+ _MANIM_AVAILABLE = True
81
+ except ImportError:
82
+ _MANIM_AVAILABLE = False
83
+ VGroup = VMobject = object # type: ignore
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # Project imports (graceful — avoids hard circular dependency)
87
+ # ---------------------------------------------------------------------------
88
+ try:
89
+ from statanim.core.colors import (
90
+ REGRESSION_FAMILY, NORMAL_FAMILY, INFERENCE_FAMILY,
91
+ DISCRETE_FAMILY, NEUTRAL_FAMILY,
92
+ DARK_THEME, LIGHT_THEME,
93
+ StatColor, ColorFamily, StatsTheme,
94
+ PURPLE_600, PURPLE_200, PURPLE_800,
95
+ CORAL_600, CORAL_200,
96
+ TEAL_600, TEAL_200,
97
+ BLUE_600, BLUE_200,
98
+ AMBER_600, AMBER_200,
99
+ GRAY_400, GRAY_600, GRAY_800,
100
+ WHITE as _WHITE, BLACK as _BLACK,
101
+ diverging_map, gradient_ramp,
102
+ )
103
+ _COLORS_AVAILABLE = True
104
+ except ImportError:
105
+ _COLORS_AVAILABLE = False
106
+
107
+ try:
108
+ from statanim.core.tex_utils import (
109
+ TexFormula, TexDerivationStep,
110
+ _frac, _sqrt, _sum, _exp, _expected, _var, _cov,
111
+ FORMULAS, register_formula,
112
+ )
113
+ _TEX_AVAILABLE = True
114
+ except ImportError:
115
+ _TEX_AVAILABLE = False
116
+
117
+
118
+ def _require_manim(name: str) -> None:
119
+ if not _MANIM_AVAILABLE:
120
+ raise ImportError(
121
+ f"{name} requires Manim. Install with: pip install manim"
122
+ )
123
+
124
+
125
+ def _require_scipy(name: str) -> None:
126
+ if not _SCIPY_AVAILABLE:
127
+ raise ImportError(
128
+ f"{name} requires SciPy for p-value computation. "
129
+ "Install with: pip install scipy "
130
+ "or pass compute_pvalue=False to suppress this error."
131
+ )
132
+
133
+
134
+ # ===========================================================================
135
+ # LAYER A — Pure-math correlation functions
136
+ # Each returns a raw numeric result (or CorrelationResult) with no Manim deps.
137
+ # ===========================================================================
138
+
139
+ class CorrelationMethod(Enum):
140
+ """Supported correlation coefficient types."""
141
+ PEARSON = "pearson"
142
+ SPEARMAN = "spearman"
143
+ KENDALL = "kendall"
144
+ POINT_BISERIAL = "point_biserial"
145
+ PHI = "phi"
146
+ CRAMERS_V = "cramers_v"
147
+ PARTIAL = "partial"
148
+
149
+
150
+ @dataclass
151
+ class CorrelationResult:
152
+ """
153
+ Structured output of a correlation computation.
154
+
155
+ Attributes
156
+ ----------
157
+ r : float
158
+ Correlation coefficient. For Cramers V this is V (0–1 unsigned).
159
+ method : CorrelationMethod
160
+ Which coefficient was computed.
161
+ n : int
162
+ Sample size.
163
+ p_value : float or None
164
+ Two-tailed p-value. None when SciPy is unavailable and
165
+ ``compute_pvalue=False`` was passed.
166
+ ci_low, ci_high : float or None
167
+ 95% confidence interval via Fisher z-transformation (Pearson only).
168
+ None for non-Pearson methods or n < 4.
169
+ df : int or None
170
+ Degrees of freedom used for the t/z test.
171
+ z_stat : float or None
172
+ Test statistic (t for Pearson/Spearman/Point-biserial, z for Kendall).
173
+ controlled_for : list[str] or None
174
+ Variable names partialled out (PartialCorrelationResult only).
175
+
176
+ Derived properties
177
+ ------------------
178
+ .stars — significance stars: "", "*", "**", "***"
179
+ .effect_size_label — Cohen's (1988) label: "negligible"/"small"/"medium"/"large"
180
+ .significant — bool: p_value < 0.05 (None if p_value is None)
181
+ .abs_r — |r|
182
+ """
183
+
184
+ r: float
185
+ method: CorrelationMethod
186
+ n: int
187
+ p_value: Optional[float] = None
188
+ ci_low: Optional[float] = None
189
+ ci_high: Optional[float] = None
190
+ df: Optional[int] = None
191
+ z_stat: Optional[float] = None
192
+ controlled_for: Optional[List[str]] = None
193
+
194
+ # ------------------------------------------------------------------
195
+ # Derived properties
196
+ # ------------------------------------------------------------------
197
+
198
+ @property
199
+ def abs_r(self) -> float:
200
+ return abs(self.r)
201
+
202
+ @property
203
+ def stars(self) -> str:
204
+ """Significance stars based on p_value."""
205
+ if self.p_value is None:
206
+ return ""
207
+ if self.p_value < 0.001:
208
+ return "***"
209
+ if self.p_value < 0.01:
210
+ return "**"
211
+ if self.p_value < 0.05:
212
+ return "*"
213
+ return ""
214
+
215
+ @property
216
+ def significant(self) -> Optional[bool]:
217
+ if self.p_value is None:
218
+ return None
219
+ return self.p_value < 0.05
220
+
221
+ @property
222
+ def effect_size_label(self) -> str:
223
+ """
224
+ Cohen (1988) benchmarks for |r|:
225
+ < 0.10 negligible, < 0.30 small, < 0.50 medium, >= 0.50 large.
226
+ """
227
+ a = self.abs_r
228
+ if a < 0.10:
229
+ return "negligible"
230
+ if a < 0.30:
231
+ return "small"
232
+ if a < 0.50:
233
+ return "medium"
234
+ return "large"
235
+
236
+ @property
237
+ def ci_str(self) -> str:
238
+ """Formatted 95% CI string, e.g. '[0.574, 0.887]'."""
239
+ if self.ci_low is None or self.ci_high is None:
240
+ return "N/A"
241
+ return f"[{self.ci_low:.3f}, {self.ci_high:.3f}]"
242
+
243
+ def summary(self) -> str:
244
+ """One-line human-readable summary."""
245
+ p_str = f"p={self.p_value:.4g}" if self.p_value is not None else "p=N/A"
246
+ return (
247
+ f"{self.method.value} r={self.r:.4f}{self.stars} "
248
+ f"n={self.n} {p_str} 95%CI={self.ci_str} "
249
+ f"effect={self.effect_size_label}"
250
+ )
251
+
252
+ # ------------------------------------------------------------------
253
+ # tex_utils bridge
254
+ # ------------------------------------------------------------------
255
+
256
+ def to_formula(self) -> "TexFormula":
257
+ """
258
+ Return a ``TexFormula`` showing the result as a typeset equation, e.g.::
259
+
260
+ r = 0.774^{**}\quad (n=30,\; p=5.3 \times 10^{-7})
261
+
262
+ Requires tex_utils to be importable (it is a project-internal dep).
263
+ """
264
+ if not _TEX_AVAILABLE:
265
+ raise ImportError(
266
+ "to_formula() requires statanim.core.tex_utils."
267
+ )
268
+ sym = {
269
+ CorrelationMethod.PEARSON: "r",
270
+ CorrelationMethod.SPEARMAN: r"\rho",
271
+ CorrelationMethod.KENDALL: r"\tau",
272
+ CorrelationMethod.POINT_BISERIAL: r"r_{pb}",
273
+ CorrelationMethod.PHI: r"\phi",
274
+ CorrelationMethod.CRAMERS_V: "V",
275
+ CorrelationMethod.PARTIAL: r"r_{partial}",
276
+ }[self.method]
277
+
278
+ stars_tex = r"^{\!" + self.stars + r"}" if self.stars else ""
279
+ p_tex = (
280
+ rf"\;p={self.p_value:.3g}"
281
+ if self.p_value is not None else ""
282
+ )
283
+ n_tex = rf"\;n={self.n}"
284
+ raw = rf"{sym} = {self.r:.4f}{stars_tex}\quad({n_tex}{p_tex})"
285
+
286
+ return TexFormula(
287
+ name = f"corr_result_{self.method.value}",
288
+ raw = raw,
289
+ description = self.summary(),
290
+ parts = {
291
+ "coefficient": sym,
292
+ "value": f"{self.r:.4f}",
293
+ "stars": self.stars,
294
+ },
295
+ tags = ["correlation", "result", self.method.value],
296
+ )
297
+
298
+ def __repr__(self) -> str:
299
+ return (
300
+ f"CorrelationResult(r={self.r:.4f}, "
301
+ f"method={self.method.value}, n={self.n}, "
302
+ f"p={self.p_value:.4g if self.p_value is not None else 'None'})"
303
+ )
304
+
305
+
306
+ # ---------------------------------------------------------------------------
307
+ # A.1 Pearson r
308
+ # ---------------------------------------------------------------------------
309
+
310
+ def pearson(
311
+ x: np.ndarray,
312
+ y: np.ndarray,
313
+ compute_pvalue: bool = True,
314
+ alpha: float = 0.05,
315
+ ) -> CorrelationResult:
316
+ """
317
+ Compute Pearson's r with Fisher z confidence interval.
318
+
319
+ Parameters
320
+ ----------
321
+ x, y : array-like of shape (n,)
322
+ Paired observations. NaNs are listwise-deleted.
323
+ compute_pvalue : bool
324
+ If False, skip the SciPy t-test (faster; p_value will be None).
325
+ alpha : float
326
+ Significance level for the confidence interval (default 0.05 → 95% CI).
327
+
328
+ Returns
329
+ -------
330
+ CorrelationResult
331
+ .r, .p_value, .ci_low, .ci_high (Fisher z), .df = n-2, .z_stat = t
332
+
333
+ Notes
334
+ -----
335
+ CI uses Fisher's z-transformation:
336
+ z = arctanh(r)
337
+ SE(z) = 1 / sqrt(n - 3)
338
+ CI = tanh(z ± z_crit * SE)
339
+ """
340
+ x, y = _clean_paired(x, y)
341
+ n = len(x)
342
+ if n < 3:
343
+ raise ValueError(f"pearson() requires n >= 3, got n={n}.")
344
+
345
+ r = float(np.corrcoef(x, y)[0, 1])
346
+ r = np.clip(r, -1 + 1e-12, 1 - 1e-12) # guard arctanh domain
347
+
348
+ p_value = z_stat = None
349
+ if compute_pvalue:
350
+ _require_scipy("pearson(compute_pvalue=True)")
351
+ r_sc, p_value = _sp.pearsonr(x, y)
352
+ z_stat = r * math.sqrt(n - 2) / math.sqrt(1 - r**2)
353
+
354
+ # Fisher z CI
355
+ ci_low = ci_high = None
356
+ if n >= 4:
357
+ z = math.atanh(r)
358
+ se_z = 1.0 / math.sqrt(n - 3)
359
+ if _SCIPY_AVAILABLE:
360
+ z_crit = float(_sp.norm.ppf(1 - alpha / 2))
361
+ else:
362
+ z_crit = 1.959963985 # 97.5th percentile of N(0,1)
363
+ ci_low = float(math.tanh(z - z_crit * se_z))
364
+ ci_high = float(math.tanh(z + z_crit * se_z))
365
+
366
+ return CorrelationResult(
367
+ r = r,
368
+ method = CorrelationMethod.PEARSON,
369
+ n = n,
370
+ p_value = p_value,
371
+ ci_low = ci_low,
372
+ ci_high = ci_high,
373
+ df = n - 2,
374
+ z_stat = z_stat,
375
+ )
376
+
377
+
378
+ # ---------------------------------------------------------------------------
379
+ # A.2 Spearman rho
380
+ # ---------------------------------------------------------------------------
381
+
382
+ def spearman(
383
+ x: np.ndarray,
384
+ y: np.ndarray,
385
+ compute_pvalue: bool = True,
386
+ ) -> CorrelationResult:
387
+ """
388
+ Compute Spearman's rank correlation.
389
+
390
+ Uses the standard formula on rank-transformed data:
391
+ rho = 1 - 6 * sum(d_i^2) / (n * (n^2 - 1))
392
+
393
+ where d_i = rank(x_i) - rank(y_i). Ties are broken with average ranks.
394
+ For n >= 10 the t approximation t = rho * sqrt((n-2)/(1-rho^2)) is used
395
+ for the p-value.
396
+
397
+ Returns
398
+ -------
399
+ CorrelationResult
400
+ .r = rho, .df = n-2, .z_stat = t approximation (for n >= 10)
401
+ """
402
+ x, y = _clean_paired(x, y)
403
+ n = len(x)
404
+ if n < 3:
405
+ raise ValueError(f"spearman() requires n >= 3, got n={n}.")
406
+
407
+ rx = _rankdata(x)
408
+ ry = _rankdata(y)
409
+ d_sq = np.sum((rx - ry) ** 2)
410
+ rho = float(1.0 - 6.0 * d_sq / (n * (n**2 - 1)))
411
+ rho = np.clip(rho, -1.0, 1.0)
412
+
413
+ p_value = z_stat = None
414
+ if compute_pvalue:
415
+ _require_scipy("spearman(compute_pvalue=True)")
416
+ _, p_value = _sp.spearmanr(x, y)
417
+ if n >= 10:
418
+ t_val = rho * math.sqrt((n - 2) / (1.0 - rho**2 + 1e-14))
419
+ z_stat = t_val
420
+
421
+ return CorrelationResult(
422
+ r = rho,
423
+ method = CorrelationMethod.SPEARMAN,
424
+ n = n,
425
+ p_value = p_value,
426
+ df = n - 2,
427
+ z_stat = z_stat,
428
+ )
429
+
430
+
431
+ # ---------------------------------------------------------------------------
432
+ # A.3 Kendall's tau-b
433
+ # ---------------------------------------------------------------------------
434
+
435
+ def kendall(
436
+ x: np.ndarray,
437
+ y: np.ndarray,
438
+ compute_pvalue: bool = True,
439
+ ) -> CorrelationResult:
440
+ """
441
+ Compute Kendall's tau-b.
442
+
443
+ tau-b adjusts for ties in both x and y, making it the most appropriate
444
+ Kendall variant for discrete or tied data.
445
+
446
+ Returns
447
+ -------
448
+ CorrelationResult
449
+ .r = tau_b, .z_stat = z approximation
450
+ """
451
+ x, y = _clean_paired(x, y)
452
+ n = len(x)
453
+ if n < 3:
454
+ raise ValueError(f"kendall() requires n >= 3, got n={n}.")
455
+
456
+ p_value = z_stat = None
457
+ if compute_pvalue:
458
+ _require_scipy("kendall(compute_pvalue=True)")
459
+ tau, p_value = _sp.kendalltau(x, y)
460
+ else:
461
+ tau = _kendall_tau_b_numpy(x, y)
462
+
463
+ if not compute_pvalue:
464
+ tau = _kendall_tau_b_numpy(x, y)
465
+
466
+ # z approximation (valid for n >= 10)
467
+ if n >= 10:
468
+ v = 2.0 * (2 * n + 5) / (9 * n * (n - 1))
469
+ z_stat = float(tau) / math.sqrt(v) if v > 0 else None
470
+
471
+ return CorrelationResult(
472
+ r = float(tau),
473
+ method = CorrelationMethod.KENDALL,
474
+ n = n,
475
+ p_value = p_value,
476
+ z_stat = z_stat,
477
+ )
478
+
479
+
480
+ def _kendall_tau_b_numpy(x: np.ndarray, y: np.ndarray) -> float:
481
+ """Pure NumPy O(n log n) Kendall tau-b via merge-sort concordance count."""
482
+ n = len(x)
483
+ order = np.argsort(x, stable=True)
484
+ y_sort = y[order]
485
+
486
+ # Count concordant (C) and discordant (D) pairs by merge-sort on y_sort
487
+ C, D, tx, ty = 0, 0, 0, 0
488
+
489
+ def _merge_count(arr):
490
+ nonlocal D
491
+ if len(arr) <= 1:
492
+ return arr
493
+ mid = len(arr) // 2
494
+ left = _merge_count(arr[:mid])
495
+ right = _merge_count(arr[mid:])
496
+ merged, i, j = [], 0, 0
497
+ while i < len(left) and j < len(right):
498
+ if left[i] <= right[j]:
499
+ D += len(right) - j
500
+ merged.append(left[i]); i += 1
501
+ else:
502
+ merged.append(right[j]); j += 1
503
+ merged.extend(left[i:])
504
+ merged.extend(right[j:])
505
+ return merged
506
+
507
+ _merge_count(list(y_sort))
508
+
509
+ P = n * (n - 1) // 2
510
+ C = P - D
511
+ # Tie corrections
512
+ tx_vals = np.unique(x, return_counts=True)[1]
513
+ ty_vals = np.unique(y, return_counts=True)[1]
514
+ tx = np.sum(tv * (tv - 1) // 2 for tv in tx_vals)
515
+ ty = np.sum(tv * (tv - 1) // 2 for tv in ty_vals)
516
+ denom = math.sqrt((P - tx) * (P - ty))
517
+ return float((C - D) / denom) if denom > 0 else 0.0
518
+
519
+
520
+ # ---------------------------------------------------------------------------
521
+ # A.4 Point-biserial r
522
+ # ---------------------------------------------------------------------------
523
+
524
+ def point_biserial(
525
+ continuous: np.ndarray,
526
+ binary: np.ndarray,
527
+ compute_pvalue: bool = True,
528
+ ) -> CorrelationResult:
529
+ """
530
+ Compute the point-biserial correlation between a continuous and a
531
+ binary (0/1) variable.
532
+
533
+ Mathematically equivalent to Pearson r between the two variables but
534
+ has a simpler closed-form:
535
+
536
+ r_pb = (M1 - M0) / s_n * sqrt(n1 * n0 / n^2)
537
+
538
+ where M1, M0 are group means, s_n the pooled (population) SD, n1 n0 group sizes.
539
+
540
+ Parameters
541
+ ----------
542
+ continuous : array-like
543
+ Continuous variable.
544
+ binary : array-like
545
+ Binary variable with values in {0, 1}. Will be coerced to int.
546
+
547
+ Returns
548
+ -------
549
+ CorrelationResult
550
+ """
551
+ c, b = _clean_paired(continuous, np.asarray(binary, dtype=float))
552
+ n = len(c)
553
+
554
+ unique_b = np.unique(b)
555
+ if not np.array_equal(np.sort(unique_b), [0.0, 1.0]):
556
+ # Recode to 0/1 by rank of unique values
557
+ b = (b == np.max(unique_b)).astype(float)
558
+
559
+ n1 = int(np.sum(b == 1))
560
+ n0 = int(np.sum(b == 0))
561
+ if n1 == 0 or n0 == 0:
562
+ raise ValueError("point_biserial() requires both groups (0 and 1) to be non-empty.")
563
+
564
+ M1 = float(np.mean(c[b == 1]))
565
+ M0 = float(np.mean(c[b == 0]))
566
+ s_n = float(np.std(c, ddof=0)) # population SD
567
+ r_pb = (M1 - M0) / s_n * math.sqrt(n1 * n0 / n**2)
568
+
569
+ p_value = z_stat = None
570
+ if compute_pvalue:
571
+ _require_scipy("point_biserial(compute_pvalue=True)")
572
+ _, p_value = _sp.pointbiserialr(b, c)
573
+ z_stat = r_pb * math.sqrt(n - 2) / math.sqrt(1 - r_pb**2 + 1e-14)
574
+
575
+ return CorrelationResult(
576
+ r = r_pb,
577
+ method = CorrelationMethod.POINT_BISERIAL,
578
+ n = n,
579
+ p_value = p_value,
580
+ df = n - 2,
581
+ z_stat = z_stat,
582
+ )
583
+
584
+
585
+ # ---------------------------------------------------------------------------
586
+ # A.5 Phi coefficient (2×2 contingency tables)
587
+ # ---------------------------------------------------------------------------
588
+
589
+ def phi_coefficient(
590
+ table: np.ndarray,
591
+ compute_pvalue: bool = True,
592
+ ) -> CorrelationResult:
593
+ """
594
+ Compute the phi coefficient for a 2x2 contingency table.
595
+
596
+ phi = (ad - bc) / sqrt((a+b)(c+d)(a+c)(b+d))
597
+
598
+ Parameters
599
+ ----------
600
+ table : ndarray of shape (2, 2)
601
+ Contingency table [[a, b], [c, d]].
602
+
603
+ Returns
604
+ -------
605
+ CorrelationResult
606
+ .r = phi, .n = total cell count
607
+ """
608
+ table = np.asarray(table, dtype=float)
609
+ if table.shape != (2, 2):
610
+ raise ValueError(
611
+ f"phi_coefficient() requires a (2,2) table, got {table.shape}."
612
+ )
613
+ a, b, c, d = table[0, 0], table[0, 1], table[1, 0], table[1, 1]
614
+ n = int(np.sum(table))
615
+ denom = math.sqrt((a+b) * (c+d) * (a+c) * (b+d))
616
+ phi = float((a * d - b * c) / denom) if denom > 0 else 0.0
617
+
618
+ p_value = None
619
+ if compute_pvalue:
620
+ _require_scipy("phi_coefficient(compute_pvalue=True)")
621
+ chi2, p_value, _, _ = _sp.chi2_contingency(table, correction=False)
622
+
623
+ return CorrelationResult(
624
+ r = phi,
625
+ method = CorrelationMethod.PHI,
626
+ n = n,
627
+ p_value = p_value,
628
+ )
629
+
630
+
631
+ # ---------------------------------------------------------------------------
632
+ # A.6 Cramér's V (r×c contingency tables)
633
+ # ---------------------------------------------------------------------------
634
+
635
+ def cramers_v(
636
+ table: np.ndarray,
637
+ compute_pvalue: bool = True,
638
+ bias_corrected: bool = True,
639
+ ) -> CorrelationResult:
640
+ """
641
+ Compute Cramér's V for an r×c contingency table.
642
+
643
+ Standard V = sqrt(chi^2 / (n * (k-1))) where k = min(r, c).
644
+
645
+ Bias-corrected version (Bergsma 2013):
646
+ phi_c^2 = max(0, chi^2/n - (k-1)/(n-1))
647
+ V_c = sqrt(phi_c^2 / (k_tilde - 1))
648
+ k_tilde = k - (k-1)^2 / (n-1)
649
+
650
+ Parameters
651
+ ----------
652
+ table : array-like
653
+ r × c contingency table of observed counts.
654
+ bias_corrected : bool
655
+ Apply the Bergsma–Wicher bias correction (default True).
656
+
657
+ Returns
658
+ -------
659
+ CorrelationResult
660
+ .r = V (0–1 unsigned), .n = total count
661
+ """
662
+ table = np.asarray(table, dtype=float)
663
+ if table.ndim != 2:
664
+ raise ValueError("cramers_v() requires a 2-D contingency table.")
665
+ n = float(np.sum(table))
666
+ r, c = table.shape
667
+ k = min(r, c)
668
+
669
+ _require_scipy("cramers_v")
670
+ chi2, p_value, _, _ = _sp.chi2_contingency(table)
671
+
672
+ if bias_corrected:
673
+ phi2 = max(0.0, chi2 / n - (k - 1) / (n - 1))
674
+ k_tilde = k - (k - 1)**2 / (n - 1)
675
+ r_tilde = r - (r - 1)**2 / (n - 1)
676
+ V = math.sqrt(phi2 / (min(k_tilde, r_tilde) - 1)) if min(k_tilde, r_tilde) > 1 else 0.0
677
+ else:
678
+ V = math.sqrt(chi2 / (n * (k - 1))) if k > 1 else 0.0
679
+
680
+ return CorrelationResult(
681
+ r = V,
682
+ method = CorrelationMethod.CRAMERS_V,
683
+ n = int(n),
684
+ p_value = p_value if compute_pvalue else None,
685
+ )
686
+
687
+
688
+ # ---------------------------------------------------------------------------
689
+ # A.7 Partial correlation
690
+ # ---------------------------------------------------------------------------
691
+
692
+ @dataclass
693
+ class PartialCorrelationResult(CorrelationResult):
694
+ """
695
+ Extension of CorrelationResult for partial / semi-partial correlations.
696
+
697
+ Additional attributes
698
+ ---------------------
699
+ control_vars : list[str]
700
+ Names of the variables that were partialled out.
701
+ x_name, y_name : str
702
+ Names of the two focal variables.
703
+ semi_partial : bool
704
+ True if this is a semi-partial (part) correlation rather than partial.
705
+ r_squared_full : float or None
706
+ R^2 of the full model (for computing the unique variance contribution).
707
+ r_squared_without_x : float or None
708
+ R^2 of the model without the focal X variable.
709
+ unique_variance : float or None
710
+ r_squared_full - r_squared_without_x (unique contribution of X).
711
+ """
712
+ control_vars: List[str] = field(default_factory=list)
713
+ x_name: str = "X"
714
+ y_name: str = "Y"
715
+ semi_partial: bool = False
716
+ r_squared_full: Optional[float] = None
717
+ r_squared_without_x: Optional[float] = None
718
+
719
+ @property
720
+ def unique_variance(self) -> Optional[float]:
721
+ if self.r_squared_full is None or self.r_squared_without_x is None:
722
+ return None
723
+ return self.r_squared_full - self.r_squared_without_x
724
+
725
+ def summary(self) -> str:
726
+ kind = "semi-partial" if self.semi_partial else "partial"
727
+ ctrl_str = ", ".join(self.control_vars) or "none"
728
+ base = super().summary()
729
+ return f"{base} [{kind}, controlling for: {ctrl_str}]"
730
+
731
+
732
+ def partial_correlation(
733
+ x: np.ndarray,
734
+ y: np.ndarray,
735
+ controls: np.ndarray,
736
+ x_name: str = "X",
737
+ y_name: str = "Y",
738
+ control_names: Optional[List[str]] = None,
739
+ compute_pvalue: bool = True,
740
+ semi_partial: bool = False,
741
+ ) -> PartialCorrelationResult:
742
+ """
743
+ Compute the partial (or semi-partial) correlation between X and Y,
744
+ controlling for one or more covariates Z.
745
+
746
+ Method
747
+ ------
748
+ 1. Regress X on Z → residuals e_X
749
+ 2. Regress Y on Z → residuals e_Y
750
+ 3. Partial r = Pearson(e_X, e_Y)
751
+
752
+ For semi-partial (part) correlation, only X is residualised:
753
+ 3. Semi-partial r = Pearson(e_X, Y)
754
+
755
+ Parameters
756
+ ----------
757
+ x, y : array-like, shape (n,)
758
+ Focal variables.
759
+ controls : array-like, shape (n,) or (n, k)
760
+ Control variable(s). Automatically prepended with an intercept column.
761
+ x_name, y_name : str
762
+ Labels used in the result summary and formula.
763
+ control_names : list[str], optional
764
+ Labels for control variables.
765
+ compute_pvalue : bool
766
+ semi_partial : bool
767
+ If True, compute the semi-partial (part) correlation.
768
+
769
+ Returns
770
+ -------
771
+ PartialCorrelationResult
772
+ """
773
+ x = np.asarray(x, dtype=float).ravel()
774
+ y = np.asarray(y, dtype=float).ravel()
775
+ Z = np.asarray(controls, dtype=float)
776
+ if Z.ndim == 1:
777
+ Z = Z.reshape(-1, 1)
778
+ n = len(x)
779
+
780
+ # Add intercept
781
+ Zc = np.column_stack([np.ones(n), Z])
782
+
783
+ def _residualise(v: np.ndarray) -> np.ndarray:
784
+ beta, _, _, _ = np.linalg.lstsq(Zc, v, rcond=None)
785
+ return v - Zc @ beta
786
+
787
+ e_x = _residualise(x)
788
+ e_y = _residualise(y) if not semi_partial else y
789
+
790
+ result = pearson(e_x, e_y, compute_pvalue=compute_pvalue)
791
+
792
+ ctrl_names = control_names or [f"Z{i+1}" for i in range(Z.shape[1])]
793
+
794
+ return PartialCorrelationResult(
795
+ r = result.r,
796
+ method = CorrelationMethod.PARTIAL,
797
+ n = n,
798
+ p_value = result.p_value,
799
+ ci_low = result.ci_low,
800
+ ci_high = result.ci_high,
801
+ df = n - 2 - Z.shape[1],
802
+ z_stat = result.z_stat,
803
+ control_vars = ctrl_names,
804
+ x_name = x_name,
805
+ y_name = y_name,
806
+ semi_partial = semi_partial,
807
+ )
808
+
809
+
810
+ # ---------------------------------------------------------------------------
811
+ # A.8 Correlation matrix
812
+ # ---------------------------------------------------------------------------
813
+
814
+ def correlation_matrix(
815
+ data: np.ndarray,
816
+ method: CorrelationMethod = CorrelationMethod.PEARSON,
817
+ compute_pvalue: bool = True,
818
+ var_names: Optional[List[str]] = None,
819
+ ) -> Tuple[np.ndarray, np.ndarray, List[str]]:
820
+ """
821
+ Compute a full p×p correlation matrix.
822
+
823
+ Parameters
824
+ ----------
825
+ data : array-like, shape (n, p)
826
+ Each column is a variable.
827
+ method : CorrelationMethod
828
+ Only PEARSON and SPEARMAN are supported for full matrices.
829
+ compute_pvalue : bool
830
+ var_names : list[str], optional
831
+ Column labels. Defaults to ["X1", "X2", …].
832
+
833
+ Returns
834
+ -------
835
+ (R, P, names)
836
+ R : ndarray (p, p) — correlation coefficients, 1 on diagonal
837
+ P : ndarray (p, p) — p-values; NaN on diagonal; None-matrix if not computed
838
+ names : list[str] — variable names
839
+ """
840
+ data = np.asarray(data, dtype=float)
841
+ if data.ndim == 1:
842
+ data = data.reshape(-1, 1)
843
+ n, p = data.shape
844
+ names = var_names or [f"X{i+1}" for i in range(p)]
845
+
846
+ R = np.ones((p, p))
847
+ P = np.full((p, p), np.nan)
848
+
849
+ _corr_fn = pearson if method == CorrelationMethod.PEARSON else spearman
850
+
851
+ for i in range(p):
852
+ for j in range(i + 1, p):
853
+ res = _corr_fn(
854
+ data[:, i], data[:, j],
855
+ compute_pvalue=compute_pvalue,
856
+ )
857
+ R[i, j] = R[j, i] = res.r
858
+ if res.p_value is not None:
859
+ P[i, j] = P[j, i] = res.p_value
860
+
861
+ if not compute_pvalue:
862
+ P = None # type: ignore
863
+
864
+ return R, P, names
865
+
866
+
867
+ # ===========================================================================
868
+ # LAYER B — Regression fitting and diagnostics
869
+ # ===========================================================================
870
+
871
+ @dataclass
872
+ class RegressionResult:
873
+ """
874
+ Structured output of an OLS regression fit.
875
+
876
+ Attributes
877
+ ----------
878
+ beta : ndarray, shape (k,)
879
+ Estimated coefficients. beta[0] is the intercept if ``fit_intercept=True``.
880
+ se : ndarray, shape (k,)
881
+ Standard errors of each coefficient.
882
+ t_stat : ndarray, shape (k,)
883
+ t-statistics: beta / se.
884
+ p_values : ndarray, shape (k,)
885
+ Two-tailed p-values for each coefficient.
886
+ r_squared : float
887
+ Coefficient of determination R^2.
888
+ adj_r_squared : float
889
+ Adjusted R^2 = 1 - (1-R^2) * (n-1) / (n-k-1).
890
+ f_stat : float
891
+ F-statistic for overall model fit.
892
+ f_p_value : float
893
+ p-value of the F-test.
894
+ aic : float
895
+ Akaike information criterion.
896
+ bic : float
897
+ Bayesian information criterion.
898
+ fitted : ndarray, shape (n,)
899
+ Predicted values y_hat.
900
+ residuals : ndarray, shape (n,)
901
+ Ordinary residuals y - y_hat.
902
+ x : ndarray, shape (n, k)
903
+ Design matrix (with intercept column if fit_intercept=True).
904
+ y : ndarray, shape (n,)
905
+ Response variable.
906
+ feature_names : list[str]
907
+ Names for each column of X (excluding intercept).
908
+ fit_intercept : bool
909
+ n : int
910
+ Sample size.
911
+ k : int
912
+ Number of predictors (excluding intercept).
913
+ """
914
+
915
+ beta: np.ndarray
916
+ se: np.ndarray
917
+ t_stat: np.ndarray
918
+ p_values: np.ndarray
919
+ r_squared: float
920
+ adj_r_squared: float
921
+ f_stat: float
922
+ f_p_value: float
923
+ aic: float
924
+ bic: float
925
+ fitted: np.ndarray
926
+ residuals: np.ndarray
927
+ x: np.ndarray
928
+ y: np.ndarray
929
+ feature_names: List[str]
930
+ fit_intercept: bool
931
+ n: int
932
+ k: int
933
+
934
+ # ------------------------------------------------------------------
935
+ # Derived diagnostic quantities
936
+ # ------------------------------------------------------------------
937
+
938
+ @property
939
+ def rss(self) -> float:
940
+ """Residual sum of squares."""
941
+ return float(np.sum(self.residuals**2))
942
+
943
+ @property
944
+ def tss(self) -> float:
945
+ """Total sum of squares."""
946
+ return float(np.sum((self.y - self.y.mean())**2))
947
+
948
+ @property
949
+ def mse(self) -> float:
950
+ """Mean squared error of residuals."""
951
+ df = self.n - self.k - (1 if self.fit_intercept else 0)
952
+ return self.rss / df if df > 0 else float("nan")
953
+
954
+ @property
955
+ def rmse(self) -> float:
956
+ """Root mean squared error."""
957
+ return math.sqrt(self.mse)
958
+
959
+ @property
960
+ def sigma_hat(self) -> float:
961
+ """Estimated residual standard deviation (same as rmse)."""
962
+ return self.rmse
963
+
964
+ @property
965
+ def hat_matrix_diag(self) -> np.ndarray:
966
+ """
967
+ Diagonal of the hat matrix H = X(X'X)^-1 X'.
968
+ Leverage values for each observation.
969
+ """
970
+ try:
971
+ XtX_inv = np.linalg.inv(self.x.T @ self.x)
972
+ return np.einsum("ij,jk,ki->i", self.x, XtX_inv, self.x.T)
973
+ except np.linalg.LinAlgError:
974
+ return np.full(self.n, float("nan"))
975
+
976
+ def coef_table(self, digits: int = 4) -> str:
977
+ """
978
+ Return a formatted coefficient table string, e.g.::
979
+
980
+ Coeff Estimate SE t p
981
+ (Intercept) 0.0581 0.0893 0.651 0.5203
982
+ X1 0.6268 0.0916 6.843 0.0000 ***
983
+
984
+ Parameters
985
+ ----------
986
+ digits : int
987
+ Decimal places for each numeric column.
988
+
989
+ Returns
990
+ -------
991
+ str
992
+ """
993
+ names = (["(Intercept)"] if self.fit_intercept else []) + list(self.feature_names)
994
+ rows = [f"{'Coeff':<18} {'Estimate':>10} {'SE':>10} {'t':>10} {'p':>12}"]
995
+ rows.append("-" * 64)
996
+ for name, b, se, t, p in zip(names, self.beta, self.se, self.t_stat, self.p_values):
997
+ stars = "***" if p < 0.001 else "**" if p < 0.01 else "*" if p < 0.05 else ""
998
+ rows.append(
999
+ f"{name:<18} {b:>10.{digits}f} {se:>10.{digits}f} "
1000
+ f"{t:>10.{digits}f} {p:>12.4g} {stars}"
1001
+ )
1002
+ rows.append("-" * 64)
1003
+ rows.append(f"R^2={self.r_squared:.4f} Adj R^2={self.adj_r_squared:.4f} "
1004
+ f"F({self.k},{self.n-self.k-1})={self.f_stat:.4f} p={self.f_p_value:.4g} "
1005
+ f"AIC={self.aic:.2f} BIC={self.bic:.2f}")
1006
+ return "\n".join(rows)
1007
+
1008
+ def to_formula(self) -> "TexFormula":
1009
+ """
1010
+ Return a TexFormula for the fitted equation, e.g.::
1011
+
1012
+ hat{Y} = 0.058 + 0.627 X_1
1013
+ """
1014
+ if not _TEX_AVAILABLE:
1015
+ raise ImportError("to_formula() requires statanim.core.tex_utils.")
1016
+ terms = []
1017
+ b_arr = list(self.beta)
1018
+ if self.fit_intercept:
1019
+ intercept = b_arr.pop(0)
1020
+ terms.append(f"{intercept:.4f}")
1021
+ for i, (b, name) in enumerate(zip(b_arr, self.feature_names)):
1022
+ sign = "+" if b >= 0 else "-"
1023
+ terms.append(f"{sign} {abs(b):.4f}\\,{name}")
1024
+ raw = r"\hat{Y} = " + " ".join(terms)
1025
+ return TexFormula(
1026
+ name = "regression_fit",
1027
+ raw = raw,
1028
+ description = f"Fitted OLS: R^2={self.r_squared:.4f}",
1029
+ parts = {"lhs": r"\hat{Y}"},
1030
+ tags = ["regression", "ols", "fitted"],
1031
+ )
1032
+
1033
+ def __repr__(self) -> str:
1034
+ return (
1035
+ f"RegressionResult("
1036
+ f"n={self.n}, k={self.k}, "
1037
+ f"R^2={self.r_squared:.4f}, "
1038
+ f"RMSE={self.rmse:.4f})"
1039
+ )
1040
+
1041
+
1042
+ @dataclass
1043
+ class InfluenceMeasures:
1044
+ """
1045
+ Diagnostic influence measures for each observation in an OLS fit.
1046
+
1047
+ All arrays have length n (one value per observation).
1048
+
1049
+ Attributes
1050
+ ----------
1051
+ leverage : ndarray
1052
+ Hat-matrix diagonal h_ii. High leverage: h_ii > 2k/n.
1053
+ studentized_residuals : ndarray
1054
+ Internally studentized (standardised) residuals.
1055
+ externally_studentized : ndarray
1056
+ Externally studentized residuals (leave-one-out SD).
1057
+ cooks_d : ndarray
1058
+ Cook's distance: measures influence of each observation on all fitted values.
1059
+ dffits : ndarray
1060
+ DFFITS: scaled change in fitted value when observation is deleted.
1061
+ dfbetas : ndarray, shape (n, k)
1062
+ Change in each coefficient when observation is deleted (scaled by SE).
1063
+ """
1064
+
1065
+ leverage: np.ndarray
1066
+ studentized_residuals: np.ndarray
1067
+ externally_studentized: np.ndarray
1068
+ cooks_d: np.ndarray
1069
+ dffits: np.ndarray
1070
+ dfbetas: np.ndarray # shape (n, k)
1071
+
1072
+ # ------------------------------------------------------------------
1073
+ # Outlier / high-influence masks
1074
+ # ------------------------------------------------------------------
1075
+
1076
+ def high_leverage_mask(self, threshold: Optional[float] = None, k: int = 1, n: int = 1) -> np.ndarray:
1077
+ """
1078
+ Boolean mask of high-leverage observations.
1079
+
1080
+ Default threshold: 2 * (k+1) / n (Huber's rule).
1081
+ """
1082
+ thresh = threshold if threshold is not None else 2 * (k + 1) / max(n, 1)
1083
+ return self.leverage > thresh
1084
+
1085
+ def outlier_mask(self, threshold: float = 2.5) -> np.ndarray:
1086
+ """Boolean mask: |externally studentized residual| > threshold."""
1087
+ return np.abs(self.externally_studentized) > threshold
1088
+
1089
+ def influential_mask(self, cooks_threshold: float = 1.0) -> np.ndarray:
1090
+ """Boolean mask: Cook's D > threshold (default 1.0, conservative 4/n also common)."""
1091
+ return self.cooks_d > cooks_threshold
1092
+
1093
+ def concerning_obs(
1094
+ self,
1095
+ leverage_mult: float = 2.0,
1096
+ outlier_thresh: float = 2.5,
1097
+ cooks_thresh: float = 1.0,
1098
+ k: int = 1,
1099
+ n: int = 1,
1100
+ ) -> np.ndarray:
1101
+ """
1102
+ Return indices of observations that are high-leverage AND/OR outliers
1103
+ AND/OR influential (Cook's D).
1104
+ """
1105
+ lev = self.high_leverage_mask(threshold=leverage_mult*(k+1)/max(n,1), k=k, n=n)
1106
+ out = self.outlier_mask(outlier_thresh)
1107
+ inf = self.influential_mask(cooks_thresh)
1108
+ return np.where(lev | out | inf)[0]
1109
+
1110
+ def __repr__(self) -> str:
1111
+ n_inf = int(np.sum(self.influential_mask()))
1112
+ n_lev = int(np.sum(self.leverage > 0.5))
1113
+ n_out = int(np.sum(self.outlier_mask()))
1114
+ return (
1115
+ f"InfluenceMeasures("
1116
+ f"n_influential={n_inf}, "
1117
+ f"n_high_leverage={n_lev}, "
1118
+ f"n_outliers={n_out})"
1119
+ )
1120
+
1121
+
1122
+ # ---------------------------------------------------------------------------
1123
+ # B.1 OLS fitting
1124
+ # ---------------------------------------------------------------------------
1125
+
1126
+ def ols_fit(
1127
+ x: np.ndarray,
1128
+ y: np.ndarray,
1129
+ fit_intercept: bool = True,
1130
+ feature_names: Optional[List[str]] = None,
1131
+ compute_pvalue: bool = True,
1132
+ ) -> RegressionResult:
1133
+ """
1134
+ Ordinary Least Squares regression via the normal equations.
1135
+
1136
+ Solves beta = (X'X)^{-1} X'y using ``np.linalg.lstsq`` for numerical
1137
+ stability. When X is near-singular a PseudoInverse fallback is used
1138
+ with a UserWarning.
1139
+
1140
+ Parameters
1141
+ ----------
1142
+ x : array-like, shape (n,) or (n, k)
1143
+ Predictor matrix. A 1-D array is treated as a single predictor.
1144
+ y : array-like, shape (n,)
1145
+ Response variable.
1146
+ fit_intercept : bool
1147
+ If True (default), prepend a column of ones to X.
1148
+ feature_names : list[str], optional
1149
+ Names for each column of X (before intercept is added).
1150
+ compute_pvalue : bool
1151
+ If True (default), compute t-test p-values via SciPy.
1152
+
1153
+ Returns
1154
+ -------
1155
+ RegressionResult
1156
+ """
1157
+ x = np.asarray(x, dtype=float)
1158
+ y = np.asarray(y, dtype=float).ravel()
1159
+ n = len(y)
1160
+
1161
+ if x.ndim == 1:
1162
+ x = x.reshape(-1, 1)
1163
+ k = x.shape[1]
1164
+ names = feature_names or [f"X{i+1}" for i in range(k)]
1165
+
1166
+ # Build design matrix
1167
+ X = np.column_stack([np.ones(n), x]) if fit_intercept else x
1168
+
1169
+ # Solve
1170
+ try:
1171
+ XtX = X.T @ X
1172
+ XtX_inv = np.linalg.inv(XtX)
1173
+ beta = XtX_inv @ X.T @ y
1174
+ except np.linalg.LinAlgError:
1175
+ warnings.warn(
1176
+ "X'X is singular; falling back to pseudoinverse (lstsq).",
1177
+ UserWarning, stacklevel=2,
1178
+ )
1179
+ beta, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
1180
+ XtX_inv = np.linalg.pinv(X.T @ X)
1181
+
1182
+ y_hat = X @ beta
1183
+ resid = y - y_hat
1184
+ rss = float(np.sum(resid**2))
1185
+ tss = float(np.sum((y - y.mean())**2))
1186
+ r2 = 1.0 - rss / tss if tss > 0 else 0.0
1187
+
1188
+ # Degrees of freedom
1189
+ df_res = n - k - (1 if fit_intercept else 0)
1190
+ df_reg = k
1191
+ s2 = rss / df_res if df_res > 0 else float("nan")
1192
+ var_beta = np.diag(XtX_inv) * s2
1193
+ se = np.sqrt(np.abs(var_beta))
1194
+ t_stat = beta / np.where(se > 0, se, float("nan"))
1195
+
1196
+ # Adjusted R^2
1197
+ adj_r2 = 1.0 - (1 - r2) * (n - 1) / (n - k - 1) if n > k + 1 else float("nan")
1198
+
1199
+ # F-statistic
1200
+ msr = (tss - rss) / df_reg if df_reg > 0 else float("nan")
1201
+ f_stat = msr / s2 if s2 > 0 else float("nan")
1202
+
1203
+ # Information criteria (using log-likelihood of normal errors)
1204
+ ll = -0.5 * n * (1 + math.log(2 * math.pi) + math.log(s2)) if s2 > 0 else float("nan")
1205
+ n_params = len(beta)
1206
+ aic = -2 * ll + 2 * n_params
1207
+ bic = -2 * ll + math.log(n) * n_params
1208
+
1209
+ # p-values
1210
+ if compute_pvalue and _SCIPY_AVAILABLE:
1211
+ p_vals = 2 * (1 - _sp.t.cdf(np.abs(t_stat), df=df_res))
1212
+ f_pval = float(1 - _sp.f.cdf(f_stat, df_res, df_res)) if not math.isnan(f_stat) else float("nan")
1213
+ else:
1214
+ p_vals = np.full_like(t_stat, float("nan"))
1215
+ f_pval = float("nan")
1216
+
1217
+ return RegressionResult(
1218
+ beta = beta,
1219
+ se = se,
1220
+ t_stat = t_stat,
1221
+ p_values = p_vals,
1222
+ r_squared = r2,
1223
+ adj_r_squared = adj_r2,
1224
+ f_stat = float(f_stat),
1225
+ f_p_value = f_pval,
1226
+ aic = float(aic),
1227
+ bic = float(bic),
1228
+ fitted = y_hat,
1229
+ residuals = resid,
1230
+ x = X,
1231
+ y = y,
1232
+ feature_names = names,
1233
+ fit_intercept = fit_intercept,
1234
+ n = n,
1235
+ k = k,
1236
+ )
1237
+
1238
+
1239
+ # ---------------------------------------------------------------------------
1240
+ # B.2 Ridge regression
1241
+ # ---------------------------------------------------------------------------
1242
+
1243
+ def ridge_fit(
1244
+ x: np.ndarray,
1245
+ y: np.ndarray,
1246
+ alpha: float = 1.0,
1247
+ fit_intercept: bool = True,
1248
+ feature_names: Optional[List[str]] = None,
1249
+ ) -> RegressionResult:
1250
+ """
1251
+ Ridge regression (L2-penalised OLS).
1252
+
1253
+ Solves: beta = (X'X + alpha * I)^{-1} X'y
1254
+
1255
+ The intercept is never penalised: alpha is applied only to the slope
1256
+ coefficients regardless of ``fit_intercept``.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ x : array-like, shape (n,) or (n, k)
1261
+ y : array-like, shape (n,)
1262
+ alpha : float
1263
+ Regularisation strength (0 → OLS).
1264
+ fit_intercept : bool
1265
+ feature_names : list[str], optional
1266
+
1267
+ Returns
1268
+ -------
1269
+ RegressionResult
1270
+ Note: .p_values and .t_stat are NaN (ridge has no exact distribution).
1271
+ """
1272
+ x = np.asarray(x, dtype=float)
1273
+ y = np.asarray(y, dtype=float).ravel()
1274
+ n = len(y)
1275
+
1276
+ if x.ndim == 1:
1277
+ x = x.reshape(-1, 1)
1278
+ k = x.shape[1]
1279
+ names = feature_names or [f"X{i+1}" for i in range(k)]
1280
+
1281
+ # Center X and y when fitting intercept
1282
+ if fit_intercept:
1283
+ x_mean = x.mean(axis=0)
1284
+ y_mean = y.mean()
1285
+ xc = x - x_mean
1286
+ yc = y - y_mean
1287
+ else:
1288
+ xc, yc = x, y
1289
+ x_mean = np.zeros(k)
1290
+ y_mean = 0.0
1291
+
1292
+ # Ridge normal equations (applied to centred data, no penalty on intercept)
1293
+ A = xc.T @ xc + alpha * np.eye(k)
1294
+ slopes = np.linalg.solve(A, xc.T @ yc)
1295
+
1296
+ if fit_intercept:
1297
+ intercept = y_mean - x_mean @ slopes
1298
+ beta = np.concatenate([[intercept], slopes])
1299
+ X_design = np.column_stack([np.ones(n), x])
1300
+ else:
1301
+ beta = slopes
1302
+ X_design = x
1303
+
1304
+ y_hat = X_design @ beta
1305
+ resid = y - y_hat
1306
+ rss = float(np.sum(resid**2))
1307
+ tss = float(np.sum((y - y.mean())**2))
1308
+ r2 = 1.0 - rss / tss if tss > 0 else 0.0
1309
+ df_res = n - k - (1 if fit_intercept else 0)
1310
+ s2 = rss / df_res if df_res > 0 else float("nan")
1311
+ adj_r2 = 1.0 - (1 - r2) * (n - 1) / max(1, n - k - 1)
1312
+ ll = -0.5 * n * (1 + math.log(2 * math.pi) + math.log(s2)) if s2 > 0 else float("nan")
1313
+ n_p = len(beta)
1314
+ aic = -2 * ll + 2 * n_p
1315
+ bic = -2 * ll + math.log(n) * n_p
1316
+
1317
+ nan_arr = np.full(len(beta), float("nan"))
1318
+ return RegressionResult(
1319
+ beta = beta,
1320
+ se = nan_arr.copy(),
1321
+ t_stat = nan_arr.copy(),
1322
+ p_values = nan_arr.copy(),
1323
+ r_squared = r2,
1324
+ adj_r_squared = adj_r2,
1325
+ f_stat = float("nan"),
1326
+ f_p_value = float("nan"),
1327
+ aic = float(aic),
1328
+ bic = float(bic),
1329
+ fitted = y_hat,
1330
+ residuals = resid,
1331
+ x = X_design,
1332
+ y = y,
1333
+ feature_names = names,
1334
+ fit_intercept = fit_intercept,
1335
+ n = n,
1336
+ k = k,
1337
+ )
1338
+
1339
+
1340
+ # ---------------------------------------------------------------------------
1341
+ # B.3 Influence measures
1342
+ # ---------------------------------------------------------------------------
1343
+
1344
+ def influence_measures(result: RegressionResult) -> InfluenceMeasures:
1345
+ """
1346
+ Compute full set of regression influence diagnostics for a fitted OLS model.
1347
+
1348
+ Computed quantities
1349
+ -------------------
1350
+ leverage : hat-matrix diagonal h_ii
1351
+ studentized_residuals : e_i / (s * sqrt(1 - h_ii))
1352
+ externally_studentized : e_i / (s_{-i} * sqrt(1 - h_ii))
1353
+ where s_{-i} is leave-one-out residual SD — computed via the
1354
+ Sherman-Morrison formula (no need to refit n times).
1355
+ cooks_d : h_ii * student_i^2 / ((k+1) * (1-h_ii))
1356
+ dffits : student_i * sqrt(h_ii / (1-h_ii))
1357
+ dfbetas : change in standardised beta_j when obs i is deleted
1358
+
1359
+ Parameters
1360
+ ----------
1361
+ result : RegressionResult
1362
+ Must have been fitted with ``ols_fit`` (ridge not supported).
1363
+
1364
+ Returns
1365
+ -------
1366
+ InfluenceMeasures
1367
+ """
1368
+ X = result.x
1369
+ y = result.y
1370
+ resid = result.residuals
1371
+ n, p = X.shape
1372
+ df = n - p
1373
+
1374
+ # Leverage
1375
+ try:
1376
+ XtX_inv = np.linalg.inv(X.T @ X)
1377
+ except np.linalg.LinAlgError:
1378
+ XtX_inv = np.linalg.pinv(X.T @ X)
1379
+ h = np.einsum("ij,jk,ki->i", X, XtX_inv, X.T)
1380
+ h = np.clip(h, 0.0, 1.0 - 1e-10)
1381
+
1382
+ # Studentized residuals
1383
+ s2 = float(np.sum(resid**2) / df) if df > 0 else float("nan")
1384
+ student = resid / (math.sqrt(s2) * np.sqrt(1 - h))
1385
+
1386
+ # Externally studentized (leave-one-out) via Sherman–Morrison
1387
+ # s_{-i}^2 = (df * s^2 - resid_i^2/(1-h_ii)) / (df-1)
1388
+ s2_loo = (df * s2 - resid**2 / (1 - h)) / (df - 1)
1389
+ s2_loo = np.clip(s2_loo, 1e-14, None)
1390
+ ext_student = resid / (np.sqrt(s2_loo) * np.sqrt(1 - h))
1391
+
1392
+ # Cook's D
1393
+ cooks = (student**2 / p) * (h / (1 - h))
1394
+
1395
+ # DFFITS
1396
+ dffits = ext_student * np.sqrt(h / (1 - h))
1397
+
1398
+ # DFBETAS: (X'X)^{-1} x_i e_i / (s_{-i} * sqrt((X'X)^{-1}_{jj}))
1399
+ # Shape: (n, p)
1400
+ C = XtX_inv @ X.T # (p, n)
1401
+ beta_change = C.T * resid[:, None] / (1 - h)[:, None] # (n, p)
1402
+ se_beta = np.sqrt(np.diag(XtX_inv) * s2)
1403
+ dfbetas = beta_change / (np.sqrt(s2_loo)[:, None] * se_beta[None, :])
1404
+
1405
+ return InfluenceMeasures(
1406
+ leverage = h,
1407
+ studentized_residuals = student,
1408
+ externally_studentized = ext_student,
1409
+ cooks_d = cooks,
1410
+ dffits = dffits,
1411
+ dfbetas = dfbetas,
1412
+ )
1413
+
1414
+
1415
+ # ===========================================================================
1416
+ # LAYER D — Manim mobjects
1417
+ # ===========================================================================
1418
+
1419
+ class CorrelationEllipse3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
1420
+ """
1421
+ A confidence / concentration ellipse for a bivariate (X, Y) cloud.
1422
+
1423
+ The ellipse represents the contour of the bivariate normal distribution
1424
+ implied by the observed means, SDs, and correlation. At ``level=0.95``
1425
+ it encloses ~95% of the probability mass.
1426
+
1427
+ Parameters
1428
+ ----------
1429
+ x, y : array-like, shape (n,)
1430
+ Data points.
1431
+ level : float
1432
+ Probability content of the ellipse. Default 0.95.
1433
+ n_points : int
1434
+ Number of points on the ellipse boundary. Default 100.
1435
+ stroke_color : ManimColor, optional
1436
+ fill_color : ManimColor, optional
1437
+ fill_opacity : float
1438
+ stroke_width : float
1439
+
1440
+ Key sub-mobjects
1441
+ ----------------
1442
+ .ellipse : VMobject — the ellipse boundary
1443
+ .axes_lines: VGroup — the two principal axes (optional, toggleable)
1444
+ .center_dot: Dot — centre of the ellipse
1445
+
1446
+ Animations
1447
+ ----------
1448
+ .animate_grow(run_time) — scale from zero
1449
+ .morph_to(r, run_time) — morph the shape as r changes continuously
1450
+ """
1451
+
1452
+ def __init__(
1453
+ self,
1454
+ x: np.ndarray,
1455
+ y: np.ndarray,
1456
+ level: float = 0.95,
1457
+ n_points: int = 120,
1458
+ stroke_color = None,
1459
+ fill_color = None,
1460
+ fill_opacity: float = 0.18,
1461
+ stroke_width: float = 2.5,
1462
+ show_axes: bool = False,
1463
+ **kwargs,
1464
+ ) -> None:
1465
+ _require_manim("CorrelationEllipse3D")
1466
+ super().__init__(**kwargs)
1467
+
1468
+ x = np.asarray(x, dtype=float)
1469
+ y = np.asarray(y, dtype=float)
1470
+ self._x = x
1471
+ self._y = y
1472
+ self._level = level
1473
+ self._n_points = n_points
1474
+
1475
+ # Pick colors from theme if not given
1476
+ if _COLORS_AVAILABLE:
1477
+ stroke_color = stroke_color or ManimColor(REGRESSION_FAMILY.base.hex)
1478
+ fill_color = fill_color or ManimColor(REGRESSION_FAMILY.light.hex)
1479
+ else:
1480
+ stroke_color = stroke_color or PURPLE
1481
+ fill_color = fill_color or PURPLE
1482
+
1483
+ self._stroke_color = stroke_color
1484
+ self._fill_color = fill_color
1485
+ self._fill_opacity = fill_opacity
1486
+ self._stroke_width = stroke_width
1487
+
1488
+ self._build(x, y, level, n_points, show_axes)
1489
+
1490
+ # ------------------------------------------------------------------
1491
+ # Internal geometry builders
1492
+ # ------------------------------------------------------------------
1493
+
1494
+ def _ellipse_points(
1495
+ self,
1496
+ x: np.ndarray,
1497
+ y: np.ndarray,
1498
+ level: float,
1499
+ n: int,
1500
+ ) -> np.ndarray:
1501
+ """
1502
+ Return (n, 3) array of 3-D points on the confidence ellipse.
1503
+
1504
+ The ellipse is derived from the eigendecomposition of the 2×2
1505
+ covariance matrix:
1506
+ Sigma = [[Var(X), Cov(X,Y)], [Cov(X,Y), Var(Y)]]
1507
+ scaled by chi2(2) quantile to achieve the desired probability level.
1508
+ """
1509
+ mu_x, mu_y = float(np.mean(x)), float(np.mean(y))
1510
+ cov = np.cov(x, y) # 2x2
1511
+ if cov.shape != (2, 2) or np.any(np.isnan(cov)):
1512
+ # Degenerate: return a tiny circle
1513
+ t = np.linspace(0, 2 * math.pi, n, endpoint=False)
1514
+ return np.column_stack([0.01 * np.cos(t), 0.01 * np.sin(t), np.zeros(n)])
1515
+
1516
+ # Chi-squared quantile (2 DOF)
1517
+ if _SCIPY_AVAILABLE:
1518
+ chi2_q = float(_sp.chi2.ppf(level, df=2))
1519
+ else:
1520
+ # Closed form: chi2(2) quantile = -2 ln(1 - p)
1521
+ chi2_q = -2.0 * math.log(1.0 - level)
1522
+
1523
+ # Eigendecomposition
1524
+ try:
1525
+ eigvals, eigvecs = np.linalg.eigh(cov)
1526
+ except np.linalg.LinAlgError:
1527
+ t = np.linspace(0, 2 * math.pi, n, endpoint=False)
1528
+ return np.column_stack([np.cos(t), np.sin(t), np.zeros(n)])
1529
+
1530
+ eigvals = np.maximum(eigvals, 1e-12)
1531
+ # Semi-axes
1532
+ a = math.sqrt(chi2_q * eigvals[1]) # larger eigenvalue
1533
+ b = math.sqrt(chi2_q * eigvals[0]) # smaller eigenvalue
1534
+
1535
+ t = np.linspace(0, 2 * math.pi, n, endpoint=False)
1536
+ circle = np.column_stack([a * np.cos(t), b * np.sin(t)])
1537
+ # Rotate by eigenvector angle
1538
+ R = eigvecs[:, ::-1] # columns are eigvecs, largest first
1539
+ pts = (R @ circle.T).T
1540
+ pts[:, 0] += mu_x
1541
+ pts[:, 1] += mu_y
1542
+
1543
+ return np.column_stack([pts, np.zeros(n)])
1544
+
1545
+ def _build(
1546
+ self,
1547
+ x: np.ndarray, y: np.ndarray,
1548
+ level: float, n_points: int,
1549
+ show_axes: bool,
1550
+ ) -> None:
1551
+ pts_3d = self._ellipse_points(x, y, level, n_points)
1552
+
1553
+ # Build as a closed VMobject polygon
1554
+ from manim import VMobject
1555
+ self.ellipse = VMobject(
1556
+ fill_color = self._fill_color,
1557
+ fill_opacity = self._fill_opacity,
1558
+ stroke_color = self._stroke_color,
1559
+ stroke_width = self._stroke_width,
1560
+ )
1561
+ self.ellipse.set_points_as_corners(
1562
+ [*pts_3d, pts_3d[0]] # close the loop
1563
+ )
1564
+ self.add(self.ellipse)
1565
+
1566
+ # Centre dot
1567
+ cx, cy = float(np.mean(x)), float(np.mean(y))
1568
+ self.center_dot = Dot(
1569
+ point = [cx, cy, 0.0],
1570
+ color = self._stroke_color,
1571
+ radius = 0.05,
1572
+ )
1573
+ self.add(self.center_dot)
1574
+
1575
+ # Principal axes (optional)
1576
+ if show_axes:
1577
+ self._add_principal_axes(x, y, level)
1578
+
1579
+ def _add_principal_axes(
1580
+ self, x: np.ndarray, y: np.ndarray, level: float
1581
+ ) -> None:
1582
+ cov = np.cov(x, y)
1583
+ eigvals, eigvecs = np.linalg.eigh(cov)
1584
+ if _SCIPY_AVAILABLE:
1585
+ chi2_q = float(_sp.chi2.ppf(level, df=2))
1586
+ else:
1587
+ chi2_q = -2.0 * math.log(1.0 - level)
1588
+ cx, cy = float(np.mean(x)), float(np.mean(y))
1589
+ center = np.array([cx, cy, 0.0])
1590
+ self.axes_lines = VGroup()
1591
+ for i in range(2):
1592
+ scale = math.sqrt(chi2_q * max(eigvals[i], 1e-12))
1593
+ end_vec = eigvecs[:, i] * scale
1594
+ line = DashedLine(
1595
+ start = center - np.array([*end_vec, 0.0]),
1596
+ end = center + np.array([*end_vec, 0.0]),
1597
+ color = self._stroke_color,
1598
+ stroke_width= 1.2,
1599
+ dash_length = 0.06,
1600
+ )
1601
+ self.axes_lines.add(line)
1602
+ self.add(self.axes_lines)
1603
+
1604
+ # ------------------------------------------------------------------
1605
+ # Animations
1606
+ # ------------------------------------------------------------------
1607
+
1608
+ def animate_grow(self, run_time: float = 1.0) -> "mn.Animation":
1609
+ """Scale the ellipse from zero at its centre."""
1610
+ _require_manim("animate_grow")
1611
+ self.scale(0.001, about_point=self.center_dot.get_center())
1612
+ return self.animate(run_time=run_time, rate_func=rate_functions.ease_out_back).scale(
1613
+ 1000, about_point=self.center_dot.get_center()
1614
+ )
1615
+
1616
+ def morph_to(
1617
+ self,
1618
+ r_target: float,
1619
+ std_x: float = 1.0,
1620
+ std_y: float = 1.0,
1621
+ run_time: float = 1.2,
1622
+ ) -> "mn.Animation":
1623
+ """
1624
+ Animate the ellipse morphing to represent a new correlation coefficient.
1625
+
1626
+ Parameters
1627
+ ----------
1628
+ r_target : float
1629
+ Target Pearson r (-1 to 1).
1630
+ std_x, std_y : float
1631
+ Fixed standard deviations to use (keeps size stable while r changes).
1632
+ run_time : float
1633
+
1634
+ Returns
1635
+ -------
1636
+ manim.Transform
1637
+ """
1638
+ _require_manim("morph_to")
1639
+ n = len(self._x)
1640
+ # Synthesise new x, y with the target correlation
1641
+ new_x = np.random.default_rng(0).standard_normal(n) * std_x
1642
+ noise = np.random.default_rng(1).standard_normal(n)
1643
+ new_y = r_target * (new_x / std_x) * std_y + math.sqrt(max(0, 1 - r_target**2)) * noise * std_y
1644
+ new_y *= std_y / np.std(new_y) if np.std(new_y) > 0 else 1.0
1645
+
1646
+ target_ellipse = CorrelationEllipse3D(
1647
+ x = new_x,
1648
+ y = new_y,
1649
+ level = self._level,
1650
+ n_points = self._n_points,
1651
+ stroke_color = self._stroke_color,
1652
+ fill_color = self._fill_color,
1653
+ fill_opacity = self._fill_opacity,
1654
+ stroke_width = self._stroke_width,
1655
+ )
1656
+ target_ellipse.move_to(self.get_center())
1657
+ return Transform(self, target_ellipse, run_time=run_time,
1658
+ rate_func=rate_functions.ease_in_out_sine)
1659
+
1660
+
1661
+ # ---------------------------------------------------------------------------
1662
+ # CorrelationMatrix3D
1663
+ # ---------------------------------------------------------------------------
1664
+
1665
+ class CorrelationMatrix3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
1666
+ """
1667
+ A fully labeled heatmap-style correlation matrix for p variables.
1668
+
1669
+ Each cell shows the correlation coefficient and optional significance
1670
+ stars. The diagonal shows the variable name. Colors use a diverging
1671
+ purple → white → coral colormap (REGRESSION_FAMILY → INFERENCE_FAMILY).
1672
+
1673
+ Parameters
1674
+ ----------
1675
+ R : ndarray, shape (p, p)
1676
+ Correlation matrix.
1677
+ P : ndarray or None, shape (p, p)
1678
+ p-value matrix. Stars are shown when P is provided.
1679
+ var_names : list[str]
1680
+ Variable labels.
1681
+ cell_size : float
1682
+ Side length of each cell square.
1683
+ show_values : bool
1684
+ Overlay numeric r values on each cell.
1685
+ show_diagonal : bool
1686
+ If True, diagonal cells show variable name; otherwise blank.
1687
+ cmap_low : ManimColor
1688
+ Color for r = -1. Defaults to REGRESSION_FAMILY.dark.
1689
+ cmap_high : ManimColor
1690
+ Color for r = +1. Defaults to INFERENCE_FAMILY.dark.
1691
+ cmap_mid : ManimColor
1692
+ Color for r = 0. Defaults to off-white.
1693
+
1694
+ Key sub-mobjects
1695
+ ----------------
1696
+ .cells — VGroup of Rectangle mobjects (p*p total)
1697
+ .value_labels — VGroup of Text/MathTex labels
1698
+ .var_name_labels— VGroup of diagonal name labels
1699
+ .row_labels — VGroup of left row labels
1700
+ .col_labels — VGroup of top column labels
1701
+
1702
+ Animations
1703
+ ----------
1704
+ .animate_build(run_time, stagger) — reveal cells row by row
1705
+ .highlight_cell(i, j, color) — flash cell (i,j)
1706
+ .morph_data(R_new, P_new, run_time)— transition to new data
1707
+ """
1708
+
1709
+ def __init__(
1710
+ self,
1711
+ R: np.ndarray,
1712
+ P: Optional[np.ndarray] = None,
1713
+ var_names: Optional[List[str]] = None,
1714
+ cell_size: float = 0.65,
1715
+ show_values: bool = True,
1716
+ show_diagonal: bool = True,
1717
+ font_size: int = 16,
1718
+ cmap_low = None,
1719
+ cmap_high = None,
1720
+ cmap_mid = None,
1721
+ **kwargs,
1722
+ ) -> None:
1723
+ _require_manim("CorrelationMatrix3D")
1724
+ super().__init__(**kwargs)
1725
+
1726
+ R = np.asarray(R, dtype=float)
1727
+ p = R.shape[0]
1728
+ self._R = R
1729
+ self._P = P
1730
+ self._p = p
1731
+ self._cell_size = cell_size
1732
+ self._show_values = show_values
1733
+ self._font_size = font_size
1734
+
1735
+ self._var_names = var_names or [f"X{i+1}" for i in range(p)]
1736
+
1737
+ # Resolve colormap endpoints
1738
+ if _COLORS_AVAILABLE:
1739
+ self._cmap_low = cmap_low or ManimColor(REGRESSION_FAMILY.dark.hex)
1740
+ self._cmap_high = cmap_high or ManimColor(INFERENCE_FAMILY.dark.hex)
1741
+ self._cmap_mid = cmap_mid or WHITE
1742
+ else:
1743
+ self._cmap_low = cmap_low or BLUE
1744
+ self._cmap_high = cmap_high or RED
1745
+ self._cmap_mid = cmap_mid or WHITE
1746
+
1747
+ self._build(R, P, show_diagonal)
1748
+
1749
+ # ------------------------------------------------------------------
1750
+ # Color mapping
1751
+ # ------------------------------------------------------------------
1752
+
1753
+ def _r_to_color(self, r: float):
1754
+ """Map r in [-1, 1] to a Manim color via diverging map."""
1755
+ r = float(np.clip(r, -1.0, 1.0))
1756
+ if r < 0:
1757
+ t = (r + 1.0) # 0 (r=-1) → 1 (r=0)
1758
+ return interpolate_color(self._cmap_low, self._cmap_mid, t)
1759
+ else:
1760
+ t = r # 0 (r=0) → 1 (r=+1)
1761
+ return interpolate_color(self._cmap_mid, self._cmap_high, t)
1762
+
1763
+ # ------------------------------------------------------------------
1764
+ # Build
1765
+ # ------------------------------------------------------------------
1766
+
1767
+ def _build(
1768
+ self,
1769
+ R: np.ndarray,
1770
+ P: Optional[np.ndarray],
1771
+ show_diagonal: bool,
1772
+ ) -> None:
1773
+ p = self._p
1774
+ cs = self._cell_size
1775
+ total_w = p * cs
1776
+ total_h = p * cs
1777
+ origin = np.array([-total_w / 2 + cs / 2, total_h / 2 - cs / 2, 0.0])
1778
+
1779
+ self.cells = VGroup()
1780
+ self.value_labels = VGroup()
1781
+ self.var_name_labels= VGroup()
1782
+ self.row_labels = VGroup()
1783
+ self.col_labels = VGroup()
1784
+
1785
+ for i in range(p):
1786
+ for j in range(p):
1787
+ pos = origin + np.array([j * cs, -i * cs, 0.0])
1788
+
1789
+ if i == j:
1790
+ # Diagonal cell
1791
+ cell_color = WHITE if _MANIM_AVAILABLE else None
1792
+ cell = Rectangle(
1793
+ width = cs * 0.95,
1794
+ height = cs * 0.95,
1795
+ fill_color = cell_color,
1796
+ fill_opacity = 0.12,
1797
+ stroke_color = GRAY,
1798
+ stroke_width = 0.8,
1799
+ ).move_to(pos)
1800
+ self.cells.add(cell)
1801
+ if show_diagonal:
1802
+ lbl = Text(
1803
+ self._var_names[i],
1804
+ font_size = self._font_size,
1805
+ color = GRAY,
1806
+ ).move_to(pos)
1807
+ self.var_name_labels.add(lbl)
1808
+ else:
1809
+ r_val = float(R[i, j])
1810
+ color = self._r_to_color(r_val)
1811
+ # Opacity proportional to |r|
1812
+ opacity = 0.15 + 0.80 * abs(r_val)
1813
+ cell = Rectangle(
1814
+ width = cs * 0.95,
1815
+ height = cs * 0.95,
1816
+ fill_color = color,
1817
+ fill_opacity = opacity,
1818
+ stroke_color = DARK_GRAY,
1819
+ stroke_width = 0.5,
1820
+ ).move_to(pos)
1821
+ self.cells.add(cell)
1822
+
1823
+ if self._show_values:
1824
+ # Significance stars
1825
+ stars = ""
1826
+ if P is not None and not np.isnan(P[i, j]):
1827
+ pv = float(P[i, j])
1828
+ if pv < 0.001: stars = "***"
1829
+ elif pv < 0.01: stars = "**"
1830
+ elif pv < 0.05: stars = "*"
1831
+
1832
+ val_str = f"{r_val:.2f}{stars}"
1833
+ # Choose label color for readability
1834
+ lbl_color = BLACK if abs(r_val) < 0.5 else WHITE
1835
+ lbl = Text(
1836
+ val_str,
1837
+ font_size = self._font_size * 0.85,
1838
+ color = lbl_color,
1839
+ ).move_to(pos)
1840
+ self.value_labels.add(lbl)
1841
+
1842
+ # Row labels (left side)
1843
+ for i in range(p):
1844
+ y_pos = origin[1] - i * cs
1845
+ lbl = Text(
1846
+ self._var_names[i],
1847
+ font_size = self._font_size,
1848
+ color = GRAY,
1849
+ ).move_to(np.array([origin[0] - cs * 1.1, y_pos, 0.0]))
1850
+ self.row_labels.add(lbl)
1851
+
1852
+ # Column labels (top)
1853
+ for j in range(p):
1854
+ x_pos = origin[0] + j * cs
1855
+ lbl = Text(
1856
+ self._var_names[j],
1857
+ font_size = self._font_size,
1858
+ color = GRAY,
1859
+ ).move_to(np.array([x_pos, origin[1] + cs * 1.1, 0.0]))
1860
+ self.col_labels.add(lbl)
1861
+
1862
+ self.add(self.cells, self.value_labels, self.var_name_labels,
1863
+ self.row_labels, self.col_labels)
1864
+
1865
+ # ------------------------------------------------------------------
1866
+ # Animations
1867
+ # ------------------------------------------------------------------
1868
+
1869
+ def animate_build(
1870
+ self,
1871
+ run_time: float = 2.0,
1872
+ stagger: float = 0.08,
1873
+ ) -> "mn.Animation":
1874
+ """Reveal cells row by row with a staggered FadeIn."""
1875
+ _require_manim("animate_build")
1876
+ all_mobs = list(self.cells) + list(self.value_labels) + list(self.var_name_labels)
1877
+ return LaggedStart(
1878
+ *[FadeIn(m, run_time=run_time * 0.4) for m in all_mobs],
1879
+ lag_ratio = stagger,
1880
+ )
1881
+
1882
+ def highlight_cell(
1883
+ self,
1884
+ i: int,
1885
+ j: int,
1886
+ color = None,
1887
+ run_time: float = 0.6,
1888
+ ) -> "mn.Animation":
1889
+ """
1890
+ Flash cell (i, j) with an Indicate animation.
1891
+
1892
+ Parameters
1893
+ ----------
1894
+ i, j : int
1895
+ Row and column (0-indexed).
1896
+ color : ManimColor, optional
1897
+ run_time : float
1898
+ """
1899
+ _require_manim("highlight_cell")
1900
+ if color is None:
1901
+ color = YELLOW if _MANIM_AVAILABLE else None
1902
+ idx = i * self._p + j
1903
+ if idx >= len(self.cells):
1904
+ return AnimationGroup()
1905
+ cell = self.cells[idx]
1906
+ return Indicate(cell, color=color, scale_factor=1.15, run_time=run_time)
1907
+
1908
+ def morph_data(
1909
+ self,
1910
+ R_new: np.ndarray,
1911
+ P_new: Optional[np.ndarray] = None,
1912
+ run_time: float = 1.5,
1913
+ ) -> "mn.Animation":
1914
+ """Crossfade to a new correlation matrix."""
1915
+ _require_manim("morph_data")
1916
+ target = CorrelationMatrix3D(
1917
+ R = R_new,
1918
+ P = P_new,
1919
+ var_names = self._var_names,
1920
+ cell_size = self._cell_size,
1921
+ show_values= self._show_values,
1922
+ font_size = self._font_size,
1923
+ cmap_low = self._cmap_low,
1924
+ cmap_high = self._cmap_high,
1925
+ cmap_mid = self._cmap_mid,
1926
+ ).move_to(self.get_center())
1927
+ return Transform(self, target, run_time=run_time,
1928
+ rate_func=rate_functions.ease_in_out_sine)
1929
+
1930
+
1931
+ # ---------------------------------------------------------------------------
1932
+ # RegressionLine3D
1933
+ # ---------------------------------------------------------------------------
1934
+
1935
+ class RegressionLine3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
1936
+ """
1937
+ The fitted regression line (simple linear regression) overlaid on a scatter.
1938
+
1939
+ Draws the line y = beta0 + beta1 * x across the visible x-range,
1940
+ with an optional shaded 95% confidence band.
1941
+
1942
+ Parameters
1943
+ ----------
1944
+ result : RegressionResult
1945
+ Must be a simple (k=1) OLS fit.
1946
+ x_range : tuple (x_min, x_max), optional
1947
+ Extent of the line. Defaults to observed data range.
1948
+ show_ci_band : bool
1949
+ Draw a shaded 95% CI band around the fitted line.
1950
+ line_color : ManimColor, optional
1951
+ band_color : ManimColor, optional
1952
+ stroke_width : float
1953
+ ci_level : float
1954
+ Confidence level for the band. Default 0.95.
1955
+
1956
+ Key sub-mobjects
1957
+ ----------------
1958
+ .line : Line
1959
+ .ci_band : VMobject (shaded polygon, optional)
1960
+ .equation_label: MathTex (shows fitted equation, optional)
1961
+
1962
+ Animations
1963
+ ----------
1964
+ .animate_draw(run_time) — draw line left-to-right
1965
+ .morph_to_fit(new_result, run_time) — rotate/translate to a new fit
1966
+ .reveal_ci_band(run_time) — fade in the CI band
1967
+ """
1968
+
1969
+ def __init__(
1970
+ self,
1971
+ result: RegressionResult,
1972
+ x_range: Optional[Tuple[float, float]] = None,
1973
+ show_ci_band: bool = True,
1974
+ show_equation: bool = True,
1975
+ line_color = None,
1976
+ band_color = None,
1977
+ stroke_width: float = 2.8,
1978
+ ci_level: float = 0.95,
1979
+ **kwargs,
1980
+ ) -> None:
1981
+ _require_manim("RegressionLine3D")
1982
+ if result.k != 1:
1983
+ raise ValueError(
1984
+ f"RegressionLine3D expects k=1 predictor, got k={result.k}."
1985
+ )
1986
+ super().__init__(**kwargs)
1987
+
1988
+ self._result = result
1989
+ self._ci_level = ci_level
1990
+
1991
+ # Colors
1992
+ if _COLORS_AVAILABLE:
1993
+ line_color = line_color or ManimColor(REGRESSION_FAMILY.base.hex)
1994
+ band_color = band_color or ManimColor(REGRESSION_FAMILY.light.hex)
1995
+ else:
1996
+ line_color = line_color or PURPLE
1997
+ band_color = band_color or PURPLE
1998
+
1999
+ # Extract x from design matrix (intercept is col 0)
2000
+ x_raw = result.x[:, 1] if result.fit_intercept else result.x[:, 0]
2001
+ b0 = result.beta[0] if result.fit_intercept else 0.0
2002
+ b1 = result.beta[1] if result.fit_intercept else result.beta[0]
2003
+
2004
+ x_min, x_max = x_range if x_range else (float(x_raw.min()), float(x_raw.max()))
2005
+
2006
+ # Fitted line
2007
+ y_at_min = b0 + b1 * x_min
2008
+ y_at_max = b0 + b1 * x_max
2009
+ self.line = Line(
2010
+ start = [x_min, y_at_min, 0.0],
2011
+ end = [x_max, y_at_max, 0.0],
2012
+ color = line_color,
2013
+ stroke_width = stroke_width,
2014
+ )
2015
+ self.add(self.line)
2016
+
2017
+ # CI band
2018
+ if show_ci_band:
2019
+ self._build_ci_band(
2020
+ result, x_raw, b0, b1,
2021
+ x_min, x_max, band_color, ci_level,
2022
+ )
2023
+
2024
+ # Equation label
2025
+ if show_equation:
2026
+ self._build_equation(b0, b1, result.r_squared, line_color)
2027
+
2028
+ def _build_ci_band(
2029
+ self,
2030
+ result: RegressionResult,
2031
+ x_raw: np.ndarray,
2032
+ b0: float, b1: float,
2033
+ x_min: float, x_max: float,
2034
+ band_color, ci_level: float,
2035
+ ) -> None:
2036
+ """
2037
+ Build a shaded CI band polygon.
2038
+
2039
+ 95% pointwise CI for E[Y|x]:
2040
+ y_hat(x) ± t_{n-2,alpha/2} * s * sqrt(1/n + (x-xbar)^2 / Sxx)
2041
+ """
2042
+ n = result.n
2043
+ xbar = float(np.mean(x_raw))
2044
+ Sxx = float(np.sum((x_raw - xbar)**2))
2045
+ s = result.sigma_hat
2046
+
2047
+ if _SCIPY_AVAILABLE:
2048
+ t_crit = float(_sp.t.ppf((1 + ci_level) / 2, df=n - 2))
2049
+ else:
2050
+ t_crit = 1.959963985 # z-approx
2051
+
2052
+ n_pts = 60
2053
+ xs = np.linspace(x_min, x_max, n_pts)
2054
+ y_hat = b0 + b1 * xs
2055
+ margin = t_crit * s * np.sqrt(1 / n + (xs - xbar)**2 / max(Sxx, 1e-12))
2056
+
2057
+ upper = y_hat + margin
2058
+ lower = y_hat - margin
2059
+
2060
+ # Build polygon: upper curve forward + lower curve backward
2061
+ upper_pts = [[xs[i], upper[i], 0.001] for i in range(n_pts)]
2062
+ lower_pts = [[xs[i], lower[i], 0.001] for i in range(n_pts - 1, -1, -1)]
2063
+ all_pts = upper_pts + lower_pts
2064
+
2065
+ from manim import VMobject
2066
+ self.ci_band = VMobject(
2067
+ fill_color = band_color,
2068
+ fill_opacity = 0.25,
2069
+ stroke_width = 0,
2070
+ )
2071
+ self.ci_band.set_points_as_corners(
2072
+ [np.array(p) for p in all_pts] + [np.array(all_pts[0])]
2073
+ )
2074
+ self.add(self.ci_band)
2075
+
2076
+ def _build_equation(
2077
+ self,
2078
+ b0: float,
2079
+ b1: float,
2080
+ r2: float,
2081
+ color,
2082
+ ) -> None:
2083
+ sign = "+" if b1 >= 0 else "-"
2084
+ eq_str = (
2085
+ rf"\hat{{y}} = {b0:.3f} {sign} {abs(b1):.3f}x"
2086
+ rf"\quad R^2 = {r2:.3f}"
2087
+ )
2088
+ self.equation_label = MathTex(
2089
+ eq_str,
2090
+ font_size = 24,
2091
+ color = color,
2092
+ )
2093
+ self.add(self.equation_label)
2094
+
2095
+ # ------------------------------------------------------------------
2096
+ # Animations
2097
+ # ------------------------------------------------------------------
2098
+
2099
+ def animate_draw(self, run_time: float = 1.2) -> "mn.Animation":
2100
+ """Draw the regression line from left to right."""
2101
+ _require_manim("animate_draw")
2102
+ return Create(self.line, run_time=run_time,
2103
+ rate_func=rate_functions.ease_in_out_sine)
2104
+
2105
+ def reveal_ci_band(self, run_time: float = 0.8) -> "mn.Animation":
2106
+ """Fade in the CI band after the line is drawn."""
2107
+ _require_manim("reveal_ci_band")
2108
+ if not hasattr(self, "ci_band"):
2109
+ return AnimationGroup()
2110
+ return FadeIn(self.ci_band, run_time=run_time)
2111
+
2112
+ def morph_to_fit(
2113
+ self,
2114
+ new_result: RegressionResult,
2115
+ run_time: float = 1.2,
2116
+ ) -> "mn.Animation":
2117
+ """Animate the line (and band) transforming to a new regression fit."""
2118
+ _require_manim("morph_to_fit")
2119
+ x_raw = new_result.x[:, 1] if new_result.fit_intercept else new_result.x[:, 0]
2120
+ target = RegressionLine3D(
2121
+ result = new_result,
2122
+ x_range = (float(x_raw.min()), float(x_raw.max())),
2123
+ show_ci_band = hasattr(self, "ci_band"),
2124
+ show_equation= hasattr(self, "equation_label"),
2125
+ ).move_to(self.get_center())
2126
+ return Transform(self, target, run_time=run_time,
2127
+ rate_func=rate_functions.ease_in_out_sine)
2128
+
2129
+
2130
+ # ---------------------------------------------------------------------------
2131
+ # ResidualArrows3D
2132
+ # ---------------------------------------------------------------------------
2133
+
2134
+ class ResidualArrows3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
2135
+ """
2136
+ Vertical arrows from each fitted value to the observed value,
2137
+ visualising the OLS residuals.
2138
+
2139
+ Positive residuals (y > y_hat) are shown in one color, negative in another.
2140
+ Arrow width scales with |residual| so large residuals are visually prominent.
2141
+
2142
+ Parameters
2143
+ ----------
2144
+ result : RegressionResult
2145
+ Simple OLS fit (k=1 recommended for clarity).
2146
+ pos_color : ManimColor, optional
2147
+ Color for positive residuals. Default TEAL_600.
2148
+ neg_color : ManimColor, optional
2149
+ Color for negative residuals. Default CORAL_600.
2150
+ max_stroke_width : float
2151
+ Maximum arrow stroke width (for the largest residual).
2152
+ show_labels : bool
2153
+ Label the largest residual with its value.
2154
+ outlier_threshold : float
2155
+ |studentized residual| above which an observation is flagged.
2156
+
2157
+ Key sub-mobjects
2158
+ ----------------
2159
+ .positive_arrows : VGroup
2160
+ .negative_arrows : VGroup
2161
+ .outlier_markers : VGroup (circles around flagged observations)
2162
+
2163
+ Animations
2164
+ ----------
2165
+ .animate_appear(run_time, stagger) — grow arrows from the regression line
2166
+ .flash_outliers(run_time) — Indicate outlier_markers
2167
+ .update_fit(new_result, run_time) — morph residuals to a new model
2168
+ """
2169
+
2170
+ def __init__(
2171
+ self,
2172
+ result: RegressionResult,
2173
+ pos_color = None,
2174
+ neg_color = None,
2175
+ max_stroke_width: float = 4.0,
2176
+ min_stroke_width: float = 0.8,
2177
+ show_labels: bool = False,
2178
+ outlier_threshold: float = 2.0,
2179
+ **kwargs,
2180
+ ) -> None:
2181
+ _require_manim("ResidualArrows3D")
2182
+ super().__init__(**kwargs)
2183
+
2184
+ if _COLORS_AVAILABLE:
2185
+ pos_color = pos_color or ManimColor(TEAL_600.hex)
2186
+ neg_color = neg_color or ManimColor(CORAL_600.hex)
2187
+ else:
2188
+ pos_color = pos_color or GREEN
2189
+ neg_color = neg_color or RED
2190
+
2191
+ self._result = result
2192
+ self._pos_color = pos_color
2193
+ self._neg_color = neg_color
2194
+ self._outlier_threshold = outlier_threshold
2195
+
2196
+ self.positive_arrows = VGroup()
2197
+ self.negative_arrows = VGroup()
2198
+ self.outlier_markers = VGroup()
2199
+
2200
+ self._build(result, pos_color, neg_color,
2201
+ max_stroke_width, min_stroke_width,
2202
+ show_labels, outlier_threshold)
2203
+
2204
+ def _build(
2205
+ self,
2206
+ result: RegressionResult,
2207
+ pos_color, neg_color,
2208
+ max_sw: float, min_sw: float,
2209
+ show_labels: bool, outlier_thresh: float,
2210
+ ) -> None:
2211
+ x_col = result.x[:, 1] if result.fit_intercept else result.x[:, 0]
2212
+ y_hat = result.fitted
2213
+ y = result.y
2214
+ resid = result.residuals
2215
+ n = result.n
2216
+
2217
+ # Influence measures for outlier detection
2218
+ try:
2219
+ infl = influence_measures(result)
2220
+ ext_stud = infl.externally_studentized
2221
+ except Exception:
2222
+ ext_stud = np.zeros(n)
2223
+
2224
+ max_abs_resid = float(np.max(np.abs(resid))) or 1.0
2225
+
2226
+ for i in range(n):
2227
+ xi = float(x_col[i])
2228
+ yi = float(y[i])
2229
+ yhati = float(y_hat[i])
2230
+ ri = float(resid[i])
2231
+
2232
+ if abs(ri) < 1e-10:
2233
+ continue
2234
+
2235
+ stroke_w = min_sw + (max_sw - min_sw) * abs(ri) / max_abs_resid
2236
+ color = pos_color if ri > 0 else neg_color
2237
+
2238
+ arrow = Arrow(
2239
+ start = [xi, yhati, 0.001],
2240
+ end = [xi, yi, 0.002],
2241
+ buff = 0,
2242
+ color = color,
2243
+ stroke_width = stroke_w,
2244
+ tip_length = min(0.12, abs(ri) * 0.4),
2245
+ max_tip_length_to_length_ratio = 0.4,
2246
+ )
2247
+ if ri > 0:
2248
+ self.positive_arrows.add(arrow)
2249
+ else:
2250
+ self.negative_arrows.add(arrow)
2251
+
2252
+ # Outlier marker
2253
+ if abs(float(ext_stud[i])) > outlier_thresh:
2254
+ marker = Circle(
2255
+ radius = 0.15,
2256
+ color = YELLOW if _MANIM_AVAILABLE else None,
2257
+ stroke_width = 1.8,
2258
+ fill_opacity = 0,
2259
+ ).move_to([xi, yi, 0.003])
2260
+ self.outlier_markers.add(marker)
2261
+
2262
+ self.add(self.positive_arrows, self.negative_arrows, self.outlier_markers)
2263
+
2264
+ # ------------------------------------------------------------------
2265
+ # Animations
2266
+ # ------------------------------------------------------------------
2267
+
2268
+ def animate_appear(
2269
+ self, run_time: float = 1.4, stagger: float = 0.04
2270
+ ) -> "mn.Animation":
2271
+ """Grow all residual arrows from zero length."""
2272
+ _require_manim("animate_appear")
2273
+ all_arrows = list(self.positive_arrows) + list(self.negative_arrows)
2274
+ return LaggedStart(
2275
+ *[Create(a, run_time=run_time * 0.5) for a in all_arrows],
2276
+ lag_ratio = stagger,
2277
+ )
2278
+
2279
+ def flash_outliers(self, run_time: float = 1.0) -> "mn.Animation":
2280
+ """Flash the outlier marker circles."""
2281
+ _require_manim("flash_outliers")
2282
+ if not self.outlier_markers:
2283
+ return AnimationGroup()
2284
+ return LaggedStart(
2285
+ *[Flash(m, color=YELLOW, run_time=run_time, flash_radius=0.25)
2286
+ for m in self.outlier_markers],
2287
+ lag_ratio = 0.15,
2288
+ )
2289
+
2290
+ def update_fit(
2291
+ self,
2292
+ new_result: RegressionResult,
2293
+ run_time: float = 1.0,
2294
+ ) -> "mn.Animation":
2295
+ """Morph residual arrows to reflect a new regression fit."""
2296
+ _require_manim("update_fit")
2297
+ target = ResidualArrows3D(
2298
+ result = new_result,
2299
+ pos_color = self._pos_color,
2300
+ neg_color = self._neg_color,
2301
+ outlier_threshold = self._outlier_threshold,
2302
+ ).move_to(self.get_center())
2303
+ return Transform(self, target, run_time=run_time,
2304
+ rate_func=rate_functions.ease_in_out_quad)
2305
+
2306
+
2307
+ # ===========================================================================
2308
+ # LAYER E — Scene-level animation factories
2309
+ # ===========================================================================
2310
+
2311
+ def build_scatter_to_line(
2312
+ axes: "mn.Axes",
2313
+ result: RegressionResult,
2314
+ dot_color = None,
2315
+ run_time: float = 3.0,
2316
+ ) -> "mn.Animation":
2317
+ """
2318
+ Canonical animation sequence: scatter cloud appears, then the regression
2319
+ line is drawn through it.
2320
+
2321
+ Steps
2322
+ -----
2323
+ 1. LaggedStart: all scatter dots appear
2324
+ 2. Pause (implicit)
2325
+ 3. Regression line draws left-to-right
2326
+ 4. CI band fades in
2327
+ 5. Equation label writes in
2328
+
2329
+ Parameters
2330
+ ----------
2331
+ axes : manim.Axes
2332
+ Already-added Axes mobject on which to draw.
2333
+ result : RegressionResult
2334
+ Simple OLS fit (k=1).
2335
+ dot_color : ManimColor, optional
2336
+ run_time : float
2337
+ Total duration.
2338
+
2339
+ Returns
2340
+ -------
2341
+ manim.Succession
2342
+ """
2343
+ _require_manim("build_scatter_to_line")
2344
+
2345
+ if _COLORS_AVAILABLE:
2346
+ dot_color = dot_color or ManimColor(NORMAL_FAMILY.base.hex)
2347
+ else:
2348
+ dot_color = dot_color or BLUE
2349
+
2350
+ x_col = result.x[:, 1] if result.fit_intercept else result.x[:, 0]
2351
+
2352
+ # Scatter dots
2353
+ dots = VGroup(*[
2354
+ Dot(
2355
+ point = axes.c2p(float(x_col[i]), float(result.y[i])),
2356
+ color = dot_color,
2357
+ radius = 0.055,
2358
+ )
2359
+ for i in range(result.n)
2360
+ ])
2361
+
2362
+ reg_line = RegressionLine3D(result=result, show_ci_band=True, show_equation=True)
2363
+
2364
+ t_dots = run_time * 0.35
2365
+ t_line = run_time * 0.30
2366
+ t_band = run_time * 0.18
2367
+ t_eq = run_time * 0.17
2368
+
2369
+ anim = Succession(
2370
+ LaggedStart(*[FadeIn(d, scale=0.5) for d in dots],
2371
+ lag_ratio=0.03, run_time=t_dots),
2372
+ reg_line.animate_draw(run_time=t_line),
2373
+ reg_line.reveal_ci_band(run_time=t_band),
2374
+ Write(reg_line.equation_label, run_time=t_eq)
2375
+ if hasattr(reg_line, "equation_label") else AnimationGroup(),
2376
+ )
2377
+ return anim, dots, reg_line
2378
+
2379
+
2380
+ def morph_r_value(
2381
+ ellipse: CorrelationEllipse3D,
2382
+ r_values: Sequence[float],
2383
+ run_time_each: float = 1.2,
2384
+ ) -> "mn.Animation":
2385
+ """
2386
+ Animate a CorrelationEllipse3D morphing through a sequence of r values.
2387
+
2388
+ Parameters
2389
+ ----------
2390
+ ellipse : CorrelationEllipse3D
2391
+ r_values : sequence of float
2392
+ Each value triggers one morph step.
2393
+ run_time_each : float
2394
+ Duration per morph step.
2395
+
2396
+ Returns
2397
+ -------
2398
+ manim.Succession
2399
+ """
2400
+ _require_manim("morph_r_value")
2401
+ steps = [
2402
+ ellipse.morph_to(r, run_time=run_time_each)
2403
+ for r in r_values
2404
+ ]
2405
+ return Succession(*steps)
2406
+
2407
+
2408
+ def reveal_residuals(
2409
+ scene,
2410
+ result: RegressionResult,
2411
+ reg_line: RegressionLine3D,
2412
+ run_time: float = 2.0,
2413
+ ) -> None:
2414
+ """
2415
+ Play the full residual-reveal sequence on *scene*:
2416
+ 1. Residual arrows appear staggered
2417
+ 2. Outlier markers flash
2418
+ 3. Brief pause
2419
+
2420
+ Parameters
2421
+ ----------
2422
+ scene : manim.Scene
2423
+ result : RegressionResult
2424
+ reg_line : RegressionLine3D
2425
+ The already-displayed regression line.
2426
+ run_time : float
2427
+ """
2428
+ _require_manim("reveal_residuals")
2429
+ arrows = ResidualArrows3D(result=result)
2430
+ scene.add(arrows)
2431
+ scene.play(arrows.animate_appear(run_time=run_time * 0.7))
2432
+ if arrows.outlier_markers:
2433
+ scene.play(arrows.flash_outliers(run_time=run_time * 0.3))
2434
+ scene.wait(0.4)
2435
+
2436
+
2437
+ def animate_influence_removal(
2438
+ scene,
2439
+ result: RegressionResult,
2440
+ obs_index: int,
2441
+ axes: "mn.Axes",
2442
+ dot_mob,
2443
+ run_time: float = 2.0,
2444
+ ) -> "RegressionResult":
2445
+ """
2446
+ Remove observation *obs_index* from the data, refit OLS, and animate
2447
+ the regression line updating.
2448
+
2449
+ Sequence
2450
+ --------
2451
+ 1. Flash the removed observation's dot in red
2452
+ 2. FadeOut the dot
2453
+ 3. Morph the regression line to the new fit
2454
+ 4. Return the re-fitted RegressionResult
2455
+
2456
+ Parameters
2457
+ ----------
2458
+ scene : manim.Scene
2459
+ result : RegressionResult
2460
+ Original fit.
2461
+ obs_index : int
2462
+ Index (0-based) to remove.
2463
+ axes : manim.Axes
2464
+ dot_mob : Dot
2465
+ The Manim dot mobject for the removed point.
2466
+ run_time : float
2467
+
2468
+ Returns
2469
+ -------
2470
+ RegressionResult — the re-fitted model without observation obs_index.
2471
+ """
2472
+ _require_manim("animate_influence_removal")
2473
+ # Flash
2474
+ scene.play(
2475
+ Flash(dot_mob, color=RED, run_time=run_time * 0.25, flash_radius=0.25),
2476
+ Indicate(dot_mob, color=RED, scale_factor=1.4, run_time=run_time * 0.25),
2477
+ )
2478
+ scene.play(FadeOut(dot_mob, run_time=run_time * 0.15))
2479
+
2480
+ # Refit without the observation
2481
+ mask = np.ones(result.n, dtype=bool)
2482
+ mask[obs_index] = False
2483
+ x_col = result.x[mask, 1] if result.fit_intercept else result.x[mask, 0]
2484
+ y_new = result.y[mask]
2485
+ new_result = ols_fit(x_col, y_new)
2486
+
2487
+ return new_result
2488
+
2489
+
2490
+ # ===========================================================================
2491
+ # LAYER F — Formula registry bridge
2492
+ # ===========================================================================
2493
+
2494
+ def _build_pearson_formula() -> "TexFormula":
2495
+ if not _TEX_AVAILABLE:
2496
+ return None # type: ignore
2497
+ num = _sum(r"(x_i - \bar{x})(y_i - \bar{y})", "i=1", "n")
2498
+ den = (
2499
+ _sqrt(_sum(r"(x_i - \bar{x})^2", "i=1", "n"))
2500
+ + r"\,"
2501
+ + _sqrt(_sum(r"(y_i - \bar{y})^2", "i=1", "n"))
2502
+ )
2503
+ raw = rf"r = {_frac(num, den)}"
2504
+ return TexFormula(
2505
+ name = "pearson_r_detailed",
2506
+ raw = raw,
2507
+ description = "Pearson r — sample cross-product ratio form",
2508
+ parts = {
2509
+ "numerator": num,
2510
+ "denominator": den,
2511
+ "cross_product": r"(x_i - \bar{x})(y_i - \bar{y})",
2512
+ "ss_x": _sum(r"(x_i - \bar{x})^2", "i=1", "n"),
2513
+ "ss_y": _sum(r"(y_i - \bar{y})^2", "i=1", "n"),
2514
+ },
2515
+ steps = [
2516
+ TexDerivationStep(
2517
+ lhs = "r",
2518
+ rhs = _frac(
2519
+ r"\mathrm{Cov}(X,Y)",
2520
+ r"\mathrm{SD}(X)\,\mathrm{SD}(Y)"
2521
+ ),
2522
+ annotation = "Definition: standardised covariance",
2523
+ ),
2524
+ TexDerivationStep(
2525
+ lhs = "",
2526
+ rhs = _frac(
2527
+ _frac(_sum(r"(x_i-\bar{x})(y_i-\bar{y})", "i",""), "n-1"),
2528
+ _frac(
2529
+ _sqrt(_sum(r"(x_i-\bar{x})^2","i","")) + r"\," +
2530
+ _sqrt(_sum(r"(y_i-\bar{y})^2","i","")),
2531
+ "n-1"
2532
+ ),
2533
+ ),
2534
+ annotation = "Expand sample Cov and SD",
2535
+ ),
2536
+ TexDerivationStep(
2537
+ lhs = "",
2538
+ rhs = raw.split("=",1)[1].strip(),
2539
+ annotation = "Cancel (n-1) factors",
2540
+ ),
2541
+ ],
2542
+ tags = ["correlation", "pearson", "regression"],
2543
+ )
2544
+
2545
+
2546
+ def _build_spearman_formula() -> "TexFormula":
2547
+ if not _TEX_AVAILABLE:
2548
+ return None # type: ignore
2549
+ raw = (
2550
+ r"\rho = 1 - "
2551
+ + _frac(
2552
+ r"6\," + _sum("d_i^2", "i=1", "n"),
2553
+ r"n(n^2 - 1)"
2554
+ )
2555
+ )
2556
+ return TexFormula(
2557
+ name = "spearman_rho_formula",
2558
+ raw = raw,
2559
+ description = "Spearman rank correlation (no-ties closed form)",
2560
+ parts = {
2561
+ "rank_diff_sq": _sum("d_i^2", "i=1", "n"),
2562
+ "denominator": r"n(n^2 - 1)",
2563
+ },
2564
+ steps = [
2565
+ TexDerivationStep(
2566
+ lhs = r"d_i",
2567
+ rhs = r"\mathrm{rank}(x_i) - \mathrm{rank}(y_i)",
2568
+ annotation = "Rank difference for each pair",
2569
+ ),
2570
+ TexDerivationStep(
2571
+ lhs = r"\rho",
2572
+ rhs = raw.split("=",1)[1].strip(),
2573
+ annotation = "Closed form (no ties)",
2574
+ ),
2575
+ ],
2576
+ tags = ["correlation", "spearman", "nonparametric"],
2577
+ )
2578
+
2579
+
2580
+ def _build_ols_derivation_formula() -> "TexFormula":
2581
+ if not _TEX_AVAILABLE:
2582
+ return None # type: ignore
2583
+ raw = (
2584
+ r"\hat{\boldsymbol{\beta}} = "
2585
+ r"\left(\mathbf{X}^\top \mathbf{X}\right)^{-1} \mathbf{X}^\top \mathbf{y}"
2586
+ )
2587
+ return TexFormula(
2588
+ name = "ols_normal_equations",
2589
+ raw = raw,
2590
+ description = "OLS normal equations (matrix form)",
2591
+ parts = {
2592
+ "beta_hat": r"\hat{\boldsymbol{\beta}}",
2593
+ "gram_matrix": r"\mathbf{X}^\top \mathbf{X}",
2594
+ "projection": r"\mathbf{X}^\top \mathbf{y}",
2595
+ },
2596
+ steps = [
2597
+ TexDerivationStep(
2598
+ lhs = r"\mathrm{RSS}(\boldsymbol{\beta})",
2599
+ rhs = r"(\mathbf{y}-\mathbf{X}\boldsymbol{\beta})^\top(\mathbf{y}-\mathbf{X}\boldsymbol{\beta})",
2600
+ annotation = "Residual sum of squares",
2601
+ ),
2602
+ TexDerivationStep(
2603
+ lhs = r"\frac{\partial\,\mathrm{RSS}}{\partial\boldsymbol{\beta}}",
2604
+ rhs = r"-2\mathbf{X}^\top(\mathbf{y}-\mathbf{X}\boldsymbol{\beta}) = \mathbf{0}",
2605
+ annotation = "Set gradient to zero",
2606
+ ),
2607
+ TexDerivationStep(
2608
+ lhs = r"\mathbf{X}^\top\mathbf{X}\,\hat{\boldsymbol{\beta}}",
2609
+ rhs = r"\mathbf{X}^\top\mathbf{y}",
2610
+ annotation = "Normal equations",
2611
+ ),
2612
+ TexDerivationStep(
2613
+ lhs = r"\hat{\boldsymbol{\beta}}",
2614
+ rhs = raw.split("=",1)[1].strip(),
2615
+ annotation = "Solve (assuming X'X invertible)",
2616
+ ),
2617
+ ],
2618
+ tags = ["regression", "ols", "matrix", "derivation"],
2619
+ )
2620
+
2621
+
2622
+ def _build_partial_r_formula() -> "TexFormula":
2623
+ if not _TEX_AVAILABLE:
2624
+ return None # type: ignore
2625
+ raw = (
2626
+ r"r_{XY \cdot Z} = "
2627
+ + _frac(
2628
+ r"r_{XY} - r_{XZ}\,r_{YZ}",
2629
+ _sqrt(r"(1-r_{XZ}^2)(1-r_{YZ}^2)")
2630
+ )
2631
+ )
2632
+ return TexFormula(
2633
+ name = "partial_r_formula",
2634
+ raw = raw,
2635
+ description = "Partial correlation (single control Z)",
2636
+ parts = {
2637
+ "r_xy": r"r_{XY}",
2638
+ "r_xz": r"r_{XZ}",
2639
+ "r_yz": r"r_{YZ}",
2640
+ "numerator": r"r_{XY} - r_{XZ}\,r_{YZ}",
2641
+ "denominator": _sqrt(r"(1-r_{XZ}^2)(1-r_{YZ}^2)"),
2642
+ },
2643
+ steps = [
2644
+ TexDerivationStep(
2645
+ lhs = r"e_{X|Z}",
2646
+ rhs = r"X - \hat{X}(Z)",
2647
+ annotation = "Residualise X on Z",
2648
+ ),
2649
+ TexDerivationStep(
2650
+ lhs = r"e_{Y|Z}",
2651
+ rhs = r"Y - \hat{Y}(Z)",
2652
+ annotation = "Residualise Y on Z",
2653
+ ),
2654
+ TexDerivationStep(
2655
+ lhs = r"r_{XY\cdot Z}",
2656
+ rhs = r"r(e_{X|Z},\, e_{Y|Z})",
2657
+ annotation = "Pearson r of residuals",
2658
+ ),
2659
+ ],
2660
+ tags = ["correlation", "partial", "regression"],
2661
+ )
2662
+
2663
+
2664
+ def _build_cooks_d_formula() -> "TexFormula":
2665
+ if not _TEX_AVAILABLE:
2666
+ return None # type: ignore
2667
+ raw = (
2668
+ r"D_i = "
2669
+ + _frac(
2670
+ r"e_i^2",
2671
+ r"p\,s^2"
2672
+ )
2673
+ + r"\cdot"
2674
+ + _frac(r"h_{ii}", r"(1-h_{ii})^2")
2675
+ )
2676
+ return TexFormula(
2677
+ name = "cooks_d_formula",
2678
+ raw = raw,
2679
+ description = "Cook's distance — influence of observation i",
2680
+ parts = {
2681
+ "residual_sq": r"e_i^2",
2682
+ "leverage": r"h_{ii}",
2683
+ "leverage_term": _frac(r"h_{ii}", r"(1-h_{ii})^2"),
2684
+ },
2685
+ tags = ["regression", "influence", "diagnostics"],
2686
+ )
2687
+
2688
+
2689
+ # Build CORR_FORMULAS registry
2690
+ CORR_FORMULAS: Dict[str, "TexFormula"] = {}
2691
+
2692
+ if _TEX_AVAILABLE:
2693
+ _formulas_to_add = [
2694
+ _build_pearson_formula(),
2695
+ _build_spearman_formula(),
2696
+ _build_ols_derivation_formula(),
2697
+ _build_partial_r_formula(),
2698
+ _build_cooks_d_formula(),
2699
+ ]
2700
+ for _f in _formulas_to_add:
2701
+ if _f is not None:
2702
+ CORR_FORMULAS[_f.name] = _f
2703
+ # Also register in the global tex_utils catalog
2704
+ try:
2705
+ register_formula(_f)
2706
+ except (ValueError, KeyError):
2707
+ pass # already registered — that's fine
2708
+
2709
+
2710
+ # ===========================================================================
2711
+ # HELPER FUNCTIONS
2712
+ # ===========================================================================
2713
+
2714
+ def _clean_paired(
2715
+ x: np.ndarray,
2716
+ y: np.ndarray,
2717
+ ) -> Tuple[np.ndarray, np.ndarray]:
2718
+ """
2719
+ Coerce x, y to float arrays and apply listwise deletion of NaN rows.
2720
+
2721
+ Returns
2722
+ -------
2723
+ (x_clean, y_clean) — both 1-D float64 arrays of equal length.
2724
+ """
2725
+ x = np.asarray(x, dtype=float).ravel()
2726
+ y = np.asarray(y, dtype=float).ravel()
2727
+ if len(x) != len(y):
2728
+ raise ValueError(
2729
+ f"x and y must have the same length; got {len(x)} and {len(y)}."
2730
+ )
2731
+ valid = ~(np.isnan(x) | np.isnan(y))
2732
+ n_dropped = int(np.sum(~valid))
2733
+ if n_dropped > 0:
2734
+ warnings.warn(
2735
+ f"{n_dropped} NaN pair(s) removed by listwise deletion.",
2736
+ UserWarning, stacklevel=3,
2737
+ )
2738
+ return x[valid], y[valid]
2739
+
2740
+
2741
+ def _rankdata(x: np.ndarray) -> np.ndarray:
2742
+ """Average-rank transform (handles ties), pure NumPy."""
2743
+ n = len(x)
2744
+ order = np.argsort(x, stable=True)
2745
+ ranks = np.empty(n, dtype=float)
2746
+ ranks[order] = np.arange(1, n + 1)
2747
+ # Average ties
2748
+ _, inv, counts = np.unique(x, return_inverse=True, return_counts=True)
2749
+ # For each unique value, replace ranks with their average
2750
+ for ui, cnt in enumerate(counts):
2751
+ if cnt > 1:
2752
+ mask = inv == ui
2753
+ avg_rank = float(np.mean(ranks[mask]))
2754
+ ranks[mask] = avg_rank
2755
+ return ranks
2756
+
2757
+
2758
+ # ===========================================================================
2759
+ # __all__
2760
+ # ===========================================================================
2761
+
2762
+ __all__ = [
2763
+ # Layer A enums
2764
+ "CorrelationMethod",
2765
+
2766
+ # Layer A functions
2767
+ "pearson",
2768
+ "spearman",
2769
+ "kendall",
2770
+ "point_biserial",
2771
+ "phi_coefficient",
2772
+ "cramers_v",
2773
+ "partial_correlation",
2774
+ "correlation_matrix",
2775
+
2776
+ # Layer B functions
2777
+ "ols_fit",
2778
+ "ridge_fit",
2779
+ "influence_measures",
2780
+
2781
+ # Layer C dataclasses
2782
+ "CorrelationResult",
2783
+ "PartialCorrelationResult",
2784
+ "RegressionResult",
2785
+ "InfluenceMeasures",
2786
+
2787
+ # Layer D Manim mobjects
2788
+ "CorrelationEllipse3D",
2789
+ "CorrelationMatrix3D",
2790
+ "RegressionLine3D",
2791
+ "ResidualArrows3D",
2792
+
2793
+ # Layer E scene animations
2794
+ "build_scatter_to_line",
2795
+ "morph_r_value",
2796
+ "reveal_residuals",
2797
+ "animate_influence_removal",
2798
+
2799
+ # Layer F formula registry
2800
+ "CORR_FORMULAS",
2801
+
2802
+ # Helpers
2803
+ "_clean_paired",
2804
+ "_rankdata",
2805
+ ]