statanim 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- statanim/__init__.py +0 -0
- statanim/animations/__init__.py +0 -0
- statanim/animations/clt_demo.py +1852 -0
- statanim/animations/flip_roll.py +1851 -0
- statanim/animations/sampling.py +2291 -0
- statanim/animations/transitions.py +1857 -0
- statanim/axes/__init__.py +0 -0
- statanim/axes/axes3d.py +1989 -0
- statanim/axes/grid3d.py +1127 -0
- statanim/axes/number_plane3d.py +1526 -0
- statanim/charts/__init__.py +0 -0
- statanim/charts/bar_chart3d.py +1572 -0
- statanim/charts/box_plot3d.py +1977 -0
- statanim/charts/heat_map3d.py +1639 -0
- statanim/charts/histogram3d.py +1019 -0
- statanim/charts/line_plot3d.py +1891 -0
- statanim/charts/scatter_plot3d.py +1469 -0
- statanim/charts/violin_plot3d.py +1567 -0
- statanim/core/__init__.py +0 -0
- statanim/core/base.py +1585 -0
- statanim/core/colors.py +1373 -0
- statanim/core/math_utils.py +2081 -0
- statanim/core/tex_utils.py +2111 -0
- statanim/distributions/__init__.py +0 -0
- statanim/distributions/base_dist.py +1936 -0
- statanim/distributions/cdf_viz.py +1773 -0
- statanim/distributions/continuous_dists.py +1769 -0
- statanim/distributions/discrete_dists.py +1734 -0
- statanim/distributions/normal3d.py +1877 -0
- statanim/distributions/pdf_viz.py +2247 -0
- statanim/distributions/pmf_viz.py +1936 -0
- statanim/inference/__init__.py +0 -0
- statanim/inference/confidence_interval.py +1693 -0
- statanim/inference/error_types.py +1825 -0
- statanim/inference/hypothesis.py +1821 -0
- statanim/inference/sampling_dist.py +1933 -0
- statanim/probability/__init__.py +0 -0
- statanim/probability/bayes.py +1682 -0
- statanim/probability/prob_tree.py +1478 -0
- statanim/probability/sample_space.py +1642 -0
- statanim/probability/venn3d.py +1857 -0
- statanim/props/__init__.py +0 -0
- statanim/props/card.py +2259 -0
- statanim/props/coin.py +1011 -0
- statanim/props/die.py +1391 -0
- statanim/props/spinner.py +1591 -0
- statanim/props/urn.py +1531 -0
- statanim/regression/__init__.py +0 -0
- statanim/regression/correlation.py +2805 -0
- statanim/regression/regression_plane.py +2286 -0
- statanim/regression/residuals.py +2599 -0
- statanim/scenes/__init__.py +0 -0
- statanim/scenes/demo_bayes.py +2056 -0
- statanim/scenes/demo_clt.py +1756 -0
- statanim/scenes/demo_distributions.py +1905 -0
- statanim/scenes/demo_hypothesis.py +1791 -0
- statanim/ui/__init__.py +0 -0
- statanim/ui/labels.py +1844 -0
- statanim/ui/panels.py +1937 -0
- statanim/ui/table3d.py +1745 -0
- statanim/ui/ticker.py +2007 -0
- statanim-0.1.0.dist-info/METADATA +463 -0
- statanim-0.1.0.dist-info/RECORD +66 -0
- statanim-0.1.0.dist-info/WHEEL +5 -0
- statanim-0.1.0.dist-info/licenses/LICENSE +21 -0
- statanim-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1526 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statanim/axes/number_plane3d.py
|
|
3
|
+
===================================
|
|
4
|
+
Full 3-D number plane system for the Manim Statistics Extension.
|
|
5
|
+
|
|
6
|
+
Unlike ``GridPlane3D`` (which only draws backdrop grid lines for axes),
|
|
7
|
+
every class here is a **self-contained 2-D coordinate plane embedded in
|
|
8
|
+
3-D space**. A plane can be:
|
|
9
|
+
|
|
10
|
+
• Snapped to an axis face (``FaceNumberPlane3D``)
|
|
11
|
+
• Floating at any data slice (``FloatingPlane3D``)
|
|
12
|
+
• Freely oriented (``NumberPlane3D`` with custom normal + basis)
|
|
13
|
+
|
|
14
|
+
Each plane exposes its own coordinate system so that 2-D statistical
|
|
15
|
+
objects (curves, regions, scatter, vectors) can be drawn directly on
|
|
16
|
+
any face of the 3-D scene without the caller doing any trigonometry.
|
|
17
|
+
|
|
18
|
+
Architecture
|
|
19
|
+
------------
|
|
20
|
+
NumberPlane3D
|
|
21
|
+
├── PlaneGeometry — background fill rectangle + edge border
|
|
22
|
+
├── PlaneGrid — major / minor line meshes in plane-local coords
|
|
23
|
+
├── PlaneAxes — two in-plane axis spines with tips
|
|
24
|
+
├── PlaneTickSystem — ticks + labels on both plane axes
|
|
25
|
+
├── PlaneOriginMark — cross / dot at the plane origin
|
|
26
|
+
└── PlaneDrawingLayer — VGroup that receives curves / regions etc.
|
|
27
|
+
|
|
28
|
+
Coordinate conventions
|
|
29
|
+
-----------------------
|
|
30
|
+
Every plane has:
|
|
31
|
+
``origin_3d`` — 3-D scene point corresponding to (0,0) on the plane
|
|
32
|
+
``basis_u`` — 3-D unit vector for the plane's "x" direction
|
|
33
|
+
``basis_v`` — 3-D unit vector for the plane's "y" direction
|
|
34
|
+
``normal`` — basis_u × basis_v (outward-facing normal)
|
|
35
|
+
|
|
36
|
+
Data ↔ scene mapping:
|
|
37
|
+
plane_c2p(u, v) → origin_3d + u_scene * basis_u + v_scene * basis_v
|
|
38
|
+
plane_p2c(pt) → (u_data, v_data) via dot-product projection
|
|
39
|
+
|
|
40
|
+
Shadow projections
|
|
41
|
+
------------------
|
|
42
|
+
``ShadowProjection3D`` takes any VGroup of 3-D Dot3Ds / Line3Ds and
|
|
43
|
+
collapses them orthogonally onto a target ``NumberPlane3D``, producing
|
|
44
|
+
a matching set of projected dots / lines with drop-lines.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
import math
|
|
50
|
+
from dataclasses import dataclass, field
|
|
51
|
+
from enum import Enum, auto
|
|
52
|
+
from typing import (
|
|
53
|
+
Any, Callable, Dict, List, Literal,
|
|
54
|
+
Optional, Sequence, Tuple, Union,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
import numpy as np
|
|
58
|
+
from numpy.typing import ArrayLike
|
|
59
|
+
|
|
60
|
+
from manim import (
|
|
61
|
+
VGroup, VMobject, Mobject, Group,
|
|
62
|
+
# Geometry
|
|
63
|
+
Line3D, Arrow3D, Dot3D, Sphere,
|
|
64
|
+
Line, DashedLine, DashedVMobject,
|
|
65
|
+
Polygon, Rectangle, RoundedRectangle,
|
|
66
|
+
Text, MathTex,
|
|
67
|
+
# Curves
|
|
68
|
+
ParametricFunction,
|
|
69
|
+
# Animations
|
|
70
|
+
Animation, AnimationGroup, Succession,
|
|
71
|
+
Create, FadeIn, FadeOut, Write,
|
|
72
|
+
DrawBorderThenFill, Transform,
|
|
73
|
+
UpdateFromAlphaFunc,
|
|
74
|
+
# Constants
|
|
75
|
+
ORIGIN, UP, DOWN, LEFT, RIGHT, IN, OUT,
|
|
76
|
+
DEGREES, PI, TAU, WHITE, BLACK,
|
|
77
|
+
# Utils
|
|
78
|
+
interpolate_color, normalize,
|
|
79
|
+
rotation_matrix, smooth, there_and_back,
|
|
80
|
+
ValueTracker, always_redraw,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
from ..core.base import (
|
|
84
|
+
StatsObject3D,
|
|
85
|
+
StatsTheme, StatsColorPalette,
|
|
86
|
+
MaterialConfig, MaterialApplicator,
|
|
87
|
+
LabelConfig, LabelAnchor,
|
|
88
|
+
AnimationConfig, BuildStyle,
|
|
89
|
+
HighlightStyle, HighlightSystem,
|
|
90
|
+
ThemeMode,
|
|
91
|
+
)
|
|
92
|
+
from ..core.math_utils import (
|
|
93
|
+
auto_range, generate_ticks, nice_number,
|
|
94
|
+
smooth_curve, FloatArray,
|
|
95
|
+
)
|
|
96
|
+
from .axes3d import (
|
|
97
|
+
AxisScaleMode, GridStyle, AxisConfig,
|
|
98
|
+
GridConfig, AxesConfig, ScaleTransform,
|
|
99
|
+
StatsAxes3D,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
104
|
+
# 0. ENUMERATIONS & CONFIG
|
|
105
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
106
|
+
|
|
107
|
+
class PlaneFace(Enum):
|
|
108
|
+
"""Which face of the bounding box a ``FaceNumberPlane3D`` occupies."""
|
|
109
|
+
XY_FRONT = auto() # z = z_max (front-facing, normal = +Z)
|
|
110
|
+
XY_BACK = auto() # z = z_min (back wall, normal = −Z)
|
|
111
|
+
XZ_TOP = auto() # y = y_max (ceiling, normal = +Y)
|
|
112
|
+
XZ_BOTTOM = auto() # y = y_min (floor, normal = −Y)
|
|
113
|
+
YZ_RIGHT = auto() # x = x_max (right wall, normal = +X)
|
|
114
|
+
YZ_LEFT = auto() # x = x_min (left wall, normal = −X)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class PlaneMaterial(Enum):
|
|
118
|
+
SOLID = auto() # opaque fill
|
|
119
|
+
FROSTED = auto() # translucent, high opacity
|
|
120
|
+
GLASS = auto() # very translucent
|
|
121
|
+
WIREFRAME = auto() # no fill, only border
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass
|
|
125
|
+
class PlaneGridConfig:
|
|
126
|
+
"""Grid configuration for a single number plane."""
|
|
127
|
+
show_major_grid: bool = True
|
|
128
|
+
show_minor_grid: bool = True
|
|
129
|
+
major_spacing: float = 1.0 # data units
|
|
130
|
+
minor_per_major: int = 4
|
|
131
|
+
major_color: Optional[str] = None
|
|
132
|
+
minor_color: Optional[str] = None
|
|
133
|
+
major_opacity: float = 0.55
|
|
134
|
+
minor_opacity: float = 0.18
|
|
135
|
+
major_width: float = 1.0
|
|
136
|
+
minor_width: float = 0.5
|
|
137
|
+
style: GridStyle = GridStyle.SOLID
|
|
138
|
+
fade_edges: bool = True
|
|
139
|
+
fade_amount: float = 0.5 # 0 = no fade, 1 = fully transparent edge
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass
|
|
143
|
+
class PlaneAxisConfig:
|
|
144
|
+
"""Configuration for the in-plane axis spines."""
|
|
145
|
+
show_u_axis: bool = True # "horizontal" axis of the plane
|
|
146
|
+
show_v_axis: bool = True # "vertical" axis
|
|
147
|
+
color: Optional[str] = None
|
|
148
|
+
width: float = 2.2
|
|
149
|
+
include_tip: bool = True
|
|
150
|
+
tip_length: float = 0.18
|
|
151
|
+
show_ticks: bool = True
|
|
152
|
+
tick_length: float = 0.14
|
|
153
|
+
show_labels: bool = True
|
|
154
|
+
label_font_size: float = 20
|
|
155
|
+
label_offset: float = 0.30
|
|
156
|
+
u_label: str = ""
|
|
157
|
+
v_label: str = ""
|
|
158
|
+
u_label_is_math: bool = True
|
|
159
|
+
v_label_is_math: bool = True
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass
|
|
163
|
+
class PlaneConfig:
|
|
164
|
+
"""
|
|
165
|
+
Complete configuration for a ``NumberPlane3D``.
|
|
166
|
+
|
|
167
|
+
u_range / v_range describe the data-space extent of the two
|
|
168
|
+
in-plane axes (u = "horizontal", v = "vertical" of the plane).
|
|
169
|
+
"""
|
|
170
|
+
u_range: Tuple[float, float] = (-5.0, 5.0)
|
|
171
|
+
v_range: Tuple[float, float] = (-5.0, 5.0)
|
|
172
|
+
u_length: float = 6.0 # scene units
|
|
173
|
+
v_length: float = 6.0
|
|
174
|
+
|
|
175
|
+
grid: PlaneGridConfig = field(default_factory=PlaneGridConfig)
|
|
176
|
+
axes: PlaneAxisConfig = field(default_factory=PlaneAxisConfig)
|
|
177
|
+
material: PlaneMaterial = PlaneMaterial.FROSTED
|
|
178
|
+
|
|
179
|
+
fill_color: Optional[str] = None # None → theme.surface
|
|
180
|
+
fill_opacity: float = 0.12
|
|
181
|
+
border_color: Optional[str] = None # None → theme.border
|
|
182
|
+
border_width: float = 1.4
|
|
183
|
+
border_opacity: float = 0.6
|
|
184
|
+
|
|
185
|
+
show_origin_mark: bool = True
|
|
186
|
+
origin_radius: float = 0.055
|
|
187
|
+
|
|
188
|
+
depth_offset: float = 0.005 # push in front of background
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
192
|
+
# 1. PLANE GEOMETRY (background fill + border)
|
|
193
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
194
|
+
|
|
195
|
+
class PlaneGeometry(VGroup):
|
|
196
|
+
"""
|
|
197
|
+
A filled quadrilateral representing the plane's background surface.
|
|
198
|
+
Constructed from the four corners in 3-D scene space.
|
|
199
|
+
|
|
200
|
+
Using a ``Polygon`` (rather than a ``Rectangle``) means this works
|
|
201
|
+
for any orientation — not just axis-aligned planes.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
corners: List[np.ndarray], # 4 corners in 3-D, CCW order
|
|
207
|
+
cfg: PlaneConfig,
|
|
208
|
+
theme: StatsColorPalette,
|
|
209
|
+
) -> None:
|
|
210
|
+
super().__init__()
|
|
211
|
+
|
|
212
|
+
fill = cfg.fill_color or theme.surface
|
|
213
|
+
border = cfg.border_color or theme.border
|
|
214
|
+
|
|
215
|
+
# Background fill polygon
|
|
216
|
+
if cfg.material != PlaneMaterial.WIREFRAME:
|
|
217
|
+
poly = Polygon(*corners)
|
|
218
|
+
poly.set_fill(fill, opacity=cfg.fill_opacity)
|
|
219
|
+
poly.set_stroke(width=0)
|
|
220
|
+
self.add(poly)
|
|
221
|
+
|
|
222
|
+
# Border edges
|
|
223
|
+
n = len(corners)
|
|
224
|
+
for i in range(n):
|
|
225
|
+
a, b = corners[i], corners[(i + 1) % n]
|
|
226
|
+
edge = Line3D(a, b, color=border,
|
|
227
|
+
thickness=cfg.border_width * 0.005)
|
|
228
|
+
edge.set_opacity(cfg.border_opacity)
|
|
229
|
+
self.add(edge)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
233
|
+
# 2. PLANE GRID
|
|
234
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
235
|
+
|
|
236
|
+
class PlaneGrid(VGroup):
|
|
237
|
+
"""
|
|
238
|
+
Major and minor grid lines drawn in the plane's local (u, v) coordinate
|
|
239
|
+
system, then mapped to 3-D world space via the plane's basis vectors.
|
|
240
|
+
"""
|
|
241
|
+
|
|
242
|
+
def __init__(
|
|
243
|
+
self,
|
|
244
|
+
cfg: PlaneConfig,
|
|
245
|
+
grid_cfg: PlaneGridConfig,
|
|
246
|
+
theme: StatsColorPalette,
|
|
247
|
+
plane_c2p_fn: Callable[[float, float], np.ndarray],
|
|
248
|
+
) -> None:
|
|
249
|
+
super().__init__()
|
|
250
|
+
self._c2p = plane_c2p_fn
|
|
251
|
+
self._theme = theme
|
|
252
|
+
|
|
253
|
+
major_color = grid_cfg.major_color or theme.border
|
|
254
|
+
minor_color = grid_cfg.minor_color or theme.border
|
|
255
|
+
|
|
256
|
+
u_lo, u_hi = cfg.u_range
|
|
257
|
+
v_lo, v_hi = cfg.v_range
|
|
258
|
+
spacing = grid_cfg.major_spacing
|
|
259
|
+
mspacing = spacing / grid_cfg.minor_per_major
|
|
260
|
+
|
|
261
|
+
# Major grid lines parallel to V axis (vertical on plane)
|
|
262
|
+
u_majors = np.arange(
|
|
263
|
+
math.ceil(u_lo / spacing) * spacing,
|
|
264
|
+
u_hi + spacing * 1e-6, spacing)
|
|
265
|
+
for u in u_majors:
|
|
266
|
+
line = self._make_line(
|
|
267
|
+
(u, v_lo), (u, v_hi),
|
|
268
|
+
major_color, grid_cfg.major_width,
|
|
269
|
+
grid_cfg.major_opacity, grid_cfg.style,
|
|
270
|
+
)
|
|
271
|
+
if line: self.add(line)
|
|
272
|
+
|
|
273
|
+
# Major grid lines parallel to U axis (horizontal on plane)
|
|
274
|
+
v_majors = np.arange(
|
|
275
|
+
math.ceil(v_lo / spacing) * spacing,
|
|
276
|
+
v_hi + spacing * 1e-6, spacing)
|
|
277
|
+
for v in v_majors:
|
|
278
|
+
line = self._make_line(
|
|
279
|
+
(u_lo, v), (u_hi, v),
|
|
280
|
+
major_color, grid_cfg.major_width,
|
|
281
|
+
grid_cfg.major_opacity, grid_cfg.style,
|
|
282
|
+
)
|
|
283
|
+
if line: self.add(line)
|
|
284
|
+
|
|
285
|
+
if grid_cfg.show_minor_grid:
|
|
286
|
+
# Minor lines parallel to V
|
|
287
|
+
u_minors = np.arange(
|
|
288
|
+
math.ceil(u_lo / mspacing) * mspacing,
|
|
289
|
+
u_hi + mspacing * 1e-6, mspacing)
|
|
290
|
+
u_minors = u_minors[~np.isin(
|
|
291
|
+
np.round(u_minors, 10), np.round(u_majors, 10))]
|
|
292
|
+
for u in u_minors:
|
|
293
|
+
line = self._make_line(
|
|
294
|
+
(u, v_lo), (u, v_hi),
|
|
295
|
+
minor_color, grid_cfg.minor_width,
|
|
296
|
+
grid_cfg.minor_opacity, grid_cfg.style,
|
|
297
|
+
)
|
|
298
|
+
if line: self.add(line)
|
|
299
|
+
|
|
300
|
+
# Minor lines parallel to U
|
|
301
|
+
v_minors = np.arange(
|
|
302
|
+
math.ceil(v_lo / mspacing) * mspacing,
|
|
303
|
+
v_hi + mspacing * 1e-6, mspacing)
|
|
304
|
+
v_minors = v_minors[~np.isin(
|
|
305
|
+
np.round(v_minors, 10), np.round(v_majors, 10))]
|
|
306
|
+
for v in v_minors:
|
|
307
|
+
line = self._make_line(
|
|
308
|
+
(u_lo, v), (u_hi, v),
|
|
309
|
+
minor_color, grid_cfg.minor_width,
|
|
310
|
+
grid_cfg.minor_opacity, grid_cfg.style,
|
|
311
|
+
)
|
|
312
|
+
if line: self.add(line)
|
|
313
|
+
|
|
314
|
+
# ── helpers ───────────────────────────────────────────────────────────
|
|
315
|
+
|
|
316
|
+
def _make_line(
|
|
317
|
+
self,
|
|
318
|
+
uv1: Tuple[float, float],
|
|
319
|
+
uv2: Tuple[float, float],
|
|
320
|
+
color: str,
|
|
321
|
+
width: float,
|
|
322
|
+
opacity: float,
|
|
323
|
+
style: GridStyle,
|
|
324
|
+
) -> Optional[VMobject]:
|
|
325
|
+
try:
|
|
326
|
+
p1 = self._c2p(*uv1)
|
|
327
|
+
p2 = self._c2p(*uv2)
|
|
328
|
+
if np.allclose(p1, p2):
|
|
329
|
+
return None
|
|
330
|
+
if style == GridStyle.SOLID:
|
|
331
|
+
line = Line3D(p1, p2, color=color,
|
|
332
|
+
thickness=width * 0.005)
|
|
333
|
+
elif style == GridStyle.DASHED:
|
|
334
|
+
line = DashedLine(p1, p2, color=color,
|
|
335
|
+
stroke_width=width * 1.3,
|
|
336
|
+
dash_length=0.12)
|
|
337
|
+
else: # DOTTED
|
|
338
|
+
line = DashedLine(p1, p2, color=color,
|
|
339
|
+
stroke_width=width,
|
|
340
|
+
dash_length=0.04,
|
|
341
|
+
dashed_ratio=0.3)
|
|
342
|
+
line.set_opacity(opacity)
|
|
343
|
+
return line
|
|
344
|
+
except Exception:
|
|
345
|
+
return None
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
349
|
+
# 3. PLANE AXES
|
|
350
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
351
|
+
|
|
352
|
+
class PlaneAxes(VGroup):
|
|
353
|
+
"""
|
|
354
|
+
Two in-plane axis spines (U and V) with tips and title labels.
|
|
355
|
+
Both spines pass through the plane origin.
|
|
356
|
+
"""
|
|
357
|
+
|
|
358
|
+
def __init__(
|
|
359
|
+
self,
|
|
360
|
+
cfg: PlaneConfig,
|
|
361
|
+
theme: StatsColorPalette,
|
|
362
|
+
plane_c2p_fn: Callable[[float, float], np.ndarray],
|
|
363
|
+
) -> None:
|
|
364
|
+
super().__init__()
|
|
365
|
+
self._c2p = plane_c2p_fn
|
|
366
|
+
ax_cfg = cfg.axes
|
|
367
|
+
color = ax_cfg.color or theme.neutral
|
|
368
|
+
|
|
369
|
+
u_lo, u_hi = cfg.u_range
|
|
370
|
+
v_lo, v_hi = cfg.v_range
|
|
371
|
+
|
|
372
|
+
# U axis (horizontal of the plane)
|
|
373
|
+
if ax_cfg.show_u_axis:
|
|
374
|
+
p_start = plane_c2p_fn(u_lo, 0.0)
|
|
375
|
+
p_end = plane_c2p_fn(u_hi, 0.0)
|
|
376
|
+
self._add_spine(p_start, p_end, color, ax_cfg)
|
|
377
|
+
# U title label
|
|
378
|
+
if ax_cfg.u_label:
|
|
379
|
+
lbl_cls = MathTex if ax_cfg.u_label_is_math else Text
|
|
380
|
+
lbl = lbl_cls(ax_cfg.u_label,
|
|
381
|
+
font_size=ax_cfg.label_font_size,
|
|
382
|
+
color=color)
|
|
383
|
+
lbl.move_to(p_end + RIGHT * 0.35 + DOWN * 0.1)
|
|
384
|
+
self.add(lbl)
|
|
385
|
+
|
|
386
|
+
# V axis (vertical of the plane)
|
|
387
|
+
if ax_cfg.show_v_axis:
|
|
388
|
+
p_start = plane_c2p_fn(0.0, v_lo)
|
|
389
|
+
p_end = plane_c2p_fn(0.0, v_hi)
|
|
390
|
+
self._add_spine(p_start, p_end, color, ax_cfg)
|
|
391
|
+
# V title label
|
|
392
|
+
if ax_cfg.v_label:
|
|
393
|
+
lbl_cls = MathTex if ax_cfg.v_label_is_math else Text
|
|
394
|
+
lbl = lbl_cls(ax_cfg.v_label,
|
|
395
|
+
font_size=ax_cfg.label_font_size,
|
|
396
|
+
color=color)
|
|
397
|
+
lbl.move_to(p_end + UP * 0.35)
|
|
398
|
+
self.add(lbl)
|
|
399
|
+
|
|
400
|
+
def _add_spine(
|
|
401
|
+
self,
|
|
402
|
+
start: np.ndarray,
|
|
403
|
+
end: np.ndarray,
|
|
404
|
+
color: str,
|
|
405
|
+
ax_cfg: PlaneAxisConfig,
|
|
406
|
+
) -> None:
|
|
407
|
+
if ax_cfg.include_tip:
|
|
408
|
+
arrow = Arrow3D(start=start, end=end,
|
|
409
|
+
color=color,
|
|
410
|
+
thickness=ax_cfg.width * 0.007,
|
|
411
|
+
tip_length=ax_cfg.tip_length)
|
|
412
|
+
self.add(arrow)
|
|
413
|
+
else:
|
|
414
|
+
line = Line3D(start=start, end=end,
|
|
415
|
+
color=color,
|
|
416
|
+
thickness=ax_cfg.width * 0.007)
|
|
417
|
+
self.add(line)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
421
|
+
# 4. PLANE TICK SYSTEM
|
|
422
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
423
|
+
|
|
424
|
+
class PlaneTickSystem(VGroup):
|
|
425
|
+
"""
|
|
426
|
+
Tick marks and numeric labels on both in-plane axes.
|
|
427
|
+
Ticks are short Line3D segments perpendicular to each axis
|
|
428
|
+
(within the plane surface).
|
|
429
|
+
"""
|
|
430
|
+
|
|
431
|
+
def __init__(
|
|
432
|
+
self,
|
|
433
|
+
cfg: PlaneConfig,
|
|
434
|
+
theme: StatsColorPalette,
|
|
435
|
+
plane_c2p_fn: Callable[[float, float], np.ndarray],
|
|
436
|
+
basis_u: np.ndarray, # 3-D unit vector along plane U
|
|
437
|
+
basis_v: np.ndarray, # 3-D unit vector along plane V
|
|
438
|
+
) -> None:
|
|
439
|
+
super().__init__()
|
|
440
|
+
ax_cfg = cfg.axes
|
|
441
|
+
if not ax_cfg.show_ticks:
|
|
442
|
+
return
|
|
443
|
+
|
|
444
|
+
color = ax_cfg.color or theme.neutral
|
|
445
|
+
lbl_color = theme.text_secondary
|
|
446
|
+
spacing = cfg.grid.major_spacing
|
|
447
|
+
tlen = ax_cfg.tick_length
|
|
448
|
+
loffset = ax_cfg.label_offset
|
|
449
|
+
|
|
450
|
+
u_lo, u_hi = cfg.u_range
|
|
451
|
+
v_lo, v_hi = cfg.v_range
|
|
452
|
+
|
|
453
|
+
# Ticks on U axis (perpendicular = basis_v)
|
|
454
|
+
u_vals = np.arange(
|
|
455
|
+
math.ceil(u_lo / spacing) * spacing,
|
|
456
|
+
u_hi + spacing * 1e-6, spacing)
|
|
457
|
+
for u in u_vals:
|
|
458
|
+
if abs(u) < 1e-9:
|
|
459
|
+
continue
|
|
460
|
+
centre = plane_c2p_fn(u, 0.0)
|
|
461
|
+
t1 = centre - basis_v * tlen * 0.5
|
|
462
|
+
t2 = centre + basis_v * tlen * 0.5
|
|
463
|
+
tick = Line3D(t1, t2, color=color, thickness=0.005)
|
|
464
|
+
tick.set_opacity(0.8)
|
|
465
|
+
self.add(tick)
|
|
466
|
+
if ax_cfg.show_labels:
|
|
467
|
+
lbl = self._fmt_label(u, ax_cfg.label_font_size, lbl_color)
|
|
468
|
+
lbl.move_to(centre - basis_v * loffset)
|
|
469
|
+
self.add(lbl)
|
|
470
|
+
|
|
471
|
+
# Ticks on V axis (perpendicular = basis_u)
|
|
472
|
+
v_vals = np.arange(
|
|
473
|
+
math.ceil(v_lo / spacing) * spacing,
|
|
474
|
+
v_hi + spacing * 1e-6, spacing)
|
|
475
|
+
for v in v_vals:
|
|
476
|
+
if abs(v) < 1e-9:
|
|
477
|
+
continue
|
|
478
|
+
centre = plane_c2p_fn(0.0, v)
|
|
479
|
+
t1 = centre - basis_u * tlen * 0.5
|
|
480
|
+
t2 = centre + basis_u * tlen * 0.5
|
|
481
|
+
tick = Line3D(t1, t2, color=color, thickness=0.005)
|
|
482
|
+
tick.set_opacity(0.8)
|
|
483
|
+
self.add(tick)
|
|
484
|
+
if ax_cfg.show_labels:
|
|
485
|
+
lbl = self._fmt_label(v, ax_cfg.label_font_size, lbl_color)
|
|
486
|
+
lbl.move_to(centre - basis_u * loffset)
|
|
487
|
+
self.add(lbl)
|
|
488
|
+
|
|
489
|
+
@staticmethod
|
|
490
|
+
def _fmt_label(val: float, size: float, color: str) -> VMobject:
|
|
491
|
+
text = f"{val:.0f}" if val == int(val) else f"{val:.2g}"
|
|
492
|
+
return Text(text, font_size=size, color=color)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
496
|
+
# 5. PLANE ORIGIN MARK
|
|
497
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
498
|
+
|
|
499
|
+
class PlaneOriginMark(VGroup):
|
|
500
|
+
"""
|
|
501
|
+
Crosshair + dot at the plane's (0, 0) origin.
|
|
502
|
+
The crosshair arms lie within the plane surface.
|
|
503
|
+
"""
|
|
504
|
+
|
|
505
|
+
def __init__(
|
|
506
|
+
self,
|
|
507
|
+
origin_3d: np.ndarray,
|
|
508
|
+
basis_u: np.ndarray,
|
|
509
|
+
basis_v: np.ndarray,
|
|
510
|
+
cfg: PlaneConfig,
|
|
511
|
+
theme: StatsColorPalette,
|
|
512
|
+
) -> None:
|
|
513
|
+
super().__init__()
|
|
514
|
+
if not cfg.show_origin_mark:
|
|
515
|
+
return
|
|
516
|
+
|
|
517
|
+
color = theme.accent
|
|
518
|
+
r = cfg.origin_radius
|
|
519
|
+
ext = r * 2.5
|
|
520
|
+
|
|
521
|
+
# Central dot
|
|
522
|
+
dot = Dot3D(origin_3d, radius=r, color=color)
|
|
523
|
+
dot.set_opacity(0.9)
|
|
524
|
+
self.add(dot)
|
|
525
|
+
|
|
526
|
+
# Crosshair arms along basis_u and basis_v
|
|
527
|
+
for direction in [basis_u, -basis_u, basis_v, -basis_v]:
|
|
528
|
+
arm = Line3D(origin_3d,
|
|
529
|
+
origin_3d + direction * ext,
|
|
530
|
+
color=color, thickness=0.007)
|
|
531
|
+
arm.set_opacity(0.55)
|
|
532
|
+
self.add(arm)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
536
|
+
# 6. PLANE DRAWING LAYER
|
|
537
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
538
|
+
|
|
539
|
+
class PlaneDrawingLayer(VGroup):
|
|
540
|
+
"""
|
|
541
|
+
A VGroup that sits on top of a ``NumberPlane3D`` and receives
|
|
542
|
+
all user-drawn content: curves, regions, scatter points, vectors.
|
|
543
|
+
|
|
544
|
+
Drawing methods accept data-space (u, v) coordinates and
|
|
545
|
+
internally call ``plane_c2p`` to convert to 3-D scene points.
|
|
546
|
+
"""
|
|
547
|
+
|
|
548
|
+
def __init__(
|
|
549
|
+
self,
|
|
550
|
+
plane_c2p_fn: Callable[[float, float], np.ndarray],
|
|
551
|
+
theme: StatsColorPalette,
|
|
552
|
+
basis_u: np.ndarray,
|
|
553
|
+
basis_v: np.ndarray,
|
|
554
|
+
normal: np.ndarray,
|
|
555
|
+
) -> None:
|
|
556
|
+
super().__init__()
|
|
557
|
+
self._c2p = plane_c2p_fn
|
|
558
|
+
self._theme = theme
|
|
559
|
+
self._bu = basis_u
|
|
560
|
+
self._bv = basis_v
|
|
561
|
+
self._normal = normal
|
|
562
|
+
self._objects: Dict[str, VMobject] = {}
|
|
563
|
+
|
|
564
|
+
# ── curve ─────────────────────────────────────────────────────────────
|
|
565
|
+
|
|
566
|
+
def draw_curve(
|
|
567
|
+
self,
|
|
568
|
+
key: str,
|
|
569
|
+
u_vals: ArrayLike,
|
|
570
|
+
v_vals: ArrayLike,
|
|
571
|
+
color: Optional[str] = None,
|
|
572
|
+
width: float = 2.5,
|
|
573
|
+
opacity: float = 1.0,
|
|
574
|
+
smooth_n: int = 0, # 0 = no smoothing
|
|
575
|
+
) -> VGroup:
|
|
576
|
+
"""
|
|
577
|
+
Draw a 2-D curve (u[i], v[i]) on the plane.
|
|
578
|
+
Optionally smooth with cubic interpolation first.
|
|
579
|
+
"""
|
|
580
|
+
us = np.asarray(u_vals, float)
|
|
581
|
+
vs = np.asarray(v_vals, float)
|
|
582
|
+
|
|
583
|
+
if smooth_n > len(us):
|
|
584
|
+
from ..core.math_utils import smooth_curve as _sc
|
|
585
|
+
us, vs = _sc(us, vs, n_out=smooth_n)
|
|
586
|
+
|
|
587
|
+
c = color or self._theme.primary
|
|
588
|
+
grp = VGroup()
|
|
589
|
+
|
|
590
|
+
for i in range(len(us) - 1):
|
|
591
|
+
p1 = self._c2p(us[i], vs[i])
|
|
592
|
+
p2 = self._c2p(us[i + 1], vs[i + 1])
|
|
593
|
+
if np.allclose(p1, p2):
|
|
594
|
+
continue
|
|
595
|
+
seg = Line3D(p1, p2, color=c, thickness=width * 0.006)
|
|
596
|
+
seg.set_opacity(opacity)
|
|
597
|
+
grp.add(seg)
|
|
598
|
+
|
|
599
|
+
self._objects[key] = grp
|
|
600
|
+
self.add(grp)
|
|
601
|
+
return grp
|
|
602
|
+
|
|
603
|
+
# ── filled region ─────────────────────────────────────────────────────
|
|
604
|
+
|
|
605
|
+
def draw_region(
|
|
606
|
+
self,
|
|
607
|
+
key: str,
|
|
608
|
+
u_vals: ArrayLike,
|
|
609
|
+
v_lo_vals: ArrayLike,
|
|
610
|
+
v_hi_vals: ArrayLike,
|
|
611
|
+
color: Optional[str] = None,
|
|
612
|
+
fill_opacity: float = 0.35,
|
|
613
|
+
stroke_width: float = 0.0,
|
|
614
|
+
) -> VGroup:
|
|
615
|
+
"""
|
|
616
|
+
Fill the region between ``v_lo_vals`` and ``v_hi_vals`` along ``u_vals``.
|
|
617
|
+
Suitable for shaded PDF areas, confidence bands, etc.
|
|
618
|
+
The polygon is assembled as [upper_path, reversed_lower_path].
|
|
619
|
+
"""
|
|
620
|
+
us = np.asarray(u_vals, float)
|
|
621
|
+
v_lo = np.asarray(v_lo_vals, float)
|
|
622
|
+
v_hi = np.asarray(v_hi_vals, float)
|
|
623
|
+
c = color or self._theme.positive
|
|
624
|
+
|
|
625
|
+
# Build polygon: upper edge L→R, lower edge R→L
|
|
626
|
+
upper = [self._c2p(u, vh) for u, vh in zip(us, v_hi)]
|
|
627
|
+
lower = [self._c2p(u, vl) for u, vl in reversed(
|
|
628
|
+
list(zip(us, v_lo)))]
|
|
629
|
+
all_pts = upper + lower
|
|
630
|
+
|
|
631
|
+
if len(all_pts) < 3:
|
|
632
|
+
return VGroup()
|
|
633
|
+
|
|
634
|
+
poly = Polygon(*all_pts)
|
|
635
|
+
poly.set_fill(c, opacity=fill_opacity)
|
|
636
|
+
poly.set_stroke(c, width=stroke_width, opacity=fill_opacity * 1.4)
|
|
637
|
+
|
|
638
|
+
grp = VGroup(poly)
|
|
639
|
+
self._objects[key] = grp
|
|
640
|
+
self.add(grp)
|
|
641
|
+
return grp
|
|
642
|
+
|
|
643
|
+
# ── scatter ────────────────────────────────────────────────────────────
|
|
644
|
+
|
|
645
|
+
def draw_scatter(
|
|
646
|
+
self,
|
|
647
|
+
key: str,
|
|
648
|
+
u_vals: ArrayLike,
|
|
649
|
+
v_vals: ArrayLike,
|
|
650
|
+
dot_radius: float = 0.06,
|
|
651
|
+
colors: Optional[List[str]] = None,
|
|
652
|
+
opacity: float = 0.85,
|
|
653
|
+
jitter_normal: float = 0.003, # tiny push off plane to avoid z-fighting
|
|
654
|
+
) -> VGroup:
|
|
655
|
+
"""
|
|
656
|
+
Place Dot3D points on the plane at each (u, v) data point.
|
|
657
|
+
"""
|
|
658
|
+
us = np.asarray(u_vals, float)
|
|
659
|
+
vs = np.asarray(v_vals, float)
|
|
660
|
+
n = len(us)
|
|
661
|
+
grp = VGroup()
|
|
662
|
+
|
|
663
|
+
for i, (u, v) in enumerate(zip(us, vs)):
|
|
664
|
+
c = colors[i % len(colors)] if colors else self._theme.primary
|
|
665
|
+
pos = self._c2p(u, v) + self._normal * jitter_normal
|
|
666
|
+
dot = Dot3D(pos, radius=dot_radius, color=c)
|
|
667
|
+
dot.set_opacity(opacity)
|
|
668
|
+
grp.add(dot)
|
|
669
|
+
|
|
670
|
+
self._objects[key] = grp
|
|
671
|
+
self.add(grp)
|
|
672
|
+
return grp
|
|
673
|
+
|
|
674
|
+
# ── vector ────────────────────────────────────────────────────────────
|
|
675
|
+
|
|
676
|
+
def draw_vector(
|
|
677
|
+
self,
|
|
678
|
+
key: str,
|
|
679
|
+
origin: Tuple[float, float],
|
|
680
|
+
tip: Tuple[float, float],
|
|
681
|
+
color: Optional[str] = None,
|
|
682
|
+
width: float = 2.0,
|
|
683
|
+
tip_size: float = 0.18,
|
|
684
|
+
) -> Arrow3D:
|
|
685
|
+
"""
|
|
686
|
+
Draw an arrow from *origin* to *tip* (both in plane data coords).
|
|
687
|
+
"""
|
|
688
|
+
c = color or self._theme.accent
|
|
689
|
+
p1 = self._c2p(*origin)
|
|
690
|
+
p2 = self._c2p(*tip)
|
|
691
|
+
arr = Arrow3D(p1, p2, color=c,
|
|
692
|
+
thickness=width * 0.006,
|
|
693
|
+
tip_length=tip_size)
|
|
694
|
+
self._objects[key] = arr
|
|
695
|
+
self.add(arr)
|
|
696
|
+
return arr
|
|
697
|
+
|
|
698
|
+
# ── text annotation ───────────────────────────────────────────────────
|
|
699
|
+
|
|
700
|
+
def draw_label(
|
|
701
|
+
self,
|
|
702
|
+
key: str,
|
|
703
|
+
u: float,
|
|
704
|
+
v: float,
|
|
705
|
+
text: str,
|
|
706
|
+
is_math: bool = False,
|
|
707
|
+
font_size: float = 22,
|
|
708
|
+
color: Optional[str] = None,
|
|
709
|
+
bg: bool = True,
|
|
710
|
+
) -> VGroup:
|
|
711
|
+
"""
|
|
712
|
+
Place a floating text label at plane data-coords (u, v).
|
|
713
|
+
"""
|
|
714
|
+
c = color or self._theme.text_primary
|
|
715
|
+
pos = self._c2p(u, v)
|
|
716
|
+
|
|
717
|
+
mob_cls = MathTex if is_math else Text
|
|
718
|
+
mob = mob_cls(text, font_size=font_size, color=c)
|
|
719
|
+
mob.move_to(pos)
|
|
720
|
+
|
|
721
|
+
if bg:
|
|
722
|
+
from ..core.base import StatsTheme
|
|
723
|
+
t = StatsTheme.current
|
|
724
|
+
bg_r = RoundedRectangle(
|
|
725
|
+
corner_radius=0.10,
|
|
726
|
+
width=mob.width + 0.25,
|
|
727
|
+
height=mob.height + 0.18,
|
|
728
|
+
)
|
|
729
|
+
bg_r.set_fill(t.surface, opacity=0.80)
|
|
730
|
+
bg_r.set_stroke(t.border, width=1.0)
|
|
731
|
+
bg_r.move_to(mob)
|
|
732
|
+
grp = VGroup(bg_r, mob)
|
|
733
|
+
else:
|
|
734
|
+
grp = VGroup(mob)
|
|
735
|
+
|
|
736
|
+
self._objects[key] = grp
|
|
737
|
+
self.add(grp)
|
|
738
|
+
return grp
|
|
739
|
+
|
|
740
|
+
# ── removal ───────────────────────────────────────────────────────────
|
|
741
|
+
|
|
742
|
+
def remove_object(self, key: str) -> None:
|
|
743
|
+
if key in self._objects:
|
|
744
|
+
self.remove(self._objects.pop(key))
|
|
745
|
+
|
|
746
|
+
def clear_all(self) -> None:
|
|
747
|
+
for key in list(self._objects):
|
|
748
|
+
self.remove_object(key)
|
|
749
|
+
|
|
750
|
+
def get_object(self, key: str) -> Optional[VMobject]:
|
|
751
|
+
return self._objects.get(key)
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
755
|
+
# 7. NUMBER PLANE 3D (master class)
|
|
756
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
757
|
+
|
|
758
|
+
class NumberPlane3D(StatsObject3D):
|
|
759
|
+
"""
|
|
760
|
+
A fully-featured 2-D number plane embedded in 3-D space.
|
|
761
|
+
|
|
762
|
+
The plane is defined by:
|
|
763
|
+
``origin_3d`` — 3-D scene position of data (0,0)
|
|
764
|
+
``basis_u`` — 3-D unit vector for the plane's U ("x") direction
|
|
765
|
+
``basis_v`` — 3-D unit vector for the plane's V ("y") direction
|
|
766
|
+
|
|
767
|
+
The ``normal`` is computed as ``basis_u × basis_v``.
|
|
768
|
+
|
|
769
|
+
Coordinate mapping
|
|
770
|
+
------------------
|
|
771
|
+
::
|
|
772
|
+
|
|
773
|
+
scene_pt = plane.plane_c2p(u, v)
|
|
774
|
+
u, v = plane.plane_p2c(scene_pt)
|
|
775
|
+
|
|
776
|
+
Drawing API
|
|
777
|
+
-----------
|
|
778
|
+
All drawing methods are on ``plane.drawing`` (``PlaneDrawingLayer``):
|
|
779
|
+
::
|
|
780
|
+
|
|
781
|
+
plane.drawing.draw_curve("pdf", u_arr, v_arr, color=BLUE)
|
|
782
|
+
plane.drawing.draw_region("shade", u_arr, v0, v_hi, color=GREEN)
|
|
783
|
+
plane.drawing.draw_scatter("pts", u_arr, v_arr)
|
|
784
|
+
plane.drawing.draw_vector("mu", (0,0), (1.5,0))
|
|
785
|
+
plane.drawing.draw_label("note", 2, 0.3, r"\\mu + \\sigma")
|
|
786
|
+
"""
|
|
787
|
+
|
|
788
|
+
def __init__(
|
|
789
|
+
self,
|
|
790
|
+
origin_3d: Optional[np.ndarray] = None,
|
|
791
|
+
basis_u: Optional[np.ndarray] = None,
|
|
792
|
+
basis_v: Optional[np.ndarray] = None,
|
|
793
|
+
plane_config: Optional[PlaneConfig] = None,
|
|
794
|
+
**kwargs,
|
|
795
|
+
) -> None:
|
|
796
|
+
# Basis vectors — default: plane lies in XY scene plane
|
|
797
|
+
self._origin_3d = np.asarray(origin_3d) if origin_3d is not None \
|
|
798
|
+
else np.array([0., 0., 0.])
|
|
799
|
+
self._basis_u = _normalize(np.asarray(basis_u) if basis_u is not None
|
|
800
|
+
else np.array([1., 0., 0.]))
|
|
801
|
+
self._basis_v = _normalize(np.asarray(basis_v) if basis_v is not None
|
|
802
|
+
else np.array([0., 1., 0.]))
|
|
803
|
+
self._normal = _normalize(np.cross(self._basis_u, self._basis_v))
|
|
804
|
+
self._plane_cfg = plane_config or PlaneConfig()
|
|
805
|
+
|
|
806
|
+
# Sub-components (populated in _build_geometry)
|
|
807
|
+
self.geometry: PlaneGeometry = None # type: ignore[assignment]
|
|
808
|
+
self.grid: PlaneGrid = None # type: ignore[assignment]
|
|
809
|
+
self.axes: PlaneAxes = None # type: ignore[assignment]
|
|
810
|
+
self.ticks: PlaneTickSystem = None # type: ignore[assignment]
|
|
811
|
+
self.origin_mk: PlaneOriginMark = None # type: ignore[assignment]
|
|
812
|
+
self.drawing: PlaneDrawingLayer = None # type: ignore[assignment]
|
|
813
|
+
|
|
814
|
+
super().__init__(**kwargs)
|
|
815
|
+
|
|
816
|
+
# ── coordinate transform ──────────────────────────────────────────────
|
|
817
|
+
|
|
818
|
+
def plane_c2p(self, u: float, v: float) -> np.ndarray:
|
|
819
|
+
"""
|
|
820
|
+
Plane data coords (u, v) → 3-D scene point.
|
|
821
|
+
"""
|
|
822
|
+
cfg = self._plane_cfg
|
|
823
|
+
u_lo, u_hi = cfg.u_range
|
|
824
|
+
v_lo, v_hi = cfg.v_range
|
|
825
|
+
|
|
826
|
+
# Normalise to [-0.5, 0.5], then scale to scene length
|
|
827
|
+
tu = (u - u_lo) / (u_hi - u_lo) - 0.5 if u_hi != u_lo else 0.
|
|
828
|
+
tv = (v - v_lo) / (v_hi - v_lo) - 0.5 if v_hi != v_lo else 0.
|
|
829
|
+
|
|
830
|
+
su = tu * cfg.u_length
|
|
831
|
+
sv = tv * cfg.v_length
|
|
832
|
+
|
|
833
|
+
return self._origin_3d + su * self._basis_u + sv * self._basis_v
|
|
834
|
+
|
|
835
|
+
def plane_p2c(self, point_3d: np.ndarray) -> Tuple[float, float]:
|
|
836
|
+
"""
|
|
837
|
+
3-D scene point → plane data coords (u, v) via projection.
|
|
838
|
+
"""
|
|
839
|
+
cfg = self._plane_cfg
|
|
840
|
+
u_lo, u_hi = cfg.u_range
|
|
841
|
+
v_lo, v_hi = cfg.v_range
|
|
842
|
+
|
|
843
|
+
delta = np.asarray(point_3d) - self._origin_3d
|
|
844
|
+
su = float(np.dot(delta, self._basis_u))
|
|
845
|
+
sv = float(np.dot(delta, self._basis_v))
|
|
846
|
+
|
|
847
|
+
tu = su / cfg.u_length + 0.5
|
|
848
|
+
tv = sv / cfg.v_length + 0.5
|
|
849
|
+
|
|
850
|
+
u = u_lo + tu * (u_hi - u_lo)
|
|
851
|
+
v = v_lo + tv * (v_hi - v_lo)
|
|
852
|
+
return u, v
|
|
853
|
+
|
|
854
|
+
def project_point(self, point_3d: np.ndarray) -> np.ndarray:
|
|
855
|
+
"""
|
|
856
|
+
Orthogonally project a 3-D point onto this plane's surface.
|
|
857
|
+
Returns the 3-D scene position of the projected point.
|
|
858
|
+
"""
|
|
859
|
+
delta = np.asarray(point_3d) - self._origin_3d
|
|
860
|
+
dist = float(np.dot(delta, self._normal))
|
|
861
|
+
return np.asarray(point_3d) - dist * self._normal
|
|
862
|
+
|
|
863
|
+
# ── geometry build ────────────────────────────────────────────────────
|
|
864
|
+
|
|
865
|
+
def _build_geometry(self) -> None:
|
|
866
|
+
cfg = self._plane_cfg
|
|
867
|
+
theme = self._palette
|
|
868
|
+
c2p = self.plane_c2p
|
|
869
|
+
|
|
870
|
+
u_lo, u_hi = cfg.u_range
|
|
871
|
+
v_lo, v_hi = cfg.v_range
|
|
872
|
+
|
|
873
|
+
# 4 corners of the plane in 3-D
|
|
874
|
+
corners = [
|
|
875
|
+
c2p(u_lo, v_lo), c2p(u_hi, v_lo),
|
|
876
|
+
c2p(u_hi, v_hi), c2p(u_lo, v_hi),
|
|
877
|
+
]
|
|
878
|
+
|
|
879
|
+
# Depth-push along normal to avoid z-fighting
|
|
880
|
+
offset = self._normal * cfg.depth_offset
|
|
881
|
+
|
|
882
|
+
# Background geometry
|
|
883
|
+
self.geometry = PlaneGeometry(
|
|
884
|
+
[pt + offset for pt in corners], cfg, theme)
|
|
885
|
+
self.add(self.geometry)
|
|
886
|
+
|
|
887
|
+
# Grid
|
|
888
|
+
if cfg.grid.show_major_grid:
|
|
889
|
+
self.grid = PlaneGrid(cfg, cfg.grid, theme, c2p)
|
|
890
|
+
self.add(self.grid)
|
|
891
|
+
|
|
892
|
+
# Axes
|
|
893
|
+
if cfg.axes.show_u_axis or cfg.axes.show_v_axis:
|
|
894
|
+
self.axes = PlaneAxes(cfg, theme, c2p)
|
|
895
|
+
self.add(self.axes)
|
|
896
|
+
|
|
897
|
+
# Ticks
|
|
898
|
+
if cfg.axes.show_ticks:
|
|
899
|
+
self.ticks = PlaneTickSystem(
|
|
900
|
+
cfg, theme, c2p, self._basis_u, self._basis_v)
|
|
901
|
+
self.add(self.ticks)
|
|
902
|
+
|
|
903
|
+
# Origin mark
|
|
904
|
+
self.origin_mk = PlaneOriginMark(
|
|
905
|
+
self._origin_3d, self._basis_u, self._basis_v, cfg, theme)
|
|
906
|
+
self.add(self.origin_mk)
|
|
907
|
+
|
|
908
|
+
# Drawing layer (empty at build time)
|
|
909
|
+
self.drawing = PlaneDrawingLayer(
|
|
910
|
+
c2p, theme, self._basis_u, self._basis_v, self._normal)
|
|
911
|
+
self.add(self.drawing)
|
|
912
|
+
|
|
913
|
+
# ── animation protocol ────────────────────────────────────────────────
|
|
914
|
+
|
|
915
|
+
def animate_build(
|
|
916
|
+
self, cfg: Optional[AnimationConfig] = None
|
|
917
|
+
) -> Animation:
|
|
918
|
+
"""
|
|
919
|
+
The plane materialises by sliding in from behind its normal vector,
|
|
920
|
+
then the grid draws itself, then axes and labels appear.
|
|
921
|
+
"""
|
|
922
|
+
cfg = cfg or self._anim_cfg
|
|
923
|
+
t = cfg.run_time
|
|
924
|
+
|
|
925
|
+
geo_in = FadeIn(self.geometry, run_time=t * 0.35, rate_func=smooth)
|
|
926
|
+
grid_in = FadeIn(self.grid, run_time=t * 0.40,
|
|
927
|
+
shift=self._normal * (-0.3),
|
|
928
|
+
rate_func=smooth)
|
|
929
|
+
axes_in = AnimationGroup(
|
|
930
|
+
FadeIn(self.axes, run_time=t * 0.30, rate_func=smooth),
|
|
931
|
+
FadeIn(self.ticks, run_time=t * 0.30, rate_func=smooth),
|
|
932
|
+
FadeIn(self.origin_mk, run_time=t * 0.20, rate_func=smooth),
|
|
933
|
+
lag_ratio=0.2,
|
|
934
|
+
)
|
|
935
|
+
return Succession(geo_in, grid_in, axes_in, lag_ratio=0)
|
|
936
|
+
|
|
937
|
+
def animate_update(
|
|
938
|
+
self, new_data: Any, cfg: Optional[AnimationConfig] = None
|
|
939
|
+
) -> Animation:
|
|
940
|
+
cfg = cfg or self._anim_cfg
|
|
941
|
+
return FadeIn(self, run_time=cfg.run_time * 0.5)
|
|
942
|
+
|
|
943
|
+
def animate_highlight(
|
|
944
|
+
self,
|
|
945
|
+
style: HighlightStyle = HighlightStyle.GLOW,
|
|
946
|
+
cfg: Optional[AnimationConfig] = None,
|
|
947
|
+
) -> Animation:
|
|
948
|
+
cfg = cfg or self._anim_cfg
|
|
949
|
+
return HighlightSystem.glow(self.geometry, cfg)
|
|
950
|
+
|
|
951
|
+
def animate_exit(
|
|
952
|
+
self, cfg: Optional[AnimationConfig] = None
|
|
953
|
+
) -> Animation:
|
|
954
|
+
cfg = cfg or self._anim_cfg
|
|
955
|
+
return FadeOut(self, shift=self._normal * 0.4,
|
|
956
|
+
run_time=cfg.run_time * 0.6)
|
|
957
|
+
|
|
958
|
+
# ── accessors ─────────────────────────────────────────────────────────
|
|
959
|
+
|
|
960
|
+
@property
|
|
961
|
+
def normal(self) -> np.ndarray:
|
|
962
|
+
return self._normal.copy()
|
|
963
|
+
|
|
964
|
+
@property
|
|
965
|
+
def basis(self) -> Tuple[np.ndarray, np.ndarray]:
|
|
966
|
+
return self._basis_u.copy(), self._basis_v.copy()
|
|
967
|
+
|
|
968
|
+
@property
|
|
969
|
+
def origin_scene(self) -> np.ndarray:
|
|
970
|
+
return self._origin_3d.copy()
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
974
|
+
# 8. FACE NUMBER PLANE
|
|
975
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
976
|
+
|
|
977
|
+
class FaceNumberPlane3D(NumberPlane3D):
|
|
978
|
+
"""
|
|
979
|
+
A ``NumberPlane3D`` that snaps exactly to one face of a ``StatsAxes3D``
|
|
980
|
+
bounding box.
|
|
981
|
+
|
|
982
|
+
The plane's (u, v) data range is automatically inherited from the
|
|
983
|
+
two axes that form that face, so ``plane_c2p`` is aligned with
|
|
984
|
+
the parent ``StatsAxes3D.c2p`` for the same data values.
|
|
985
|
+
|
|
986
|
+
Usage
|
|
987
|
+
-----
|
|
988
|
+
::
|
|
989
|
+
|
|
990
|
+
axes = StatsAxes3D.for_3d_surface(...)
|
|
991
|
+
floor = FaceNumberPlane3D(axes, face=PlaneFace.XZ_BOTTOM)
|
|
992
|
+
scene.add(axes, floor)
|
|
993
|
+
"""
|
|
994
|
+
|
|
995
|
+
# Maps face → (u_axis_key, v_axis_key, normal_direction, fixed_axis_key)
|
|
996
|
+
_FACE_MAP: Dict[PlaneFace, Dict] = {
|
|
997
|
+
PlaneFace.XY_FRONT: dict(u="x", v="y", normal=OUT, fixed="z", sign=+1),
|
|
998
|
+
PlaneFace.XY_BACK: dict(u="x", v="y", normal=IN, fixed="z", sign=-1),
|
|
999
|
+
PlaneFace.XZ_TOP: dict(u="x", v="z", normal=UP, fixed="y", sign=+1),
|
|
1000
|
+
PlaneFace.XZ_BOTTOM: dict(u="x", v="z", normal=DOWN, fixed="y", sign=-1),
|
|
1001
|
+
PlaneFace.YZ_RIGHT: dict(u="y", v="z", normal=RIGHT,fixed="x", sign=+1),
|
|
1002
|
+
PlaneFace.YZ_LEFT: dict(u="y", v="z", normal=LEFT, fixed="x", sign=-1),
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
# Maps normal direction string → (basis_u, basis_v)
|
|
1006
|
+
_BASIS_MAP: Dict[str, Tuple[np.ndarray, np.ndarray]] = {
|
|
1007
|
+
"OUT": (np.array([1,0,0]), np.array([0,1,0])),
|
|
1008
|
+
"IN": (np.array([-1,0,0]),np.array([0,1,0])),
|
|
1009
|
+
"UP": (np.array([1,0,0]), np.array([0,0,1])),
|
|
1010
|
+
"DOWN": (np.array([1,0,0]), np.array([0,0,-1])),
|
|
1011
|
+
"RIGHT": (np.array([0,1,0]), np.array([0,0,1])),
|
|
1012
|
+
"LEFT": (np.array([0,-1,0]),np.array([0,0,1])),
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
def __init__(
|
|
1016
|
+
self,
|
|
1017
|
+
parent_axes: StatsAxes3D,
|
|
1018
|
+
face: PlaneFace = PlaneFace.XY_FRONT,
|
|
1019
|
+
plane_config: Optional[PlaneConfig] = None,
|
|
1020
|
+
**kwargs,
|
|
1021
|
+
) -> None:
|
|
1022
|
+
fm = self._FACE_MAP[face]
|
|
1023
|
+
axes_cfg = parent_axes.config
|
|
1024
|
+
pcfg = parent_axes.c2p # use parent's c2p to compute origin
|
|
1025
|
+
|
|
1026
|
+
# Resolve u, v ranges from parent axes
|
|
1027
|
+
u_ax = getattr(axes_cfg, fm["u"])
|
|
1028
|
+
v_ax = getattr(axes_cfg, fm["v"])
|
|
1029
|
+
f_ax = getattr(axes_cfg, fm["fixed"])
|
|
1030
|
+
u_range = u_ax.range[:2]
|
|
1031
|
+
v_range = v_ax.range[:2]
|
|
1032
|
+
f_val = f_ax.range[1] if fm["sign"] > 0 else f_ax.range[0]
|
|
1033
|
+
|
|
1034
|
+
# Compute origin_3d: the scene point at (u_mid, v_mid, f_val)
|
|
1035
|
+
u_mid = (u_range[0] + u_range[1]) / 2
|
|
1036
|
+
v_mid = (v_range[0] + v_range[1]) / 2
|
|
1037
|
+
|
|
1038
|
+
coord_map = {"x": 0.0, "y": 0.0, "z": 0.0}
|
|
1039
|
+
coord_map[fm["u"]] = u_mid
|
|
1040
|
+
coord_map[fm["v"]] = v_mid
|
|
1041
|
+
coord_map[fm["fixed"]] = f_val
|
|
1042
|
+
origin_3d = pcfg(coord_map["x"], coord_map["y"], coord_map["z"])
|
|
1043
|
+
|
|
1044
|
+
# Basis vectors
|
|
1045
|
+
normal_key = {OUT: "OUT", IN: "IN", UP: "UP",
|
|
1046
|
+
DOWN: "DOWN", RIGHT: "RIGHT", LEFT: "LEFT"}[fm["normal"]]
|
|
1047
|
+
basis_u, basis_v = self._BASIS_MAP[normal_key]
|
|
1048
|
+
|
|
1049
|
+
# Build plane config with inherited ranges
|
|
1050
|
+
cfg = plane_config or PlaneConfig()
|
|
1051
|
+
cfg.u_range = u_range
|
|
1052
|
+
cfg.v_range = v_range
|
|
1053
|
+
cfg.u_length = parent_axes._x_length if fm["u"] == "x" else \
|
|
1054
|
+
parent_axes._y_length if fm["u"] == "y" else \
|
|
1055
|
+
parent_axes._z_length
|
|
1056
|
+
cfg.v_length = parent_axes._x_length if fm["v"] == "x" else \
|
|
1057
|
+
parent_axes._y_length if fm["v"] == "y" else \
|
|
1058
|
+
parent_axes._z_length
|
|
1059
|
+
|
|
1060
|
+
self._face = face
|
|
1061
|
+
self._parent_c2p = pcfg
|
|
1062
|
+
|
|
1063
|
+
super().__init__(
|
|
1064
|
+
origin_3d=origin_3d,
|
|
1065
|
+
basis_u=basis_u,
|
|
1066
|
+
basis_v=basis_v,
|
|
1067
|
+
plane_config=cfg,
|
|
1068
|
+
**kwargs,
|
|
1069
|
+
)
|
|
1070
|
+
|
|
1071
|
+
# Override plane_c2p to use parent axes coordinate system exactly
|
|
1072
|
+
def plane_c2p(self, u: float, v: float) -> np.ndarray:
|
|
1073
|
+
fm = self._FACE_MAP[self._face]
|
|
1074
|
+
f_ax = getattr(self._plane_cfg, "fixed_val", 0.0)
|
|
1075
|
+
coords: Dict[str, float] = {}
|
|
1076
|
+
coords[fm["u"]] = u
|
|
1077
|
+
coords[fm["v"]] = v
|
|
1078
|
+
coords[fm["fixed"]] = f_ax
|
|
1079
|
+
return self._parent_c2p(coords.get("x", 0.0),
|
|
1080
|
+
coords.get("y", 0.0),
|
|
1081
|
+
coords.get("z", 0.0))
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1085
|
+
# 9. FLOATING PLANE 3D
|
|
1086
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1087
|
+
|
|
1088
|
+
class FloatingPlane3D(NumberPlane3D):
|
|
1089
|
+
"""
|
|
1090
|
+
A ``NumberPlane3D`` that lives at a **variable data-value slice**
|
|
1091
|
+
along one axis of a ``StatsAxes3D``.
|
|
1092
|
+
|
|
1093
|
+
The slice position is controlled by a ``ValueTracker``, enabling
|
|
1094
|
+
smooth ``animate_slice()`` animations through the data volume.
|
|
1095
|
+
|
|
1096
|
+
Typical use: slicing a bivariate normal surface at z = const,
|
|
1097
|
+
showing a cross-sectional distribution as a glowing plane.
|
|
1098
|
+
|
|
1099
|
+
Usage
|
|
1100
|
+
-----
|
|
1101
|
+
::
|
|
1102
|
+
|
|
1103
|
+
axes = StatsAxes3D.for_3d_surface(...)
|
|
1104
|
+
plane = FloatingPlane3D(axes, slice_axis=AxisID.Z,
|
|
1105
|
+
slice_value=0.0)
|
|
1106
|
+
scene.add(plane)
|
|
1107
|
+
scene.play(plane.animate_slice(target_value=2.0, run_time=3))
|
|
1108
|
+
"""
|
|
1109
|
+
|
|
1110
|
+
def __init__(
|
|
1111
|
+
self,
|
|
1112
|
+
parent_axes: StatsAxes3D,
|
|
1113
|
+
slice_axis: "AxisID" = None,
|
|
1114
|
+
slice_value: float = 0.0,
|
|
1115
|
+
plane_config: Optional[PlaneConfig] = None,
|
|
1116
|
+
**kwargs,
|
|
1117
|
+
) -> None:
|
|
1118
|
+
from .axes3d import AxisID as _AID
|
|
1119
|
+
slice_axis = slice_axis or _AID.Z
|
|
1120
|
+
|
|
1121
|
+
self._parent_axes = parent_axes
|
|
1122
|
+
self._slice_axis = slice_axis
|
|
1123
|
+
self._slice_tracker = ValueTracker(slice_value)
|
|
1124
|
+
|
|
1125
|
+
# Determine orientation based on which axis is sliced
|
|
1126
|
+
axes_cfg = parent_axes.config
|
|
1127
|
+
if slice_axis == _AID.Z:
|
|
1128
|
+
u_range = axes_cfg.x.range[:2]
|
|
1129
|
+
v_range = axes_cfg.y.range[:2]
|
|
1130
|
+
basis_u = np.array([1., 0., 0.])
|
|
1131
|
+
basis_v = np.array([0., 1., 0.])
|
|
1132
|
+
def _origin():
|
|
1133
|
+
sv = self._slice_tracker.get_value()
|
|
1134
|
+
return parent_axes.c2p(
|
|
1135
|
+
(u_range[0]+u_range[1])/2,
|
|
1136
|
+
(v_range[0]+v_range[1])/2,
|
|
1137
|
+
sv)
|
|
1138
|
+
elif slice_axis == _AID.X:
|
|
1139
|
+
u_range = axes_cfg.y.range[:2]
|
|
1140
|
+
v_range = axes_cfg.z.range[:2]
|
|
1141
|
+
basis_u = np.array([0., 1., 0.])
|
|
1142
|
+
basis_v = np.array([0., 0., 1.])
|
|
1143
|
+
def _origin():
|
|
1144
|
+
sv = self._slice_tracker.get_value()
|
|
1145
|
+
return parent_axes.c2p(
|
|
1146
|
+
sv,
|
|
1147
|
+
(u_range[0]+u_range[1])/2,
|
|
1148
|
+
(v_range[0]+v_range[1])/2)
|
|
1149
|
+
else: # Y
|
|
1150
|
+
u_range = axes_cfg.x.range[:2]
|
|
1151
|
+
v_range = axes_cfg.z.range[:2]
|
|
1152
|
+
basis_u = np.array([1., 0., 0.])
|
|
1153
|
+
basis_v = np.array([0., 0., 1.])
|
|
1154
|
+
def _origin():
|
|
1155
|
+
sv = self._slice_tracker.get_value()
|
|
1156
|
+
return parent_axes.c2p(
|
|
1157
|
+
(u_range[0]+u_range[1])/2,
|
|
1158
|
+
sv,
|
|
1159
|
+
(v_range[0]+v_range[1])/2)
|
|
1160
|
+
|
|
1161
|
+
self._origin_fn = _origin
|
|
1162
|
+
|
|
1163
|
+
cfg = plane_config or PlaneConfig(
|
|
1164
|
+
u_range=u_range,
|
|
1165
|
+
v_range=v_range,
|
|
1166
|
+
fill_opacity=0.08,
|
|
1167
|
+
material=PlaneMaterial.GLASS,
|
|
1168
|
+
)
|
|
1169
|
+
|
|
1170
|
+
super().__init__(
|
|
1171
|
+
origin_3d=_origin(),
|
|
1172
|
+
basis_u=basis_u,
|
|
1173
|
+
basis_v=basis_v,
|
|
1174
|
+
plane_config=cfg,
|
|
1175
|
+
**kwargs,
|
|
1176
|
+
)
|
|
1177
|
+
|
|
1178
|
+
# Attach updater so the plane follows the tracker
|
|
1179
|
+
self.add_updater(lambda m, dt: m._update_slice_position())
|
|
1180
|
+
|
|
1181
|
+
def _update_slice_position(self) -> None:
|
|
1182
|
+
"""Move the plane to the current tracker value."""
|
|
1183
|
+
new_origin = self._origin_fn()
|
|
1184
|
+
delta = new_origin - self._origin_3d
|
|
1185
|
+
self.shift(delta)
|
|
1186
|
+
self._origin_3d = new_origin
|
|
1187
|
+
|
|
1188
|
+
def animate_slice(
|
|
1189
|
+
self,
|
|
1190
|
+
target_value: float,
|
|
1191
|
+
run_time: float = 2.5,
|
|
1192
|
+
rate_func: Callable = smooth,
|
|
1193
|
+
) -> Animation:
|
|
1194
|
+
"""
|
|
1195
|
+
Animate the plane sliding to *target_value* along its slice axis.
|
|
1196
|
+
"""
|
|
1197
|
+
return self._slice_tracker.animate(
|
|
1198
|
+
run_time=run_time,
|
|
1199
|
+
rate_func=rate_func,
|
|
1200
|
+
).set_value(target_value)
|
|
1201
|
+
|
|
1202
|
+
@property
|
|
1203
|
+
def slice_value(self) -> float:
|
|
1204
|
+
return self._slice_tracker.get_value()
|
|
1205
|
+
|
|
1206
|
+
|
|
1207
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1208
|
+
# 10. SHADOW PROJECTION SYSTEM
|
|
1209
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1210
|
+
|
|
1211
|
+
@dataclass
|
|
1212
|
+
class ShadowConfig:
|
|
1213
|
+
"""Configuration for shadow projection."""
|
|
1214
|
+
dot_radius: float = 0.045
|
|
1215
|
+
dot_opacity: float = 0.45
|
|
1216
|
+
dot_color: Optional[str] = None # None → dim version of source color
|
|
1217
|
+
show_drop_lines: bool = True
|
|
1218
|
+
drop_line_color: Optional[str] = None
|
|
1219
|
+
drop_line_opacity: float = 0.25
|
|
1220
|
+
drop_line_width: float = 0.8
|
|
1221
|
+
drop_line_style: GridStyle = GridStyle.DASHED
|
|
1222
|
+
shadow_offset: float = 0.005 # push shadow onto plane surface
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
class ShadowProjection3D(VGroup):
|
|
1226
|
+
"""
|
|
1227
|
+
Projects a group of 3-D Dot3D points (or any mobjects with a
|
|
1228
|
+
``get_center()`` method) orthogonally onto a target ``NumberPlane3D``.
|
|
1229
|
+
|
|
1230
|
+
For each source point it creates:
|
|
1231
|
+
• A Dot3D on the plane surface (the shadow)
|
|
1232
|
+
• An optional dashed drop-line from the source to the shadow
|
|
1233
|
+
|
|
1234
|
+
The projected dots and lines are stored in two sub-VGroups:
|
|
1235
|
+
``self.shadows`` — projected dots on the plane
|
|
1236
|
+
``self.drop_lines`` — dashed connector lines
|
|
1237
|
+
|
|
1238
|
+
Usage
|
|
1239
|
+
-----
|
|
1240
|
+
::
|
|
1241
|
+
|
|
1242
|
+
scatter_3d = VGroup(*[Dot3D(pt) for pt in pts])
|
|
1243
|
+
floor = FaceNumberPlane3D(axes, PlaneFace.XZ_BOTTOM)
|
|
1244
|
+
proj = ShadowProjection3D(scatter_3d, floor,
|
|
1245
|
+
ShadowConfig(dot_color=BLUE_A))
|
|
1246
|
+
scene.add(proj)
|
|
1247
|
+
scene.play(FadeIn(proj))
|
|
1248
|
+
"""
|
|
1249
|
+
|
|
1250
|
+
def __init__(
|
|
1251
|
+
self,
|
|
1252
|
+
source_mobs: VGroup,
|
|
1253
|
+
target_plane: NumberPlane3D,
|
|
1254
|
+
cfg: Optional[ShadowConfig] = None,
|
|
1255
|
+
theme: Optional[StatsColorPalette] = None,
|
|
1256
|
+
) -> None:
|
|
1257
|
+
super().__init__()
|
|
1258
|
+
cfg = cfg or ShadowConfig()
|
|
1259
|
+
theme = theme or StatsTheme.current
|
|
1260
|
+
|
|
1261
|
+
self.shadows = VGroup()
|
|
1262
|
+
self.drop_lines = VGroup()
|
|
1263
|
+
|
|
1264
|
+
for mob in source_mobs.submobjects:
|
|
1265
|
+
src_pt = mob.get_center()
|
|
1266
|
+
proj_pt = target_plane.project_point(src_pt)
|
|
1267
|
+
proj_pt = proj_pt + target_plane.normal * cfg.shadow_offset
|
|
1268
|
+
|
|
1269
|
+
# Shadow colour: dim the source colour if none specified
|
|
1270
|
+
src_color = mob.get_fill_color() or theme.primary
|
|
1271
|
+
s_color = cfg.dot_color or _dim_color(src_color, 0.55)
|
|
1272
|
+
|
|
1273
|
+
dot = Dot3D(proj_pt, radius=cfg.dot_radius, color=s_color)
|
|
1274
|
+
dot.set_opacity(cfg.dot_opacity)
|
|
1275
|
+
self.shadows.add(dot)
|
|
1276
|
+
|
|
1277
|
+
if cfg.show_drop_lines:
|
|
1278
|
+
dl_color = cfg.drop_line_color or theme.neutral
|
|
1279
|
+
if cfg.drop_line_style == GridStyle.DASHED:
|
|
1280
|
+
dl = DashedLine(src_pt, proj_pt,
|
|
1281
|
+
color=dl_color,
|
|
1282
|
+
stroke_width=cfg.drop_line_width * 1.2,
|
|
1283
|
+
dash_length=0.08)
|
|
1284
|
+
else:
|
|
1285
|
+
dl = Line3D(src_pt, proj_pt, color=dl_color,
|
|
1286
|
+
thickness=cfg.drop_line_width * 0.005)
|
|
1287
|
+
dl.set_opacity(cfg.drop_line_opacity)
|
|
1288
|
+
self.drop_lines.add(dl)
|
|
1289
|
+
|
|
1290
|
+
self.add(self.drop_lines, self.shadows)
|
|
1291
|
+
|
|
1292
|
+
def animate_project(
|
|
1293
|
+
self,
|
|
1294
|
+
source_mobs: VGroup,
|
|
1295
|
+
target_plane: NumberPlane3D,
|
|
1296
|
+
run_time: float = 1.5,
|
|
1297
|
+
lag_ratio: float = 0.03,
|
|
1298
|
+
) -> Animation:
|
|
1299
|
+
"""
|
|
1300
|
+
Animate each source point collapsing onto its projected shadow.
|
|
1301
|
+
Each source dot moves along its drop-line to its shadow position.
|
|
1302
|
+
"""
|
|
1303
|
+
anims = []
|
|
1304
|
+
for src, shadow, dl in zip(
|
|
1305
|
+
source_mobs.submobjects,
|
|
1306
|
+
self.shadows.submobjects,
|
|
1307
|
+
self.drop_lines.submobjects,
|
|
1308
|
+
):
|
|
1309
|
+
anims.append(AnimationGroup(
|
|
1310
|
+
Create(dl, run_time=run_time * 0.6),
|
|
1311
|
+
FadeIn(shadow, run_time=run_time * 0.4),
|
|
1312
|
+
))
|
|
1313
|
+
return AnimationGroup(*anims, lag_ratio=lag_ratio)
|
|
1314
|
+
|
|
1315
|
+
|
|
1316
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1317
|
+
# 11. NUMBER PLANE 3D SYSTEM (manages multiple planes)
|
|
1318
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1319
|
+
|
|
1320
|
+
class NumberPlane3DSystem(VGroup):
|
|
1321
|
+
"""
|
|
1322
|
+
Manages a coordinated set of ``NumberPlane3D`` objects — typically
|
|
1323
|
+
the three face-planes of a ``StatsAxes3D`` bounding box.
|
|
1324
|
+
|
|
1325
|
+
Provides:
|
|
1326
|
+
• Simultaneous build / exit animations for all planes
|
|
1327
|
+
• Coordinated shadow projection from 3-D data objects
|
|
1328
|
+
• Easy access to individual planes by face key
|
|
1329
|
+
|
|
1330
|
+
Usage
|
|
1331
|
+
-----
|
|
1332
|
+
::
|
|
1333
|
+
|
|
1334
|
+
axes = StatsAxes3D.for_3d_surface(...)
|
|
1335
|
+
system = NumberPlane3DSystem.for_axes(axes,
|
|
1336
|
+
faces=[PlaneFace.XZ_BOTTOM,
|
|
1337
|
+
PlaneFace.YZ_LEFT,
|
|
1338
|
+
PlaneFace.XY_BACK])
|
|
1339
|
+
scene.add(axes, system)
|
|
1340
|
+
scene.play(system.animate_build_all())
|
|
1341
|
+
"""
|
|
1342
|
+
|
|
1343
|
+
def __init__(self) -> None:
|
|
1344
|
+
super().__init__()
|
|
1345
|
+
self._planes: Dict[str, NumberPlane3D] = {}
|
|
1346
|
+
|
|
1347
|
+
def add_plane(self, key: str, plane: NumberPlane3D) -> None:
|
|
1348
|
+
"""Register and add a plane under *key*."""
|
|
1349
|
+
self._planes[key] = plane
|
|
1350
|
+
self.add(plane)
|
|
1351
|
+
|
|
1352
|
+
def get_plane(self, key: str) -> Optional[NumberPlane3D]:
|
|
1353
|
+
return self._planes.get(key)
|
|
1354
|
+
|
|
1355
|
+
def animate_build_all(
|
|
1356
|
+
self,
|
|
1357
|
+
cfg: Optional[AnimationConfig] = None,
|
|
1358
|
+
lag_ratio: float = 0.15,
|
|
1359
|
+
) -> Animation:
|
|
1360
|
+
"""Build all planes with a staggered reveal."""
|
|
1361
|
+
cfg = cfg or AnimationConfig()
|
|
1362
|
+
anims = [p.animate_build(cfg) for p in self._planes.values()]
|
|
1363
|
+
return AnimationGroup(*anims, lag_ratio=lag_ratio)
|
|
1364
|
+
|
|
1365
|
+
def animate_exit_all(
|
|
1366
|
+
self,
|
|
1367
|
+
cfg: Optional[AnimationConfig] = None,
|
|
1368
|
+
lag_ratio: float = 0.1,
|
|
1369
|
+
) -> Animation:
|
|
1370
|
+
cfg = cfg or AnimationConfig()
|
|
1371
|
+
anims = [p.animate_exit(cfg) for p in self._planes.values()]
|
|
1372
|
+
return AnimationGroup(*anims, lag_ratio=lag_ratio)
|
|
1373
|
+
|
|
1374
|
+
def project_to_all(
|
|
1375
|
+
self,
|
|
1376
|
+
source_mobs: VGroup,
|
|
1377
|
+
shadow_cfg: Optional[ShadowConfig] = None,
|
|
1378
|
+
) -> Dict[str, ShadowProjection3D]:
|
|
1379
|
+
"""
|
|
1380
|
+
Project *source_mobs* onto every registered plane.
|
|
1381
|
+
Returns dict[key, ShadowProjection3D].
|
|
1382
|
+
"""
|
|
1383
|
+
projections = {}
|
|
1384
|
+
for key, plane in self._planes.items():
|
|
1385
|
+
proj = ShadowProjection3D(source_mobs, plane, shadow_cfg)
|
|
1386
|
+
self.add(proj)
|
|
1387
|
+
projections[key] = proj
|
|
1388
|
+
return projections
|
|
1389
|
+
|
|
1390
|
+
def animate_project_to_all(
|
|
1391
|
+
self,
|
|
1392
|
+
source_mobs: VGroup,
|
|
1393
|
+
shadow_cfg: Optional[ShadowConfig] = None,
|
|
1394
|
+
run_time: float = 2.0,
|
|
1395
|
+
) -> Animation:
|
|
1396
|
+
"""Animate projections onto all planes simultaneously."""
|
|
1397
|
+
projections = self.project_to_all(source_mobs, shadow_cfg)
|
|
1398
|
+
anims = [
|
|
1399
|
+
proj.animate_project(source_mobs, plane, run_time=run_time)
|
|
1400
|
+
for (key, plane), proj in zip(self._planes.items(),
|
|
1401
|
+
projections.values())
|
|
1402
|
+
]
|
|
1403
|
+
return AnimationGroup(*anims)
|
|
1404
|
+
|
|
1405
|
+
# ── factory ───────────────────────────────────────────────────────────
|
|
1406
|
+
|
|
1407
|
+
@classmethod
|
|
1408
|
+
def for_axes(
|
|
1409
|
+
cls,
|
|
1410
|
+
parent_axes: StatsAxes3D,
|
|
1411
|
+
faces: List[PlaneFace] = None,
|
|
1412
|
+
plane_config: Optional[PlaneConfig] = None,
|
|
1413
|
+
) -> "NumberPlane3DSystem":
|
|
1414
|
+
"""
|
|
1415
|
+
Build a system of ``FaceNumberPlane3D`` objects for the given *faces*.
|
|
1416
|
+
Defaults to bottom floor + back wall + left wall.
|
|
1417
|
+
"""
|
|
1418
|
+
faces = faces or [
|
|
1419
|
+
PlaneFace.XZ_BOTTOM,
|
|
1420
|
+
PlaneFace.XY_BACK,
|
|
1421
|
+
PlaneFace.YZ_LEFT,
|
|
1422
|
+
]
|
|
1423
|
+
system = cls()
|
|
1424
|
+
for face in faces:
|
|
1425
|
+
plane = FaceNumberPlane3D(parent_axes, face, plane_config)
|
|
1426
|
+
system.add_plane(face.name, plane)
|
|
1427
|
+
return system
|
|
1428
|
+
|
|
1429
|
+
|
|
1430
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1431
|
+
# 12. UTILITIES
|
|
1432
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1433
|
+
|
|
1434
|
+
def _normalize(v: np.ndarray) -> np.ndarray:
|
|
1435
|
+
"""Safe unit-vector normalisation."""
|
|
1436
|
+
n = np.linalg.norm(v)
|
|
1437
|
+
return v / n if n > 1e-9 else v
|
|
1438
|
+
|
|
1439
|
+
|
|
1440
|
+
def _dim_color(hex_color: str, factor: float = 0.6) -> str:
|
|
1441
|
+
"""
|
|
1442
|
+
Darken *hex_color* by *factor* (0 = black, 1 = original).
|
|
1443
|
+
Used for shadow dot colours.
|
|
1444
|
+
"""
|
|
1445
|
+
from colour import Color
|
|
1446
|
+
try:
|
|
1447
|
+
c = Color(hex_color)
|
|
1448
|
+
c.luminance = max(0.0, c.luminance * factor)
|
|
1449
|
+
return c.hex_l
|
|
1450
|
+
except Exception:
|
|
1451
|
+
return hex_color
|
|
1452
|
+
|
|
1453
|
+
|
|
1454
|
+
def make_plane_for_distribution(
|
|
1455
|
+
u_range: Tuple[float, float] = (-4.0, 4.0),
|
|
1456
|
+
v_range: Tuple[float, float] = (0.0, 0.45),
|
|
1457
|
+
origin: Optional[np.ndarray] = None,
|
|
1458
|
+
facing: Literal["front", "right", "top"] = "front",
|
|
1459
|
+
theme: Optional[StatsColorPalette] = None,
|
|
1460
|
+
) -> NumberPlane3D:
|
|
1461
|
+
"""
|
|
1462
|
+
Convenience factory: return a ``NumberPlane3D`` pre-configured for
|
|
1463
|
+
displaying a 1-D probability distribution curve on a given face.
|
|
1464
|
+
"""
|
|
1465
|
+
t = theme or StatsTheme.current
|
|
1466
|
+
cfg = PlaneConfig(
|
|
1467
|
+
u_range=u_range,
|
|
1468
|
+
v_range=v_range,
|
|
1469
|
+
fill_opacity=0.10,
|
|
1470
|
+
material=PlaneMaterial.FROSTED,
|
|
1471
|
+
fill_color=t.surface,
|
|
1472
|
+
border_color=t.border,
|
|
1473
|
+
grid=PlaneGridConfig(
|
|
1474
|
+
major_spacing=1.0,
|
|
1475
|
+
major_opacity=0.35,
|
|
1476
|
+
minor_opacity=0.12,
|
|
1477
|
+
style=GridStyle.DASHED,
|
|
1478
|
+
),
|
|
1479
|
+
axes=PlaneAxisConfig(
|
|
1480
|
+
u_label="x", v_label="f(x)",
|
|
1481
|
+
show_ticks=True,
|
|
1482
|
+
),
|
|
1483
|
+
)
|
|
1484
|
+
basis_map = {
|
|
1485
|
+
"front": (np.array([1,0,0]), np.array([0,1,0])),
|
|
1486
|
+
"right": (np.array([0,1,0]), np.array([0,0,1])),
|
|
1487
|
+
"top": (np.array([1,0,0]), np.array([0,0,1])),
|
|
1488
|
+
}
|
|
1489
|
+
bu, bv = basis_map.get(facing, (np.array([1,0,0]), np.array([0,1,0])))
|
|
1490
|
+
return NumberPlane3D(
|
|
1491
|
+
origin_3d=origin if origin is not None else np.zeros(3),
|
|
1492
|
+
basis_u=bu,
|
|
1493
|
+
basis_v=bv,
|
|
1494
|
+
plane_config=cfg,
|
|
1495
|
+
)
|
|
1496
|
+
|
|
1497
|
+
|
|
1498
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1499
|
+
# 13. MODULE EXPORTS
|
|
1500
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1501
|
+
|
|
1502
|
+
__all__ = [
|
|
1503
|
+
# Enumerations
|
|
1504
|
+
"PlaneFace",
|
|
1505
|
+
"PlaneMaterial",
|
|
1506
|
+
# Config dataclasses
|
|
1507
|
+
"PlaneGridConfig",
|
|
1508
|
+
"PlaneAxisConfig",
|
|
1509
|
+
"PlaneConfig",
|
|
1510
|
+
"ShadowConfig",
|
|
1511
|
+
# Sub-components
|
|
1512
|
+
"PlaneGeometry",
|
|
1513
|
+
"PlaneGrid",
|
|
1514
|
+
"PlaneAxes",
|
|
1515
|
+
"PlaneTickSystem",
|
|
1516
|
+
"PlaneOriginMark",
|
|
1517
|
+
"PlaneDrawingLayer",
|
|
1518
|
+
# Main classes
|
|
1519
|
+
"NumberPlane3D",
|
|
1520
|
+
"FaceNumberPlane3D",
|
|
1521
|
+
"FloatingPlane3D",
|
|
1522
|
+
"ShadowProjection3D",
|
|
1523
|
+
"NumberPlane3DSystem",
|
|
1524
|
+
# Utilities
|
|
1525
|
+
"make_plane_for_distribution",
|
|
1526
|
+
]
|