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,2286 @@
1
+ """
2
+ statanim/regression/regression_plane.py
3
+ ==========================================
4
+ Three-dimensional regression plane visualisation for multiple linear regression
5
+ with two predictors. Extends the 2-D work in ``correlation.py`` into full 3-D.
6
+
7
+ Scope
8
+ -----
9
+ This file covers **everything a statistics educator needs to visualise a
10
+ regression plane**:
11
+
12
+ * The plane itself — a smooth, tilted ``Surface`` coloured by fitted value,
13
+ residual magnitude, or leverage.
14
+ * The scatter cloud — 3-D ``Dot`` objects at (x1, x2, y) with colour maps.
15
+ * Residual lines — vertical sticks from each point down to the plane.
16
+ * Confidence and prediction shells — semi-transparent upper/lower surfaces
17
+ bounding the 95 % CI or PI region.
18
+ * Animated coefficient sliders — morph the plane live as beta changes.
19
+ * Projection arrows — drop perpendiculars from a point to the plane.
20
+ * A complete ``ThreeDAxes`` scaffold with axis labels and tick formatters.
21
+
22
+ Architecture
23
+ ------------
24
+ Layer A Pure-math helpers — plane_predict, plane_grid, ci_surface,
25
+ pi_surface, plane_normal, rotation_angles
26
+ Layer B Geometry dataclasses — PlaneGeometry, SurfaceColorMap
27
+ Layer C Manim mobjects — RegressionPlane3D, ScatterCloud3D,
28
+ PlaneResiduals3D, CIShell3D, PIShell3D,
29
+ ProjectionArrow3D, CoefficientSlider3D
30
+ Layer D Scene-level animations — build_plane_scene, morph_beta,
31
+ sweep_x1, sweep_x2, rotate_view
32
+ Layer E Formula registry bridge — PLANE_FORMULAS with derivation chains
33
+
34
+ Design notes
35
+ ------------
36
+ * Surface resolution is configurable: default 30 × 30 for smooth rendering
37
+ while keeping Manim's vertex count manageable.
38
+
39
+ * All colour work uses ``core.colors`` families so the plane respects whatever
40
+ ``StatsTheme`` the caller sets. The default ``colouring`` is
41
+ ``'fitted'`` (hue = fitted value, sequential REGRESSION palette).
42
+ Alternatives: ``'residual'`` (diverging, teal↔coral),
43
+ ``'leverage'`` (sequential amber), ``'flat'`` (solid colour).
44
+
45
+ * The CI surface is the locus of pointwise 95 % confidence bounds for E[Y|x]:
46
+ y_hat(x) ± t_{n-p,0.025} · s · sqrt(x' (X'X)^{-1} x)
47
+ The PI surface adds the individual prediction variance:
48
+ y_hat(x) ± t_{n-p,0.025} · s · sqrt(1 + x' (X'X)^{-1} x)
49
+
50
+ * ``ThreeDAxes`` is created by ``build_plane_scene()`` — callers get back the
51
+ axes and all mobjects so they can compose their own animations around them.
52
+
53
+ * No hard Manim dependency at import time — all Layers A and B work in a
54
+ plain Python / NumPy environment; Layers C-E raise ``ImportError`` cleanly.
55
+
56
+ * ``RegressionResult`` (from correlation.py) is accepted everywhere a fit is
57
+ required; the module re-exports ``ols_fit`` for convenience so callers only
58
+ need to import from this file.
59
+
60
+ Typical usage
61
+ -------------
62
+ ::
63
+
64
+ from statanim.regression.regression_plane import (
65
+ RegressionPlane3D, ScatterCloud3D, PlaneResiduals3D, build_plane_scene,
66
+ )
67
+ from statanim.regression.correlation import ols_fit
68
+ import numpy as np
69
+
70
+ class MyScene(ThreeDScene):
71
+ def construct(self):
72
+ rng = np.random.default_rng(0)
73
+ x1 = rng.normal(0, 1, 60)
74
+ x2 = rng.normal(0, 1, 60)
75
+ y = 1 + 0.8*x1 - 0.5*x2 + rng.normal(0, 0.4, 60)
76
+
77
+ result = ols_fit(np.column_stack([x1, x2]), y)
78
+
79
+ axes, cloud, plane, residuals = build_plane_scene(
80
+ result, x1, x2, y, self
81
+ )
82
+ self.play(Create(axes))
83
+ self.play(cloud.animate_appear())
84
+ self.play(plane.animate_grow())
85
+ self.play(residuals.animate_appear())
86
+ self.wait(2)
87
+ """
88
+
89
+ from __future__ import annotations
90
+
91
+ import math
92
+ import warnings
93
+ from dataclasses import dataclass, field
94
+ from enum import Enum, auto
95
+ from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
96
+
97
+ import numpy as np
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Optional SciPy
101
+ # ---------------------------------------------------------------------------
102
+ try:
103
+ from scipy import stats as _sp
104
+ _SCIPY_AVAILABLE = True
105
+ except ImportError:
106
+ _SCIPY_AVAILABLE = False
107
+ _sp = None # type: ignore
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Graceful Manim import — full 3-D toolkit
111
+ # ---------------------------------------------------------------------------
112
+ try:
113
+ import manim as mn
114
+ from manim import (
115
+ # Core
116
+ VGroup, VMobject, Mobject,
117
+ # 3-D scene
118
+ ThreeDScene, ThreeDAxes,
119
+ # 3-D surfaces
120
+ Surface,
121
+ # 2-D primitives re-used in 3-D
122
+ Line, Arrow, DashedLine, Dot, Sphere,
123
+ Text, MathTex,
124
+ # Colours
125
+ ManimColor, WHITE, BLACK, GRAY, DARK_GRAY, LIGHT_GRAY,
126
+ RED, BLUE, GREEN, YELLOW, ORANGE, PURPLE,
127
+ DARK_BLUE, PURE_RED,
128
+ # Direction constants
129
+ UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
130
+ TAU, PI,
131
+ # Animations
132
+ Write, Create, FadeIn, FadeOut,
133
+ Transform, ReplacementTransform,
134
+ Rotate, Flash, Indicate,
135
+ AnimationGroup, Succession, LaggedStart,
136
+ rate_functions,
137
+ interpolate_color,
138
+ # Camera
139
+ GrowFromCenter,
140
+ )
141
+ _MANIM_AVAILABLE = True
142
+ except ImportError:
143
+ _MANIM_AVAILABLE = False
144
+ # Stubs so type annotations don't crash
145
+ VGroup = VMobject = Surface = object # type: ignore
146
+ ThreeDAxes = object # type: ignore
147
+
148
+ # ---------------------------------------------------------------------------
149
+ # Project imports
150
+ # ---------------------------------------------------------------------------
151
+ try:
152
+ from statanim.regression.correlation import (
153
+ RegressionResult,
154
+ ols_fit,
155
+ influence_measures,
156
+ InfluenceMeasures,
157
+ )
158
+ _CORR_AVAILABLE = True
159
+ except ImportError:
160
+ _CORR_AVAILABLE = False
161
+ RegressionResult = object # type: ignore
162
+
163
+ try:
164
+ from statanim.core.colors import (
165
+ REGRESSION_FAMILY, NORMAL_FAMILY, INFERENCE_FAMILY,
166
+ DISCRETE_FAMILY, NEUTRAL_FAMILY,
167
+ TEAL_600, TEAL_200, TEAL_800,
168
+ CORAL_600, CORAL_200, CORAL_800,
169
+ PURPLE_600, PURPLE_200, PURPLE_800,
170
+ BLUE_600, BLUE_200,
171
+ AMBER_600, AMBER_200,
172
+ GRAY_400, GRAY_200,
173
+ StatColor, diverging_map, gradient_ramp,
174
+ )
175
+ _COLORS_AVAILABLE = True
176
+ except ImportError:
177
+ _COLORS_AVAILABLE = False
178
+
179
+ try:
180
+ from statanim.core.tex_utils import (
181
+ TexFormula, TexDerivationStep,
182
+ _frac, _sqrt, _sum, _exp,
183
+ FORMULAS, register_formula,
184
+ )
185
+ _TEX_AVAILABLE = True
186
+ except ImportError:
187
+ _TEX_AVAILABLE = False
188
+
189
+
190
+ def _require_manim(name: str) -> None:
191
+ if not _MANIM_AVAILABLE:
192
+ raise ImportError(
193
+ f"{name} requires Manim. Install with: pip install manim"
194
+ )
195
+
196
+
197
+ def _require_corr(name: str) -> None:
198
+ if not _CORR_AVAILABLE:
199
+ raise ImportError(
200
+ f"{name} requires statanim.regression.correlation."
201
+ )
202
+
203
+
204
+ # ===========================================================================
205
+ # LAYER A — Pure-math helpers
206
+ # All functions operate on plain NumPy arrays. No Manim dependency.
207
+ # ===========================================================================
208
+
209
+ def plane_predict(
210
+ beta: np.ndarray,
211
+ x1: Union[float, np.ndarray],
212
+ x2: Union[float, np.ndarray],
213
+ ) -> np.ndarray:
214
+ """
215
+ Evaluate the fitted plane z = b0 + b1*x1 + b2*x2.
216
+
217
+ Parameters
218
+ ----------
219
+ beta : ndarray, shape (3,)
220
+ Coefficients [b0, b1, b2]. If the RegressionResult was fitted with
221
+ ``fit_intercept=True``, pass ``result.beta`` directly.
222
+ x1, x2 : float or ndarray
223
+ Predictor values. Arrays may be any broadcastable shape.
224
+
225
+ Returns
226
+ -------
227
+ ndarray
228
+ Fitted values, same shape as the broadcast of x1 and x2.
229
+ """
230
+ b0, b1, b2 = float(beta[0]), float(beta[1]), float(beta[2])
231
+ return b0 + b1 * np.asarray(x1) + b2 * np.asarray(x2)
232
+
233
+
234
+ def plane_grid(
235
+ beta: np.ndarray,
236
+ x1_range: Tuple[float, float],
237
+ x2_range: Tuple[float, float],
238
+ resolution: int = 30,
239
+ padding: float = 0.15,
240
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
241
+ """
242
+ Build a regular grid of fitted-plane values for surface rendering.
243
+
244
+ Parameters
245
+ ----------
246
+ beta : ndarray, shape (3,)
247
+ Regression coefficients [b0, b1, b2].
248
+ x1_range, x2_range : (float, float)
249
+ Data range for each predictor.
250
+ resolution : int
251
+ Number of grid points per axis. Default 30.
252
+ padding : float
253
+ Fractional padding beyond the data range. Default 0.15 (15 %).
254
+
255
+ Returns
256
+ -------
257
+ (X1, X2, Z) — each ndarray of shape (resolution, resolution).
258
+ X1, X2 are the meshgrid matrices; Z = plane_predict(beta, X1, X2).
259
+ """
260
+ def _padded(lo, hi, p):
261
+ span = max(hi - lo, 1e-6)
262
+ return lo - p * span, hi + p * span
263
+
264
+ u1_lo, u1_hi = _padded(*x1_range, padding)
265
+ u2_lo, u2_hi = _padded(*x2_range, padding)
266
+
267
+ u1 = np.linspace(u1_lo, u1_hi, resolution)
268
+ u2 = np.linspace(u2_lo, u2_hi, resolution)
269
+ X1, X2 = np.meshgrid(u1, u2)
270
+ Z = plane_predict(beta, X1, X2)
271
+ return X1, X2, Z
272
+
273
+
274
+ def ci_surface(
275
+ beta: np.ndarray,
276
+ XtX_inv: np.ndarray,
277
+ s: float,
278
+ n: int,
279
+ x1_range: Tuple[float, float],
280
+ x2_range: Tuple[float, float],
281
+ resolution: int = 25,
282
+ level: float = 0.95,
283
+ padding: float = 0.15,
284
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
285
+ """
286
+ Compute upper and lower pointwise confidence interval surfaces for E[Y|x].
287
+
288
+ Formula (pointwise, for a grid point x0):
289
+ CI = y_hat(x0) ± t_{n-p, alpha/2} · s · sqrt(x0' (X'X)^{-1} x0)
290
+
291
+ Parameters
292
+ ----------
293
+ beta : ndarray (3,)
294
+ Coefficients [b0, b1, b2].
295
+ XtX_inv : ndarray (3, 3)
296
+ Inverse of the design matrix Gram matrix (X'X)^{-1}.
297
+ s : float
298
+ Residual standard deviation (sigma_hat).
299
+ n : int
300
+ Sample size.
301
+ x1_range, x2_range : (float, float)
302
+ resolution : int
303
+ level : float
304
+ Confidence level (default 0.95).
305
+ padding : float
306
+
307
+ Returns
308
+ -------
309
+ (X1, X2, Z_upper, Z_lower)
310
+ Each ndarray of shape (resolution, resolution).
311
+ """
312
+ df = n - 3 # degrees of freedom for two-predictor model
313
+ if _SCIPY_AVAILABLE:
314
+ t_crit = float(_sp.t.ppf((1 + level) / 2, df=max(df, 1)))
315
+ else:
316
+ t_crit = 1.959963985 # fallback to z-crit
317
+
318
+ X1, X2, Z_hat = plane_grid(beta, x1_range, x2_range, resolution, padding)
319
+ margin = np.zeros_like(Z_hat)
320
+
321
+ for i in range(resolution):
322
+ for j in range(resolution):
323
+ x0 = np.array([1.0, X1[i, j], X2[i, j]])
324
+ var_fit = float(x0 @ XtX_inv @ x0)
325
+ margin[i, j] = t_crit * s * math.sqrt(max(var_fit, 0.0))
326
+
327
+ return X1, X2, Z_hat + margin, Z_hat - margin
328
+
329
+
330
+ def pi_surface(
331
+ beta: np.ndarray,
332
+ XtX_inv: np.ndarray,
333
+ s: float,
334
+ n: int,
335
+ x1_range: Tuple[float, float],
336
+ x2_range: Tuple[float, float],
337
+ resolution: int = 25,
338
+ level: float = 0.95,
339
+ padding: float = 0.15,
340
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
341
+ """
342
+ Compute upper and lower pointwise prediction interval surfaces for Y_new.
343
+
344
+ Formula (pointwise, for a grid point x0):
345
+ PI = y_hat(x0) ± t_{n-p, alpha/2} · s · sqrt(1 + x0' (X'X)^{-1} x0)
346
+
347
+ The PI is wider than the CI because it accounts for individual-observation
348
+ variance (the extra ``1`` inside the square root).
349
+
350
+ Parameters are identical to ``ci_surface()``.
351
+
352
+ Returns
353
+ -------
354
+ (X1, X2, Z_upper, Z_lower)
355
+ Each ndarray of shape (resolution, resolution).
356
+ """
357
+ df = n - 3
358
+ if _SCIPY_AVAILABLE:
359
+ t_crit = float(_sp.t.ppf((1 + level) / 2, df=max(df, 1)))
360
+ else:
361
+ t_crit = 1.959963985
362
+
363
+ X1, X2, Z_hat = plane_grid(beta, x1_range, x2_range, resolution, padding)
364
+ margin = np.zeros_like(Z_hat)
365
+
366
+ for i in range(resolution):
367
+ for j in range(resolution):
368
+ x0 = np.array([1.0, X1[i, j], X2[i, j]])
369
+ var_pred = float(1.0 + x0 @ XtX_inv @ x0)
370
+ margin[i, j] = t_crit * s * math.sqrt(max(var_pred, 0.0))
371
+
372
+ return X1, X2, Z_hat + margin, Z_hat - margin
373
+
374
+
375
+ def plane_normal(beta: np.ndarray) -> np.ndarray:
376
+ """
377
+ Return the unit normal vector of the plane z = b0 + b1*x + b2*y.
378
+
379
+ The plane can be written as -b1*x - b2*y + z = b0,
380
+ so the normal is (-b1, -b2, 1) (unnormalised).
381
+
382
+ Parameters
383
+ ----------
384
+ beta : ndarray (3,)
385
+ [b0, b1, b2]
386
+
387
+ Returns
388
+ -------
389
+ ndarray (3,) — unit normal vector.
390
+ """
391
+ b1, b2 = float(beta[1]), float(beta[2])
392
+ n = np.array([-b1, -b2, 1.0])
393
+ return n / np.linalg.norm(n)
394
+
395
+
396
+ def tilt_angle_deg(beta: np.ndarray) -> float:
397
+ """
398
+ Return the tilt angle of the fitted plane from horizontal, in degrees.
399
+
400
+ A plane with b1 = b2 = 0 has tilt = 0. Steeper slopes give larger angles.
401
+ """
402
+ n = plane_normal(beta)
403
+ horiz = np.array([0.0, 0.0, 1.0])
404
+ cos_a = abs(float(np.dot(n, horiz)))
405
+ return math.degrees(math.acos(min(cos_a, 1.0)))
406
+
407
+
408
+ def leverage_grid(
409
+ XtX_inv: np.ndarray,
410
+ x1_range: Tuple[float, float],
411
+ x2_range: Tuple[float, float],
412
+ resolution: int = 30,
413
+ padding: float = 0.15,
414
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
415
+ """
416
+ Compute leverage (x0' (X'X)^{-1} x0) on a grid — used to colour the
417
+ regression plane by leverage when ``colouring='leverage'``.
418
+
419
+ Returns
420
+ -------
421
+ (X1, X2, H) where H[i,j] is the leverage at grid point (X1[i,j], X2[i,j]).
422
+ """
423
+ def _padded(lo, hi, p):
424
+ span = max(hi - lo, 1e-6)
425
+ return lo - p * span, hi + p * span
426
+
427
+ u1 = np.linspace(*_padded(*x1_range, padding), resolution)
428
+ u2 = np.linspace(*_padded(*x2_range, padding), resolution)
429
+ X1, X2 = np.meshgrid(u1, u2)
430
+ H = np.zeros((resolution, resolution))
431
+ for i in range(resolution):
432
+ for j in range(resolution):
433
+ x0 = np.array([1.0, X1[i, j], X2[i, j]])
434
+ H[i, j] = float(x0 @ XtX_inv @ x0)
435
+ return X1, X2, H
436
+
437
+
438
+ def standardise_grid(Z: np.ndarray) -> np.ndarray:
439
+ """
440
+ Map Z values to [0, 1] for use as colormap parameter t.
441
+ Handles degenerate (constant) grids by returning 0.5 everywhere.
442
+ """
443
+ lo, hi = float(Z.min()), float(Z.max())
444
+ if hi - lo < 1e-10:
445
+ return np.full_like(Z, 0.5)
446
+ return (Z - lo) / (hi - lo)
447
+
448
+
449
+ # ===========================================================================
450
+ # LAYER B — Geometry and colouring configuration dataclasses
451
+ # ===========================================================================
452
+
453
+ class SurfaceColouring(Enum):
454
+ """
455
+ Colour strategy for the regression plane surface.
456
+
457
+ FITTED
458
+ Sequential hue proportional to the fitted value z_hat.
459
+ Uses REGRESSION_FAMILY gradient (light → dark purple).
460
+
461
+ RESIDUAL
462
+ Diverging hue: coral for over-prediction, teal for under-prediction.
463
+ Colour is applied to each *data point* and residual line;
464
+ the plane itself is shown in a neutral flat colour.
465
+
466
+ LEVERAGE
467
+ Sequential amber hue proportional to x0'(X'X)^{-1}x0 at each grid point.
468
+ Highlights corners (high-leverage regions) in dark amber.
469
+
470
+ FLAT
471
+ Solid single colour (REGRESSION_FAMILY.base), maximum readability.
472
+ """
473
+ FITTED = "fitted"
474
+ RESIDUAL = "residual"
475
+ LEVERAGE = "leverage"
476
+ FLAT = "flat"
477
+
478
+
479
+ @dataclass
480
+ class PlaneGeometry:
481
+ """
482
+ Physical dimensions and sampling parameters for a 3-D regression plane.
483
+
484
+ All lengths are in Manim world-units. A ThreeDAxes with default
485
+ ``x_length=6, y_length=6, z_length=5`` fits well on a standard
486
+ 1920×1080 scene frame.
487
+
488
+ Attributes
489
+ ----------
490
+ x1_length, x2_length, z_length : float
491
+ Lengths of the three axes in world-units.
492
+ resolution : int
493
+ Number of grid vertices per axis on the regression surface.
494
+ Default 30 balances smoothness with Manim vertex budget.
495
+ ci_resolution : int
496
+ Resolution for CI / PI shells (can be coarser — default 20).
497
+ dot_radius : float
498
+ Radius of each scatter-cloud data point sphere.
499
+ residual_stroke_width : float
500
+ Stroke width of residual lines.
501
+ axis_label_font_size : int
502
+ Font size for x1, x2, y axis labels.
503
+ ci_opacity, pi_opacity : float
504
+ Fill opacity of the CI and PI shells.
505
+ plane_opacity : float
506
+ Fill opacity of the regression plane surface.
507
+ """
508
+ x1_length: float = 6.0
509
+ x2_length: float = 6.0
510
+ z_length: float = 5.0
511
+ resolution: int = 30
512
+ ci_resolution: int = 20
513
+ dot_radius: float = 0.055
514
+ residual_stroke_width: float = 1.8
515
+ axis_label_font_size: int = 24
516
+ ci_opacity: float = 0.22
517
+ pi_opacity: float = 0.12
518
+ plane_opacity: float = 0.72
519
+
520
+ @property
521
+ def axes_kwargs(self) -> dict:
522
+ """
523
+ Ready-to-unpack kwargs for ``manim.ThreeDAxes``.
524
+
525
+ Includes axis lengths, range auto-scaled later by ``build_plane_scene``.
526
+ """
527
+ return {
528
+ "x_length": self.x1_length,
529
+ "y_length": self.x2_length,
530
+ "z_length": self.z_length,
531
+ "axis_config": {
532
+ "include_tip": True,
533
+ "tip_width": 0.12,
534
+ "tip_height": 0.12,
535
+ "stroke_width": 2.0,
536
+ "include_numbers": False,
537
+ },
538
+ }
539
+
540
+
541
+ #: Sensible defaults for a standard scene
542
+ DEFAULT_GEOMETRY = PlaneGeometry()
543
+
544
+ #: Smaller geometry preset for inset / thumbnail panels
545
+ COMPACT_GEOMETRY = PlaneGeometry(
546
+ x1_length=4.0, x2_length=4.0, z_length=3.5,
547
+ resolution=22, ci_resolution=14,
548
+ dot_radius=0.045,
549
+ axis_label_font_size=18,
550
+ )
551
+
552
+ #: High-resolution preset for close-up detail scenes
553
+ HIRES_GEOMETRY = PlaneGeometry(
554
+ x1_length=7.0, x2_length=7.0, z_length=6.0,
555
+ resolution=45, ci_resolution=30,
556
+ dot_radius=0.065,
557
+ )
558
+
559
+
560
+ # ===========================================================================
561
+ # LAYER C — Manim mobjects
562
+ # ===========================================================================
563
+
564
+ class RegressionPlane3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
565
+ """
566
+ The fitted regression plane for y = b0 + b1*x1 + b2*x2 as a Manim
567
+ ``Surface`` wrapped in a ``VGroup`` with axis helpers.
568
+
569
+ The plane surface is built from Manim's ``Surface`` class with a
570
+ parametric function f(u, v) = [u, v, b0 + b1*u + b2*v].
571
+
572
+ Colour strategies (``colouring`` parameter)
573
+ -------------------------------------------
574
+ ``'fitted'`` Sequential gradient along z_hat (purple light → dark).
575
+ ``'leverage'`` Sequential gradient along h(x0) (amber).
576
+ ``'flat'`` Solid single colour.
577
+
578
+ Parameters
579
+ ----------
580
+ result : RegressionResult
581
+ A two-predictor OLS fit (k=2). ``result.beta`` must have 3 elements
582
+ (intercept + 2 slopes).
583
+ x1_range, x2_range : (float, float)
584
+ Data ranges for each predictor (used to set the surface extent).
585
+ geometry : PlaneGeometry
586
+ colouring : SurfaceColouring or str
587
+ plane_color : ManimColor, optional
588
+ Override the base colour (used for ``FLAT`` or as the gradient anchor).
589
+ opacity : float
590
+ Surface fill opacity.
591
+ show_grid_lines : bool
592
+ Whether to render the surface with wireframe grid lines.
593
+ grid_stroke_width : float
594
+ Width of wireframe lines (if ``show_grid_lines=True``).
595
+ axes : ThreeDAxes, optional
596
+ If provided, the plane is scaled to this axes object's coordinate system.
597
+
598
+ Key sub-mobjects
599
+ ----------------
600
+ .surface : Surface — the parametric plane
601
+ .equation_label: MathTex — fitted equation displayed near the plane
602
+ .axes_ref : ThreeDAxes or None
603
+
604
+ Animations
605
+ ----------
606
+ .animate_grow(run_time) — scale plane from zero at centroid
607
+ .animate_tilt(target_beta, run_time)— morph plane to new coefficients
608
+ .flash_plane(color, run_time) — Indicate the entire surface
609
+ .update_coefficients(beta, run_time)— morph plane + equation to new beta
610
+ """
611
+
612
+ def __init__(
613
+ self,
614
+ result: "RegressionResult",
615
+ x1_range: Tuple[float, float],
616
+ x2_range: Tuple[float, float],
617
+ geometry: PlaneGeometry = DEFAULT_GEOMETRY,
618
+ colouring: Union[SurfaceColouring, str] = SurfaceColouring.FITTED,
619
+ plane_color = None,
620
+ opacity: float = None,
621
+ show_grid_lines: bool = True,
622
+ grid_stroke_width: float = 0.4,
623
+ axes: Optional["ThreeDAxes"] = None,
624
+ show_equation: bool = True,
625
+ **kwargs,
626
+ ) -> None:
627
+ _require_manim("RegressionPlane3D.__init__")
628
+ _require_corr("RegressionPlane3D.__init__")
629
+
630
+ if result.k != 2:
631
+ raise ValueError(
632
+ f"RegressionPlane3D requires a 2-predictor fit (k=2), "
633
+ f"got k={result.k}. Use RegressionLine3D for k=1."
634
+ )
635
+
636
+ super().__init__(**kwargs)
637
+
638
+ self._result = result
639
+ self._x1_range = x1_range
640
+ self._x2_range = x2_range
641
+ self._geometry = geometry
642
+ self._axes_ref = axes
643
+
644
+ beta = result.beta # [b0, b1, b2]
645
+ self._beta = beta.copy()
646
+
647
+ if isinstance(colouring, str):
648
+ colouring = SurfaceColouring(colouring)
649
+ self._colouring = colouring
650
+
651
+ opacity = opacity if opacity is not None else geometry.plane_opacity
652
+
653
+ # Resolve colours
654
+ if _COLORS_AVAILABLE:
655
+ self._plane_color = plane_color or ManimColor(REGRESSION_FAMILY.base.hex)
656
+ self._light_color = ManimColor(REGRESSION_FAMILY.light.hex)
657
+ self._dark_color = ManimColor(REGRESSION_FAMILY.dark.hex)
658
+ self._amber_color = ManimColor(AMBER_600.hex)
659
+ self._amber_light = ManimColor(AMBER_200.hex)
660
+ else:
661
+ self._plane_color = plane_color or PURPLE
662
+ self._light_color = BLUE
663
+ self._dark_color = DARK_BLUE
664
+ self._amber_color = ORANGE
665
+ self._amber_light = YELLOW
666
+
667
+ self._opacity = opacity
668
+ self._show_grid_lines = show_grid_lines
669
+ self._grid_sw = grid_stroke_width
670
+ self._resolution = geometry.resolution
671
+
672
+ # Pre-compute colouring grids
673
+ self._X1, self._X2, self._Z = plane_grid(
674
+ beta, x1_range, x2_range, geometry.resolution
675
+ )
676
+ if colouring == SurfaceColouring.LEVERAGE:
677
+ try:
678
+ X_design = result.x
679
+ XtX_inv = np.linalg.inv(X_design.T @ X_design)
680
+ _, _, self._H_grid = leverage_grid(
681
+ XtX_inv, x1_range, x2_range, geometry.resolution
682
+ )
683
+ except (np.linalg.LinAlgError, AttributeError):
684
+ self._H_grid = None
685
+ else:
686
+ self._H_grid = None
687
+
688
+ # Build surface
689
+ self._build_surface(beta, x1_range, x2_range, axes)
690
+
691
+ # Equation label
692
+ if show_equation:
693
+ self._build_equation_label(beta)
694
+
695
+ # ------------------------------------------------------------------
696
+ # Internal builders
697
+ # ------------------------------------------------------------------
698
+
699
+ def _build_surface(
700
+ self,
701
+ beta: np.ndarray,
702
+ x1_range: Tuple[float, float],
703
+ x2_range: Tuple[float, float],
704
+ axes: Optional["ThreeDAxes"],
705
+ ) -> None:
706
+ """
707
+ Construct the Manim ``Surface`` parametric object.
708
+
709
+ The Surface's parametric function maps (u, v) in the data coordinate
710
+ ranges to 3-D world coordinates. When ``axes`` is provided, we use
711
+ ``axes.c2p`` to map data → scene coordinates; otherwise we map
712
+ data → world-units directly (caller must position the axes themselves).
713
+ """
714
+ b0, b1, b2 = float(beta[0]), float(beta[1]), float(beta[2])
715
+
716
+ # Build padded data ranges for the surface extent
717
+ def _pad(lo, hi, p=0.15):
718
+ span = max(hi - lo, 1e-6)
719
+ return lo - p * span, hi + p * span
720
+
721
+ u_lo, u_hi = _pad(*x1_range)
722
+ v_lo, v_hi = _pad(*x2_range)
723
+
724
+ # Pre-compute Z range for colour mapping
725
+ z_corners = [b0 + b1*u + b2*v
726
+ for u in (u_lo, u_hi) for v in (v_lo, v_hi)]
727
+ z_lo, z_hi = min(z_corners), max(z_corners)
728
+ z_span = max(z_hi - z_lo, 1e-6)
729
+
730
+ # Pre-compute H range for leverage colouring
731
+ if self._H_grid is not None:
732
+ h_lo = float(self._H_grid.min())
733
+ h_span = max(float(self._H_grid.max()) - h_lo, 1e-6)
734
+ else:
735
+ h_lo = h_span = 1.0
736
+
737
+ colouring = self._colouring
738
+ light_color = self._light_color
739
+ dark_color = self._dark_color
740
+ amber_color = self._amber_color
741
+ amber_light = self._amber_light
742
+ plane_color = self._plane_color
743
+ H_grid = self._H_grid
744
+ res = self._resolution
745
+
746
+ if axes is not None:
747
+ def _func(u: float, v: float) -> np.ndarray:
748
+ z = b0 + b1 * u + b2 * v
749
+ return axes.c2p(u, v, z)
750
+ else:
751
+ # Direct world-space mapping (u, v) → (u, v, z) unchanged
752
+ def _func(u: float, v: float) -> np.ndarray:
753
+ z = b0 + b1 * u + b2 * v
754
+ return np.array([u, v, z])
755
+
756
+ def _color_func(u: float, v: float) -> "ManimColor":
757
+ """
758
+ Determine the colour of the surface at parameter (u, v).
759
+
760
+ For FITTED: t = (z - z_lo) / z_span → interpolate light→dark
761
+ For LEVERAGE: t = (h - h_lo) / h_span → interpolate amber_light→amber
762
+ For FLAT: constant plane_color
763
+ """
764
+ if colouring == SurfaceColouring.FITTED:
765
+ z = b0 + b1 * u + b2 * v
766
+ t = max(0.0, min(1.0, (z - z_lo) / z_span))
767
+ return interpolate_color(light_color, dark_color, t)
768
+
769
+ elif colouring == SurfaceColouring.LEVERAGE:
770
+ if H_grid is not None:
771
+ # Nearest-grid-point lookup (simple, no interp)
772
+ ui = int((u - u_lo) / (u_hi - u_lo) * (res - 1) + 0.5)
773
+ vi = int((v - v_lo) / (v_hi - v_lo) * (res - 1) + 0.5)
774
+ ui = max(0, min(res - 1, ui))
775
+ vi = max(0, min(res - 1, vi))
776
+ h = float(H_grid[vi, ui])
777
+ t = max(0.0, min(1.0, (h - h_lo) / h_span))
778
+ return interpolate_color(amber_light, amber_color, t)
779
+ return plane_color
780
+
781
+ else: # FLAT
782
+ return plane_color
783
+
784
+ self.surface = Surface(
785
+ func = _func,
786
+ u_range = [u_lo, u_hi],
787
+ v_range = [v_lo, v_hi],
788
+ resolution = (self._resolution, self._resolution),
789
+ fill_opacity = self._opacity,
790
+ checkerboard_colors = None,
791
+ )
792
+ self.surface.set_fill_by_value(
793
+ axes = axes,
794
+ colors = [
795
+ (self._light_color, float(z_lo)),
796
+ (self._dark_color, float(z_hi)),
797
+ ],
798
+ ) if colouring == SurfaceColouring.FITTED and axes is not None else None
799
+
800
+ if self._show_grid_lines:
801
+ self.surface.set_stroke(
802
+ color = self._dark_color,
803
+ width = self._grid_sw,
804
+ opacity = 0.35,
805
+ )
806
+ else:
807
+ self.surface.set_stroke(width=0)
808
+
809
+ self.add(self.surface)
810
+
811
+ def _build_equation_label(self, beta: np.ndarray) -> None:
812
+ """Build a MathTex label showing the fitted equation."""
813
+ b0, b1, b2 = float(beta[0]), float(beta[1]), float(beta[2])
814
+
815
+ def _signed(val: float, var: str, first: bool = False) -> str:
816
+ if first:
817
+ return rf"{val:.3f}"
818
+ sign = "+" if val >= 0 else "-"
819
+ return rf"{sign} {abs(val):.3f}\,{var}"
820
+
821
+ eq = (
822
+ rf"\hat{{y}} = {_signed(b0,'',True)}"
823
+ rf"\;{_signed(b1, 'x_1')}"
824
+ rf"\;{_signed(b2, 'x_2')}"
825
+ rf"\quad R^2\!=\!{self._result.r_squared:.3f}"
826
+ )
827
+ self.equation_label = MathTex(
828
+ eq,
829
+ font_size = 26,
830
+ color = self._plane_color,
831
+ )
832
+ self.add(self.equation_label)
833
+
834
+ # ------------------------------------------------------------------
835
+ # Public properties
836
+ # ------------------------------------------------------------------
837
+
838
+ @property
839
+ def beta(self) -> np.ndarray:
840
+ return self._beta.copy()
841
+
842
+ @property
843
+ def r_squared(self) -> float:
844
+ return self._result.r_squared
845
+
846
+ @property
847
+ def tilt_degrees(self) -> float:
848
+ return tilt_angle_deg(self._beta)
849
+
850
+ # ------------------------------------------------------------------
851
+ # Animations
852
+ # ------------------------------------------------------------------
853
+
854
+ def animate_grow(self, run_time: float = 1.4) -> "mn.Animation":
855
+ """
856
+ Grow the plane from zero scale at its geometric centroid.
857
+
858
+ Implementation: scale to 0.001, then animate back to 1.0 with
859
+ ease_out_back so it slightly overshoots and settles.
860
+ """
861
+ _require_manim("animate_grow")
862
+ centre = self.surface.get_center()
863
+ self.surface.scale(0.001, about_point=centre)
864
+ return self.surface.animate(
865
+ run_time = run_time,
866
+ rate_func = rate_functions.ease_out_back,
867
+ ).scale(1000, about_point=centre)
868
+
869
+ def animate_tilt(
870
+ self,
871
+ target_beta: np.ndarray,
872
+ run_time: float = 1.5,
873
+ ) -> "mn.Animation":
874
+ """
875
+ Animate the plane tilting from its current orientation to the one
876
+ implied by ``target_beta``.
877
+
878
+ This is implemented as a ``Transform`` to a freshly constructed
879
+ ``RegressionPlane3D`` with the target coefficients. The equation
880
+ label morphs simultaneously.
881
+
882
+ Parameters
883
+ ----------
884
+ target_beta : ndarray (3,)
885
+ New [b0, b1, b2] coefficients.
886
+ run_time : float
887
+
888
+ Returns
889
+ -------
890
+ manim.Transform
891
+ """
892
+ _require_manim("animate_tilt")
893
+
894
+ # Build a temporary result-like object so we can re-use the constructor
895
+ class _FakeResult:
896
+ def __init__(self, result, beta):
897
+ self.beta = np.asarray(beta, dtype=float)
898
+ self.k = result.k
899
+ self.x = result.x
900
+ self.r_squared = result.r_squared
901
+ self.fit_intercept = result.fit_intercept
902
+
903
+ fake = _FakeResult(self._result, target_beta)
904
+ target_plane = RegressionPlane3D(
905
+ result = fake,
906
+ x1_range = self._x1_range,
907
+ x2_range = self._x2_range,
908
+ geometry = self._geometry,
909
+ colouring = self._colouring,
910
+ opacity = self._opacity,
911
+ show_equation = hasattr(self, "equation_label"),
912
+ axes = self._axes_ref,
913
+ ).move_to(self.get_center())
914
+
915
+ return Transform(
916
+ self, target_plane,
917
+ run_time = run_time,
918
+ rate_func = rate_functions.ease_in_out_sine,
919
+ )
920
+
921
+ def flash_plane(
922
+ self,
923
+ color = None,
924
+ run_time: float = 0.7,
925
+ ) -> "mn.Animation":
926
+ """Flash the entire plane surface with Indicate."""
927
+ _require_manim("flash_plane")
928
+ color = color or (self._plane_color if _COLORS_AVAILABLE else YELLOW)
929
+ return Indicate(
930
+ self.surface,
931
+ color = color,
932
+ scale_factor = 1.04,
933
+ run_time = run_time,
934
+ )
935
+
936
+ def update_coefficients(
937
+ self,
938
+ new_beta: np.ndarray,
939
+ run_time: float = 1.2,
940
+ ) -> "mn.Animation":
941
+ """
942
+ Morph both the plane and its equation label to reflect ``new_beta``.
943
+
944
+ Returns a combined ``AnimationGroup``.
945
+ """
946
+ _require_manim("update_coefficients")
947
+ return AnimationGroup(
948
+ self.animate_tilt(new_beta, run_time=run_time),
949
+ )
950
+
951
+ def __repr__(self) -> str:
952
+ b = self._beta
953
+ return (
954
+ f"RegressionPlane3D("
955
+ f"y = {b[0]:.3f} + {b[1]:.3f}x1 + {b[2]:.3f}x2, "
956
+ f"tilt={self.tilt_degrees:.1f}°, "
957
+ f"R²={self.r_squared:.3f})"
958
+ )
959
+
960
+
961
+ # ---------------------------------------------------------------------------
962
+ # ScatterCloud3D
963
+ # ---------------------------------------------------------------------------
964
+
965
+ class ScatterCloud3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
966
+ """
967
+ A 3-D scatter cloud of data points for a two-predictor regression scene.
968
+
969
+ Each observation is rendered as a coloured ``Sphere`` (or ``Dot`` in 2-D
970
+ fallback mode) at position (x1_i, x2_i, y_i).
971
+
972
+ Colour strategies (``colouring`` parameter)
973
+ -------------------------------------------
974
+ ``'residual'``
975
+ Diverging teal ↔ coral based on the sign and magnitude of the residual.
976
+ Matches ``PlaneResiduals3D`` colour convention so colours are consistent.
977
+ ``'leverage'``
978
+ Sequential amber, brighter = higher leverage.
979
+ ``'cooks_d'``
980
+ Sequential coral; large Cook's D = bright coral.
981
+ ``'flat'``
982
+ Uniform NORMAL_FAMILY.base colour.
983
+
984
+ Parameters
985
+ ----------
986
+ x1, x2, y : array-like (n,)
987
+ Observation coordinates.
988
+ result : RegressionResult
989
+ Used to extract residuals, leverage, Cook's D.
990
+ colouring : str or SurfaceColouring
991
+ dot_radius : float
992
+ axes : ThreeDAxes, optional
993
+ highlight_indices : list[int], optional
994
+ Observation indices to mark with a larger dot and bright ring.
995
+
996
+ Key sub-mobjects
997
+ ----------------
998
+ .dots : VGroup of Sphere / Dot objects, indexed like the data.
999
+ .highlight_rings: VGroup of Circle rings around flagged points.
1000
+
1001
+ Animations
1002
+ ----------
1003
+ .animate_appear(run_time, stagger) — LaggedStart FadeIn
1004
+ .highlight_obs(idx, color, run_time) — Indicate + scale up one dot
1005
+ .dim_all_except(indices, run_time) — fade non-selected dots
1006
+ .undim_all(run_time) — restore full opacity
1007
+ """
1008
+
1009
+ def __init__(
1010
+ self,
1011
+ x1: np.ndarray,
1012
+ x2: np.ndarray,
1013
+ y: np.ndarray,
1014
+ result: "RegressionResult",
1015
+ colouring: str = "residual",
1016
+ dot_radius: float = None,
1017
+ geometry: PlaneGeometry = DEFAULT_GEOMETRY,
1018
+ axes: Optional["ThreeDAxes"] = None,
1019
+ highlight_indices: Optional[List[int]] = None,
1020
+ **kwargs,
1021
+ ) -> None:
1022
+ _require_manim("ScatterCloud3D.__init__")
1023
+ _require_corr("ScatterCloud3D.__init__")
1024
+ super().__init__(**kwargs)
1025
+
1026
+ self._x1 = np.asarray(x1, dtype=float)
1027
+ self._x2 = np.asarray(x2, dtype=float)
1028
+ self._y = np.asarray(y, dtype=float)
1029
+ self._result = result
1030
+ self._axes = axes
1031
+ self._radius = dot_radius or geometry.dot_radius
1032
+
1033
+ resid = result.residuals
1034
+
1035
+ # Compute per-point colour
1036
+ colors = self._compute_colors(colouring, resid, result)
1037
+
1038
+ # Build dots
1039
+ self.dots = VGroup()
1040
+ n = len(x1)
1041
+ for i in range(n):
1042
+ pt = self._data_to_world(float(self._x1[i]),
1043
+ float(self._x2[i]),
1044
+ float(self._y[i]), axes)
1045
+ dot = Sphere(radius=self._radius, color=colors[i])
1046
+ dot.move_to(pt)
1047
+ self.dots.add(dot)
1048
+
1049
+ self.add(self.dots)
1050
+
1051
+ # Highlight rings
1052
+ self.highlight_rings = VGroup()
1053
+ if highlight_indices:
1054
+ for idx in highlight_indices:
1055
+ if 0 <= idx < n:
1056
+ pt = self._data_to_world(
1057
+ float(self._x1[idx]),
1058
+ float(self._x2[idx]),
1059
+ float(self._y[idx]), axes,
1060
+ )
1061
+ ring = Sphere(
1062
+ radius = self._radius * 2.0,
1063
+ color = YELLOW if _MANIM_AVAILABLE else None,
1064
+ )
1065
+ ring.set_fill(opacity=0)
1066
+ ring.set_stroke(color=YELLOW, width=2.0)
1067
+ ring.move_to(pt)
1068
+ self.highlight_rings.add(ring)
1069
+ self.add(self.highlight_rings)
1070
+
1071
+ @staticmethod
1072
+ def _data_to_world(
1073
+ x1: float, x2: float, y: float,
1074
+ axes: Optional["ThreeDAxes"],
1075
+ ) -> np.ndarray:
1076
+ if axes is not None:
1077
+ return np.array(axes.c2p(x1, x2, y))
1078
+ return np.array([x1, x2, y])
1079
+
1080
+ def _compute_colors(
1081
+ self,
1082
+ colouring: str,
1083
+ resid: np.ndarray,
1084
+ result: "RegressionResult",
1085
+ ) -> List["ManimColor"]:
1086
+ """Compute one ManimColor per observation."""
1087
+ n = len(resid)
1088
+ if _COLORS_AVAILABLE:
1089
+ pos_color = ManimColor(TEAL_600.hex)
1090
+ neg_color = ManimColor(CORAL_600.hex)
1091
+ base_color = ManimColor(NORMAL_FAMILY.base.hex)
1092
+ amber_lo = ManimColor(AMBER_200.hex)
1093
+ amber_hi = ManimColor(AMBER_600.hex)
1094
+ coral_lo = ManimColor(CORAL_200.hex)
1095
+ coral_hi = ManimColor(CORAL_600.hex)
1096
+ else:
1097
+ pos_color = neg_color = base_color = BLUE
1098
+ amber_lo = amber_hi = ORANGE
1099
+ coral_lo = coral_hi = RED
1100
+
1101
+ if colouring == "residual":
1102
+ max_abs = max(float(np.max(np.abs(resid))), 1e-6)
1103
+ colors = []
1104
+ for r in resid:
1105
+ t = min(abs(float(r)) / max_abs, 1.0)
1106
+ color = interpolate_color(base_color,
1107
+ pos_color if r > 0 else neg_color,
1108
+ t * 0.9)
1109
+ colors.append(color)
1110
+ return colors
1111
+
1112
+ elif colouring == "leverage":
1113
+ try:
1114
+ infl = influence_measures(result)
1115
+ h = infl.leverage
1116
+ except Exception:
1117
+ h = np.ones(n) / n
1118
+ h_norm = (h - h.min()) / max(h.max() - h.min(), 1e-6)
1119
+ return [interpolate_color(amber_lo, amber_hi, float(t))
1120
+ for t in h_norm]
1121
+
1122
+ elif colouring == "cooks_d":
1123
+ try:
1124
+ infl = influence_measures(result)
1125
+ cooks = infl.cooks_d
1126
+ except Exception:
1127
+ cooks = np.zeros(n)
1128
+ c_norm = (cooks - cooks.min()) / max(cooks.max() - cooks.min(), 1e-6)
1129
+ return [interpolate_color(coral_lo, coral_hi, float(t))
1130
+ for t in c_norm]
1131
+
1132
+ else: # flat
1133
+ return [base_color] * n
1134
+
1135
+ # ------------------------------------------------------------------
1136
+ # Animations
1137
+ # ------------------------------------------------------------------
1138
+
1139
+ def animate_appear(
1140
+ self, run_time: float = 1.8, stagger: float = 0.025
1141
+ ) -> "mn.Animation":
1142
+ """Staggered FadeIn of all dots."""
1143
+ _require_manim("animate_appear")
1144
+ return LaggedStart(
1145
+ *[FadeIn(d, scale=0.4, run_time=run_time * 0.4)
1146
+ for d in self.dots],
1147
+ lag_ratio = stagger,
1148
+ )
1149
+
1150
+ def highlight_obs(
1151
+ self,
1152
+ idx: int,
1153
+ color = None,
1154
+ run_time: float = 0.6,
1155
+ ) -> "mn.Animation":
1156
+ """Indicate + scale a single observation."""
1157
+ _require_manim("highlight_obs")
1158
+ if idx < 0 or idx >= len(self.dots):
1159
+ return AnimationGroup()
1160
+ color = color or (YELLOW if _MANIM_AVAILABLE else None)
1161
+ return AnimationGroup(
1162
+ Indicate(self.dots[idx], color=color,
1163
+ scale_factor=1.8, run_time=run_time),
1164
+ Flash(self.dots[idx], color=color,
1165
+ flash_radius=self._radius * 3, run_time=run_time),
1166
+ )
1167
+
1168
+ def dim_all_except(
1169
+ self,
1170
+ indices: Sequence[int],
1171
+ run_time: float = 0.5,
1172
+ dim_opacity: float = 0.12,
1173
+ ) -> "mn.Animation":
1174
+ """Fade all dots except those in ``indices`` to ``dim_opacity``."""
1175
+ _require_manim("dim_all_except")
1176
+ keep = set(indices)
1177
+ anims = []
1178
+ for i, dot in enumerate(self.dots):
1179
+ if i not in keep:
1180
+ anims.append(dot.animate(run_time=run_time).set_opacity(dim_opacity))
1181
+ return AnimationGroup(*anims) if anims else AnimationGroup()
1182
+
1183
+ def undim_all(self, run_time: float = 0.4) -> "mn.Animation":
1184
+ """Restore all dots to full opacity."""
1185
+ _require_manim("undim_all")
1186
+ return AnimationGroup(
1187
+ *[dot.animate(run_time=run_time).set_opacity(1.0)
1188
+ for dot in self.dots]
1189
+ )
1190
+
1191
+
1192
+ # ---------------------------------------------------------------------------
1193
+ # PlaneResiduals3D
1194
+ # ---------------------------------------------------------------------------
1195
+
1196
+ class PlaneResiduals3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
1197
+ """
1198
+ Vertical line segments from each observed point (x1_i, x2_i, y_i) down
1199
+ (or up) to its fitted value (x1_i, x2_i, y_hat_i) on the regression plane.
1200
+
1201
+ Colour convention (matching ``ScatterCloud3D``):
1202
+ Positive residual (y > y_hat) → teal line going UP from plane.
1203
+ Negative residual (y < y_hat) → coral line going DOWN from plane.
1204
+ Stroke width scales with |residual| so large errors are visually prominent.
1205
+
1206
+ Parameters
1207
+ ----------
1208
+ x1, x2 : array-like (n,)
1209
+ result : RegressionResult
1210
+ geometry : PlaneGeometry
1211
+ axes : ThreeDAxes, optional
1212
+ pos_color, neg_color : ManimColor, optional
1213
+ max_stroke_width : float
1214
+ min_stroke_width : float
1215
+ outlier_threshold : float
1216
+ |externally studentized residual| above which a circle is added.
1217
+ show_zero_line : bool
1218
+ Draw a faint circle on the plane at y_hat for each obs (expensive).
1219
+
1220
+ Key sub-mobjects
1221
+ ----------------
1222
+ .positive_lines : VGroup
1223
+ .negative_lines : VGroup
1224
+ .outlier_markers : VGroup
1225
+
1226
+ Animations
1227
+ ----------
1228
+ .animate_appear(run_time, stagger)
1229
+ .flash_outliers(run_time)
1230
+ .fade_to_zero(run_time) — shrink residuals to zero (model fit improves)
1231
+ .update_fit(new_result, run_time) — morph to a new model
1232
+ """
1233
+
1234
+ def __init__(
1235
+ self,
1236
+ x1: np.ndarray,
1237
+ x2: np.ndarray,
1238
+ result: "RegressionResult",
1239
+ geometry: PlaneGeometry = DEFAULT_GEOMETRY,
1240
+ axes: Optional["ThreeDAxes"] = None,
1241
+ pos_color = None,
1242
+ neg_color = None,
1243
+ max_stroke_width: float = 3.2,
1244
+ min_stroke_width: float = 0.6,
1245
+ outlier_threshold: float = 2.5,
1246
+ **kwargs,
1247
+ ) -> None:
1248
+ _require_manim("PlaneResiduals3D.__init__")
1249
+ _require_corr("PlaneResiduals3D.__init__")
1250
+ super().__init__(**kwargs)
1251
+
1252
+ self._x1 = np.asarray(x1, dtype=float)
1253
+ self._x2 = np.asarray(x2, dtype=float)
1254
+ self._result = result
1255
+ self._axes = axes
1256
+ self._geo = geometry
1257
+
1258
+ if _COLORS_AVAILABLE:
1259
+ pos_color = pos_color or ManimColor(TEAL_600.hex)
1260
+ neg_color = neg_color or ManimColor(CORAL_600.hex)
1261
+ else:
1262
+ pos_color = pos_color or GREEN
1263
+ neg_color = neg_color or RED
1264
+
1265
+ self._pos_color = pos_color
1266
+ self._neg_color = neg_color
1267
+
1268
+ self.positive_lines = VGroup()
1269
+ self.negative_lines = VGroup()
1270
+ self.outlier_markers = VGroup()
1271
+
1272
+ self._build(result, x1, x2, axes,
1273
+ pos_color, neg_color,
1274
+ max_stroke_width, min_stroke_width,
1275
+ outlier_threshold)
1276
+
1277
+ def _build(
1278
+ self,
1279
+ result: "RegressionResult",
1280
+ x1: np.ndarray,
1281
+ x2: np.ndarray,
1282
+ axes: Optional["ThreeDAxes"],
1283
+ pos_color,
1284
+ neg_color,
1285
+ max_sw: float,
1286
+ min_sw: float,
1287
+ outlier_threshold: float,
1288
+ ) -> None:
1289
+ y_hat = result.fitted
1290
+ y = result.y
1291
+ resid = result.residuals
1292
+ n = result.n
1293
+ max_abs = max(float(np.max(np.abs(resid))), 1e-6)
1294
+
1295
+ # Influence measures for outlier detection
1296
+ try:
1297
+ infl = influence_measures(result)
1298
+ ext_stud = infl.externally_studentized
1299
+ except Exception:
1300
+ ext_stud = np.zeros(n)
1301
+
1302
+ def _pt(x1v, x2v, yv):
1303
+ if axes is not None:
1304
+ return np.array(axes.c2p(float(x1v), float(x2v), float(yv)))
1305
+ return np.array([float(x1v), float(x2v), float(yv)])
1306
+
1307
+ for i in range(n):
1308
+ ri = float(resid[i])
1309
+ if abs(ri) < 1e-10:
1310
+ continue
1311
+ stroke = min_sw + (max_sw - min_sw) * abs(ri) / max_abs
1312
+ color = pos_color if ri > 0 else neg_color
1313
+
1314
+ plane_pt = _pt(x1[i], x2[i], y_hat[i])
1315
+ obs_pt = _pt(x1[i], x2[i], y[i])
1316
+
1317
+ line = Line(
1318
+ start = plane_pt,
1319
+ end = obs_pt,
1320
+ color = color,
1321
+ stroke_width = stroke,
1322
+ )
1323
+ if ri > 0:
1324
+ self.positive_lines.add(line)
1325
+ else:
1326
+ self.negative_lines.add(line)
1327
+
1328
+ # Outlier circle at the observation point
1329
+ if abs(float(ext_stud[i])) > outlier_threshold:
1330
+ ring = Sphere(
1331
+ radius = self._geo.dot_radius * 2.5,
1332
+ color = YELLOW if _MANIM_AVAILABLE else None,
1333
+ )
1334
+ ring.set_fill(opacity=0)
1335
+ ring.set_stroke(color=YELLOW, width=2.0)
1336
+ ring.move_to(obs_pt)
1337
+ self.outlier_markers.add(ring)
1338
+
1339
+ self.add(self.positive_lines, self.negative_lines, self.outlier_markers)
1340
+
1341
+ # ------------------------------------------------------------------
1342
+ # Animations
1343
+ # ------------------------------------------------------------------
1344
+
1345
+ def animate_appear(
1346
+ self,
1347
+ run_time: float = 1.8,
1348
+ stagger: float = 0.03,
1349
+ ) -> "mn.Animation":
1350
+ """Grow residual lines from their plane endpoints."""
1351
+ _require_manim("animate_appear")
1352
+ all_lines = list(self.positive_lines) + list(self.negative_lines)
1353
+ return LaggedStart(
1354
+ *[Create(line, run_time=run_time * 0.45) for line in all_lines],
1355
+ lag_ratio = stagger,
1356
+ )
1357
+
1358
+ def flash_outliers(self, run_time: float = 1.0) -> "mn.Animation":
1359
+ """Flash rings around outlier observations."""
1360
+ _require_manim("flash_outliers")
1361
+ if not self.outlier_markers:
1362
+ return AnimationGroup()
1363
+ return LaggedStart(
1364
+ *[Flash(m, color=YELLOW,
1365
+ flash_radius=self._geo.dot_radius * 4,
1366
+ run_time=run_time)
1367
+ for m in self.outlier_markers],
1368
+ lag_ratio = 0.12,
1369
+ )
1370
+
1371
+ def fade_to_zero(self, run_time: float = 1.5) -> "mn.Animation":
1372
+ """
1373
+ Animate residual lines shrinking to zero — useful for showing
1374
+ how a better model reduces RSS.
1375
+ """
1376
+ _require_manim("fade_to_zero")
1377
+ all_lines = list(self.positive_lines) + list(self.negative_lines)
1378
+ return AnimationGroup(
1379
+ *[line.animate(run_time=run_time).scale(
1380
+ 0.001, about_point=line.get_start()
1381
+ )
1382
+ for line in all_lines]
1383
+ )
1384
+
1385
+ def update_fit(
1386
+ self,
1387
+ new_result: "RegressionResult",
1388
+ run_time: float = 1.0,
1389
+ ) -> "mn.Animation":
1390
+ """Morph residual lines to match a re-fitted model."""
1391
+ _require_manim("update_fit")
1392
+ target = PlaneResiduals3D(
1393
+ x1 = self._x1,
1394
+ x2 = self._x2,
1395
+ result = new_result,
1396
+ geometry = self._geo,
1397
+ axes = self._axes,
1398
+ pos_color= self._pos_color,
1399
+ neg_color= self._neg_color,
1400
+ ).move_to(self.get_center())
1401
+ return Transform(self, target, run_time=run_time,
1402
+ rate_func=rate_functions.ease_in_out_quad)
1403
+
1404
+
1405
+ # ---------------------------------------------------------------------------
1406
+ # CIShell3D — Confidence interval surface pair
1407
+ # ---------------------------------------------------------------------------
1408
+
1409
+ class CIShell3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
1410
+ """
1411
+ Upper and lower 95 % confidence interval surfaces bounding E[Y|x].
1412
+
1413
+ The CI shell is two semi-transparent ``Surface`` objects rendered above
1414
+ and below the regression plane. The gap between them widens toward the
1415
+ corners where leverage (and thus uncertainty) is highest.
1416
+
1417
+ Parameters
1418
+ ----------
1419
+ result : RegressionResult (k=2)
1420
+ x1_range, x2_range : (float, float)
1421
+ geometry : PlaneGeometry
1422
+ axes : ThreeDAxes, optional
1423
+ level : float
1424
+ Confidence level. Default 0.95.
1425
+ color : ManimColor, optional
1426
+ Color of both shell surfaces (default REGRESSION_FAMILY.light).
1427
+ opacity : float
1428
+
1429
+ Key sub-mobjects
1430
+ ----------------
1431
+ .upper_surface : Surface
1432
+ .lower_surface : Surface
1433
+
1434
+ Animations
1435
+ ----------
1436
+ .animate_appear(run_time) — FadeIn both surfaces
1437
+ .morph_level(new_level, run_time) — morph to a different CI level
1438
+ """
1439
+
1440
+ def __init__(
1441
+ self,
1442
+ result: "RegressionResult",
1443
+ x1_range: Tuple[float, float],
1444
+ x2_range: Tuple[float, float],
1445
+ geometry: PlaneGeometry = DEFAULT_GEOMETRY,
1446
+ axes: Optional["ThreeDAxes"] = None,
1447
+ level: float = 0.95,
1448
+ color = None,
1449
+ opacity: float = None,
1450
+ **kwargs,
1451
+ ) -> None:
1452
+ _require_manim("CIShell3D.__init__")
1453
+ _require_corr("CIShell3D.__init__")
1454
+ super().__init__(**kwargs)
1455
+
1456
+ if result.k != 2:
1457
+ raise ValueError(
1458
+ f"CIShell3D requires k=2 predictor fit, got k={result.k}."
1459
+ )
1460
+
1461
+ self._result = result
1462
+ self._x1_range = x1_range
1463
+ self._x2_range = x2_range
1464
+ self._level = level
1465
+ self._geo = geometry
1466
+ self._axes = axes
1467
+
1468
+ if _COLORS_AVAILABLE:
1469
+ color = color or ManimColor(REGRESSION_FAMILY.light.hex)
1470
+ else:
1471
+ color = color or BLUE
1472
+ opacity = opacity if opacity is not None else geometry.ci_opacity
1473
+
1474
+ # Compute CI surfaces
1475
+ try:
1476
+ X_design = result.x
1477
+ XtX_inv = np.linalg.inv(X_design.T @ X_design)
1478
+ except (np.linalg.LinAlgError, AttributeError):
1479
+ XtX_inv = np.eye(3)
1480
+
1481
+ X1, X2, Z_upper, Z_lower = ci_surface(
1482
+ beta = result.beta,
1483
+ XtX_inv = XtX_inv,
1484
+ s = result.sigma_hat,
1485
+ n = result.n,
1486
+ x1_range = x1_range,
1487
+ x2_range = x2_range,
1488
+ resolution = geometry.ci_resolution,
1489
+ level = level,
1490
+ )
1491
+
1492
+ self.upper_surface = self._make_surface(
1493
+ result.beta, XtX_inv, result.sigma_hat, result.n,
1494
+ x1_range, x2_range, geometry.ci_resolution,
1495
+ level, upper=True, axes=axes, color=color, opacity=opacity,
1496
+ )
1497
+ self.lower_surface = self._make_surface(
1498
+ result.beta, XtX_inv, result.sigma_hat, result.n,
1499
+ x1_range, x2_range, geometry.ci_resolution,
1500
+ level, upper=False, axes=axes, color=color, opacity=opacity,
1501
+ )
1502
+ self.add(self.upper_surface, self.lower_surface)
1503
+
1504
+ @staticmethod
1505
+ def _make_surface(
1506
+ beta, XtX_inv, s, n,
1507
+ x1_range, x2_range, resolution,
1508
+ level, upper, axes, color, opacity,
1509
+ ) -> "Surface":
1510
+ df = n - 3
1511
+ if _SCIPY_AVAILABLE:
1512
+ t_crit = float(_sp.t.ppf((1 + level) / 2, df=max(df, 1)))
1513
+ else:
1514
+ t_crit = 1.959963985
1515
+
1516
+ b0, b1, b2 = float(beta[0]), float(beta[1]), float(beta[2])
1517
+ sign = 1.0 if upper else -1.0
1518
+
1519
+ def _pad(lo, hi, p=0.15):
1520
+ span = max(hi - lo, 1e-6)
1521
+ return lo - p * span, hi + p * span
1522
+
1523
+ u_lo, u_hi = _pad(*x1_range)
1524
+ v_lo, v_hi = _pad(*x2_range)
1525
+
1526
+ def _func(u: float, v: float) -> np.ndarray:
1527
+ x0 = np.array([1.0, u, v])
1528
+ var_fit = float(x0 @ XtX_inv @ x0)
1529
+ margin = t_crit * s * math.sqrt(max(var_fit, 0.0))
1530
+ z = b0 + b1 * u + b2 * v + sign * margin
1531
+ if axes is not None:
1532
+ return np.array(axes.c2p(u, v, z))
1533
+ return np.array([u, v, z])
1534
+
1535
+ surf = Surface(
1536
+ func = _func,
1537
+ u_range = [u_lo, u_hi],
1538
+ v_range = [v_lo, v_hi],
1539
+ resolution = (resolution, resolution),
1540
+ fill_opacity = opacity,
1541
+ checkerboard_colors = None,
1542
+ )
1543
+ surf.set_color(color)
1544
+ surf.set_stroke(width=0)
1545
+ return surf
1546
+
1547
+ def animate_appear(self, run_time: float = 1.0) -> "mn.Animation":
1548
+ """Fade both CI surfaces in."""
1549
+ _require_manim("animate_appear")
1550
+ return AnimationGroup(
1551
+ FadeIn(self.upper_surface, run_time=run_time),
1552
+ FadeIn(self.lower_surface, run_time=run_time),
1553
+ )
1554
+
1555
+ def morph_level(
1556
+ self,
1557
+ new_level: float,
1558
+ run_time: float = 1.2,
1559
+ ) -> "mn.Animation":
1560
+ """Morph CI shells to a different confidence level."""
1561
+ _require_manim("morph_level")
1562
+ target = CIShell3D(
1563
+ result = self._result,
1564
+ x1_range = self._x1_range,
1565
+ x2_range = self._x2_range,
1566
+ geometry = self._geo,
1567
+ axes = self._axes,
1568
+ level = new_level,
1569
+ ).move_to(self.get_center())
1570
+ return Transform(self, target, run_time=run_time,
1571
+ rate_func=rate_functions.ease_in_out_sine)
1572
+
1573
+
1574
+ # ---------------------------------------------------------------------------
1575
+ # PIShell3D — Prediction interval surface pair
1576
+ # ---------------------------------------------------------------------------
1577
+
1578
+ class PIShell3D(CIShell3D if _MANIM_AVAILABLE else object): # type: ignore
1579
+ """
1580
+ Upper and lower 95 % prediction interval surfaces.
1581
+
1582
+ Identical to ``CIShell3D`` except uses the prediction variance formula:
1583
+ PI = y_hat ± t * s * sqrt(1 + x0'(X'X)^{-1}x0)
1584
+
1585
+ The PI shell is always wider than the CI shell. Rendering it in the same
1586
+ scene clearly illustrates the distinction between confidence in the mean
1587
+ vs. prediction of a new individual.
1588
+
1589
+ Inherits all parameters and animations from ``CIShell3D``.
1590
+ """
1591
+
1592
+ def __init__(
1593
+ self,
1594
+ result: "RegressionResult",
1595
+ x1_range: Tuple[float, float],
1596
+ x2_range: Tuple[float, float],
1597
+ geometry: PlaneGeometry = DEFAULT_GEOMETRY,
1598
+ axes: Optional["ThreeDAxes"] = None,
1599
+ level: float = 0.95,
1600
+ color = None,
1601
+ opacity: float = None,
1602
+ **kwargs,
1603
+ ) -> None:
1604
+ _require_manim("PIShell3D.__init__")
1605
+
1606
+ # Bypass CIShell3D.__init__ — rebuild with PI formula
1607
+ VGroup.__init__(self, **kwargs)
1608
+
1609
+ if result.k != 2:
1610
+ raise ValueError(
1611
+ f"PIShell3D requires k=2 predictor fit, got k={result.k}."
1612
+ )
1613
+
1614
+ self._result = result
1615
+ self._x1_range = x1_range
1616
+ self._x2_range = x2_range
1617
+ self._level = level
1618
+ self._geo = geometry
1619
+ self._axes = axes
1620
+
1621
+ if _COLORS_AVAILABLE:
1622
+ color = color or ManimColor(REGRESSION_FAMILY.muted.hex)
1623
+ else:
1624
+ color = color or BLUE
1625
+ opacity = opacity if opacity is not None else geometry.pi_opacity
1626
+
1627
+ try:
1628
+ XtX_inv = np.linalg.inv(result.x.T @ result.x)
1629
+ except (np.linalg.LinAlgError, AttributeError):
1630
+ XtX_inv = np.eye(3)
1631
+
1632
+ df = result.n - 3
1633
+ if _SCIPY_AVAILABLE:
1634
+ t_crit = float(_sp.t.ppf((1 + level) / 2, df=max(df, 1)))
1635
+ else:
1636
+ t_crit = 1.959963985
1637
+
1638
+ beta = result.beta
1639
+ b0, b1, b2 = float(beta[0]), float(beta[1]), float(beta[2])
1640
+ s = result.sigma_hat
1641
+
1642
+ def _pad(lo, hi, p=0.15):
1643
+ span = max(hi - lo, 1e-6)
1644
+ return lo - p * span, hi + p * span
1645
+
1646
+ u_lo, u_hi = _pad(*x1_range)
1647
+ v_lo, v_hi = _pad(*x2_range)
1648
+ res = geometry.ci_resolution
1649
+
1650
+ def _make(sign):
1651
+ def _func(u, v):
1652
+ x0 = np.array([1.0, u, v])
1653
+ var_pred = float(1.0 + x0 @ XtX_inv @ x0)
1654
+ margin = t_crit * s * math.sqrt(max(var_pred, 0.0))
1655
+ z = b0 + b1*u + b2*v + sign * margin
1656
+ if axes is not None:
1657
+ return np.array(axes.c2p(u, v, z))
1658
+ return np.array([u, v, z])
1659
+ surf = Surface(
1660
+ func = _func,
1661
+ u_range = [u_lo, u_hi],
1662
+ v_range = [v_lo, v_hi],
1663
+ resolution = (res, res),
1664
+ fill_opacity = opacity,
1665
+ checkerboard_colors = None,
1666
+ )
1667
+ surf.set_color(color)
1668
+ surf.set_stroke(width=0)
1669
+ return surf
1670
+
1671
+ self.upper_surface = _make(+1.0)
1672
+ self.lower_surface = _make(-1.0)
1673
+ self.add(self.upper_surface, self.lower_surface)
1674
+
1675
+
1676
+ # ---------------------------------------------------------------------------
1677
+ # ProjectionArrow3D
1678
+ # ---------------------------------------------------------------------------
1679
+
1680
+ class ProjectionArrow3D(VGroup if _MANIM_AVAILABLE else object): # type: ignore
1681
+ """
1682
+ Visual showing how a single point (x1, x2, y) projects onto the fitted plane.
1683
+
1684
+ Draws three components:
1685
+ 1. A vertical dashed line from (x1, x2, y_hat) straight down/up to (x1, x2, y).
1686
+ 2. A horizontal dashed line from (x1_bar, x2_bar, y_hat) to (x1, x2, y_hat)
1687
+ on the plane surface.
1688
+ 3. A label showing the residual value.
1689
+
1690
+ Parameters
1691
+ ----------
1692
+ x1_val, x2_val, y_val : float
1693
+ Coordinates of the focal point.
1694
+ result : RegressionResult
1695
+ axes : ThreeDAxes, optional
1696
+ color : ManimColor, optional
1697
+ label : str, optional
1698
+ Custom label text. Defaults to showing the residual value.
1699
+
1700
+ Key sub-mobjects
1701
+ ----------------
1702
+ .vertical_line : DashedLine
1703
+ .horizontal_line : DashedLine
1704
+ .plane_dot : Sphere (the foot of the perpendicular on the plane)
1705
+ .obs_dot : Sphere (the observation itself)
1706
+ .residual_label : MathTex
1707
+
1708
+ Animations
1709
+ ----------
1710
+ .animate_draw(run_time) — draw lines in sequence
1711
+ .flash(run_time) — Flash both line endpoints
1712
+ """
1713
+
1714
+ def __init__(
1715
+ self,
1716
+ x1_val: float,
1717
+ x2_val: float,
1718
+ y_val: float,
1719
+ result: "RegressionResult",
1720
+ axes: Optional["ThreeDAxes"] = None,
1721
+ color = None,
1722
+ label: Optional[str] = None,
1723
+ dot_radius: float = 0.07,
1724
+ **kwargs,
1725
+ ) -> None:
1726
+ _require_manim("ProjectionArrow3D.__init__")
1727
+ _require_corr("ProjectionArrow3D.__init__")
1728
+ super().__init__(**kwargs)
1729
+
1730
+ if _COLORS_AVAILABLE:
1731
+ color = color or ManimColor(DISCRETE_FAMILY.base.hex)
1732
+ else:
1733
+ color = color or YELLOW
1734
+
1735
+ # Fitted value at this point
1736
+ beta = result.beta
1737
+ y_hat = float(plane_predict(beta, x1_val, x2_val))
1738
+ resid = y_val - y_hat
1739
+
1740
+ def _pt(x1, x2, y):
1741
+ if axes is not None:
1742
+ return np.array(axes.c2p(float(x1), float(x2), float(y)))
1743
+ return np.array([float(x1), float(x2), float(y)])
1744
+
1745
+ plane_pt = _pt(x1_val, x2_val, y_hat)
1746
+ obs_pt = _pt(x1_val, x2_val, y_val)
1747
+
1748
+ # Vertical residual line
1749
+ self.vertical_line = DashedLine(
1750
+ start = plane_pt,
1751
+ end = obs_pt,
1752
+ color = color,
1753
+ stroke_width = 2.2,
1754
+ dash_length = 0.10,
1755
+ )
1756
+
1757
+ # Plane-foot dot
1758
+ self.plane_dot = Sphere(radius=dot_radius, color=color)
1759
+ self.plane_dot.move_to(plane_pt)
1760
+
1761
+ # Observation dot
1762
+ self.obs_dot = Sphere(radius=dot_radius * 1.3, color=color)
1763
+ self.obs_dot.move_to(obs_pt)
1764
+
1765
+ # Residual label
1766
+ resid_str = label or rf"e = {resid:+.3f}"
1767
+ self.residual_label = MathTex(
1768
+ resid_str,
1769
+ font_size = 22,
1770
+ color = color,
1771
+ )
1772
+ # Place label beside the midpoint of the residual line
1773
+ mid = (plane_pt + obs_pt) / 2
1774
+ self.residual_label.move_to(mid + np.array([0.35, 0.0, 0.0]))
1775
+
1776
+ self.add(self.vertical_line, self.plane_dot,
1777
+ self.obs_dot, self.residual_label)
1778
+
1779
+ def animate_draw(self, run_time: float = 1.2) -> "mn.Animation":
1780
+ """Draw the vertical line, then flash the dots."""
1781
+ _require_manim("animate_draw")
1782
+ return Succession(
1783
+ Create(self.vertical_line, run_time=run_time * 0.55),
1784
+ AnimationGroup(
1785
+ GrowFromCenter(self.plane_dot, run_time=run_time * 0.20),
1786
+ GrowFromCenter(self.obs_dot, run_time=run_time * 0.20),
1787
+ Write(self.residual_label, run_time=run_time * 0.25),
1788
+ ),
1789
+ )
1790
+
1791
+ def flash(self, run_time: float = 0.7) -> "mn.Animation":
1792
+ """Flash both endpoint dots simultaneously."""
1793
+ _require_manim("flash")
1794
+ return AnimationGroup(
1795
+ Flash(self.plane_dot, run_time=run_time),
1796
+ Flash(self.obs_dot, run_time=run_time),
1797
+ )
1798
+
1799
+
1800
+ # ===========================================================================
1801
+ # LAYER D — Scene-level animation factories
1802
+ # ===========================================================================
1803
+
1804
+ def build_plane_scene(
1805
+ result: "RegressionResult",
1806
+ x1: np.ndarray,
1807
+ x2: np.ndarray,
1808
+ y: np.ndarray,
1809
+ x1_name: str = "x_1",
1810
+ x2_name: str = "x_2",
1811
+ y_name: str = "y",
1812
+ geometry: PlaneGeometry = DEFAULT_GEOMETRY,
1813
+ colouring: Union[SurfaceColouring, str] = SurfaceColouring.FITTED,
1814
+ show_ci: bool = True,
1815
+ show_residuals: bool = True,
1816
+ cloud_colouring: str = "residual",
1817
+ ) -> Tuple[
1818
+ "ThreeDAxes",
1819
+ "ScatterCloud3D",
1820
+ "RegressionPlane3D",
1821
+ Optional["PlaneResiduals3D"],
1822
+ Optional["CIShell3D"],
1823
+ ]:
1824
+ """
1825
+ Build all mobjects needed for a canonical two-predictor regression scene.
1826
+
1827
+ Creates and positions:
1828
+ - ``ThreeDAxes`` spanning the data range with axis labels
1829
+ - ``ScatterCloud3D`` of data points
1830
+ - ``RegressionPlane3D``
1831
+ - ``PlaneResiduals3D`` (optional)
1832
+ - ``CIShell3D`` (optional)
1833
+
1834
+ The function does **not** call any ``scene.play()`` — it only creates
1835
+ and positions the mobjects. The caller controls what to display and when.
1836
+
1837
+ Parameters
1838
+ ----------
1839
+ result : RegressionResult
1840
+ k=2 OLS fit.
1841
+ x1, x2, y : ndarray
1842
+ Original data arrays.
1843
+ x1_name, x2_name, y_name : str
1844
+ Variable names for axis labels.
1845
+ geometry : PlaneGeometry
1846
+ colouring : SurfaceColouring
1847
+ Plane colouring strategy.
1848
+ show_ci : bool
1849
+ Build a CIShell3D.
1850
+ show_residuals : bool
1851
+ Build a PlaneResiduals3D.
1852
+ cloud_colouring : str
1853
+ Colour strategy for scatter cloud ('residual', 'leverage', 'cooks_d', 'flat').
1854
+
1855
+ Returns
1856
+ -------
1857
+ (axes, cloud, plane, residuals, ci_shell)
1858
+ ``residuals`` and ``ci_shell`` are ``None`` when their flags are False.
1859
+ """
1860
+ _require_manim("build_plane_scene")
1861
+ _require_corr("build_plane_scene")
1862
+
1863
+ x1 = np.asarray(x1, dtype=float)
1864
+ x2 = np.asarray(x2, dtype=float)
1865
+ y = np.asarray(y, dtype=float)
1866
+
1867
+ x1_range = (float(x1.min()), float(x1.max()))
1868
+ x2_range = (float(x2.min()), float(x2.max()))
1869
+ y_range = (float(y.min()), float(y.max()))
1870
+
1871
+ # ---- ThreeDAxes ----
1872
+ x1_pad = (x1_range[1] - x1_range[0]) * 0.18
1873
+ x2_pad = (x2_range[1] - x2_range[0]) * 0.18
1874
+ y_pad = (y_range[1] - y_range[0]) * 0.22
1875
+
1876
+ axes = ThreeDAxes(
1877
+ x_range = [x1_range[0] - x1_pad, x1_range[1] + x1_pad, (x1_range[1]-x1_range[0])/4],
1878
+ y_range = [x2_range[0] - x2_pad, x2_range[1] + x2_pad, (x2_range[1]-x2_range[0])/4],
1879
+ z_range = [y_range[0] - y_pad, y_range[1] + y_pad, (y_range[1] -y_range[0]) /4],
1880
+ **geometry.axes_kwargs,
1881
+ )
1882
+
1883
+ # Axis labels
1884
+ x1_label = MathTex(x1_name, font_size=geometry.axis_label_font_size)
1885
+ x2_label = MathTex(x2_name, font_size=geometry.axis_label_font_size)
1886
+ y_label = MathTex(y_name, font_size=geometry.axis_label_font_size)
1887
+
1888
+ x1_label.next_to(axes.x_axis, RIGHT, buff=0.15)
1889
+ x2_label.next_to(axes.y_axis, UP, buff=0.15)
1890
+ y_label.next_to(axes.z_axis, OUT, buff=0.15)
1891
+
1892
+ axes_group = VGroup(axes, x1_label, x2_label, y_label)
1893
+
1894
+ # ---- Scatter cloud ----
1895
+ cloud = ScatterCloud3D(
1896
+ x1 = x1,
1897
+ x2 = x2,
1898
+ y = y,
1899
+ result = result,
1900
+ colouring = cloud_colouring,
1901
+ geometry = geometry,
1902
+ axes = axes,
1903
+ )
1904
+
1905
+ # ---- Regression plane ----
1906
+ plane = RegressionPlane3D(
1907
+ result = result,
1908
+ x1_range = x1_range,
1909
+ x2_range = x2_range,
1910
+ geometry = geometry,
1911
+ colouring = colouring,
1912
+ axes = axes,
1913
+ )
1914
+
1915
+ # ---- Residuals ----
1916
+ residuals = None
1917
+ if show_residuals:
1918
+ residuals = PlaneResiduals3D(
1919
+ x1 = x1,
1920
+ x2 = x2,
1921
+ result = result,
1922
+ geometry = geometry,
1923
+ axes = axes,
1924
+ )
1925
+
1926
+ # ---- CI shell ----
1927
+ ci_shell = None
1928
+ if show_ci:
1929
+ ci_shell = CIShell3D(
1930
+ result = result,
1931
+ x1_range = x1_range,
1932
+ x2_range = x2_range,
1933
+ geometry = geometry,
1934
+ axes = axes,
1935
+ )
1936
+
1937
+ return axes_group, cloud, plane, residuals, ci_shell
1938
+
1939
+
1940
+ def morph_beta(
1941
+ plane: RegressionPlane3D,
1942
+ scene,
1943
+ beta_sequence: Sequence[np.ndarray],
1944
+ run_time_each: float = 1.2,
1945
+ wait_each: float = 0.5,
1946
+ ) -> None:
1947
+ """
1948
+ Animate a ``RegressionPlane3D`` morphing through a sequence of coefficient
1949
+ vectors, playing each transition on ``scene`` and waiting briefly between.
1950
+
1951
+ Parameters
1952
+ ----------
1953
+ plane : RegressionPlane3D
1954
+ scene : ThreeDScene
1955
+ beta_sequence : sequence of ndarray (3,)
1956
+ Each array is [b0, b1, b2].
1957
+ run_time_each : float
1958
+ wait_each : float
1959
+ """
1960
+ _require_manim("morph_beta")
1961
+ for beta in beta_sequence:
1962
+ scene.play(plane.animate_tilt(np.asarray(beta), run_time=run_time_each))
1963
+ scene.wait(wait_each)
1964
+
1965
+
1966
+ def sweep_x1(
1967
+ plane: RegressionPlane3D,
1968
+ scene,
1969
+ x1_vals: Sequence[float],
1970
+ x2_fixed: float,
1971
+ marker: Optional["ProjectionArrow3D"] = None,
1972
+ run_time: float = 2.5,
1973
+ ) -> None:
1974
+ """
1975
+ Animate a vertical marker sweeping along x1 at fixed x2,
1976
+ tracing the regression plane's prediction curve for X2 = x2_fixed.
1977
+
1978
+ If ``marker`` is not provided, one is created from the first x1 value.
1979
+
1980
+ Parameters
1981
+ ----------
1982
+ plane : RegressionPlane3D
1983
+ scene : ThreeDScene
1984
+ x1_vals : sequence of float
1985
+ x2_fixed : float
1986
+ marker : ProjectionArrow3D, optional
1987
+ run_time : float
1988
+ Total sweep duration.
1989
+ """
1990
+ _require_manim("sweep_x1")
1991
+ result = plane._result
1992
+ beta = plane._beta
1993
+
1994
+ dt = run_time / max(len(x1_vals) - 1, 1)
1995
+ for i, x1v in enumerate(x1_vals[1:], 1):
1996
+ y_hat = float(plane_predict(beta, x1v, x2_fixed))
1997
+ axes = plane._axes_ref
1998
+ if axes is not None:
1999
+ target = np.array(axes.c2p(x1v, x2_fixed, y_hat))
2000
+ else:
2001
+ target = np.array([x1v, x2_fixed, y_hat])
2002
+
2003
+ if marker is not None:
2004
+ scene.play(
2005
+ marker.animate(run_time=dt).move_to(target),
2006
+ rate_func=rate_functions.linear,
2007
+ )
2008
+ else:
2009
+ scene.wait(dt)
2010
+
2011
+
2012
+ def rotate_view(
2013
+ scene,
2014
+ phi: float = 70 * (3.14159 / 180),
2015
+ theta: float = -45 * (3.14159 / 180),
2016
+ run_time: float = 2.0,
2017
+ ) -> None:
2018
+ """
2019
+ Animate the camera rotating to a new (phi, theta) viewpoint
2020
+ for a ``ThreeDScene``.
2021
+
2022
+ Parameters
2023
+ ----------
2024
+ scene : ThreeDScene
2025
+ phi : float
2026
+ Polar angle in radians (0 = top-down, pi/2 = side-on).
2027
+ theta : float
2028
+ Azimuthal angle in radians.
2029
+ run_time : float
2030
+ """
2031
+ _require_manim("rotate_view")
2032
+ scene.move_camera(phi=phi, theta=theta, run_time=run_time)
2033
+
2034
+
2035
+ # ===========================================================================
2036
+ # LAYER E — Formula registry bridge
2037
+ # ===========================================================================
2038
+
2039
+ def _build_multiple_regression_formula() -> Optional["TexFormula"]:
2040
+ if not _TEX_AVAILABLE:
2041
+ return None
2042
+ raw = (
2043
+ r"y_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + \varepsilon_i"
2044
+ r",\quad \varepsilon_i \overset{\mathrm{iid}}{\sim} \mathcal{N}(0, \sigma^2)"
2045
+ )
2046
+ return TexFormula(
2047
+ name = "multiple_regression_model",
2048
+ raw = raw,
2049
+ description = "Multiple linear regression model (k=2 predictors)",
2050
+ parts = {
2051
+ "response": r"y_i",
2052
+ "intercept": r"\beta_0",
2053
+ "slope_x1": r"\beta_1 x_{1i}",
2054
+ "slope_x2": r"\beta_2 x_{2i}",
2055
+ "error": r"\varepsilon_i",
2056
+ "error_dist": r"\mathcal{N}(0, \sigma^2)",
2057
+ },
2058
+ tags = ["regression", "multiple", "model"],
2059
+ )
2060
+
2061
+
2062
+ def _build_plane_ols_formula() -> Optional["TexFormula"]:
2063
+ if not _TEX_AVAILABLE:
2064
+ return None
2065
+ raw = (
2066
+ r"\hat{\boldsymbol{\beta}} = "
2067
+ r"\left(\mathbf{X}^\top \mathbf{X}\right)^{-1} \mathbf{X}^\top \mathbf{y}"
2068
+ )
2069
+ rss_raw = (
2070
+ r"\mathrm{RSS} = "
2071
+ r"\sum_{i=1}^{n}\left(y_i - \hat{y}_i\right)^2 = "
2072
+ r"\left\|\mathbf{y} - \mathbf{X}\hat{\boldsymbol{\beta}}\right\|^2"
2073
+ )
2074
+ return TexFormula(
2075
+ name = "ols_plane_estimator",
2076
+ raw = raw,
2077
+ description = "OLS estimator for the regression plane coefficients",
2078
+ parts = {
2079
+ "beta_hat": r"\hat{\boldsymbol{\beta}}",
2080
+ "gram": r"\mathbf{X}^\top \mathbf{X}",
2081
+ "gram_inv": r"\left(\mathbf{X}^\top \mathbf{X}\right)^{-1}",
2082
+ "projection": r"\mathbf{X}^\top \mathbf{y}",
2083
+ },
2084
+ steps = [
2085
+ TexDerivationStep(
2086
+ lhs = r"\mathrm{RSS}(\boldsymbol{\beta})",
2087
+ rhs = r"\|\mathbf{y} - \mathbf{X}\boldsymbol{\beta}\|^2",
2088
+ annotation = "Residual sum of squares",
2089
+ ),
2090
+ TexDerivationStep(
2091
+ lhs = r"\nabla_{\boldsymbol{\beta}}\,\mathrm{RSS}",
2092
+ rhs = r"-2\mathbf{X}^\top(\mathbf{y}-\mathbf{X}\boldsymbol{\beta}) = \mathbf{0}",
2093
+ annotation = "Set gradient to zero",
2094
+ ),
2095
+ TexDerivationStep(
2096
+ lhs = r"\hat{\boldsymbol{\beta}}",
2097
+ rhs = raw.split("=", 1)[1].strip(),
2098
+ annotation = "Normal equations solved",
2099
+ ),
2100
+ ],
2101
+ tags = ["regression", "ols", "plane", "matrix"],
2102
+ )
2103
+
2104
+
2105
+ def _build_plane_ci_formula() -> Optional["TexFormula"]:
2106
+ if not _TEX_AVAILABLE:
2107
+ return None
2108
+ ci_margin = (
2109
+ r"t_{n-p,\,\alpha/2} \cdot \hat{\sigma}"
2110
+ r"\sqrt{\mathbf{x}_0^\top \left(\mathbf{X}^\top\mathbf{X}\right)^{-1} \mathbf{x}_0}"
2111
+ )
2112
+ raw = rf"\hat{{y}}(\mathbf{{x}}_0) \pm {ci_margin}"
2113
+ return TexFormula(
2114
+ name = "plane_ci_formula",
2115
+ raw = raw,
2116
+ description = "Pointwise 95% CI for E[Y|x0] on the regression plane",
2117
+ parts = {
2118
+ "fitted": r"\hat{y}(\mathbf{x}_0)",
2119
+ "t_crit": r"t_{n-p,\,\alpha/2}",
2120
+ "sigma_hat": r"\hat{\sigma}",
2121
+ "leverage_sq": (
2122
+ r"\mathbf{x}_0^\top \left(\mathbf{X}^\top\mathbf{X}\right)^{-1}"
2123
+ r"\mathbf{x}_0"
2124
+ ),
2125
+ "margin": ci_margin,
2126
+ },
2127
+ tags = ["regression", "confidence_interval", "plane"],
2128
+ )
2129
+
2130
+
2131
+ def _build_plane_pi_formula() -> Optional["TexFormula"]:
2132
+ if not _TEX_AVAILABLE:
2133
+ return None
2134
+ pi_margin = (
2135
+ r"t_{n-p,\,\alpha/2} \cdot \hat{\sigma}"
2136
+ r"\sqrt{1 + \mathbf{x}_0^\top \left(\mathbf{X}^\top\mathbf{X}\right)^{-1} \mathbf{x}_0}"
2137
+ )
2138
+ raw = rf"\hat{{y}}(\mathbf{{x}}_0) \pm {pi_margin}"
2139
+ return TexFormula(
2140
+ name = "plane_pi_formula",
2141
+ raw = raw,
2142
+ description = "Pointwise 95% PI for a new observation Y_new at x0",
2143
+ parts = {
2144
+ "fitted": r"\hat{y}(\mathbf{x}_0)",
2145
+ "margin": pi_margin,
2146
+ "extra_1": r"1 +",
2147
+ },
2148
+ steps = [
2149
+ TexDerivationStep(
2150
+ lhs = r"\mathrm{Var}\!\left(Y_{\mathrm{new}} - \hat{y}\right)",
2151
+ rhs = (
2152
+ r"\sigma^2\!\left(1 + "
2153
+ r"\mathbf{x}_0^\top(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{x}_0\right)"
2154
+ ),
2155
+ annotation = "Individual + estimation variance",
2156
+ ),
2157
+ TexDerivationStep(
2158
+ lhs = "PI",
2159
+ rhs = raw.split("\\pm", 1)[0].strip()
2160
+ + r" \pm " + pi_margin,
2161
+ annotation = "Plug in estimated sigma",
2162
+ ),
2163
+ ],
2164
+ tags = ["regression", "prediction_interval", "plane"],
2165
+ )
2166
+
2167
+
2168
+ def _build_rsq_decomp_formula() -> Optional["TexFormula"]:
2169
+ if not _TEX_AVAILABLE:
2170
+ return None
2171
+ raw = (
2172
+ r"\underbrace{\sum(y_i-\bar{y})^2}_{\mathrm{SST}} = "
2173
+ r"\underbrace{\sum(\hat{y}_i-\bar{y})^2}_{\mathrm{SSR}} + "
2174
+ r"\underbrace{\sum(y_i-\hat{y}_i)^2}_{\mathrm{SSE}}"
2175
+ )
2176
+ return TexFormula(
2177
+ name = "sst_decomposition",
2178
+ raw = raw,
2179
+ description = "Total = Regression + Error sum-of-squares decomposition",
2180
+ parts = {
2181
+ "SST": r"\sum(y_i-\bar{y})^2",
2182
+ "SSR": r"\sum(\hat{y}_i-\bar{y})^2",
2183
+ "SSE": r"\sum(y_i-\hat{y}_i)^2",
2184
+ },
2185
+ steps = [
2186
+ TexDerivationStep(
2187
+ lhs = r"y_i - \bar{y}",
2188
+ rhs = r"(\hat{y}_i - \bar{y}) + (y_i - \hat{y}_i)",
2189
+ annotation = "Add and subtract y_hat",
2190
+ ),
2191
+ TexDerivationStep(
2192
+ lhs = r"\sum(y_i-\bar{y})^2",
2193
+ rhs = (
2194
+ r"\sum(\hat{y}_i-\bar{y})^2"
2195
+ r" + \sum(y_i-\hat{y}_i)^2"
2196
+ r" + 2\sum(\hat{y}_i-\bar{y})(y_i-\hat{y}_i)"
2197
+ ),
2198
+ annotation = "Square and expand",
2199
+ ),
2200
+ TexDerivationStep(
2201
+ lhs = "",
2202
+ rhs = (
2203
+ r"= \mathrm{SSR} + \mathrm{SSE}"
2204
+ r"\quad \text{(cross-term = 0 by OLS)}"
2205
+ ),
2206
+ annotation = "Cross-term vanishes",
2207
+ ),
2208
+ ],
2209
+ tags = ["regression", "r_squared", "anova"],
2210
+ )
2211
+
2212
+
2213
+ # Build PLANE_FORMULAS registry
2214
+ PLANE_FORMULAS: Dict[str, "TexFormula"] = {}
2215
+
2216
+ if _TEX_AVAILABLE:
2217
+ _plane_formula_builders = [
2218
+ _build_multiple_regression_formula,
2219
+ _build_plane_ols_formula,
2220
+ _build_plane_ci_formula,
2221
+ _build_plane_pi_formula,
2222
+ _build_rsq_decomp_formula,
2223
+ ]
2224
+ for _builder in _plane_formula_builders:
2225
+ _f = _builder()
2226
+ if _f is not None:
2227
+ PLANE_FORMULAS[_f.name] = _f
2228
+ try:
2229
+ register_formula(_f)
2230
+ except (ValueError, KeyError):
2231
+ pass
2232
+
2233
+
2234
+ # ===========================================================================
2235
+ # Re-export convenience
2236
+ # ===========================================================================
2237
+
2238
+ # Make ols_fit available from this module so callers only need one import
2239
+ try:
2240
+ from statanim.regression.correlation import ols_fit as ols_fit
2241
+ except ImportError:
2242
+ pass
2243
+
2244
+
2245
+ # ===========================================================================
2246
+ # __all__
2247
+ # ===========================================================================
2248
+
2249
+ __all__ = [
2250
+ # Layer A — math helpers
2251
+ "plane_predict",
2252
+ "plane_grid",
2253
+ "ci_surface",
2254
+ "pi_surface",
2255
+ "plane_normal",
2256
+ "tilt_angle_deg",
2257
+ "leverage_grid",
2258
+ "standardise_grid",
2259
+
2260
+ # Layer B — config dataclasses
2261
+ "SurfaceColouring",
2262
+ "PlaneGeometry",
2263
+ "DEFAULT_GEOMETRY",
2264
+ "COMPACT_GEOMETRY",
2265
+ "HIRES_GEOMETRY",
2266
+
2267
+ # Layer C — Manim mobjects
2268
+ "RegressionPlane3D",
2269
+ "ScatterCloud3D",
2270
+ "PlaneResiduals3D",
2271
+ "CIShell3D",
2272
+ "PIShell3D",
2273
+ "ProjectionArrow3D",
2274
+
2275
+ # Layer D — scene-level animations
2276
+ "build_plane_scene",
2277
+ "morph_beta",
2278
+ "sweep_x1",
2279
+ "rotate_view",
2280
+
2281
+ # Layer E — formula registry
2282
+ "PLANE_FORMULAS",
2283
+
2284
+ # Re-export
2285
+ "ols_fit",
2286
+ ]