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,1989 @@
1
+ """
2
+ statanim/axes/axes3d.py
3
+ ==========================
4
+ Master 3-D axes system for the Manim Statistics Extension.
5
+
6
+ Every chart, distribution, regression, and inference asset uses
7
+ ``StatsAxes3D`` as its coordinate backbone.
8
+
9
+ Architecture
10
+ ------------
11
+ StatsAxes3D
12
+ ├── AxisSpine3D — individual X / Y / Z spine with tip
13
+ ├── TickSystem3D — major + minor ticks on one axis
14
+ ├── TickLabelSystem3D — numeric / custom labels for one axis
15
+ ├── GridPlane3D — one face of the grid box (XY / YZ / XZ)
16
+ ├── GridSystem3D — all active grid planes together
17
+ ├── OriginDecoration3D — dot, crosshair, zero-plane highlight
18
+ ├── BoundingBox3D — optional wireframe cube around axes
19
+ ├── ReferenceLineSystem — h-lines, v-lines, planes, brackets
20
+ ├── AnnotationSystem3D — point annotations, region highlights
21
+ └── AxisLabel3D — per-axis MathTex / Text title
22
+
23
+ Coordinate systems
24
+ ------------------
25
+ Data space — the (x, y, z) numbers the user works with
26
+ Scene space — Manim 3-D world units centred at ORIGIN
27
+ Axes map data → scene via ``c2p(x, y, z)`` (coordinate to point)
28
+ and scene → data via ``p2c(px, py, pz)`` (point to coordinate).
29
+
30
+ Scale modes (per axis independently)
31
+ --------------------------------------
32
+ LINEAR — standard linear mapping
33
+ LOG — log₁₀ mapping (x_data > 0 required)
34
+ SYMLOG — signed-log (safe for data crossing zero)
35
+ LOGIT — logit mapping (x_data ∈ (0, 1) required)
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import math
41
+ from dataclasses import dataclass, field
42
+ from enum import Enum, auto
43
+ from typing import (
44
+ Any, Callable, Dict, List, Literal,
45
+ Optional, Sequence, Tuple, Union,
46
+ )
47
+
48
+ import numpy as np
49
+ from numpy.typing import ArrayLike, NDArray
50
+
51
+ from manim import (
52
+ # Mobjects
53
+ VGroup, VMobject, Group, Mobject,
54
+ Line3D, Arrow3D, Dot3D, Sphere, Cylinder,
55
+ Text, MathTex, Tex,
56
+ Line, DashedLine, DashedVMobject,
57
+ Dot, Rectangle, RoundedRectangle,
58
+ SurroundingRectangle, Polygon,
59
+ # Animations
60
+ Animation, AnimationGroup, Succession,
61
+ Create, FadeIn, FadeOut, Write,
62
+ DrawBorderThenFill, GrowArrow,
63
+ Transform, MoveAlongPath,
64
+ UpdateFromAlphaFunc,
65
+ # Constants
66
+ ORIGIN, UP, DOWN, LEFT, RIGHT, IN, OUT,
67
+ X_AXIS, Y_AXIS, Z_AXIS,
68
+ WHITE, BLACK, GRAY, GRAY_A, GRAY_B, GRAY_C,
69
+ DEGREES, PI, TAU,
70
+ # Utilities
71
+ interpolate_color, normalize,
72
+ rotation_matrix, angle_of_vector,
73
+ smooth, rate_functions, there_and_back,
74
+ DecimalNumber, Integer,
75
+ # 3-D
76
+ ThreeDAxes, NumberPlane,
77
+ always_redraw, ValueTracker,
78
+ )
79
+
80
+ from ..core.base import (
81
+ StatsObject3D, StatsProp3D,
82
+ StatsTheme, StatsColorPalette,
83
+ MaterialConfig, MaterialApplicator,
84
+ LabelConfig, LabelAnchor, LabelAttachment,
85
+ AnimationConfig, BuildStyle, DataUpdateMode,
86
+ HighlightStyle, HighlightSystem,
87
+ BoundData, ThemeMode,
88
+ )
89
+ from ..core.math_utils import (
90
+ auto_range, generate_ticks, nice_number, format_stat_value,
91
+ FloatArray,
92
+ )
93
+
94
+
95
+ # ─────────────────────────────────────────────────────────────────────────────
96
+ # 0. ENUMERATIONS & CONFIG DATACLASSES
97
+ # ─────────────────────────────────────────────────────────────────────────────
98
+
99
+ class AxisScaleMode(Enum):
100
+ LINEAR = auto()
101
+ LOG = auto() # log₁₀
102
+ SYMLOG = auto() # signed log
103
+ LOGIT = auto() # logit (0–1 data)
104
+
105
+
106
+ class TickStyle(Enum):
107
+ OUTWARD = auto() # tick extends away from plot area
108
+ INWARD = auto() # tick extends into plot area
109
+ CROSS = auto() # tick extends both ways
110
+
111
+
112
+ class GridStyle(Enum):
113
+ SOLID = auto()
114
+ DASHED = auto()
115
+ DOTTED = auto()
116
+
117
+
118
+ class AxisID(Enum):
119
+ X = "x"
120
+ Y = "y"
121
+ Z = "z"
122
+
123
+
124
+ @dataclass
125
+ class AxisConfig:
126
+ """
127
+ Complete configuration for one axis (X, Y, or Z).
128
+ """
129
+ # Range: (min, max, step). step=None → auto-computed
130
+ range: Tuple[float, float, Optional[float]] = (-5.0, 5.0, None)
131
+ scale_mode: AxisScaleMode = AxisScaleMode.LINEAR
132
+ symlog_thresh: float = 1.0 # linear threshold for SYMLOG
133
+
134
+ # Spine
135
+ visible: bool = True
136
+ spine_color: Optional[str] = None # None → theme.neutral
137
+ spine_width: float = 2.5
138
+ include_tip: bool = True
139
+ tip_length: float = 0.2
140
+ tip_width: float = 0.12
141
+ length: float = 6.0 # scene units
142
+
143
+ # Ticks
144
+ show_major_ticks: bool = True
145
+ show_minor_ticks: bool = True
146
+ major_tick_length: float = 0.18
147
+ minor_tick_length: float = 0.09
148
+ tick_style: TickStyle = TickStyle.OUTWARD
149
+ tick_color: Optional[str] = None # None → spine_color
150
+ minor_per_major: int = 4
151
+ custom_ticks: Optional[List[float]] = None # override auto ticks
152
+
153
+ # Labels
154
+ show_tick_labels: bool = True
155
+ tick_font_size: float = 20
156
+ tick_color_label: Optional[str] = None
157
+ tick_label_offset: float = 0.35
158
+ tick_decimal_places: int = 1
159
+ use_sci_notation: bool = False # force sci notation
160
+ sci_threshold: float = 1e-3 # auto sci if |val| < this
161
+ custom_tick_labels: Optional[Dict[float, str]] = None # val → str overrides
162
+
163
+ # Axis title
164
+ label: str = ""
165
+ label_is_math: bool = True
166
+ label_font_size: float = 28
167
+ label_color: Optional[str] = None
168
+ label_offset: float = 0.6 # beyond last tick label
169
+
170
+ # Extras
171
+ include_zero_line: bool = False
172
+ zero_line_color: Optional[str] = None
173
+ zero_line_width: float = 1.2
174
+ zero_line_opacity: float = 0.5
175
+
176
+
177
+ @dataclass
178
+ class GridConfig:
179
+ """Configuration for the 3-D grid system."""
180
+ show_xy_plane: bool = True
181
+ show_xz_plane: bool = False # floor grid
182
+ show_yz_plane: bool = False
183
+
184
+ style: GridStyle = GridStyle.SOLID
185
+ major_color: Optional[str] = None # None → theme.border
186
+ minor_color: Optional[str] = None
187
+ major_opacity: float = 0.55
188
+ minor_opacity: float = 0.20
189
+ major_width: float = 1.0
190
+ minor_width: float = 0.5
191
+
192
+ # Fade out toward edges
193
+ fade_edges: bool = True
194
+ fade_strength: float = 0.6 # 0 = no fade, 1 = fully transparent at edge
195
+
196
+ # Depth
197
+ z_offset: float = -0.01 # push slightly behind data
198
+
199
+
200
+ @dataclass
201
+ class AxesConfig:
202
+ """
203
+ Top-level configuration for a complete ``StatsAxes3D`` instance.
204
+ Holds sub-configs for each axis and the grid.
205
+ """
206
+ x: AxisConfig = field(default_factory=AxisConfig)
207
+ y: AxisConfig = field(default_factory=lambda: AxisConfig(
208
+ range=(0.0, 1.0, None), length=5.0, label="y"))
209
+ z: AxisConfig = field(default_factory=lambda: AxisConfig(
210
+ range=(-5.0, 5.0, None), length=6.0, label="z",
211
+ visible=False,
212
+ show_tick_labels=False,
213
+ show_major_ticks=False,
214
+ ))
215
+ grid: GridConfig = field(default_factory=GridConfig)
216
+
217
+ # Global scene-space dimensions
218
+ x_length: float = 7.0
219
+ y_length: float = 5.0
220
+ z_length: float = 5.0
221
+
222
+ # Origin
223
+ show_origin_dot: bool = True
224
+ origin_dot_radius: float = 0.055
225
+ origin_dot_color: Optional[str] = None # None → theme.accent
226
+
227
+ # Bounding box
228
+ show_bounding_box: bool = False
229
+ bounding_box_color: Optional[str] = None
230
+ bounding_box_opacity: float = 0.12
231
+ bounding_box_width: float = 0.8
232
+
233
+ # Global appearance
234
+ background_rect: bool = False # filled background rectangle
235
+ background_opacity: float = 0.08
236
+
237
+
238
+ # ─────────────────────────────────────────────────────────────────────────────
239
+ # 1. SCALE TRANSFORMS
240
+ # ─────────────────────────────────────────────────────────────────────────────
241
+
242
+ class ScaleTransform:
243
+ """
244
+ Forward (data → normalised [0,1]) and inverse transforms for each scale mode.
245
+ Used internally by ``StatsAxes3D.c2p()`` and ``p2c()``.
246
+ """
247
+
248
+ @staticmethod
249
+ def forward(
250
+ value: float,
251
+ lo: float,
252
+ hi: float,
253
+ mode: AxisScaleMode,
254
+ thresh: float = 1.0,
255
+ ) -> float:
256
+ """Map *value* ∈ [lo, hi] → [0, 1]."""
257
+ if mode == AxisScaleMode.LINEAR:
258
+ return (value - lo) / (hi - lo) if hi != lo else 0.0
259
+
260
+ elif mode == AxisScaleMode.LOG:
261
+ if lo <= 0:
262
+ raise ValueError("LOG scale requires lo > 0.")
263
+ lv = math.log10(max(value, lo * 1e-9))
264
+ llo = math.log10(lo)
265
+ lhi = math.log10(hi)
266
+ return (lv - llo) / (lhi - llo) if lhi != llo else 0.0
267
+
268
+ elif mode == AxisScaleMode.SYMLOG:
269
+ def _symlog(v: float) -> float:
270
+ if abs(v) <= thresh:
271
+ return v / thresh * math.log10(1 + 1)
272
+ sign = 1 if v > 0 else -1
273
+ return sign * (math.log10(abs(v)) - math.log10(thresh) +
274
+ math.log10(1 + 1))
275
+ sv = _symlog(value)
276
+ slo = _symlog(lo)
277
+ shi = _symlog(hi)
278
+ return (sv - slo) / (shi - slo) if shi != slo else 0.0
279
+
280
+ elif mode == AxisScaleMode.LOGIT:
281
+ v = max(min(value, 1 - 1e-9), 1e-9)
282
+ lv = math.log(v / (1 - v))
283
+ llo = math.log(lo / (1 - lo))
284
+ lhi = math.log(hi / (1 - hi))
285
+ return (lv - llo) / (lhi - llo) if lhi != llo else 0.0
286
+
287
+ return 0.0
288
+
289
+ @staticmethod
290
+ def inverse(
291
+ t: float,
292
+ lo: float,
293
+ hi: float,
294
+ mode: AxisScaleMode,
295
+ thresh: float = 1.0,
296
+ ) -> float:
297
+ """Map *t* ∈ [0, 1] → data value in [lo, hi]."""
298
+ if mode == AxisScaleMode.LINEAR:
299
+ return lo + t * (hi - lo)
300
+
301
+ elif mode == AxisScaleMode.LOG:
302
+ llo = math.log10(lo)
303
+ lhi = math.log10(hi)
304
+ return 10 ** (llo + t * (lhi - llo))
305
+
306
+ elif mode == AxisScaleMode.SYMLOG:
307
+ def _symlog(v: float) -> float:
308
+ if abs(v) <= thresh:
309
+ return v / thresh * math.log10(2)
310
+ sign = 1 if v > 0 else -1
311
+ return sign * (math.log10(abs(v)) - math.log10(thresh) +
312
+ math.log10(2))
313
+ slo = _symlog(lo); shi = _symlog(hi)
314
+ sv = slo + t * (shi - slo)
315
+ c = math.log10(2)
316
+ if abs(sv) <= c:
317
+ return sv / c * thresh
318
+ sign = 1 if sv > 0 else -1
319
+ return sign * (10 ** (abs(sv) - c + math.log10(thresh)))
320
+
321
+ elif mode == AxisScaleMode.LOGIT:
322
+ llo = math.log(lo / (1 - lo))
323
+ lhi = math.log(hi / (1 - hi))
324
+ lv = llo + t * (lhi - llo)
325
+ return 1 / (1 + math.exp(-lv))
326
+
327
+ return lo
328
+
329
+
330
+ # ─────────────────────────────────────────────────────────────────────────────
331
+ # 2. AXIS SPINE
332
+ # ─────────────────────────────────────────────────────────────────────────────
333
+
334
+ class AxisSpine3D(VGroup):
335
+ """
336
+ One 3-D axis spine: a Line3D body + optional Arrow3D tip.
337
+
338
+ The spine runs from ``start`` to ``end`` in scene space.
339
+ A negative extension (``neg_extend``) can push the spine slightly
340
+ past the origin so it covers tick marks that fall at the boundary.
341
+ """
342
+
343
+ def __init__(
344
+ self,
345
+ start: np.ndarray,
346
+ end: np.ndarray,
347
+ cfg: AxisConfig,
348
+ theme: StatsColorPalette,
349
+ neg_extend: float = 0.1,
350
+ ) -> None:
351
+ super().__init__()
352
+ self._cfg = cfg
353
+ self._theme = theme
354
+
355
+ color = cfg.spine_color or theme.neutral
356
+ direction = end - start
357
+ length = np.linalg.norm(direction)
358
+
359
+ # Extend slightly past origin
360
+ unit = direction / length if length > 0 else RIGHT
361
+ body_start = start - unit * neg_extend
362
+
363
+ if cfg.include_tip:
364
+ # Use Arrow3D: shaft + tip
365
+ arrow = Arrow3D(
366
+ start=body_start,
367
+ end=end,
368
+ color=color,
369
+ thickness=cfg.spine_width * 0.008, # Arrow3D uses radius
370
+ tip_length=cfg.tip_length,
371
+ tip_base_radius=cfg.tip_width * 0.6,
372
+ )
373
+ self.add(arrow)
374
+ self._body = arrow
375
+ else:
376
+ line = Line3D(
377
+ start=body_start, end=end,
378
+ color=color,
379
+ thickness=cfg.spine_width * 0.008,
380
+ )
381
+ self.add(line)
382
+ self._body = line
383
+
384
+ self.set_color(color)
385
+
386
+ def set_spine_color(self, color: str) -> None:
387
+ self._body.set_color(color)
388
+
389
+
390
+ # ─────────────────────────────────────────────────────────────────────────────
391
+ # 3. TICK SYSTEM
392
+ # ─────────────────────────────────────────────────────────────────────────────
393
+
394
+ class TickSystem3D(VGroup):
395
+ """
396
+ Major + minor tick marks for one axis.
397
+
398
+ Ticks are short Line3D segments placed perpendicular to the spine
399
+ in the plane of the nearest grid face.
400
+ """
401
+
402
+ def __init__(
403
+ self,
404
+ axis_id: AxisID,
405
+ cfg: AxisConfig,
406
+ axes_cfg: AxesConfig,
407
+ theme: StatsColorPalette,
408
+ c2p_fn: Callable[[float, float, float], np.ndarray],
409
+ ) -> None:
410
+ super().__init__()
411
+ self._axis_id = axis_id
412
+ self._cfg = cfg
413
+ self._theme = theme
414
+ self._c2p = c2p_fn
415
+
416
+ lo, hi, step = self._resolve_range(cfg)
417
+ tick_info = generate_ticks(lo, hi, step,
418
+ cfg.minor_per_major)
419
+ color = cfg.tick_color or cfg.spine_color or theme.neutral
420
+
421
+ if cfg.show_major_ticks:
422
+ for tv in tick_info["major"]:
423
+ tick = self._make_tick(tv, cfg.major_tick_length,
424
+ color, cfg.spine_width * 0.7)
425
+ if tick is not None:
426
+ self.add(tick)
427
+
428
+ if cfg.show_minor_ticks:
429
+ for tv in tick_info["minor"]:
430
+ tick = self._make_tick(tv, cfg.minor_tick_length,
431
+ color, cfg.spine_width * 0.45)
432
+ if tick is not None:
433
+ self.add(tick)
434
+
435
+ # ── helpers ───────────────────────────────────────────────────────────
436
+
437
+ def _resolve_range(
438
+ self, cfg: AxisConfig
439
+ ) -> Tuple[float, float, float]:
440
+ lo, hi, step = cfg.range
441
+ if step is None:
442
+ lo, hi, step = auto_range([lo, hi], padding=0.0, n_ticks=5)
443
+ return lo, hi, step
444
+
445
+ def _make_tick(
446
+ self,
447
+ data_val: float,
448
+ length: float,
449
+ color: str,
450
+ width: float,
451
+ ) -> Optional[Line3D]:
452
+ """Build one tick Line3D at *data_val* along this axis."""
453
+ axis = self._axis_id
454
+ c2p = self._c2p
455
+ style = self._cfg.tick_style
456
+
457
+ # Scene position of the tick centre
458
+ if axis == AxisID.X:
459
+ pos = c2p(data_val, 0.0, 0.0)
460
+ perp = UP # ticks point up (in XY plane)
461
+ elif axis == AxisID.Y:
462
+ pos = c2p(0.0, data_val, 0.0)
463
+ perp = RIGHT
464
+ else:
465
+ pos = c2p(0.0, 0.0, data_val)
466
+ perp = UP
467
+
468
+ if style == TickStyle.OUTWARD:
469
+ start_pt = pos
470
+ end_pt = pos - perp * length # "outside" the axes box
471
+ elif style == TickStyle.INWARD:
472
+ start_pt = pos
473
+ end_pt = pos + perp * length
474
+ else: # CROSS
475
+ start_pt = pos - perp * length * 0.5
476
+ end_pt = pos + perp * length * 0.5
477
+
478
+ try:
479
+ tick = Line3D(start=start_pt, end=end_pt,
480
+ color=color, thickness=width * 0.006)
481
+ return tick
482
+ except Exception:
483
+ return None
484
+
485
+
486
+ # ─────────────────────────────────────────────────────────────────────────────
487
+ # 4. TICK LABEL SYSTEM
488
+ # ─────────────────────────────────────────────────────────────────────────────
489
+
490
+ class TickLabelSystem3D(VGroup):
491
+ """
492
+ Numeric (or custom) labels for the tick marks on one axis.
493
+
494
+ Labels are always-redraw VMobjects that optionally face the camera.
495
+ """
496
+
497
+ def __init__(
498
+ self,
499
+ axis_id: AxisID,
500
+ cfg: AxisConfig,
501
+ theme: StatsColorPalette,
502
+ c2p_fn: Callable[[float, float, float], np.ndarray],
503
+ ) -> None:
504
+ super().__init__()
505
+ self._axis_id = axis_id
506
+ self._cfg = cfg
507
+ self._theme = theme
508
+ self._c2p = c2p_fn
509
+ self._mobs: List[VMobject] = []
510
+
511
+ lo, hi, step = self._resolve_range(cfg)
512
+ tick_info = generate_ticks(lo, hi, step, cfg.minor_per_major)
513
+ color = cfg.tick_color_label or theme.text_secondary
514
+
515
+ for tv, lbl_str in zip(tick_info["major"], tick_info["labels"]):
516
+ # Custom label override
517
+ if cfg.custom_tick_labels and tv in cfg.custom_tick_labels:
518
+ lbl_str = cfg.custom_tick_labels[tv]
519
+ elif cfg.use_sci_notation or abs(tv) > 0 and abs(tv) < cfg.sci_threshold:
520
+ lbl_str = f"{tv:.2e}"
521
+
522
+ mob = self._make_label(tv, lbl_str, color)
523
+ if mob is not None:
524
+ self.add(mob)
525
+ self._mobs.append(mob)
526
+
527
+ # ── helpers ───────────────────────────────────────────────────────────
528
+
529
+ def _resolve_range(
530
+ self, cfg: AxisConfig
531
+ ) -> Tuple[float, float, float]:
532
+ lo, hi, step = cfg.range
533
+ if step is None:
534
+ lo, hi, step = auto_range([lo, hi], padding=0.0, n_ticks=5)
535
+ return lo, hi, step
536
+
537
+ def _make_label(
538
+ self,
539
+ data_val: float,
540
+ text: str,
541
+ color: str,
542
+ ) -> Optional[VMobject]:
543
+ axis = self._axis_id
544
+ c2p = self._c2p
545
+ offset = self._cfg.tick_label_offset
546
+
547
+ if axis == AxisID.X:
548
+ pos = c2p(data_val, 0.0, 0.0) + DOWN * offset
549
+ elif axis == AxisID.Y:
550
+ pos = c2p(0.0, data_val, 0.0) + LEFT * offset
551
+ else:
552
+ pos = c2p(0.0, 0.0, data_val) + LEFT * offset + DOWN * 0.1
553
+
554
+ try:
555
+ mob = Text(text,
556
+ font_size=self._cfg.tick_font_size,
557
+ color=color)
558
+ mob.move_to(pos)
559
+ return mob
560
+ except Exception:
561
+ return None
562
+
563
+
564
+ # ─────────────────────────────────────────────────────────────────────────────
565
+ # 5. AXIS LABEL (TITLE)
566
+ # ─────────────────────────────────────────────────────────────────────────────
567
+
568
+ class AxisLabel3D(VGroup):
569
+ """
570
+ Axis title label with MathTex / Text support and camera-facing rotation.
571
+ Positioned beyond the last tick label, offset along the perpendicular.
572
+ """
573
+
574
+ def __init__(
575
+ self,
576
+ axis_id: AxisID,
577
+ cfg: AxisConfig,
578
+ theme: StatsColorPalette,
579
+ scene_end: np.ndarray, # scene-space end of the axis spine
580
+ ) -> None:
581
+ super().__init__()
582
+ if not cfg.label:
583
+ return
584
+
585
+ color = cfg.label_color or theme.text_primary
586
+ if cfg.label_is_math:
587
+ mob = MathTex(cfg.label,
588
+ font_size=cfg.label_font_size,
589
+ color=color)
590
+ else:
591
+ mob = Text(cfg.label,
592
+ font_size=cfg.label_font_size,
593
+ color=color)
594
+
595
+ # Position beyond spine tip
596
+ if axis_id == AxisID.X:
597
+ mob.next_to(scene_end, RIGHT * cfg.label_offset + DOWN * 0.25)
598
+ elif axis_id == AxisID.Y:
599
+ mob.next_to(scene_end, UP * cfg.label_offset)
600
+ else:
601
+ mob.next_to(scene_end, OUT * cfg.label_offset + RIGHT * 0.3)
602
+
603
+ self.add(mob)
604
+ self._label_mob = mob
605
+
606
+ def get_label_mob(self) -> Optional[VMobject]:
607
+ return getattr(self, "_label_mob", None)
608
+
609
+
610
+ # ─────────────────────────────────────────────────────────────────────────────
611
+ # 6. GRID PLANE
612
+ # ─────────────────────────────────────────────────────────────────────────────
613
+
614
+ class GridPlane3D(VGroup):
615
+ """
616
+ One face of the 3-D grid box.
617
+
618
+ Draws major and minor grid lines on one plane (XY, YZ, or XZ),
619
+ with optional edge-fade opacity gradient.
620
+
621
+ The plane face is parameterised by two axes (``axis_a``, ``axis_b``)
622
+ and a fixed value on the third axis (``fixed_val``, default 0).
623
+ """
624
+
625
+ def __init__(
626
+ self,
627
+ axis_a: AxisID, # "horizontal" axis of this plane
628
+ axis_b: AxisID, # "vertical" axis of this plane
629
+ cfg_a: AxisConfig, # config for axis_a
630
+ cfg_b: AxisConfig, # config for axis_b
631
+ grid_cfg: GridConfig,
632
+ theme: StatsColorPalette,
633
+ c2p_fn: Callable[[float, float, float], np.ndarray],
634
+ fixed_val: float = 0.0,
635
+ ) -> None:
636
+ super().__init__()
637
+ self._theme = theme
638
+ self._grid = grid_cfg
639
+ self._c2p = c2p_fn
640
+
641
+ major_color = grid_cfg.major_color or theme.border
642
+ minor_color = grid_cfg.minor_color or theme.border
643
+
644
+ lo_a, hi_a, step_a = self._resolve(cfg_a)
645
+ lo_b, hi_b, step_b = self._resolve(cfg_b)
646
+
647
+ ticks_a = generate_ticks(lo_a, hi_a, step_a, cfg_a.minor_per_major)
648
+ ticks_b = generate_ticks(lo_b, hi_b, step_b, cfg_b.minor_per_major)
649
+
650
+ # Major gridlines along axis_a (lines parallel to axis_b)
651
+ for val in ticks_a["major"]:
652
+ line = self._make_line(axis_a, axis_b, val,
653
+ lo_b, hi_b, fixed_val,
654
+ major_color, grid_cfg.major_width,
655
+ grid_cfg.major_opacity, grid_cfg.style)
656
+ if line: self.add(line)
657
+
658
+ # Major gridlines along axis_b (lines parallel to axis_a)
659
+ for val in ticks_b["major"]:
660
+ line = self._make_line(axis_b, axis_a, val,
661
+ lo_a, hi_a, fixed_val,
662
+ major_color, grid_cfg.major_width,
663
+ grid_cfg.major_opacity, grid_cfg.style)
664
+ if line: self.add(line)
665
+
666
+ # Minor gridlines along axis_a
667
+ for val in ticks_a["minor"]:
668
+ line = self._make_line(axis_a, axis_b, val,
669
+ lo_b, hi_b, fixed_val,
670
+ minor_color, grid_cfg.minor_width,
671
+ grid_cfg.minor_opacity, grid_cfg.style)
672
+ if line: self.add(line)
673
+
674
+ # Minor gridlines along axis_b
675
+ for val in ticks_b["minor"]:
676
+ line = self._make_line(axis_b, axis_a, val,
677
+ lo_a, hi_a, fixed_val,
678
+ minor_color, grid_cfg.minor_width,
679
+ grid_cfg.minor_opacity, grid_cfg.style)
680
+ if line: self.add(line)
681
+
682
+ # Push plane behind data
683
+ self.shift(self._plane_normal(axis_a, axis_b) * grid_cfg.z_offset)
684
+
685
+ # ── helpers ───────────────────────────────────────────────────────────
686
+
687
+ @staticmethod
688
+ def _resolve(cfg: AxisConfig) -> Tuple[float, float, float]:
689
+ lo, hi, step = cfg.range
690
+ if step is None:
691
+ lo, hi, step = auto_range([lo, hi], padding=0.0, n_ticks=5)
692
+ return lo, hi, step
693
+
694
+ def _coord(
695
+ self,
696
+ fixed_axis: AxisID,
697
+ fixed_val: float,
698
+ free_axis: AxisID,
699
+ free_val: float,
700
+ plane_fixed_val: float,
701
+ ) -> np.ndarray:
702
+ """
703
+ Build a (x, y, z) data coordinate where one axis is fixed at
704
+ *fixed_val*, one runs freely at *free_val*, and the plane's
705
+ constant axis is at *plane_fixed_val*.
706
+ """
707
+ coords: Dict[AxisID, float] = {
708
+ AxisID.X: plane_fixed_val,
709
+ AxisID.Y: plane_fixed_val,
710
+ AxisID.Z: plane_fixed_val,
711
+ }
712
+ coords[fixed_axis] = fixed_val
713
+ coords[free_axis] = free_val
714
+ return self._c2p(coords[AxisID.X], coords[AxisID.Y], coords[AxisID.Z])
715
+
716
+ def _make_line(
717
+ self,
718
+ fixed_axis: AxisID,
719
+ free_axis: AxisID,
720
+ fixed_val: float,
721
+ free_lo: float,
722
+ free_hi: float,
723
+ plane_val: float,
724
+ color: str,
725
+ width: float,
726
+ opacity: float,
727
+ style: GridStyle,
728
+ ) -> Optional[VMobject]:
729
+ """Draw one grid line at *fixed_val* on *fixed_axis*, spanning *free_axis*."""
730
+ try:
731
+ # Determine which axis is the "plane's normal"
732
+ # so we can correctly assign coordinate slots
733
+ used = {fixed_axis, free_axis}
734
+ third = next(a for a in AxisID if a not in used)
735
+
736
+ def _pt(fv: float) -> np.ndarray:
737
+ d: Dict[AxisID, float] = {third: plane_val,
738
+ fixed_axis: fixed_val,
739
+ free_axis: fv}
740
+ return self._c2p(d[AxisID.X], d[AxisID.Y], d[AxisID.Z])
741
+
742
+ p1 = _pt(free_lo)
743
+ p2 = _pt(free_hi)
744
+
745
+ if style == GridStyle.SOLID:
746
+ line = Line3D(start=p1, end=p2,
747
+ color=color,
748
+ thickness=width * 0.005)
749
+ line.set_opacity(opacity)
750
+ elif style == GridStyle.DASHED:
751
+ line = DashedLine(start=p1, end=p2,
752
+ color=color,
753
+ stroke_width=width * 1.2,
754
+ dash_length=0.12)
755
+ line.set_opacity(opacity)
756
+ else: # DOTTED
757
+ line = DashedLine(start=p1, end=p2,
758
+ color=color,
759
+ stroke_width=width,
760
+ dash_length=0.04,
761
+ dashed_ratio=0.3)
762
+ line.set_opacity(opacity)
763
+
764
+ if self._grid.fade_edges:
765
+ # Reduce opacity at end segments (edge fade approximation)
766
+ line.set_opacity(opacity * (1.0 - self._grid.fade_strength * 0.3))
767
+
768
+ return line
769
+ except Exception:
770
+ return None
771
+
772
+ @staticmethod
773
+ def _plane_normal(axis_a: AxisID, axis_b: AxisID) -> np.ndarray:
774
+ """Return a unit vector pointing 'into' the scene for this plane."""
775
+ used = {axis_a, axis_b}
776
+ normal_axis = next(a for a in AxisID if a not in used)
777
+ return {AxisID.X: RIGHT, AxisID.Y: UP, AxisID.Z: OUT}[normal_axis]
778
+
779
+
780
+ # ─────────────────────────────────────────────────────────────────────────────
781
+ # 7. GRID SYSTEM (composite of all planes)
782
+ # ─────────────────────────────────────────────────────────────────────────────
783
+
784
+ class GridSystem3D(VGroup):
785
+ """
786
+ Aggregates all active ``GridPlane3D`` objects.
787
+ """
788
+
789
+ def __init__(
790
+ self,
791
+ axes_cfg: AxesConfig,
792
+ theme: StatsColorPalette,
793
+ c2p_fn: Callable[[float, float, float], np.ndarray],
794
+ ) -> None:
795
+ super().__init__()
796
+ gc = axes_cfg.grid
797
+ xc, yc, zc = axes_cfg.x, axes_cfg.y, axes_cfg.z
798
+
799
+ if gc.show_xy_plane:
800
+ plane = GridPlane3D(AxisID.X, AxisID.Y, xc, yc, gc,
801
+ theme, c2p_fn, fixed_val=0.0)
802
+ self.add(plane)
803
+
804
+ if gc.show_xz_plane:
805
+ lo_y = axes_cfg.y.range[0]
806
+ plane = GridPlane3D(AxisID.X, AxisID.Z, xc, zc, gc,
807
+ theme, c2p_fn, fixed_val=lo_y)
808
+ self.add(plane)
809
+
810
+ if gc.show_yz_plane:
811
+ lo_x = axes_cfg.x.range[0]
812
+ plane = GridPlane3D(AxisID.Y, AxisID.Z, yc, zc, gc,
813
+ theme, c2p_fn, fixed_val=lo_x)
814
+ self.add(plane)
815
+
816
+
817
+ # ─────────────────────────────────────────────────────────────────────────────
818
+ # 8. ORIGIN DECORATION
819
+ # ─────────────────────────────────────────────────────────────────────────────
820
+
821
+ class OriginDecoration3D(VGroup):
822
+ """
823
+ Visual elements at the axes origin:
824
+ • Dot3D sphere
825
+ • Optional crosshair lines (tiny extensions along each axis)
826
+ • Optional zero-plane highlight ring
827
+ """
828
+
829
+ def __init__(
830
+ self,
831
+ cfg: AxesConfig,
832
+ theme: StatsColorPalette,
833
+ c2p_fn: Callable[[float, float, float], np.ndarray],
834
+ ) -> None:
835
+ super().__init__()
836
+ if not cfg.show_origin_dot:
837
+ return
838
+
839
+ origin_pt = c2p_fn(0.0, 0.0, 0.0)
840
+ color = cfg.origin_dot_color or theme.accent
841
+
842
+ # Origin sphere
843
+ dot = Dot3D(point=origin_pt,
844
+ radius=cfg.origin_dot_radius,
845
+ color=color)
846
+ dot.set_opacity(0.9)
847
+ self.add(dot)
848
+
849
+ # Crosshair micro-lines
850
+ ext = 0.15
851
+ for direction, ax_id in [
852
+ (RIGHT, AxisID.X),
853
+ (UP, AxisID.Y),
854
+ (OUT, AxisID.Z),
855
+ ]:
856
+ h1 = Line3D(origin_pt - direction * ext,
857
+ origin_pt + direction * ext,
858
+ color=color,
859
+ thickness=0.004)
860
+ h1.set_opacity(0.5)
861
+ self.add(h1)
862
+
863
+
864
+ # ─────────────────────────────────────────────────────────────────────────────
865
+ # 9. BOUNDING BOX
866
+ # ─────────────────────────────────────────────────────────────────────────────
867
+
868
+ class BoundingBox3D(VGroup):
869
+ """
870
+ Wireframe cube drawn at the boundary of the 3-D axes.
871
+ Useful for communicating the full 3-D data volume.
872
+ """
873
+
874
+ def __init__(
875
+ self,
876
+ axes_cfg: AxesConfig,
877
+ theme: StatsColorPalette,
878
+ c2p_fn: Callable[[float, float, float], np.ndarray],
879
+ ) -> None:
880
+ super().__init__()
881
+ xlo, xhi = axes_cfg.x.range[0], axes_cfg.x.range[1]
882
+ ylo, yhi = axes_cfg.y.range[0], axes_cfg.y.range[1]
883
+ zlo, zhi = axes_cfg.z.range[0], axes_cfg.z.range[1]
884
+
885
+ color = axes_cfg.bounding_box_color or theme.border
886
+ opacity = axes_cfg.bounding_box_opacity
887
+ width = axes_cfg.bounding_box_width
888
+
889
+ corners = {
890
+ "lll": c2p_fn(xlo, ylo, zlo), "lhl": c2p_fn(xlo, yhi, zlo),
891
+ "hll": c2p_fn(xhi, ylo, zlo), "hhl": c2p_fn(xhi, yhi, zlo),
892
+ "llh": c2p_fn(xlo, ylo, zhi), "lhh": c2p_fn(xlo, yhi, zhi),
893
+ "hlh": c2p_fn(xhi, ylo, zhi), "hhh": c2p_fn(xhi, yhi, zhi),
894
+ }
895
+
896
+ edges = [
897
+ # Bottom face
898
+ ("lll","hll"), ("hll","hhl"), ("hhl","lhl"), ("lhl","lll"),
899
+ # Top face
900
+ ("llh","hlh"), ("hlh","hhh"), ("hhh","lhh"), ("lhh","llh"),
901
+ # Verticals
902
+ ("lll","llh"), ("hll","hlh"), ("hhl","hhh"), ("lhl","lhh"),
903
+ ]
904
+
905
+ for a, b in edges:
906
+ edge = Line3D(corners[a], corners[b],
907
+ color=color, thickness=width * 0.005)
908
+ edge.set_opacity(opacity)
909
+ self.add(edge)
910
+
911
+
912
+ # ─────────────────────────────────────────────────────────────────────────────
913
+ # 10. REFERENCE LINE SYSTEM
914
+ # ─────────────────────────────────────────────────────────────────────────────
915
+
916
+ @dataclass
917
+ class ReferenceLineConfig:
918
+ value: float
919
+ axis: AxisID
920
+ color: Optional[str] = None
921
+ width: float = 1.8
922
+ opacity: float = 0.85
923
+ style: GridStyle = GridStyle.DASHED
924
+ label: str = ""
925
+ label_side: Literal["left", "right", "top", "bottom"] = "right"
926
+ label_font_size: float = 22
927
+
928
+
929
+ class ReferenceLineSystem(VGroup):
930
+ """
931
+ Adds horizontal, vertical, or z-level reference lines to the axes.
932
+
933
+ Typical uses:
934
+ - Mean / median lines on a histogram
935
+ - Alpha threshold on a p-value axis
936
+ - Decision boundary on a classification plot
937
+ """
938
+
939
+ def __init__(
940
+ self,
941
+ theme: StatsColorPalette,
942
+ c2p_fn: Callable[[float, float, float], np.ndarray],
943
+ axes_cfg: AxesConfig,
944
+ ) -> None:
945
+ super().__init__()
946
+ self._theme = theme
947
+ self._c2p = c2p_fn
948
+ self._axes = axes_cfg
949
+ self._lines: Dict[str, VGroup] = {}
950
+
951
+ def add_line(self, key: str, cfg: ReferenceLineConfig) -> VGroup:
952
+ """
953
+ Draw one reference line and optionally label it.
954
+ Returns the VGroup of [line, label] for external animation.
955
+ """
956
+ color = cfg.color or self._theme.accent
957
+ xlo, xhi = self._axes.x.range[:2]
958
+ ylo, yhi = self._axes.y.range[:2]
959
+ zlo, zhi = self._axes.z.range[:2]
960
+
961
+ if cfg.axis == AxisID.Y:
962
+ p1 = self._c2p(xlo, cfg.value, 0.0)
963
+ p2 = self._c2p(xhi, cfg.value, 0.0)
964
+ elif cfg.axis == AxisID.X:
965
+ p1 = self._c2p(cfg.value, ylo, 0.0)
966
+ p2 = self._c2p(cfg.value, yhi, 0.0)
967
+ else:
968
+ p1 = self._c2p(0.0, ylo, cfg.value)
969
+ p2 = self._c2p(0.0, yhi, cfg.value)
970
+
971
+ if cfg.style == GridStyle.SOLID:
972
+ line = Line3D(p1, p2, color=color,
973
+ thickness=cfg.width * 0.007)
974
+ else:
975
+ line = DashedLine(p1, p2, color=color,
976
+ stroke_width=cfg.width * 1.4,
977
+ dash_length=0.15)
978
+ line.set_opacity(cfg.opacity)
979
+
980
+ grp = VGroup(line)
981
+
982
+ if cfg.label:
983
+ lbl_pos = p2 + {
984
+ "right": RIGHT * 0.25,
985
+ "left": LEFT * 0.25,
986
+ "top": UP * 0.25,
987
+ "bottom": DOWN * 0.25,
988
+ }.get(cfg.label_side, RIGHT * 0.25)
989
+ lbl = Text(cfg.label,
990
+ font_size=cfg.label_font_size,
991
+ color=color)
992
+ lbl.move_to(lbl_pos)
993
+ grp.add(lbl)
994
+
995
+ self._lines[key] = grp
996
+ self.add(grp)
997
+ return grp
998
+
999
+ def remove_line(self, key: str) -> None:
1000
+ if key in self._lines:
1001
+ self.remove(self._lines.pop(key))
1002
+
1003
+ def update_line_value(self, key: str, new_value: float) -> None:
1004
+ """Remove and redraw a reference line at a new data value."""
1005
+ if key in self._lines:
1006
+ cfg_old = self._lines[key]
1007
+ self.remove_line(key)
1008
+
1009
+ def add_span(
1010
+ self,
1011
+ key: str,
1012
+ lo: float,
1013
+ hi: float,
1014
+ axis: AxisID,
1015
+ color: Optional[str] = None,
1016
+ opacity: float = 0.18,
1017
+ label: str = "",
1018
+ label_font_size: float = 20,
1019
+ ) -> VGroup:
1020
+ """
1021
+ Shade a region between *lo* and *hi* along *axis*.
1022
+ Returns the shaded VGroup.
1023
+ """
1024
+ c = color or self._theme.accent
1025
+ xlo, xhi = self._axes.x.range[:2]
1026
+ ylo, yhi = self._axes.y.range[:2]
1027
+
1028
+ if axis == AxisID.X:
1029
+ corners = [
1030
+ self._c2p(lo, ylo, 0), self._c2p(hi, ylo, 0),
1031
+ self._c2p(hi, yhi, 0), self._c2p(lo, yhi, 0),
1032
+ ]
1033
+ else: # Y axis span
1034
+ corners = [
1035
+ self._c2p(xlo, lo, 0), self._c2p(xhi, lo, 0),
1036
+ self._c2p(xhi, hi, 0), self._c2p(xlo, hi, 0),
1037
+ ]
1038
+
1039
+ poly = Polygon(*corners)
1040
+ poly.set_fill(c, opacity=opacity)
1041
+ poly.set_stroke(c, width=1.0, opacity=opacity * 1.5)
1042
+
1043
+ grp = VGroup(poly)
1044
+
1045
+ if label:
1046
+ mid_x = (lo + hi) / 2
1047
+ mid_y = (ylo + yhi) / 2
1048
+ if axis == AxisID.X:
1049
+ lbl_pt = self._c2p(mid_x, yhi, 0) + UP * 0.2
1050
+ else:
1051
+ lbl_pt = self._c2p(xhi, mid_y, 0) + RIGHT * 0.2
1052
+ lbl = Text(label, font_size=label_font_size, color=c)
1053
+ lbl.move_to(lbl_pt)
1054
+ grp.add(lbl)
1055
+
1056
+ self._lines[key] = grp
1057
+ self.add(grp)
1058
+ return grp
1059
+
1060
+ def add_bracket(
1061
+ self,
1062
+ key: str,
1063
+ lo: float,
1064
+ hi: float,
1065
+ axis: AxisID,
1066
+ color: Optional[str] = None,
1067
+ offset: float = 0.4,
1068
+ label: str = "",
1069
+ label_font_size: float = 22,
1070
+ ) -> VGroup:
1071
+ """
1072
+ Draw a bracket indicating a span [lo, hi] along *axis*,
1073
+ offset from the axis by *offset* scene units.
1074
+ Useful for annotating IQR, CI, critical regions.
1075
+ """
1076
+ c = color or self._theme.accent
1077
+ yval = self._axes.y.range[0] - offset # below x-axis
1078
+
1079
+ if axis == AxisID.X:
1080
+ p_lo = self._c2p(lo, yval, 0)
1081
+ p_hi = self._c2p(hi, yval, 0)
1082
+ mid = self._c2p((lo + hi) / 2, yval, 0)
1083
+ # Bracket shape: p_lo─────p_hi with tiny serifs
1084
+ bar = Line3D(p_lo, p_hi, color=c, thickness=0.01)
1085
+ s_lo = Line3D(p_lo, p_lo + UP * 0.15, color=c, thickness=0.008)
1086
+ s_hi = Line3D(p_hi, p_hi + UP * 0.15, color=c, thickness=0.008)
1087
+ grp = VGroup(bar, s_lo, s_hi)
1088
+ else:
1089
+ # Vertical bracket
1090
+ p_lo = self._c2p(self._axes.x.range[0] - offset, lo, 0)
1091
+ p_hi = self._c2p(self._axes.x.range[0] - offset, hi, 0)
1092
+ mid = self._c2p(self._axes.x.range[0] - offset, (lo + hi)/2, 0)
1093
+ bar = Line3D(p_lo, p_hi, color=c, thickness=0.01)
1094
+ s_lo = Line3D(p_lo, p_lo + RIGHT * 0.15, color=c, thickness=0.008)
1095
+ s_hi = Line3D(p_hi, p_hi + RIGHT * 0.15, color=c, thickness=0.008)
1096
+ grp = VGroup(bar, s_lo, s_hi)
1097
+
1098
+ if label:
1099
+ lbl = Text(label, font_size=label_font_size, color=c)
1100
+ lbl.move_to(mid + DOWN * 0.35 if axis == AxisID.X
1101
+ else mid + LEFT * 0.4)
1102
+ grp.add(lbl)
1103
+
1104
+ self._lines[key] = grp
1105
+ self.add(grp)
1106
+ return grp
1107
+
1108
+
1109
+ # ─────────────────────────────────────────────────────────────────────────────
1110
+ # 11. ANNOTATION SYSTEM
1111
+ # ─────────────────────────────────────────────────────────────────────────────
1112
+
1113
+ @dataclass
1114
+ class PointAnnotationConfig:
1115
+ x: float
1116
+ y: float
1117
+ z: float = 0.0
1118
+ label: str = ""
1119
+ label_is_math: bool = False
1120
+ dot_color: Optional[str] = None
1121
+ dot_radius: float = 0.08
1122
+ line_color: Optional[str] = None
1123
+ line_style: GridStyle = GridStyle.DASHED
1124
+ line_width: float = 1.5
1125
+ line_opacity: float = 0.7
1126
+ label_offset: np.ndarray = field(default_factory=lambda: np.array([0.3, 0.3, 0.0]))
1127
+ label_font_size: float = 22
1128
+ show_drop_lines: bool = True # drop lines to axes
1129
+ drop_line_opacity: float = 0.35
1130
+
1131
+
1132
+ class AnnotationSystem3D(VGroup):
1133
+ """
1134
+ Point annotations, drop lines, and region labels for 3-D axes.
1135
+
1136
+ Each annotation consists of:
1137
+ • A Dot3D at the data point
1138
+ • A text/math label with a leader line
1139
+ • Optional drop lines to the axis planes (like a 3-D coordinate cross)
1140
+ """
1141
+
1142
+ def __init__(
1143
+ self,
1144
+ theme: StatsColorPalette,
1145
+ c2p_fn: Callable[[float, float, float], np.ndarray],
1146
+ axes_cfg: AxesConfig,
1147
+ ) -> None:
1148
+ super().__init__()
1149
+ self._theme = theme
1150
+ self._c2p = c2p_fn
1151
+ self._axes = axes_cfg
1152
+ self._annotations: Dict[str, VGroup] = {}
1153
+
1154
+ def add_point(self, key: str, cfg: PointAnnotationConfig) -> VGroup:
1155
+ """Annotate a data point at (x, y, z)."""
1156
+ t = self._theme
1157
+ color = cfg.dot_color or t.accent
1158
+
1159
+ scene_pt = self._c2p(cfg.x, cfg.y, cfg.z)
1160
+ dot = Dot3D(scene_pt, radius=cfg.dot_radius, color=color)
1161
+ grp = VGroup(dot)
1162
+
1163
+ # Leader line + label
1164
+ if cfg.label:
1165
+ label_pt = scene_pt + cfg.label_offset
1166
+ if cfg.line_style == GridStyle.DASHED:
1167
+ leader = DashedLine(scene_pt, label_pt,
1168
+ color=cfg.line_color or color,
1169
+ stroke_width=cfg.line_width,
1170
+ dash_length=0.08)
1171
+ else:
1172
+ leader = Line3D(scene_pt, label_pt,
1173
+ color=cfg.line_color or color,
1174
+ thickness=cfg.line_width * 0.004)
1175
+ leader.set_opacity(cfg.line_opacity)
1176
+
1177
+ mob_cls = MathTex if cfg.label_is_math else Text
1178
+ lbl = mob_cls(cfg.label,
1179
+ font_size=cfg.label_font_size,
1180
+ color=color)
1181
+ lbl.move_to(label_pt + RIGHT * lbl.width / 2 + UP * 0.05)
1182
+ grp.add(leader, lbl)
1183
+
1184
+ # Drop lines to the three axis planes
1185
+ if cfg.show_drop_lines:
1186
+ origin = self._c2p(0, 0, 0)
1187
+ xlo = self._axes.x.range[0]
1188
+ ylo = self._axes.y.range[0]
1189
+
1190
+ for end_pt, opacity in [
1191
+ (self._c2p(cfg.x, ylo, cfg.z), cfg.drop_line_opacity), # to XZ floor
1192
+ (self._c2p(xlo, cfg.y, cfg.z), cfg.drop_line_opacity), # to YZ wall
1193
+ (self._c2p(cfg.x, cfg.y, 0.0), cfg.drop_line_opacity), # to XY back
1194
+ ]:
1195
+ dl = DashedLine(scene_pt, end_pt,
1196
+ color=t.neutral,
1197
+ stroke_width=0.9,
1198
+ dash_length=0.07)
1199
+ dl.set_opacity(opacity)
1200
+ grp.add(dl)
1201
+
1202
+ self._annotations[key] = grp
1203
+ self.add(grp)
1204
+ return grp
1205
+
1206
+ def remove_annotation(self, key: str) -> None:
1207
+ if key in self._annotations:
1208
+ self.remove(self._annotations.pop(key))
1209
+
1210
+ def add_region_label(
1211
+ self,
1212
+ key: str,
1213
+ x: float,
1214
+ y: float,
1215
+ label: str,
1216
+ color: Optional[str] = None,
1217
+ font_size: float = 24,
1218
+ bg: bool = True,
1219
+ ) -> VMobject:
1220
+ """
1221
+ Floating label at (x, y) with optional pill background.
1222
+ Useful for labelling distribution regions (e.g. "Rejection Region").
1223
+ """
1224
+ t = self._theme
1225
+ c = color or t.text_primary
1226
+ pos = self._c2p(x, y, 0.0)
1227
+
1228
+ mob = Text(label, font_size=font_size, color=c)
1229
+ mob.move_to(pos)
1230
+
1231
+ if bg:
1232
+ bg_rect = RoundedRectangle(
1233
+ corner_radius=0.12,
1234
+ width=mob.width + 0.3,
1235
+ height=mob.height + 0.2,
1236
+ )
1237
+ bg_rect.set_fill(t.surface, opacity=0.8)
1238
+ bg_rect.set_stroke(c, width=1.2, opacity=0.6)
1239
+ bg_rect.move_to(mob)
1240
+ grp = VGroup(bg_rect, mob)
1241
+ else:
1242
+ grp = VGroup(mob)
1243
+
1244
+ self._annotations[key] = grp
1245
+ self.add(grp)
1246
+ return grp
1247
+
1248
+
1249
+ # ─────────────────────────────────────────────────────────────────────────────
1250
+ # 12. ZERO LINES
1251
+ # ─────────────────────────────────────────────────────────────────────────────
1252
+
1253
+ class ZeroLines3D(VGroup):
1254
+ """
1255
+ Optional zero-crossing lines (x=0, y=0 spine extensions)
1256
+ drawn with reduced opacity when the data range crosses zero.
1257
+ Used for signed data axes like z-scores, residuals, log-ratios.
1258
+ """
1259
+
1260
+ def __init__(
1261
+ self,
1262
+ axes_cfg: AxesConfig,
1263
+ theme: StatsColorPalette,
1264
+ c2p_fn: Callable[[float, float, float], np.ndarray],
1265
+ ) -> None:
1266
+ super().__init__()
1267
+ for axis_id, axis_cfg in [
1268
+ (AxisID.X, axes_cfg.x),
1269
+ (AxisID.Y, axes_cfg.y),
1270
+ ]:
1271
+ if not axis_cfg.include_zero_line:
1272
+ continue
1273
+ lo, hi = axis_cfg.range[:2]
1274
+ if lo >= 0 or hi <= 0:
1275
+ continue # zero not in range — nothing to do
1276
+ color = axis_cfg.zero_line_color or theme.neutral
1277
+ if axis_id == AxisID.X:
1278
+ p1 = c2p_fn(0.0, axes_cfg.y.range[0], 0.0)
1279
+ p2 = c2p_fn(0.0, axes_cfg.y.range[1], 0.0)
1280
+ else:
1281
+ p1 = c2p_fn(axes_cfg.x.range[0], 0.0, 0.0)
1282
+ p2 = c2p_fn(axes_cfg.x.range[1], 0.0, 0.0)
1283
+ line = Line3D(p1, p2, color=color,
1284
+ thickness=axis_cfg.zero_line_width * 0.005)
1285
+ line.set_opacity(axis_cfg.zero_line_opacity)
1286
+ self.add(line)
1287
+
1288
+
1289
+ # ─────────────────────────────────────────────────────────────────────────────
1290
+ # 13. MASTER CLASS — StatsAxes3D
1291
+ # ─────────────────────────────────────────────────────────────────────────────
1292
+
1293
+ class StatsAxes3D(StatsObject3D):
1294
+ """
1295
+ Master 3-D axes object for the Manim Statistics Extension.
1296
+
1297
+ Every chart, histogram, distribution, scatter, and inference asset
1298
+ owns a ``StatsAxes3D`` for its coordinate system.
1299
+
1300
+ Quick start
1301
+ -----------
1302
+ ::
1303
+
1304
+ axes = StatsAxes3D(
1305
+ x_range=(-3, 3, 1),
1306
+ y_range=(0, 0.5, 0.1),
1307
+ x_label="x",
1308
+ y_label="f(x)",
1309
+ )
1310
+ scene.add(axes)
1311
+ scene.play(axes.animate_build())
1312
+
1313
+ Or use a preset factory::
1314
+
1315
+ axes = StatsAxes3D.for_distribution(
1316
+ x_range=(-4, 4, 1),
1317
+ y_range=(0, 0.45, 0.1),
1318
+ )
1319
+
1320
+ Coordinate transform
1321
+ --------------------
1322
+ ``axes.c2p(x, y, z)`` → scene np.ndarray
1323
+ ``axes.p2c(px, py, pz)`` → data (x, y, z) tuple
1324
+
1325
+ Adding reference lines
1326
+ ----------------------
1327
+ ::
1328
+
1329
+ axes.add_h_line("mean", value=0.0, label=r"\\mu", color=BLUE)
1330
+ axes.add_v_line("alpha", value=1.96, label=r"z_{\\alpha/2}")
1331
+ axes.add_span("ci", lo=-1.96, hi=1.96, axis=AxisID.X)
1332
+
1333
+ Annotating points
1334
+ -----------------
1335
+ ::
1336
+
1337
+ axes.annotate_point("mode", x=0, y=0.4,
1338
+ label="Mode", show_drop_lines=True)
1339
+ """
1340
+
1341
+ def __init__(
1342
+ self,
1343
+ # Convenience shortcuts (override AxesConfig if supplied)
1344
+ x_range: Optional[Tuple[float, float, float]] = None,
1345
+ y_range: Optional[Tuple[float, float, float]] = None,
1346
+ z_range: Optional[Tuple[float, float, float]] = None,
1347
+ x_label: Optional[str] = None,
1348
+ y_label: Optional[str] = None,
1349
+ z_label: Optional[str] = None,
1350
+ x_length: float = 7.0,
1351
+ y_length: float = 5.0,
1352
+ z_length: float = 5.0,
1353
+ # Full config override
1354
+ axes_config: Optional[AxesConfig] = None,
1355
+ # base class pass-through
1356
+ **kwargs,
1357
+ ) -> None:
1358
+
1359
+ # ── resolve config ────────────────────────────────────────────────
1360
+ cfg = axes_config or AxesConfig()
1361
+
1362
+ if x_range is not None: cfg.x.range = x_range
1363
+ if y_range is not None: cfg.y.range = y_range
1364
+ if z_range is not None: cfg.z.range = z_range
1365
+ if x_label is not None: cfg.x.label = x_label
1366
+ if y_label is not None: cfg.y.label = y_label
1367
+ if z_label is not None: cfg.z.label = z_label
1368
+ cfg.x_length = x_length
1369
+ cfg.y_length = y_length
1370
+ cfg.z_length = z_length
1371
+
1372
+ self._axes_cfg = cfg
1373
+
1374
+ # Scene-space axis lengths mapped from config
1375
+ self._x_length = x_length
1376
+ self._y_length = y_length
1377
+ self._z_length = z_length
1378
+
1379
+ # Sub-system handles (populated in _build_geometry)
1380
+ self.spines: VGroup = VGroup()
1381
+ self.tick_system: VGroup = VGroup()
1382
+ self.label_system: VGroup = VGroup()
1383
+ self.grid: GridSystem3D = None # type: ignore[assignment]
1384
+ self.origin_deco: OriginDecoration3D = None # type: ignore[assignment]
1385
+ self.bbox: BoundingBox3D = None # type: ignore[assignment]
1386
+ self.ref_lines: ReferenceLineSystem = None # type: ignore[assignment]
1387
+ self.annotations: AnnotationSystem3D = None # type: ignore[assignment]
1388
+ self.zero_lines: ZeroLines3D = None # type: ignore[assignment]
1389
+
1390
+ super().__init__(**kwargs)
1391
+
1392
+ # ── geometry build ────────────────────────────────────────────────────
1393
+
1394
+ def _build_geometry(self) -> None:
1395
+ cfg = self._axes_cfg
1396
+ theme = self._palette
1397
+
1398
+ # ── spines ────────────────────────────────────────────────────────
1399
+ ox = self.c2p(cfg.x.range[0], 0, 0)
1400
+ ex = self.c2p(cfg.x.range[1], 0, 0)
1401
+ oy = self.c2p(0, cfg.y.range[0], 0)
1402
+ ey = self.c2p(0, cfg.y.range[1], 0)
1403
+ oz = self.c2p(0, 0, cfg.z.range[0])
1404
+ ez = self.c2p(0, 0, cfg.z.range[1])
1405
+
1406
+ if cfg.x.visible:
1407
+ sx = AxisSpine3D(ox, ex, cfg.x, theme)
1408
+ self.spines.add(sx)
1409
+ if cfg.y.visible:
1410
+ sy = AxisSpine3D(oy, ey, cfg.y, theme)
1411
+ self.spines.add(sy)
1412
+ if cfg.z.visible:
1413
+ sz = AxisSpine3D(oz, ez, cfg.z, theme)
1414
+ self.spines.add(sz)
1415
+ self.add(self.spines)
1416
+
1417
+ # ── ticks ─────────────────────────────────────────────────────────
1418
+ for axis_id, axis_cfg in [
1419
+ (AxisID.X, cfg.x),
1420
+ (AxisID.Y, cfg.y),
1421
+ (AxisID.Z, cfg.z),
1422
+ ]:
1423
+ if axis_cfg.visible:
1424
+ ts = TickSystem3D(axis_id, axis_cfg, cfg, theme, self.c2p)
1425
+ self.tick_system.add(ts)
1426
+ self.add(self.tick_system)
1427
+
1428
+ # ── tick labels ───────────────────────────────────────────────────
1429
+ for axis_id, axis_cfg in [
1430
+ (AxisID.X, cfg.x),
1431
+ (AxisID.Y, cfg.y),
1432
+ (AxisID.Z, cfg.z),
1433
+ ]:
1434
+ if axis_cfg.visible and axis_cfg.show_tick_labels:
1435
+ tls = TickLabelSystem3D(axis_id, axis_cfg, theme, self.c2p)
1436
+ self.label_system.add(tls)
1437
+ self.add(self.label_system)
1438
+
1439
+ # ── axis title labels ─────────────────────────────────────────────
1440
+ axis_titles = VGroup()
1441
+ for axis_id, axis_cfg, spine_end in [
1442
+ (AxisID.X, cfg.x, ex),
1443
+ (AxisID.Y, cfg.y, ey),
1444
+ (AxisID.Z, cfg.z, ez),
1445
+ ]:
1446
+ if axis_cfg.visible and axis_cfg.label:
1447
+ al = AxisLabel3D(axis_id, axis_cfg, theme, spine_end)
1448
+ axis_titles.add(al)
1449
+ self.add(axis_titles)
1450
+
1451
+ # ── grid ──────────────────────────────────────────────────────────
1452
+ self.grid = GridSystem3D(cfg, theme, self.c2p)
1453
+ self.add(self.grid)
1454
+
1455
+ # ── origin decoration ─────────────────────────────────────────────
1456
+ self.origin_deco = OriginDecoration3D(cfg, theme, self.c2p)
1457
+ self.add(self.origin_deco)
1458
+
1459
+ # ── bounding box ──────────────────────────────────────────────────
1460
+ if cfg.show_bounding_box:
1461
+ self.bbox = BoundingBox3D(cfg, theme, self.c2p)
1462
+ self.add(self.bbox)
1463
+
1464
+ # ── reference lines & annotations (empty at build time) ───────────
1465
+ self.ref_lines = ReferenceLineSystem(theme, self.c2p, cfg)
1466
+ self.annotations = AnnotationSystem3D(theme, self.c2p, cfg)
1467
+ self.zero_lines = ZeroLines3D(cfg, theme, self.c2p)
1468
+ self.add(self.ref_lines)
1469
+ self.add(self.annotations)
1470
+ self.add(self.zero_lines)
1471
+
1472
+ # ── coordinate transforms ─────────────────────────────────────────────
1473
+
1474
+ def c2p(self, x: float, y: float, z: float = 0.0) -> np.ndarray:
1475
+ """
1476
+ Data coordinates → scene 3-D point (np.ndarray).
1477
+ Handles linear, log, symlog, logit per-axis independently.
1478
+ """
1479
+ cfg = self._axes_cfg
1480
+
1481
+ tx = ScaleTransform.forward(
1482
+ x, cfg.x.range[0], cfg.x.range[1],
1483
+ cfg.x.scale_mode, cfg.x.symlog_thresh,
1484
+ )
1485
+ ty = ScaleTransform.forward(
1486
+ y, cfg.y.range[0], cfg.y.range[1],
1487
+ cfg.y.scale_mode, cfg.y.symlog_thresh,
1488
+ )
1489
+ tz = ScaleTransform.forward(
1490
+ z, cfg.z.range[0], cfg.z.range[1],
1491
+ cfg.z.scale_mode, cfg.z.symlog_thresh,
1492
+ ) if cfg.z.visible else 0.0
1493
+
1494
+ # Map [0,1] → scene length, centred at ORIGIN
1495
+ px = (tx - 0.5) * self._x_length
1496
+ py = (ty - 0.5) * self._y_length
1497
+ pz = (tz - 0.5) * self._z_length if cfg.z.visible else 0.0
1498
+
1499
+ return np.array([px, py, pz])
1500
+
1501
+ def p2c(
1502
+ self, px: float, py: float, pz: float = 0.0
1503
+ ) -> Tuple[float, float, float]:
1504
+ """
1505
+ Scene 3-D point → data coordinates.
1506
+ """
1507
+ cfg = self._axes_cfg
1508
+
1509
+ tx = px / self._x_length + 0.5
1510
+ ty = py / self._y_length + 0.5
1511
+ tz = pz / self._z_length + 0.5 if cfg.z.visible else 0.5
1512
+
1513
+ x = ScaleTransform.inverse(tx, cfg.x.range[0], cfg.x.range[1],
1514
+ cfg.x.scale_mode, cfg.x.symlog_thresh)
1515
+ y = ScaleTransform.inverse(ty, cfg.y.range[0], cfg.y.range[1],
1516
+ cfg.y.scale_mode, cfg.y.symlog_thresh)
1517
+ z = ScaleTransform.inverse(tz, cfg.z.range[0], cfg.z.range[1],
1518
+ cfg.z.scale_mode, cfg.z.symlog_thresh)
1519
+ return x, y, z
1520
+
1521
+ def data_to_scene_length(self, data_delta: float, axis: AxisID) -> float:
1522
+ """
1523
+ Convert a data-space distance to a scene-space length.
1524
+ Useful for sizing bars, error-bar heights, etc.
1525
+ For non-linear scales this is an approximation at the midpoint.
1526
+ """
1527
+ cfg = self._axes_cfg
1528
+ ax_cfg = {AxisID.X: cfg.x, AxisID.Y: cfg.y, AxisID.Z: cfg.z}[axis]
1529
+ lo, hi = ax_cfg.range[:2]
1530
+ mid = (lo + hi) / 2
1531
+ p1 = self.c2p(*{AxisID.X: (mid, 0, 0),
1532
+ AxisID.Y: (0, mid, 0),
1533
+ AxisID.Z: (0, 0, mid)}[axis])
1534
+ p2 = self.c2p(*{AxisID.X: (mid + data_delta, 0, 0),
1535
+ AxisID.Y: (0, mid + data_delta, 0),
1536
+ AxisID.Z: (0, 0, mid + data_delta)}[axis])
1537
+ return float(np.linalg.norm(p2 - p1))
1538
+
1539
+ # ── reference line convenience API ────────────────────────────────────
1540
+
1541
+ def add_h_line(
1542
+ self,
1543
+ key: str,
1544
+ value: float,
1545
+ color: Optional[str] = None,
1546
+ width: float = 1.8,
1547
+ opacity: float = 0.85,
1548
+ style: GridStyle = GridStyle.DASHED,
1549
+ label: str = "",
1550
+ ) -> VGroup:
1551
+ """Add a horizontal reference line at y = *value*."""
1552
+ cfg = ReferenceLineConfig(
1553
+ value=value, axis=AxisID.Y,
1554
+ color=color, width=width, opacity=opacity,
1555
+ style=style, label=label,
1556
+ )
1557
+ return self.ref_lines.add_line(key, cfg)
1558
+
1559
+ def add_v_line(
1560
+ self,
1561
+ key: str,
1562
+ value: float,
1563
+ color: Optional[str] = None,
1564
+ width: float = 1.8,
1565
+ opacity: float = 0.85,
1566
+ style: GridStyle = GridStyle.DASHED,
1567
+ label: str = "",
1568
+ ) -> VGroup:
1569
+ """Add a vertical reference line at x = *value*."""
1570
+ cfg = ReferenceLineConfig(
1571
+ value=value, axis=AxisID.X,
1572
+ color=color, width=width, opacity=opacity,
1573
+ style=style, label=label,
1574
+ )
1575
+ return self.ref_lines.add_line(key, cfg)
1576
+
1577
+ def add_span(
1578
+ self,
1579
+ key: str,
1580
+ lo: float,
1581
+ hi: float,
1582
+ axis: AxisID = AxisID.X,
1583
+ color: Optional[str] = None,
1584
+ opacity: float = 0.18,
1585
+ label: str = "",
1586
+ ) -> VGroup:
1587
+ """Shade a region between *lo* and *hi* along *axis*."""
1588
+ return self.ref_lines.add_span(key, lo, hi, axis,
1589
+ color, opacity, label)
1590
+
1591
+ def add_bracket(
1592
+ self,
1593
+ key: str,
1594
+ lo: float,
1595
+ hi: float,
1596
+ axis: AxisID = AxisID.X,
1597
+ color: Optional[str] = None,
1598
+ offset: float = 0.4,
1599
+ label: str = "",
1600
+ ) -> VGroup:
1601
+ """Draw a bracket indicating span [lo, hi] along *axis*."""
1602
+ return self.ref_lines.add_bracket(key, lo, hi, axis,
1603
+ color, offset, label)
1604
+
1605
+ def annotate_point(
1606
+ self,
1607
+ key: str,
1608
+ x: float,
1609
+ y: float,
1610
+ z: float = 0.0,
1611
+ label: str = "",
1612
+ show_drop_lines: bool = True,
1613
+ label_is_math: bool = False,
1614
+ color: Optional[str] = None,
1615
+ label_offset: Optional[np.ndarray] = None,
1616
+ ) -> VGroup:
1617
+ """Annotate a data point with a dot, leader line, and label."""
1618
+ offset = label_offset if label_offset is not None \
1619
+ else np.array([0.3, 0.3, 0.0])
1620
+ cfg = PointAnnotationConfig(
1621
+ x=x, y=y, z=z,
1622
+ label=label,
1623
+ label_is_math=label_is_math,
1624
+ dot_color=color,
1625
+ line_color=color,
1626
+ show_drop_lines=show_drop_lines,
1627
+ label_offset=offset,
1628
+ )
1629
+ return self.annotations.add_point(key, cfg)
1630
+
1631
+ # ── animations ────────────────────────────────────────────────────────
1632
+
1633
+ def animate_build(
1634
+ self, cfg: Optional[AnimationConfig] = None
1635
+ ) -> Animation:
1636
+ """
1637
+ Reveal the axes in a structured sequence:
1638
+ 1. Grid planes fade in softly
1639
+ 2. Spines grow outward from origin
1640
+ 3. Ticks and labels write themselves
1641
+ 4. Origin dot pulses once
1642
+ """
1643
+ cfg = cfg or self._anim_cfg
1644
+ t = cfg.run_time
1645
+
1646
+ grid_in = FadeIn(self.grid, run_time=t * 0.4,
1647
+ rate_func=smooth)
1648
+ spines_in = AnimationGroup(
1649
+ *[Create(s, run_time=t * 0.5, rate_func=smooth)
1650
+ for s in self.spines.submobjects],
1651
+ lag_ratio=0.15,
1652
+ )
1653
+ ticks_in = FadeIn(self.tick_system,
1654
+ run_time=t * 0.3, rate_func=smooth)
1655
+ labels_in = AnimationGroup(
1656
+ *[Write(lbl, run_time=t * 0.4)
1657
+ for lbl in self.label_system.submobjects],
1658
+ lag_ratio=0.05,
1659
+ )
1660
+ origin_in = FadeIn(self.origin_deco,
1661
+ run_time=t * 0.2, rate_func=smooth)
1662
+ return Succession(
1663
+ grid_in,
1664
+ spines_in,
1665
+ AnimationGroup(ticks_in, labels_in, origin_in, lag_ratio=0.1),
1666
+ lag_ratio=0,
1667
+ )
1668
+
1669
+ def animate_update(
1670
+ self,
1671
+ new_data: Any,
1672
+ cfg: Optional[AnimationConfig] = None,
1673
+ ) -> Animation:
1674
+ """
1675
+ Alias for ``animate_update_range`` when *new_data* is a
1676
+ dict of {axis_key: (lo, hi, step)}.
1677
+ """
1678
+ if isinstance(new_data, dict):
1679
+ return self.animate_update_range(cfg=cfg, **new_data)
1680
+ return FadeIn(self, run_time=0.01)
1681
+
1682
+ def animate_update_range(
1683
+ self,
1684
+ x_range: Optional[Tuple[float, float, float]] = None,
1685
+ y_range: Optional[Tuple[float, float, float]] = None,
1686
+ z_range: Optional[Tuple[float, float, float]] = None,
1687
+ cfg: Optional[AnimationConfig] = None,
1688
+ ) -> Animation:
1689
+ """
1690
+ Smoothly rescale axes to new data ranges.
1691
+ Rebuilds geometry and returns a Transform animation.
1692
+ """
1693
+ cfg = cfg or self._anim_cfg
1694
+ old = self.copy()
1695
+
1696
+ if x_range: self._axes_cfg.x.range = x_range
1697
+ if y_range: self._axes_cfg.y.range = y_range
1698
+ if z_range: self._axes_cfg.z.range = z_range
1699
+
1700
+ # Remove old sub-objects and rebuild
1701
+ self.submobjects.clear()
1702
+ self._build_geometry()
1703
+
1704
+ return Transform(old, self,
1705
+ run_time=cfg.run_time,
1706
+ rate_func=cfg.rate_func)
1707
+
1708
+ def animate_highlight(
1709
+ self,
1710
+ style: HighlightStyle = HighlightStyle.PULSE,
1711
+ cfg: Optional[AnimationConfig] = None,
1712
+ ) -> Animation:
1713
+ cfg = cfg or self._anim_cfg
1714
+ return HighlightSystem.pulse(self.spines, cfg)
1715
+
1716
+ def animate_exit(
1717
+ self, cfg: Optional[AnimationConfig] = None
1718
+ ) -> Animation:
1719
+ cfg = cfg or self._anim_cfg
1720
+ return FadeOut(self, run_time=cfg.run_time * 0.6,
1721
+ rate_func=smooth)
1722
+
1723
+ # ── scale mode setters ────────────────────────────────────────────────
1724
+
1725
+ def set_x_scale(self, mode: AxisScaleMode, thresh: float = 1.0) -> "StatsAxes3D":
1726
+ self._axes_cfg.x.scale_mode = mode
1727
+ self._axes_cfg.x.symlog_thresh = thresh
1728
+ return self
1729
+
1730
+ def set_y_scale(self, mode: AxisScaleMode, thresh: float = 1.0) -> "StatsAxes3D":
1731
+ self._axes_cfg.y.scale_mode = mode
1732
+ self._axes_cfg.y.symlog_thresh = thresh
1733
+ return self
1734
+
1735
+ def set_z_scale(self, mode: AxisScaleMode, thresh: float = 1.0) -> "StatsAxes3D":
1736
+ self._axes_cfg.z.scale_mode = mode
1737
+ self._axes_cfg.z.symlog_thresh = thresh
1738
+ return self
1739
+
1740
+ # ── preset factory methods ────────────────────────────────────────────
1741
+
1742
+ @classmethod
1743
+ def for_distribution(
1744
+ cls,
1745
+ x_range: Tuple[float, float, float] = (-4.0, 4.0, 1.0),
1746
+ y_range: Tuple[float, float, float] = (0.0, 0.45, 0.1),
1747
+ x_label: str = "x",
1748
+ y_label: str = "f(x)",
1749
+ **kwargs,
1750
+ ) -> "StatsAxes3D":
1751
+ """
1752
+ Preset for PDF / PMF distribution plots.
1753
+ Y-axis starts at 0, no z-axis shown, XY grid enabled.
1754
+ """
1755
+ cfg = AxesConfig(
1756
+ x=AxisConfig(range=x_range, label=x_label,
1757
+ include_zero_line=True),
1758
+ y=AxisConfig(range=y_range, label=y_label,
1759
+ length=5.0),
1760
+ z=AxisConfig(visible=False),
1761
+ grid=GridConfig(show_xy_plane=True,
1762
+ show_xz_plane=False,
1763
+ show_yz_plane=False,
1764
+ style=GridStyle.SOLID,
1765
+ fade_edges=True),
1766
+ show_origin_dot=True,
1767
+ )
1768
+ return cls(axes_config=cfg, **kwargs)
1769
+
1770
+ @classmethod
1771
+ def for_scatter(
1772
+ cls,
1773
+ x_range: Tuple[float, float, float] = (-3.0, 3.0, 1.0),
1774
+ y_range: Tuple[float, float, float] = (-3.0, 3.0, 1.0),
1775
+ x_label: str = "X",
1776
+ y_label: str = "Y",
1777
+ **kwargs,
1778
+ ) -> "StatsAxes3D":
1779
+ """Preset for scatter plots and regression. Both axes cross zero."""
1780
+ cfg = AxesConfig(
1781
+ x=AxisConfig(range=x_range, label=x_label,
1782
+ include_zero_line=True),
1783
+ y=AxisConfig(range=y_range, label=y_label,
1784
+ include_zero_line=True),
1785
+ z=AxisConfig(visible=False),
1786
+ grid=GridConfig(show_xy_plane=True,
1787
+ style=GridStyle.SOLID,
1788
+ major_opacity=0.45,
1789
+ minor_opacity=0.15),
1790
+ show_bounding_box=False,
1791
+ )
1792
+ return cls(axes_config=cfg, **kwargs)
1793
+
1794
+ @classmethod
1795
+ def for_histogram(
1796
+ cls,
1797
+ x_range: Tuple[float, float, float] = (-4.0, 4.0, 1.0),
1798
+ y_range: Tuple[float, float, float] = (0.0, 1.0, 0.2),
1799
+ x_label: str = "Value",
1800
+ y_label: str = "Frequency",
1801
+ **kwargs,
1802
+ ) -> "StatsAxes3D":
1803
+ """Preset for histograms: y starts at 0, no minor grid clutter."""
1804
+ cfg = AxesConfig(
1805
+ x=AxisConfig(range=x_range, label=x_label),
1806
+ y=AxisConfig(range=y_range, label=y_label,
1807
+ show_minor_ticks=False),
1808
+ z=AxisConfig(visible=False),
1809
+ grid=GridConfig(show_xy_plane=True,
1810
+ style=GridStyle.DASHED,
1811
+ major_opacity=0.35,
1812
+ minor_opacity=0.0),
1813
+ )
1814
+ return cls(axes_config=cfg, **kwargs)
1815
+
1816
+ @classmethod
1817
+ def for_3d_surface(
1818
+ cls,
1819
+ x_range: Tuple[float, float, float] = (-3.0, 3.0, 1.0),
1820
+ y_range: Tuple[float, float, float] = (-3.0, 3.0, 1.0),
1821
+ z_range: Tuple[float, float, float] = (0.0, 0.5, 0.1),
1822
+ x_label: str = "x",
1823
+ y_label: str = "y",
1824
+ z_label: str = "f(x,y)",
1825
+ **kwargs,
1826
+ ) -> "StatsAxes3D":
1827
+ """
1828
+ Preset for bivariate distribution surfaces and 3-D scatter.
1829
+ All three axes visible with XY floor grid.
1830
+ """
1831
+ cfg = AxesConfig(
1832
+ x=AxisConfig(range=x_range, label=x_label),
1833
+ y=AxisConfig(range=y_range, label=y_label),
1834
+ z=AxisConfig(range=z_range, label=z_label,
1835
+ visible=True,
1836
+ show_tick_labels=True,
1837
+ show_major_ticks=True),
1838
+ grid=GridConfig(show_xy_plane=False,
1839
+ show_xz_plane=True, # floor
1840
+ show_yz_plane=False,
1841
+ style=GridStyle.SOLID,
1842
+ major_opacity=0.30),
1843
+ show_bounding_box=True,
1844
+ bounding_box_opacity=0.10,
1845
+ )
1846
+ return cls(axes_config=cfg, z_length=4.0, **kwargs)
1847
+
1848
+ @classmethod
1849
+ def for_correlation(
1850
+ cls,
1851
+ n_vars: int = 4,
1852
+ var_names: Optional[List[str]] = None,
1853
+ **kwargs,
1854
+ ) -> "StatsAxes3D":
1855
+ """
1856
+ Preset for correlation matrix heatmaps.
1857
+ X and Y axes use categorical integer ticks with variable names.
1858
+ """
1859
+ names = var_names or [f"X_{i+1}" for i in range(n_vars)]
1860
+ custom = {float(i): names[i] for i in range(n_vars)}
1861
+ cfg = AxesConfig(
1862
+ x=AxisConfig(range=(-0.5, n_vars - 0.5, 1.0),
1863
+ label="",
1864
+ custom_tick_labels=custom,
1865
+ show_minor_ticks=False),
1866
+ y=AxisConfig(range=(-0.5, n_vars - 0.5, 1.0),
1867
+ label="",
1868
+ custom_tick_labels=custom,
1869
+ show_minor_ticks=False),
1870
+ z=AxisConfig(visible=False),
1871
+ grid=GridConfig(show_xy_plane=False),
1872
+ show_origin_dot=False,
1873
+ )
1874
+ return cls(axes_config=cfg, **kwargs)
1875
+
1876
+ @classmethod
1877
+ def for_hypothesis(
1878
+ cls,
1879
+ dist_name: Literal["normal", "t", "chi2", "f"] = "normal",
1880
+ df: Optional[float] = None,
1881
+ **kwargs,
1882
+ ) -> "StatsAxes3D":
1883
+ """
1884
+ Preset for hypothesis testing visualisations.
1885
+ X = test statistic, Y = probability density.
1886
+ Grid shows critical region spans.
1887
+ """
1888
+ x_ranges = {
1889
+ "normal": (-4.0, 4.0, 1.0),
1890
+ "t": (-4.5, 4.5, 1.0),
1891
+ "chi2": (0.0, 20.0, 2.0),
1892
+ "f": (0.0, 6.0, 1.0),
1893
+ }
1894
+ xr = x_ranges.get(dist_name, (-4.0, 4.0, 1.0))
1895
+ cfg = AxesConfig(
1896
+ x=AxisConfig(range=xr,
1897
+ label={"normal": "z", "t": "t",
1898
+ "chi2": r"\chi^2", "f": "F"}[dist_name],
1899
+ include_zero_line=dist_name in ("normal", "t")),
1900
+ y=AxisConfig(range=(0.0, 0.45, 0.1),
1901
+ label="f(x)"),
1902
+ z=AxisConfig(visible=False),
1903
+ grid=GridConfig(show_xy_plane=True,
1904
+ style=GridStyle.DASHED,
1905
+ major_opacity=0.30),
1906
+ )
1907
+ return cls(axes_config=cfg, **kwargs)
1908
+
1909
+ @classmethod
1910
+ def for_time_series(
1911
+ cls,
1912
+ x_range: Tuple[float, float, float] = (0.0, 100.0, 10.0),
1913
+ y_range: Tuple[float, float, float] = (-3.0, 3.0, 1.0),
1914
+ x_label: str = "t",
1915
+ y_label: str = "X_t",
1916
+ **kwargs,
1917
+ ) -> "StatsAxes3D":
1918
+ """Preset for time-series / running statistics plots."""
1919
+ cfg = AxesConfig(
1920
+ x=AxisConfig(range=x_range, label=x_label,
1921
+ tick_decimal_places=0),
1922
+ y=AxisConfig(range=y_range, label=y_label,
1923
+ include_zero_line=True),
1924
+ z=AxisConfig(visible=False),
1925
+ grid=GridConfig(show_xy_plane=True,
1926
+ style=GridStyle.DASHED,
1927
+ major_opacity=0.25),
1928
+ )
1929
+ return cls(axes_config=cfg, **kwargs)
1930
+
1931
+ # ── property accessors ────────────────────────────────────────────────
1932
+
1933
+ @property
1934
+ def x_range(self) -> Tuple[float, float, float]:
1935
+ return tuple(self._axes_cfg.x.range) # type: ignore[return-value]
1936
+
1937
+ @property
1938
+ def y_range(self) -> Tuple[float, float, float]:
1939
+ return tuple(self._axes_cfg.y.range) # type: ignore[return-value]
1940
+
1941
+ @property
1942
+ def z_range(self) -> Tuple[float, float, float]:
1943
+ return tuple(self._axes_cfg.z.range) # type: ignore[return-value]
1944
+
1945
+ @property
1946
+ def config(self) -> AxesConfig:
1947
+ return self._axes_cfg
1948
+
1949
+ def __repr__(self) -> str:
1950
+ xr = self._axes_cfg.x.range
1951
+ yr = self._axes_cfg.y.range
1952
+ return (f"StatsAxes3D("
1953
+ f"x=[{xr[0]}, {xr[1]}], "
1954
+ f"y=[{yr[0]}, {yr[1]}])")
1955
+
1956
+
1957
+ # ─────────────────────────────────────────────────────────────────────────────
1958
+ # 14. MODULE EXPORTS
1959
+ # ─────────────────────────────────────────────────────────────────────────────
1960
+
1961
+ __all__ = [
1962
+ # Enumerations
1963
+ "AxisScaleMode",
1964
+ "TickStyle",
1965
+ "GridStyle",
1966
+ "AxisID",
1967
+ # Config dataclasses
1968
+ "AxisConfig",
1969
+ "GridConfig",
1970
+ "AxesConfig",
1971
+ "ReferenceLineConfig",
1972
+ "PointAnnotationConfig",
1973
+ # Scale transform
1974
+ "ScaleTransform",
1975
+ # Sub-components
1976
+ "AxisSpine3D",
1977
+ "TickSystem3D",
1978
+ "TickLabelSystem3D",
1979
+ "AxisLabel3D",
1980
+ "GridPlane3D",
1981
+ "GridSystem3D",
1982
+ "OriginDecoration3D",
1983
+ "BoundingBox3D",
1984
+ "ReferenceLineSystem",
1985
+ "AnnotationSystem3D",
1986
+ "ZeroLines3D",
1987
+ # Master class
1988
+ "StatsAxes3D",
1989
+ ]