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,1591 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statanim/props/spinner.py
|
|
3
|
+
============================
|
|
4
|
+
Spinner3D — A highly detailed, physically-inspired probability spinner
|
|
5
|
+
for Manim statistics animations.
|
|
6
|
+
|
|
7
|
+
Primary use cases
|
|
8
|
+
-----------------
|
|
9
|
+
Uniform discrete / continuous probability — equal-sector spinners
|
|
10
|
+
Non-uniform probability — custom sector weights
|
|
11
|
+
Experimental vs theoretical probability — repeated spin demos
|
|
12
|
+
Geometric distribution — spin until outcome X
|
|
13
|
+
Markov chains — state-transition spinner
|
|
14
|
+
|
|
15
|
+
Design goals
|
|
16
|
+
------------
|
|
17
|
+
Board
|
|
18
|
+
* Circular wooden/acrylic base with a raised rim.
|
|
19
|
+
* Wood-grain texture approximated by thin concentric and radial
|
|
20
|
+
Line strokes at low opacity.
|
|
21
|
+
* Four countersunk screw holes at cardinal points on the rim.
|
|
22
|
+
* Raised outer rim ring with evenly-spaced tick marks (major ticks
|
|
23
|
+
at sector boundaries, minor ticks between them — like a protractor).
|
|
24
|
+
|
|
25
|
+
Sectors
|
|
26
|
+
* Each sector is a filled pie wedge (Polygon approximating an arc).
|
|
27
|
+
* Three visual layers per sector:
|
|
28
|
+
– base fill (sector colour)
|
|
29
|
+
– inner shading gradient (radial dark→light approximated with
|
|
30
|
+
a slightly brighter inner annulus wedge)
|
|
31
|
+
– outer arc label zone (slightly darkened annular strip for text)
|
|
32
|
+
* Thin bright divider lines between sectors (raised border effect).
|
|
33
|
+
* Sector label: probability fraction + percentage, font-size scaled
|
|
34
|
+
to wedge arc length so it always fits.
|
|
35
|
+
|
|
36
|
+
Hub
|
|
37
|
+
* Outer brass ring (Annulus).
|
|
38
|
+
* Inner bearing disc (Circle, slightly recessed colour).
|
|
39
|
+
* Center pin (small Circle, very dark).
|
|
40
|
+
* Specular dot highlight offset toward top-left.
|
|
41
|
+
|
|
42
|
+
Needle
|
|
43
|
+
* True elongated diamond / rhombus shape — wide at the pivot,
|
|
44
|
+
tapering to a sharp point at the tip and a rounded counterweight
|
|
45
|
+
tail at the base.
|
|
46
|
+
* Specular stripe down the lit side.
|
|
47
|
+
* Drop shadow (slightly dark ellipse beneath the needle on the board).
|
|
48
|
+
* Pivot hole circle at center.
|
|
49
|
+
|
|
50
|
+
Animations
|
|
51
|
+
----------
|
|
52
|
+
SpinToOutcome — exponential angular deceleration, lands on target
|
|
53
|
+
sector with a realistic overshoot-and-settle wobble.
|
|
54
|
+
FreeSpinDecay — pure physics spin with no pre-determined outcome;
|
|
55
|
+
needle decelerates and stops wherever it lands.
|
|
56
|
+
FlickSpin — short sharp impulse, needle travels only 1–3 sectors.
|
|
57
|
+
RicochetSpin — needle "catches" on a sector boundary and ticks
|
|
58
|
+
backward slightly before settling (ratchet sound feel).
|
|
59
|
+
SpinSequence — animate N successive spins, yielding outcome list.
|
|
60
|
+
|
|
61
|
+
Dependencies
|
|
62
|
+
------------
|
|
63
|
+
manim (CE or GL), numpy, fractions
|
|
64
|
+
|
|
65
|
+
Usage
|
|
66
|
+
-----
|
|
67
|
+
from statanim.props.spinner import Spinner3D, SpinToOutcome
|
|
68
|
+
|
|
69
|
+
class GeometricScene(ThreeDScene):
|
|
70
|
+
def construct(self):
|
|
71
|
+
spinner = Spinner3D.uniform(n=4, radius=2.0)
|
|
72
|
+
self.add(spinner)
|
|
73
|
+
for _ in range(6):
|
|
74
|
+
self.play(SpinToOutcome(spinner, outcome=0,
|
|
75
|
+
n_full_rotations=3))
|
|
76
|
+
self.wait(0.4)
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
from __future__ import annotations
|
|
80
|
+
|
|
81
|
+
import numpy as np
|
|
82
|
+
from fractions import Fraction
|
|
83
|
+
from typing import Optional, Sequence, Literal, List, Tuple
|
|
84
|
+
|
|
85
|
+
from manim import (
|
|
86
|
+
VGroup,
|
|
87
|
+
Circle, Annulus, Arc, Line, Polygon, Rectangle, Dot,
|
|
88
|
+
Text, MathTex, Tex,
|
|
89
|
+
Animation, Succession, AnimationGroup,
|
|
90
|
+
ApplyMethod, Rotate, FadeIn, FadeOut,
|
|
91
|
+
interpolate_color, color_to_rgb,
|
|
92
|
+
WHITE, BLACK,
|
|
93
|
+
GREY, GREY_A, GREY_B, GREY_C, GREY_D, LIGHT_GREY,
|
|
94
|
+
RED, RED_A, RED_B, RED_C, RED_D,
|
|
95
|
+
BLUE, BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E,
|
|
96
|
+
GREEN, GREEN_A, GREEN_B, GREEN_C, GREEN_D, GREEN_E,
|
|
97
|
+
YELLOW, YELLOW_A, YELLOW_B, YELLOW_E,
|
|
98
|
+
ORANGE, PURPLE_A, PURPLE_B, TEAL, TEAL_A, TEAL_B,
|
|
99
|
+
GOLD, GOLD_A, GOLD_B, GOLD_C, GOLD_D, GOLD_E,
|
|
100
|
+
MAROON, PINK,
|
|
101
|
+
UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
|
|
102
|
+
PI, TAU,
|
|
103
|
+
rate_functions,
|
|
104
|
+
ManimColor,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
108
|
+
# Default sector colour cycle
|
|
109
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
110
|
+
|
|
111
|
+
SECTOR_COLORS: list[str] = [
|
|
112
|
+
"#E63946", # vivid red
|
|
113
|
+
"#457B9D", # steel blue
|
|
114
|
+
"#2A9D8F", # teal
|
|
115
|
+
"#E9C46A", # warm yellow
|
|
116
|
+
"#F4A261", # orange
|
|
117
|
+
"#A8DADC", # light teal
|
|
118
|
+
"#9B2226", # crimson
|
|
119
|
+
"#D4AF37", # gold
|
|
120
|
+
"#6A4C93", # purple
|
|
121
|
+
"#1B998B", # seafoam
|
|
122
|
+
"#FFBC42", # amber
|
|
123
|
+
"#3A86FF", # bright blue
|
|
124
|
+
"#8AC926", # lime green
|
|
125
|
+
"#FF595E", # coral
|
|
126
|
+
"#6D6875", # dusty purple
|
|
127
|
+
"#B5838D", # rose
|
|
128
|
+
]
|
|
129
|
+
|
|
130
|
+
# Board palette options
|
|
131
|
+
BOARD_PALETTES: dict[str, dict] = {
|
|
132
|
+
"wood": {
|
|
133
|
+
"base": "#C8A96E", # warm maple
|
|
134
|
+
"grain": "#B8955A", # grain lines
|
|
135
|
+
"rim": "#8B6340", # darker rim
|
|
136
|
+
"tick_major": "#3A2510",
|
|
137
|
+
"tick_minor": "#6A4820",
|
|
138
|
+
"screw": "#706050",
|
|
139
|
+
"screw_head": "#D4B896",
|
|
140
|
+
},
|
|
141
|
+
"acrylic_white": {
|
|
142
|
+
"base": "#F4F0E8",
|
|
143
|
+
"grain": "#E0DCD0",
|
|
144
|
+
"rim": "#C8C0B0",
|
|
145
|
+
"tick_major": "#1A1A1A",
|
|
146
|
+
"tick_minor": "#7A7A7A",
|
|
147
|
+
"screw": "#8A8A8A",
|
|
148
|
+
"screw_head": "#E8E8E8",
|
|
149
|
+
},
|
|
150
|
+
"acrylic_dark": {
|
|
151
|
+
"base": "#1C1C1E",
|
|
152
|
+
"grain": "#2A2A2C",
|
|
153
|
+
"rim": "#0A0A0C",
|
|
154
|
+
"tick_major": "#D4AF37",
|
|
155
|
+
"tick_minor": "#605840",
|
|
156
|
+
"screw": "#3A3A3A",
|
|
157
|
+
"screw_head": "#5A5A5A",
|
|
158
|
+
},
|
|
159
|
+
"felt_green": {
|
|
160
|
+
"base": "#2D5A27",
|
|
161
|
+
"grain": "#265220",
|
|
162
|
+
"rim": "#1A3A16",
|
|
163
|
+
"tick_major": "#F0E8C0",
|
|
164
|
+
"tick_minor": "#A0C878",
|
|
165
|
+
"screw": "#3A5030",
|
|
166
|
+
"screw_head": "#608050",
|
|
167
|
+
},
|
|
168
|
+
"casino_red": {
|
|
169
|
+
"base": "#7A1018",
|
|
170
|
+
"grain": "#6A0C14",
|
|
171
|
+
"rim": "#4A0810",
|
|
172
|
+
"tick_major": "#F0E8C0",
|
|
173
|
+
"tick_minor": "#C08840",
|
|
174
|
+
"screw": "#5A2820",
|
|
175
|
+
"screw_head": "#C08878",
|
|
176
|
+
},
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
HUB_PALETTES: dict[str, dict] = {
|
|
180
|
+
"brass": {
|
|
181
|
+
"outer": "#B8860B",
|
|
182
|
+
"outer_hl": "#DAA520",
|
|
183
|
+
"bearing": "#8B6914",
|
|
184
|
+
"pin": "#2A1A08",
|
|
185
|
+
"spec": "#FFD700",
|
|
186
|
+
},
|
|
187
|
+
"chrome": {
|
|
188
|
+
"outer": "#B0B8C0",
|
|
189
|
+
"outer_hl": "#E8F0F8",
|
|
190
|
+
"bearing": "#808898",
|
|
191
|
+
"pin": "#1A1A2A",
|
|
192
|
+
"spec": "#FFFFFF",
|
|
193
|
+
},
|
|
194
|
+
"black_oxide": {
|
|
195
|
+
"outer": "#2A2A30",
|
|
196
|
+
"outer_hl": "#4A4A58",
|
|
197
|
+
"bearing": "#1A1A20",
|
|
198
|
+
"pin": "#080810",
|
|
199
|
+
"spec": "#6A6A80",
|
|
200
|
+
},
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
NEEDLE_PALETTES: dict[str, dict] = {
|
|
204
|
+
"red_chrome": {
|
|
205
|
+
"body": "#CC2222",
|
|
206
|
+
"dark": "#6A0808",
|
|
207
|
+
"spec": "#FF8080",
|
|
208
|
+
"shadow": "#1A0808",
|
|
209
|
+
"tail": "#881818",
|
|
210
|
+
},
|
|
211
|
+
"black_chrome": {
|
|
212
|
+
"body": "#1A1A20",
|
|
213
|
+
"dark": "#080810",
|
|
214
|
+
"spec": "#5A5A70",
|
|
215
|
+
"shadow": "#050508",
|
|
216
|
+
"tail": "#2A2A30",
|
|
217
|
+
},
|
|
218
|
+
"gold": {
|
|
219
|
+
"body": "#D4AF37",
|
|
220
|
+
"dark": "#8B7010",
|
|
221
|
+
"spec": "#FFE066",
|
|
222
|
+
"shadow": "#2A1A08",
|
|
223
|
+
"tail": "#B89028",
|
|
224
|
+
},
|
|
225
|
+
"white": {
|
|
226
|
+
"body": "#F0EEE8",
|
|
227
|
+
"dark": "#A0A098",
|
|
228
|
+
"spec": "#FFFFFF",
|
|
229
|
+
"shadow": "#202020",
|
|
230
|
+
"tail": "#C8C8C0",
|
|
231
|
+
},
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
236
|
+
# Geometry helpers
|
|
237
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
238
|
+
|
|
239
|
+
def _wedge_polygon(
|
|
240
|
+
r_inner: float,
|
|
241
|
+
r_outer: float,
|
|
242
|
+
start_angle: float,
|
|
243
|
+
end_angle: float,
|
|
244
|
+
n_arc_pts: int = 32,
|
|
245
|
+
z: float = 0.0,
|
|
246
|
+
) -> list[list[float]]:
|
|
247
|
+
"""
|
|
248
|
+
Vertices for a filled annular wedge (sector ring).
|
|
249
|
+
Returns a flat list suitable for Polygon(*verts).
|
|
250
|
+
"""
|
|
251
|
+
angles_fwd = np.linspace(start_angle, end_angle, n_arc_pts)
|
|
252
|
+
angles_rev = np.linspace(end_angle, start_angle, n_arc_pts)
|
|
253
|
+
|
|
254
|
+
outer_pts = [[r_outer * np.cos(a), r_outer * np.sin(a), z]
|
|
255
|
+
for a in angles_fwd]
|
|
256
|
+
inner_pts = [[r_inner * np.cos(a), r_inner * np.sin(a), z]
|
|
257
|
+
for a in angles_rev]
|
|
258
|
+
return outer_pts + inner_pts
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _pie_polygon(
|
|
262
|
+
radius: float,
|
|
263
|
+
start_angle: float,
|
|
264
|
+
end_angle: float,
|
|
265
|
+
n_arc_pts: int = 48,
|
|
266
|
+
z: float = 0.0,
|
|
267
|
+
) -> list[list[float]]:
|
|
268
|
+
"""Vertices for a filled pie-slice (sector from centre)."""
|
|
269
|
+
angles = np.linspace(start_angle, end_angle, n_arc_pts)
|
|
270
|
+
arc_pts = [[radius * np.cos(a), radius * np.sin(a), z]
|
|
271
|
+
for a in angles]
|
|
272
|
+
return [[0, 0, z]] + arc_pts
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _sector_label_position(
|
|
276
|
+
r_mid: float,
|
|
277
|
+
mid_angle: float,
|
|
278
|
+
) -> np.ndarray:
|
|
279
|
+
"""World position for a label at the centre of a sector."""
|
|
280
|
+
return np.array([r_mid * np.cos(mid_angle),
|
|
281
|
+
r_mid * np.sin(mid_angle),
|
|
282
|
+
0.0])
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _arc_text_centered(
|
|
286
|
+
text: str,
|
|
287
|
+
radius: float,
|
|
288
|
+
mid_angle: float,
|
|
289
|
+
font_size: float,
|
|
290
|
+
color: str,
|
|
291
|
+
font: str = "sans-serif",
|
|
292
|
+
) -> Text:
|
|
293
|
+
"""Single text mob centred at the sector midpoint."""
|
|
294
|
+
t = Text(text, font_size=font_size, color=color, font=font)
|
|
295
|
+
pos = _sector_label_position(radius, mid_angle)
|
|
296
|
+
t.move_to(pos)
|
|
297
|
+
# Rotate to face outward from centre
|
|
298
|
+
t.rotate(mid_angle - PI / 2, about_point=pos)
|
|
299
|
+
return t
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
303
|
+
# Sub-components
|
|
304
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
305
|
+
|
|
306
|
+
class _SpinnerBoard(VGroup):
|
|
307
|
+
"""
|
|
308
|
+
The circular board of the spinner.
|
|
309
|
+
|
|
310
|
+
Layers (back → front):
|
|
311
|
+
1. base_disc — filled circle, board body colour
|
|
312
|
+
2. grain_lines — concentric and radial lines at low opacity
|
|
313
|
+
(wood/felt texture approximation)
|
|
314
|
+
3. rim_ring — Annulus for the raised outer rim
|
|
315
|
+
4. tick_marks — minor + major ticks around the rim
|
|
316
|
+
5. screw_holes — 4 decorative countersunk screw holes
|
|
317
|
+
|
|
318
|
+
Parameters
|
|
319
|
+
----------
|
|
320
|
+
radius : float — board radius
|
|
321
|
+
board_palette: dict
|
|
322
|
+
tick_minor_n : int — minor ticks between sector boundaries (default 4)
|
|
323
|
+
n_sectors : int — number of sectors (drives major tick placement)
|
|
324
|
+
"""
|
|
325
|
+
|
|
326
|
+
def __init__(
|
|
327
|
+
self,
|
|
328
|
+
radius: float,
|
|
329
|
+
board_palette: dict,
|
|
330
|
+
n_sectors: int = 4,
|
|
331
|
+
tick_minor_n: int = 4,
|
|
332
|
+
**kwargs,
|
|
333
|
+
):
|
|
334
|
+
super().__init__(**kwargs)
|
|
335
|
+
bp = board_palette
|
|
336
|
+
rim_w = radius * 0.055
|
|
337
|
+
|
|
338
|
+
# ── 1. Base disc ──────────────────────────────────────────────
|
|
339
|
+
base = Circle(
|
|
340
|
+
radius=radius,
|
|
341
|
+
fill_color=bp["base"],
|
|
342
|
+
fill_opacity=1.0,
|
|
343
|
+
stroke_width=0,
|
|
344
|
+
)
|
|
345
|
+
self.add(base)
|
|
346
|
+
|
|
347
|
+
# ── 2. Wood / felt grain texture ──────────────────────────────
|
|
348
|
+
grain = VGroup()
|
|
349
|
+
# Concentric rings
|
|
350
|
+
n_rings = 8
|
|
351
|
+
for i in range(1, n_rings + 1):
|
|
352
|
+
r_g = radius * 0.92 * (i / n_rings)
|
|
353
|
+
ring = Circle(
|
|
354
|
+
radius=r_g,
|
|
355
|
+
stroke_color=bp["grain"],
|
|
356
|
+
stroke_width=0.5,
|
|
357
|
+
stroke_opacity=0.30,
|
|
358
|
+
fill_opacity=0,
|
|
359
|
+
)
|
|
360
|
+
grain.add(ring)
|
|
361
|
+
# Radial grain lines (sparse)
|
|
362
|
+
n_grain_lines = 24
|
|
363
|
+
for i in range(n_grain_lines):
|
|
364
|
+
ang = i * TAU / n_grain_lines
|
|
365
|
+
grain.add(Line(
|
|
366
|
+
start=[0, 0, 0.001],
|
|
367
|
+
end=[(radius * 0.90) * np.cos(ang),
|
|
368
|
+
(radius * 0.90) * np.sin(ang), 0.001],
|
|
369
|
+
stroke_color=bp["grain"],
|
|
370
|
+
stroke_width=0.4,
|
|
371
|
+
stroke_opacity=0.18,
|
|
372
|
+
))
|
|
373
|
+
self.add(grain)
|
|
374
|
+
|
|
375
|
+
# ── 3. Rim ring ───────────────────────────────────────────────
|
|
376
|
+
rim = Annulus(
|
|
377
|
+
inner_radius=radius - rim_w,
|
|
378
|
+
outer_radius=radius,
|
|
379
|
+
fill_color=bp["rim"],
|
|
380
|
+
fill_opacity=1.0,
|
|
381
|
+
stroke_width=0,
|
|
382
|
+
)
|
|
383
|
+
rim.move_to([0, 0, 0.002])
|
|
384
|
+
self.add(rim)
|
|
385
|
+
|
|
386
|
+
# ── 4. Tick marks on the rim ──────────────────────────────────
|
|
387
|
+
ticks = VGroup()
|
|
388
|
+
# Total ticks: n_sectors major + n_sectors*(tick_minor_n) minor
|
|
389
|
+
total_ticks = n_sectors * (tick_minor_n + 1)
|
|
390
|
+
for i in range(total_ticks):
|
|
391
|
+
ang = i * TAU / total_ticks
|
|
392
|
+
is_major = (i % (tick_minor_n + 1) == 0)
|
|
393
|
+
t_len = rim_w * (0.85 if is_major else 0.45)
|
|
394
|
+
t_width = 1.6 if is_major else 0.8
|
|
395
|
+
t_color = bp["tick_major"] if is_major else bp["tick_minor"]
|
|
396
|
+
r_outer = radius - rim_w * 0.08
|
|
397
|
+
r_inner = r_outer - t_len
|
|
398
|
+
ticks.add(Line(
|
|
399
|
+
start=[r_outer * np.cos(ang), r_outer * np.sin(ang), 0.003],
|
|
400
|
+
end =[r_inner * np.cos(ang), r_inner * np.sin(ang), 0.003],
|
|
401
|
+
stroke_color=t_color,
|
|
402
|
+
stroke_width=t_width,
|
|
403
|
+
))
|
|
404
|
+
self.add(ticks)
|
|
405
|
+
|
|
406
|
+
# ── 5. Screw holes (4 cardinal points) ───────────────────────
|
|
407
|
+
screws = VGroup()
|
|
408
|
+
screw_r = rim_w * 0.38
|
|
409
|
+
for ang in [0, PI/2, PI, 3*PI/2]:
|
|
410
|
+
r_pos = radius - rim_w * 0.50
|
|
411
|
+
cx, cy = r_pos * np.cos(ang), r_pos * np.sin(ang)
|
|
412
|
+
# Countersink shadow
|
|
413
|
+
sink = Circle(
|
|
414
|
+
radius=screw_r * 1.35,
|
|
415
|
+
fill_color=bp["screw"],
|
|
416
|
+
fill_opacity=0.80,
|
|
417
|
+
stroke_width=0,
|
|
418
|
+
)
|
|
419
|
+
sink.move_to([cx, cy, 0.003])
|
|
420
|
+
# Screw head
|
|
421
|
+
head = Circle(
|
|
422
|
+
radius=screw_r,
|
|
423
|
+
fill_color=bp["screw_head"],
|
|
424
|
+
fill_opacity=1.0,
|
|
425
|
+
stroke_width=0,
|
|
426
|
+
)
|
|
427
|
+
head.move_to([cx, cy, 0.004])
|
|
428
|
+
# Cross slot lines
|
|
429
|
+
for slot_ang in [0, PI/2]:
|
|
430
|
+
screws.add(Line(
|
|
431
|
+
start=[cx + screw_r*0.70*np.cos(slot_ang),
|
|
432
|
+
cy + screw_r*0.70*np.sin(slot_ang), 0.005],
|
|
433
|
+
end =[cx - screw_r*0.70*np.cos(slot_ang),
|
|
434
|
+
cy - screw_r*0.70*np.sin(slot_ang), 0.005],
|
|
435
|
+
stroke_color=bp["screw"],
|
|
436
|
+
stroke_width=0.8,
|
|
437
|
+
))
|
|
438
|
+
screws.add(sink, head)
|
|
439
|
+
self.add(screws)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class _SpinnerSectors(VGroup):
|
|
443
|
+
"""
|
|
444
|
+
All pie sectors of the spinner, with labels.
|
|
445
|
+
|
|
446
|
+
Each sector has:
|
|
447
|
+
1. base wedge — filled pie slice
|
|
448
|
+
2. light inner wedge — brighter annular arc near the centre
|
|
449
|
+
(radial highlight, simulates convex sheen)
|
|
450
|
+
3. dark outer strip — slightly darker arc near the rim (label bg)
|
|
451
|
+
4. divider line — bright thin line at each sector boundary
|
|
452
|
+
5. label text — probability string, rotated to face outward
|
|
453
|
+
|
|
454
|
+
Parameters
|
|
455
|
+
----------
|
|
456
|
+
weights : sequence[float] — unnormalised sector weights
|
|
457
|
+
labels : sequence[str] | None — override labels per sector
|
|
458
|
+
colors : sequence[str] | None — override colours per sector
|
|
459
|
+
radius : float — usable board radius (inside rim)
|
|
460
|
+
start_angle : float — angle of first sector's leading edge (default PI/2)
|
|
461
|
+
show_labels : bool
|
|
462
|
+
label_style : "fraction" | "percent" | "both" | "name"
|
|
463
|
+
"""
|
|
464
|
+
|
|
465
|
+
def __init__(
|
|
466
|
+
self,
|
|
467
|
+
weights: Sequence[float],
|
|
468
|
+
radius: float,
|
|
469
|
+
labels: Optional[Sequence[str]] = None,
|
|
470
|
+
colors: Optional[Sequence[str]] = None,
|
|
471
|
+
start_angle: float = PI / 2,
|
|
472
|
+
show_labels: bool = True,
|
|
473
|
+
label_style: Literal["fraction", "percent", "both", "name"] = "both",
|
|
474
|
+
**kwargs,
|
|
475
|
+
):
|
|
476
|
+
super().__init__(**kwargs)
|
|
477
|
+
|
|
478
|
+
total = sum(weights)
|
|
479
|
+
n = len(weights)
|
|
480
|
+
r_board = radius * 0.95 # slightly inside rim
|
|
481
|
+
r_inner = r_board * 0.12 # inner dead zone (hub will cover)
|
|
482
|
+
r_label = r_board * 0.65 # label radial position
|
|
483
|
+
|
|
484
|
+
# Cumulative angles
|
|
485
|
+
cum_angles = [start_angle]
|
|
486
|
+
for w in weights:
|
|
487
|
+
cum_angles.append(cum_angles[-1] - (w / total) * TAU)
|
|
488
|
+
|
|
489
|
+
self._sector_angles = [] # (mid_angle, start, end) for each sector
|
|
490
|
+
self._sector_colors = []
|
|
491
|
+
|
|
492
|
+
for i in range(n):
|
|
493
|
+
a_start = cum_angles[i]
|
|
494
|
+
a_end = cum_angles[i + 1]
|
|
495
|
+
mid_ang = (a_start + a_end) / 2
|
|
496
|
+
span = abs(a_end - a_start)
|
|
497
|
+
|
|
498
|
+
col = (colors[i % len(colors)] if colors
|
|
499
|
+
else SECTOR_COLORS[i % len(SECTOR_COLORS)])
|
|
500
|
+
dark_col = interpolate_color(col, BLACK, 0.32)
|
|
501
|
+
lite_col = interpolate_color(col, WHITE, 0.28)
|
|
502
|
+
|
|
503
|
+
self._sector_angles.append((mid_ang, a_start, a_end))
|
|
504
|
+
self._sector_colors.append(col)
|
|
505
|
+
|
|
506
|
+
# ── 1. Base pie slice ─────────────────────────────────────
|
|
507
|
+
verts = _pie_polygon(r_board, a_end, a_start, n_arc_pts=48,
|
|
508
|
+
z=0.001)
|
|
509
|
+
base = Polygon(
|
|
510
|
+
*verts,
|
|
511
|
+
fill_color=col,
|
|
512
|
+
fill_opacity=1.0,
|
|
513
|
+
stroke_width=0,
|
|
514
|
+
)
|
|
515
|
+
self.add(base)
|
|
516
|
+
|
|
517
|
+
# ── 2. Inner bright arc (convex highlight near centre) ────
|
|
518
|
+
if span > 0.08:
|
|
519
|
+
hl_verts = _wedge_polygon(
|
|
520
|
+
r_inner, r_board * 0.42,
|
|
521
|
+
a_end, a_start, n_arc_pts=24, z=0.002,
|
|
522
|
+
)
|
|
523
|
+
hl_wedge = Polygon(
|
|
524
|
+
*hl_verts,
|
|
525
|
+
fill_color=lite_col,
|
|
526
|
+
fill_opacity=0.28,
|
|
527
|
+
stroke_width=0,
|
|
528
|
+
)
|
|
529
|
+
self.add(hl_wedge)
|
|
530
|
+
|
|
531
|
+
# ── 3. Outer dark strip (label background) ────────────────
|
|
532
|
+
if span > 0.08:
|
|
533
|
+
outer_verts = _wedge_polygon(
|
|
534
|
+
r_board * 0.80, r_board,
|
|
535
|
+
a_end, a_start, n_arc_pts=24, z=0.002,
|
|
536
|
+
)
|
|
537
|
+
outer_strip = Polygon(
|
|
538
|
+
*outer_verts,
|
|
539
|
+
fill_color=dark_col,
|
|
540
|
+
fill_opacity=0.30,
|
|
541
|
+
stroke_width=0,
|
|
542
|
+
)
|
|
543
|
+
self.add(outer_strip)
|
|
544
|
+
|
|
545
|
+
# ── 4. Labels ─────────────────────────────────────────────
|
|
546
|
+
if show_labels and span > 0.15:
|
|
547
|
+
label_str = self._make_label_str(
|
|
548
|
+
weights[i], total, labels, i, label_style
|
|
549
|
+
)
|
|
550
|
+
# Scale font to arc length
|
|
551
|
+
arc_len = r_label * span
|
|
552
|
+
font_size = max(8, min(28, arc_len * 18))
|
|
553
|
+
|
|
554
|
+
lbl_color = (WHITE
|
|
555
|
+
if _perceived_luminance(col) < 0.50
|
|
556
|
+
else "#1A1A1A")
|
|
557
|
+
lbl = Text(
|
|
558
|
+
label_str,
|
|
559
|
+
font_size=font_size,
|
|
560
|
+
color=lbl_color,
|
|
561
|
+
font="sans-serif",
|
|
562
|
+
)
|
|
563
|
+
lbl_pos = _sector_label_position(r_label, mid_ang)
|
|
564
|
+
lbl.move_to(lbl_pos + np.array([0, 0, 0.012]))
|
|
565
|
+
lbl.rotate(mid_ang - PI / 2, about_point=lbl_pos)
|
|
566
|
+
self.add(lbl)
|
|
567
|
+
|
|
568
|
+
# ── 5. Sector divider lines ───────────────────────────────────
|
|
569
|
+
for ang in cum_angles:
|
|
570
|
+
divider = Line(
|
|
571
|
+
start=[r_inner * np.cos(ang), r_inner * np.sin(ang), 0.006],
|
|
572
|
+
end =[r_board * np.cos(ang), r_board * np.sin(ang), 0.006],
|
|
573
|
+
stroke_color=WHITE,
|
|
574
|
+
stroke_width=1.6,
|
|
575
|
+
stroke_opacity=0.70,
|
|
576
|
+
)
|
|
577
|
+
self.add(divider)
|
|
578
|
+
|
|
579
|
+
@staticmethod
|
|
580
|
+
def _make_label_str(
|
|
581
|
+
w: float,
|
|
582
|
+
total: float,
|
|
583
|
+
labels: Optional[Sequence[str]],
|
|
584
|
+
i: int,
|
|
585
|
+
style: str,
|
|
586
|
+
) -> str:
|
|
587
|
+
if style == "name" and labels is not None:
|
|
588
|
+
return str(labels[i])
|
|
589
|
+
pct = w / total * 100
|
|
590
|
+
try:
|
|
591
|
+
frac = Fraction(w / total).limit_denominator(20)
|
|
592
|
+
frac_str = f"{frac.numerator}/{frac.denominator}"
|
|
593
|
+
except Exception:
|
|
594
|
+
frac_str = f"{pct:.0f}%"
|
|
595
|
+
|
|
596
|
+
if style == "fraction":
|
|
597
|
+
return frac_str
|
|
598
|
+
elif style == "percent":
|
|
599
|
+
return f"{pct:.1f}%"
|
|
600
|
+
elif style == "both":
|
|
601
|
+
return f"{frac_str}\n{pct:.0f}%"
|
|
602
|
+
elif style == "name" and labels is not None:
|
|
603
|
+
return str(labels[i])
|
|
604
|
+
return f"{pct:.0f}%"
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _perceived_luminance(hex_color: str) -> float:
|
|
608
|
+
"""Relative luminance of a hex colour (0=black, 1=white)."""
|
|
609
|
+
try:
|
|
610
|
+
rgb = np.array(color_to_rgb(hex_color), dtype=float)
|
|
611
|
+
return 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]
|
|
612
|
+
except Exception:
|
|
613
|
+
return 0.5
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
class _SpinnerHub(VGroup):
|
|
617
|
+
"""
|
|
618
|
+
Multi-layer center hub: brass ring → bearing disc → pin → specular.
|
|
619
|
+
|
|
620
|
+
Parameters
|
|
621
|
+
----------
|
|
622
|
+
radius : float — hub outer radius
|
|
623
|
+
hub_palette : dict
|
|
624
|
+
"""
|
|
625
|
+
|
|
626
|
+
def __init__(
|
|
627
|
+
self,
|
|
628
|
+
radius: float,
|
|
629
|
+
hub_palette: dict,
|
|
630
|
+
**kwargs,
|
|
631
|
+
):
|
|
632
|
+
super().__init__(**kwargs)
|
|
633
|
+
hp = hub_palette
|
|
634
|
+
z0 = 0.020
|
|
635
|
+
|
|
636
|
+
# Outer brass ring
|
|
637
|
+
outer = Circle(
|
|
638
|
+
radius=radius,
|
|
639
|
+
fill_color=hp["outer"],
|
|
640
|
+
fill_opacity=1.0,
|
|
641
|
+
stroke_width=0,
|
|
642
|
+
)
|
|
643
|
+
outer.move_to([0, 0, z0])
|
|
644
|
+
self.add(outer)
|
|
645
|
+
|
|
646
|
+
# Highlight ring (top-left arc brightening)
|
|
647
|
+
hl_ring = Annulus(
|
|
648
|
+
inner_radius=radius * 0.72,
|
|
649
|
+
outer_radius=radius,
|
|
650
|
+
fill_color=hp["outer_hl"],
|
|
651
|
+
fill_opacity=0.35,
|
|
652
|
+
stroke_width=0,
|
|
653
|
+
)
|
|
654
|
+
hl_ring.move_to([-radius * 0.12, radius * 0.12, z0 + 0.001])
|
|
655
|
+
self.add(hl_ring)
|
|
656
|
+
|
|
657
|
+
# Bearing disc
|
|
658
|
+
bearing = Circle(
|
|
659
|
+
radius=radius * 0.65,
|
|
660
|
+
fill_color=hp["bearing"],
|
|
661
|
+
fill_opacity=1.0,
|
|
662
|
+
stroke_width=0,
|
|
663
|
+
)
|
|
664
|
+
bearing.move_to([0, 0, z0 + 0.002])
|
|
665
|
+
self.add(bearing)
|
|
666
|
+
|
|
667
|
+
# Knurling lines on bearing (decorative)
|
|
668
|
+
n_knurl = 12
|
|
669
|
+
for i in range(n_knurl):
|
|
670
|
+
ang = i * TAU / n_knurl
|
|
671
|
+
r0 = radius * 0.40
|
|
672
|
+
r1 = radius * 0.62
|
|
673
|
+
self.add(Line(
|
|
674
|
+
start=[r0 * np.cos(ang), r0 * np.sin(ang), z0 + 0.003],
|
|
675
|
+
end =[r1 * np.cos(ang), r1 * np.sin(ang), z0 + 0.003],
|
|
676
|
+
stroke_color=interpolate_color(hp["bearing"], BLACK, 0.25),
|
|
677
|
+
stroke_width=0.6,
|
|
678
|
+
stroke_opacity=0.60,
|
|
679
|
+
))
|
|
680
|
+
|
|
681
|
+
# Center pin
|
|
682
|
+
pin = Circle(
|
|
683
|
+
radius=radius * 0.22,
|
|
684
|
+
fill_color=hp["pin"],
|
|
685
|
+
fill_opacity=1.0,
|
|
686
|
+
stroke_width=0,
|
|
687
|
+
)
|
|
688
|
+
pin.move_to([0, 0, z0 + 0.004])
|
|
689
|
+
self.add(pin)
|
|
690
|
+
|
|
691
|
+
# Specular highlight dot
|
|
692
|
+
spec = Circle(
|
|
693
|
+
radius=radius * 0.10,
|
|
694
|
+
fill_color=hp["spec"],
|
|
695
|
+
fill_opacity=0.80,
|
|
696
|
+
stroke_width=0,
|
|
697
|
+
)
|
|
698
|
+
spec.move_to([-radius * 0.08, radius * 0.09, z0 + 0.005])
|
|
699
|
+
self.add(spec)
|
|
700
|
+
|
|
701
|
+
self._hub_radius = radius
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
class _SpinnerNeedle(VGroup):
|
|
705
|
+
"""
|
|
706
|
+
The spinner needle — an elongated diamond / rhombus shape with:
|
|
707
|
+
* Tapered tip (sharp point in the +Y direction)
|
|
708
|
+
* Counterweight tail (shorter blunt lobe in the -Y direction)
|
|
709
|
+
* Specular stripe along the lit (+X) face
|
|
710
|
+
* Drop shadow ellipse underneath
|
|
711
|
+
* Pivot hole circle at the rotation centre
|
|
712
|
+
|
|
713
|
+
The needle is built in its "pointing up" orientation (tip = +Y).
|
|
714
|
+
Rotation is applied by `SpinToOutcome` / `FreeSpinDecay`.
|
|
715
|
+
|
|
716
|
+
Parameters
|
|
717
|
+
----------
|
|
718
|
+
length : float — tip-to-tail total length
|
|
719
|
+
width : float — max width at the pivot (default length * 0.09)
|
|
720
|
+
needle_palette : dict
|
|
721
|
+
"""
|
|
722
|
+
|
|
723
|
+
def __init__(
|
|
724
|
+
self,
|
|
725
|
+
length: float,
|
|
726
|
+
width: Optional[float] = None,
|
|
727
|
+
needle_palette: Optional[dict] = None,
|
|
728
|
+
**kwargs,
|
|
729
|
+
):
|
|
730
|
+
super().__init__(**kwargs)
|
|
731
|
+
if needle_palette is None:
|
|
732
|
+
needle_palette = NEEDLE_PALETTES["red_chrome"]
|
|
733
|
+
if width is None:
|
|
734
|
+
width = length * 0.085
|
|
735
|
+
|
|
736
|
+
np_ = needle_palette
|
|
737
|
+
z0 = 0.025
|
|
738
|
+
|
|
739
|
+
tip_y = length * 0.62 # tip above pivot
|
|
740
|
+
tail_y = -length * 0.38 # tail below pivot
|
|
741
|
+
hw = width / 2 # half-width at pivot
|
|
742
|
+
|
|
743
|
+
# ── Drop shadow (dark ellipse on board) ──────────────────────
|
|
744
|
+
shadow = Circle(
|
|
745
|
+
radius=length * 0.48,
|
|
746
|
+
fill_color=np_["shadow"],
|
|
747
|
+
fill_opacity=0.18,
|
|
748
|
+
stroke_width=0,
|
|
749
|
+
)
|
|
750
|
+
shadow.scale([0.18, 1.0, 1.0])
|
|
751
|
+
shadow.move_to([length * 0.04, 0, z0 - 0.002])
|
|
752
|
+
self.add(shadow)
|
|
753
|
+
|
|
754
|
+
# ── Main needle body (diamond polygon) ───────────────────────
|
|
755
|
+
# 4 vertices: tip, right-shoulder, tail, left-shoulder
|
|
756
|
+
shoulder_y = length * 0.05 # shoulders are slightly above pivot
|
|
757
|
+
tip_v = [0, tip_y, z0]
|
|
758
|
+
right_v = [ hw, shoulder_y, z0]
|
|
759
|
+
tail_v = [0, tail_y, z0]
|
|
760
|
+
left_v = [-hw, shoulder_y, z0]
|
|
761
|
+
|
|
762
|
+
body = Polygon(
|
|
763
|
+
tip_v, right_v, tail_v, left_v,
|
|
764
|
+
fill_color=np_["body"],
|
|
765
|
+
fill_opacity=1.0,
|
|
766
|
+
stroke_width=0,
|
|
767
|
+
)
|
|
768
|
+
self.add(body)
|
|
769
|
+
|
|
770
|
+
# ── Dark underside (right half slightly darker) ───────────────
|
|
771
|
+
dark_right = Polygon(
|
|
772
|
+
tip_v, right_v, tail_v,
|
|
773
|
+
fill_color=np_["dark"],
|
|
774
|
+
fill_opacity=0.40,
|
|
775
|
+
stroke_width=0,
|
|
776
|
+
)
|
|
777
|
+
dark_right.move_to(dark_right.get_center() + np.array([0, 0, 0.001]))
|
|
778
|
+
self.add(dark_right)
|
|
779
|
+
|
|
780
|
+
# ── Specular stripe (left face) ───────────────────────────────
|
|
781
|
+
# A thin tapered polygon along the left edge of the needle
|
|
782
|
+
spec_w = hw * 0.35
|
|
783
|
+
spec = Polygon(
|
|
784
|
+
[0, tip_y * 0.92, z0 + 0.002],
|
|
785
|
+
[-spec_w, shoulder_y, z0 + 0.002],
|
|
786
|
+
[0, tail_y * 0.65, z0 + 0.002],
|
|
787
|
+
fill_color=np_["spec"],
|
|
788
|
+
fill_opacity=0.55,
|
|
789
|
+
stroke_width=0,
|
|
790
|
+
)
|
|
791
|
+
self.add(spec)
|
|
792
|
+
|
|
793
|
+
# ── Tail cap (blunt rounded lobe) ─────────────────────────────
|
|
794
|
+
tail_cap = Circle(
|
|
795
|
+
radius=hw * 1.10,
|
|
796
|
+
fill_color=np_["tail"],
|
|
797
|
+
fill_opacity=1.0,
|
|
798
|
+
stroke_width=0,
|
|
799
|
+
)
|
|
800
|
+
tail_cap.move_to([0, tail_y + hw * 0.80, z0 + 0.001])
|
|
801
|
+
self.add(tail_cap)
|
|
802
|
+
|
|
803
|
+
# ── Tip cap ───────────────────────────────────────────────────
|
|
804
|
+
tip_cap = Circle(
|
|
805
|
+
radius=hw * 0.22,
|
|
806
|
+
fill_color=interpolate_color(np_["body"], WHITE, 0.45),
|
|
807
|
+
fill_opacity=1.0,
|
|
808
|
+
stroke_width=0,
|
|
809
|
+
)
|
|
810
|
+
tip_cap.move_to([0, tip_y - hw * 0.10, z0 + 0.002])
|
|
811
|
+
self.add(tip_cap)
|
|
812
|
+
|
|
813
|
+
# ── Pivot hole ────────────────────────────────────────────────
|
|
814
|
+
pivot_hole = Circle(
|
|
815
|
+
radius=hw * 0.42,
|
|
816
|
+
fill_color=np_["dark"],
|
|
817
|
+
fill_opacity=1.0,
|
|
818
|
+
stroke_width=0,
|
|
819
|
+
)
|
|
820
|
+
pivot_hole.move_to([0, 0, z0 + 0.005])
|
|
821
|
+
self.add(pivot_hole)
|
|
822
|
+
|
|
823
|
+
self._tip_y = tip_y
|
|
824
|
+
self._tail_y = tail_y
|
|
825
|
+
self._length = length
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
829
|
+
# Spinner3D ── the main export
|
|
830
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
831
|
+
|
|
832
|
+
class Spinner3D(VGroup):
|
|
833
|
+
"""
|
|
834
|
+
A detailed circular probability spinner.
|
|
835
|
+
|
|
836
|
+
Parameters
|
|
837
|
+
----------
|
|
838
|
+
weights : sequence[float]
|
|
839
|
+
Unnormalised sector weights. E.g. ``[1, 1, 1, 1]`` for uniform
|
|
840
|
+
4-sector; ``[3, 1, 2]`` for 3 unequal sectors.
|
|
841
|
+
radius : float
|
|
842
|
+
Board radius in Manim units. Default ``2.0``.
|
|
843
|
+
labels : sequence[str] | None
|
|
844
|
+
Override label text per sector (used with ``label_style="name"``).
|
|
845
|
+
If ``None``, labels are derived from the weights.
|
|
846
|
+
colors : sequence[str] | None
|
|
847
|
+
Override sector colours. Cycles through ``SECTOR_COLORS`` if None.
|
|
848
|
+
sector_names : sequence[str] | None
|
|
849
|
+
Display names shown on sectors (label_style="name").
|
|
850
|
+
board_palette : str
|
|
851
|
+
Named board palette key. Default ``"wood"``.
|
|
852
|
+
hub_palette : str
|
|
853
|
+
Named hub palette key. Default ``"brass"``.
|
|
854
|
+
needle_palette : str
|
|
855
|
+
Named needle palette key. Default ``"red_chrome"``.
|
|
856
|
+
show_labels : bool
|
|
857
|
+
Show probability labels on sectors. Default ``True``.
|
|
858
|
+
label_style : "fraction" | "percent" | "both" | "name"
|
|
859
|
+
Label format. Default ``"both"``.
|
|
860
|
+
start_angle : float
|
|
861
|
+
Angle of first sector's leading edge. Default ``PI/2`` (12 o'clock).
|
|
862
|
+
needle_angle : float
|
|
863
|
+
Initial needle pointing angle. Default ``PI/2`` (pointing up).
|
|
864
|
+
tick_minor_n : int
|
|
865
|
+
Minor tick marks per sector. Default ``4``.
|
|
866
|
+
lathe_slices : int
|
|
867
|
+
Unused (kept for API consistency).
|
|
868
|
+
|
|
869
|
+
Attributes
|
|
870
|
+
----------
|
|
871
|
+
board : _SpinnerBoard
|
|
872
|
+
sectors : _SpinnerSectors
|
|
873
|
+
hub : _SpinnerHub
|
|
874
|
+
needle : _SpinnerNeedle
|
|
875
|
+
weights : list[float]
|
|
876
|
+
n_sectors : int
|
|
877
|
+
needle_angle: float — current needle pointing angle (radians)
|
|
878
|
+
sector_mid_angles : list[float] — midpoint angle of each sector
|
|
879
|
+
|
|
880
|
+
Class methods
|
|
881
|
+
-------------
|
|
882
|
+
Spinner3D.uniform(n, **kw) — equal-weight n-sector spinner
|
|
883
|
+
Spinner3D.from_probs(p, **kw) — from probability list summing to 1
|
|
884
|
+
Spinner3D.named(items, **kw) — from [(name, weight), ...] list
|
|
885
|
+
|
|
886
|
+
Examples
|
|
887
|
+
--------
|
|
888
|
+
::
|
|
889
|
+
|
|
890
|
+
# 4-sector uniform spinner
|
|
891
|
+
s = Spinner3D.uniform(4, radius=2.0, board_palette="wood")
|
|
892
|
+
|
|
893
|
+
# Custom weights spinner
|
|
894
|
+
s = Spinner3D([3, 1, 2], radius=2.5, label_style="percent")
|
|
895
|
+
|
|
896
|
+
# Named outcomes
|
|
897
|
+
s = Spinner3D.named([
|
|
898
|
+
("Red", 3),
|
|
899
|
+
("Blue", 2),
|
|
900
|
+
("Green", 1),
|
|
901
|
+
], label_style="name")
|
|
902
|
+
|
|
903
|
+
# Animate
|
|
904
|
+
scene.play(SpinToOutcome(s, outcome=0, n_full_rotations=4))
|
|
905
|
+
"""
|
|
906
|
+
|
|
907
|
+
def __init__(
|
|
908
|
+
self,
|
|
909
|
+
weights: Sequence[float],
|
|
910
|
+
radius: float = 2.0,
|
|
911
|
+
labels: Optional[Sequence[str]] = None,
|
|
912
|
+
colors: Optional[Sequence[str]] = None,
|
|
913
|
+
sector_names: Optional[Sequence[str]] = None,
|
|
914
|
+
board_palette: str = "wood",
|
|
915
|
+
hub_palette: str = "brass",
|
|
916
|
+
needle_palette: str = "red_chrome",
|
|
917
|
+
show_labels: bool = True,
|
|
918
|
+
label_style: Literal[
|
|
919
|
+
"fraction", "percent", "both", "name"
|
|
920
|
+
] = "both",
|
|
921
|
+
start_angle: float = PI / 2,
|
|
922
|
+
needle_angle: float = PI / 2,
|
|
923
|
+
tick_minor_n: int = 4,
|
|
924
|
+
**kwargs,
|
|
925
|
+
):
|
|
926
|
+
super().__init__(**kwargs)
|
|
927
|
+
|
|
928
|
+
weights = list(weights)
|
|
929
|
+
n = len(weights)
|
|
930
|
+
total = sum(weights)
|
|
931
|
+
|
|
932
|
+
self._weights = weights
|
|
933
|
+
self._total = total
|
|
934
|
+
self._n_sectors = n
|
|
935
|
+
self._radius = radius
|
|
936
|
+
self._start_angle = start_angle
|
|
937
|
+
self._needle_angle = needle_angle
|
|
938
|
+
|
|
939
|
+
# Resolve palettes
|
|
940
|
+
bp = BOARD_PALETTES.get(board_palette, BOARD_PALETTES["wood"])
|
|
941
|
+
hp = HUB_PALETTES.get(hub_palette, HUB_PALETTES["brass"])
|
|
942
|
+
np_ = NEEDLE_PALETTES.get(needle_palette, NEEDLE_PALETTES["red_chrome"])
|
|
943
|
+
|
|
944
|
+
# ── Board ─────────────────────────────────────────────────────
|
|
945
|
+
self.board = _SpinnerBoard(
|
|
946
|
+
radius=radius,
|
|
947
|
+
board_palette=bp,
|
|
948
|
+
n_sectors=n,
|
|
949
|
+
tick_minor_n=tick_minor_n,
|
|
950
|
+
)
|
|
951
|
+
self.add(self.board)
|
|
952
|
+
|
|
953
|
+
# ── Sectors ───────────────────────────────────────────────────
|
|
954
|
+
display_labels = sector_names if (label_style == "name"
|
|
955
|
+
and sector_names) else labels
|
|
956
|
+
self.sectors = _SpinnerSectors(
|
|
957
|
+
weights=weights,
|
|
958
|
+
radius=radius,
|
|
959
|
+
labels=display_labels,
|
|
960
|
+
colors=colors,
|
|
961
|
+
start_angle=start_angle,
|
|
962
|
+
show_labels=show_labels,
|
|
963
|
+
label_style=label_style,
|
|
964
|
+
)
|
|
965
|
+
self.add(self.sectors)
|
|
966
|
+
|
|
967
|
+
# Precompute sector midpoint angles for outcome lookup
|
|
968
|
+
cum = [start_angle]
|
|
969
|
+
for w in weights:
|
|
970
|
+
cum.append(cum[-1] - (w / total) * TAU)
|
|
971
|
+
self._sector_mid_angles = [
|
|
972
|
+
(cum[i] + cum[i+1]) / 2 for i in range(n)
|
|
973
|
+
]
|
|
974
|
+
self._sector_start_angles = cum[:-1]
|
|
975
|
+
self._sector_end_angles = cum[1:]
|
|
976
|
+
|
|
977
|
+
# ── Hub ───────────────────────────────────────────────────────
|
|
978
|
+
hub_r = radius * 0.085
|
|
979
|
+
self.hub = _SpinnerHub(radius=hub_r, hub_palette=hp)
|
|
980
|
+
self.add(self.hub)
|
|
981
|
+
|
|
982
|
+
# ── Needle ────────────────────────────────────────────────────
|
|
983
|
+
needle_len = radius * 0.82
|
|
984
|
+
self.needle = _SpinnerNeedle(
|
|
985
|
+
length=needle_len,
|
|
986
|
+
needle_palette=np_,
|
|
987
|
+
)
|
|
988
|
+
# Rotate to initial angle
|
|
989
|
+
self.needle.rotate(
|
|
990
|
+
needle_angle - PI / 2, # offset: needle built pointing +Y = PI/2
|
|
991
|
+
axis=OUT,
|
|
992
|
+
about_point=ORIGIN,
|
|
993
|
+
)
|
|
994
|
+
self.add(self.needle)
|
|
995
|
+
|
|
996
|
+
# Track current angle
|
|
997
|
+
self._current_angle = needle_angle
|
|
998
|
+
|
|
999
|
+
# ──────────────────────────────────────────────────────────────────
|
|
1000
|
+
# Properties
|
|
1001
|
+
# ──────────────────────────────────────────────────────────────────
|
|
1002
|
+
|
|
1003
|
+
@property
|
|
1004
|
+
def weights(self) -> list[float]:
|
|
1005
|
+
return self._weights
|
|
1006
|
+
|
|
1007
|
+
@property
|
|
1008
|
+
def n_sectors(self) -> int:
|
|
1009
|
+
return self._n_sectors
|
|
1010
|
+
|
|
1011
|
+
@property
|
|
1012
|
+
def needle_angle(self) -> float:
|
|
1013
|
+
return self._current_angle
|
|
1014
|
+
|
|
1015
|
+
@needle_angle.setter
|
|
1016
|
+
def needle_angle(self, angle: float):
|
|
1017
|
+
delta = angle - self._current_angle
|
|
1018
|
+
self.needle.rotate(delta, axis=OUT,
|
|
1019
|
+
about_point=self.get_center())
|
|
1020
|
+
self._current_angle = angle
|
|
1021
|
+
|
|
1022
|
+
@property
|
|
1023
|
+
def sector_mid_angles(self) -> list[float]:
|
|
1024
|
+
return self._sector_mid_angles
|
|
1025
|
+
|
|
1026
|
+
# ──────────────────────────────────────────────────────────────────
|
|
1027
|
+
# Outcome lookup
|
|
1028
|
+
# ──────────────────────────────────────────────────────────────────
|
|
1029
|
+
|
|
1030
|
+
def angle_to_sector(self, angle: float) -> int:
|
|
1031
|
+
"""
|
|
1032
|
+
Return the sector index (0-based) that contains ``angle``.
|
|
1033
|
+
``angle`` is in radians; needle typically points in +Y direction
|
|
1034
|
+
initially.
|
|
1035
|
+
"""
|
|
1036
|
+
# Normalise angle to [0, TAU)
|
|
1037
|
+
a = angle % TAU
|
|
1038
|
+
for i, (sa, ea) in enumerate(
|
|
1039
|
+
zip(self._sector_start_angles, self._sector_end_angles)
|
|
1040
|
+
):
|
|
1041
|
+
# Sectors go clockwise (end < start), normalise
|
|
1042
|
+
sa_n = sa % TAU
|
|
1043
|
+
ea_n = ea % TAU
|
|
1044
|
+
if ea_n <= sa_n: # wraps around
|
|
1045
|
+
if a >= ea_n and a <= sa_n:
|
|
1046
|
+
return i
|
|
1047
|
+
else:
|
|
1048
|
+
if ea_n <= a <= sa_n:
|
|
1049
|
+
return i
|
|
1050
|
+
return 0 # fallback
|
|
1051
|
+
|
|
1052
|
+
def sector_target_angle(self, sector: int) -> float:
|
|
1053
|
+
"""Mid-angle of sector ``sector`` (for landing the needle)."""
|
|
1054
|
+
return self._sector_mid_angles[sector % self._n_sectors]
|
|
1055
|
+
|
|
1056
|
+
def random_spin_outcome(self) -> int:
|
|
1057
|
+
"""Sample a sector index according to the weight distribution."""
|
|
1058
|
+
rng = np.random.default_rng()
|
|
1059
|
+
probs = np.array(self._weights) / self._total
|
|
1060
|
+
return int(rng.choice(self._n_sectors, p=probs))
|
|
1061
|
+
|
|
1062
|
+
# ──────────────────────────────────────────────────────────────────
|
|
1063
|
+
# Class-method constructors
|
|
1064
|
+
# ──────────────────────────────────────────────────────────────────
|
|
1065
|
+
|
|
1066
|
+
@classmethod
|
|
1067
|
+
def uniform(cls, n: int = 4, **kwargs) -> "Spinner3D":
|
|
1068
|
+
"""
|
|
1069
|
+
Equal-weight spinner with ``n`` sectors.
|
|
1070
|
+
|
|
1071
|
+
Example::
|
|
1072
|
+
|
|
1073
|
+
s = Spinner3D.uniform(6, radius=2.5, board_palette="acrylic_dark")
|
|
1074
|
+
"""
|
|
1075
|
+
return cls(weights=[1] * n, **kwargs)
|
|
1076
|
+
|
|
1077
|
+
@classmethod
|
|
1078
|
+
def from_probs(
|
|
1079
|
+
cls,
|
|
1080
|
+
probs: Sequence[float],
|
|
1081
|
+
**kwargs,
|
|
1082
|
+
) -> "Spinner3D":
|
|
1083
|
+
"""
|
|
1084
|
+
Create spinner from a probability list (need not sum to exactly 1;
|
|
1085
|
+
will be normalised).
|
|
1086
|
+
|
|
1087
|
+
Example::
|
|
1088
|
+
|
|
1089
|
+
s = Spinner3D.from_probs([0.5, 0.3, 0.2],
|
|
1090
|
+
label_style="percent")
|
|
1091
|
+
"""
|
|
1092
|
+
return cls(weights=list(probs), **kwargs)
|
|
1093
|
+
|
|
1094
|
+
@classmethod
|
|
1095
|
+
def named(
|
|
1096
|
+
cls,
|
|
1097
|
+
items: Sequence[tuple[str, float]],
|
|
1098
|
+
**kwargs,
|
|
1099
|
+
) -> "Spinner3D":
|
|
1100
|
+
"""
|
|
1101
|
+
Create spinner from ``[(name, weight), ...]``.
|
|
1102
|
+
|
|
1103
|
+
Example::
|
|
1104
|
+
|
|
1105
|
+
s = Spinner3D.named([
|
|
1106
|
+
("Heads", 1),
|
|
1107
|
+
("Tails", 1),
|
|
1108
|
+
], radius=1.8, label_style="name")
|
|
1109
|
+
"""
|
|
1110
|
+
names, weights = zip(*items)
|
|
1111
|
+
return cls(
|
|
1112
|
+
weights=list(weights),
|
|
1113
|
+
sector_names=list(names),
|
|
1114
|
+
label_style="name",
|
|
1115
|
+
**kwargs,
|
|
1116
|
+
)
|
|
1117
|
+
|
|
1118
|
+
|
|
1119
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1120
|
+
# Physics helpers
|
|
1121
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1122
|
+
|
|
1123
|
+
def _exponential_decay_angle(
|
|
1124
|
+
alpha: float,
|
|
1125
|
+
start_angle: float,
|
|
1126
|
+
total_extra_angle: float,
|
|
1127
|
+
decay_k: float = 4.0,
|
|
1128
|
+
) -> float:
|
|
1129
|
+
"""
|
|
1130
|
+
Angular position following exponential deceleration.
|
|
1131
|
+
|
|
1132
|
+
θ(α) = start + total_extra * (1 - e^(-k·α)) / (1 - e^(-k))
|
|
1133
|
+
|
|
1134
|
+
At α=0: θ = start
|
|
1135
|
+
At α=1: θ = start + total_extra
|
|
1136
|
+
"""
|
|
1137
|
+
norm = (1 - np.exp(-decay_k * alpha)) / (1 - np.exp(-decay_k) + 1e-12)
|
|
1138
|
+
return start_angle + total_extra_angle * norm
|
|
1139
|
+
|
|
1140
|
+
|
|
1141
|
+
def _wobble_offset(alpha: float, amplitude: float, n_wobbles: int = 3) -> float:
|
|
1142
|
+
"""
|
|
1143
|
+
Small overshoot wobble near the end of the spin (α → 1).
|
|
1144
|
+
|
|
1145
|
+
Returns an angular offset that decays quickly to 0.
|
|
1146
|
+
Used to simulate a needle "settling" into its sector.
|
|
1147
|
+
"""
|
|
1148
|
+
# Only active in the last 15% of the animation
|
|
1149
|
+
if alpha < 0.85:
|
|
1150
|
+
return 0.0
|
|
1151
|
+
local = (alpha - 0.85) / 0.15 # 0 → 1 in the last 15%
|
|
1152
|
+
decay = np.exp(-local * 6)
|
|
1153
|
+
return amplitude * decay * np.sin(local * n_wobbles * PI)
|
|
1154
|
+
|
|
1155
|
+
|
|
1156
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1157
|
+
# Animations
|
|
1158
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1159
|
+
|
|
1160
|
+
class SpinToOutcome(Animation):
|
|
1161
|
+
"""
|
|
1162
|
+
Spin the needle to land precisely on a target sector, using
|
|
1163
|
+
exponential angular deceleration with a settling wobble.
|
|
1164
|
+
|
|
1165
|
+
The needle completes ``n_full_rotations`` complete turns plus enough
|
|
1166
|
+
extra angle to land on the midpoint of ``outcome``.
|
|
1167
|
+
|
|
1168
|
+
Parameters
|
|
1169
|
+
----------
|
|
1170
|
+
spinner : Spinner3D
|
|
1171
|
+
outcome : int — target sector index (0-based)
|
|
1172
|
+
n_full_rotations: int — full revolutions before landing (default 4)
|
|
1173
|
+
wobble_amplitude: float — settling overshoot angle (radians, default 0.06)
|
|
1174
|
+
decay_k : float — exponential decay rate (default 4.5)
|
|
1175
|
+
run_time : float
|
|
1176
|
+
"""
|
|
1177
|
+
|
|
1178
|
+
def __init__(
|
|
1179
|
+
self,
|
|
1180
|
+
spinner: Spinner3D,
|
|
1181
|
+
outcome: int,
|
|
1182
|
+
n_full_rotations: int = 4,
|
|
1183
|
+
wobble_amplitude: float = 0.06,
|
|
1184
|
+
decay_k: float = 4.5,
|
|
1185
|
+
**kwargs,
|
|
1186
|
+
):
|
|
1187
|
+
self.spinner = spinner
|
|
1188
|
+
self.outcome = outcome % spinner.n_sectors
|
|
1189
|
+
self.wobble_amplitude = wobble_amplitude
|
|
1190
|
+
self.decay_k = decay_k
|
|
1191
|
+
|
|
1192
|
+
start_angle = spinner._current_angle
|
|
1193
|
+
target_angle = spinner.sector_target_angle(outcome)
|
|
1194
|
+
|
|
1195
|
+
# We always spin clockwise (decreasing angle).
|
|
1196
|
+
# Total angle = full rotations + delta to target
|
|
1197
|
+
delta = (start_angle - target_angle) % TAU
|
|
1198
|
+
self.total_sweep = n_full_rotations * TAU + delta
|
|
1199
|
+
self.start_angle = start_angle
|
|
1200
|
+
|
|
1201
|
+
kwargs.setdefault("run_time", 3.0)
|
|
1202
|
+
kwargs.setdefault("rate_func", rate_functions.linear) # custom below
|
|
1203
|
+
super().__init__(spinner.needle, **kwargs)
|
|
1204
|
+
|
|
1205
|
+
def interpolate_mobject(self, alpha: float):
|
|
1206
|
+
# Exponential deceleration
|
|
1207
|
+
swept = _exponential_decay_angle(
|
|
1208
|
+
alpha, 0, self.total_sweep, self.decay_k
|
|
1209
|
+
)
|
|
1210
|
+
# Settling wobble in the final phase
|
|
1211
|
+
wobble = _wobble_offset(alpha, self.wobble_amplitude)
|
|
1212
|
+
|
|
1213
|
+
new_angle = self.start_angle - swept + wobble
|
|
1214
|
+
|
|
1215
|
+
# Apply rotation
|
|
1216
|
+
self.spinner.needle.become(self.starting_mobject.copy())
|
|
1217
|
+
delta = new_angle - self.start_angle
|
|
1218
|
+
self.spinner.needle.rotate(
|
|
1219
|
+
delta, axis=OUT,
|
|
1220
|
+
about_point=self.spinner.get_center(),
|
|
1221
|
+
)
|
|
1222
|
+
|
|
1223
|
+
if alpha >= 1.0:
|
|
1224
|
+
self.spinner._current_angle = (
|
|
1225
|
+
self.start_angle - self.total_sweep
|
|
1226
|
+
) % TAU
|
|
1227
|
+
|
|
1228
|
+
|
|
1229
|
+
class FreeSpinDecay(Animation):
|
|
1230
|
+
"""
|
|
1231
|
+
Pure physics spin with no predetermined outcome.
|
|
1232
|
+
The needle starts at ``angular_velocity`` rad/s and decelerates
|
|
1233
|
+
via exponential drag, stopping wherever it lands.
|
|
1234
|
+
|
|
1235
|
+
After the animation, ``spinner.needle_angle`` holds the final angle
|
|
1236
|
+
and ``spinner.angle_to_sector(spinner.needle_angle)`` gives the outcome.
|
|
1237
|
+
|
|
1238
|
+
Parameters
|
|
1239
|
+
----------
|
|
1240
|
+
spinner : Spinner3D
|
|
1241
|
+
angular_velocity : float — initial angular speed (rad/s, default 8π)
|
|
1242
|
+
drag_k : float — drag coefficient (default 1.5)
|
|
1243
|
+
run_time : float
|
|
1244
|
+
"""
|
|
1245
|
+
|
|
1246
|
+
def __init__(
|
|
1247
|
+
self,
|
|
1248
|
+
spinner: Spinner3D,
|
|
1249
|
+
angular_velocity: float = 8 * PI,
|
|
1250
|
+
drag_k: float = 1.5,
|
|
1251
|
+
**kwargs,
|
|
1252
|
+
):
|
|
1253
|
+
self.spinner = spinner
|
|
1254
|
+
self.omega_0 = angular_velocity
|
|
1255
|
+
self.drag_k = drag_k
|
|
1256
|
+
self.start_angle = spinner._current_angle
|
|
1257
|
+
|
|
1258
|
+
# Total angle swept: ∫₀^T ω₀·e^(−k·t) dt = ω₀/k·(1 − e^(−k·T))
|
|
1259
|
+
# With normalised time (T=1): total = ω₀/k · (1 − e^(−k))
|
|
1260
|
+
run_time_ = kwargs.get("run_time", 3.5)
|
|
1261
|
+
self.total_swept = (
|
|
1262
|
+
angular_velocity / drag_k * (1 - np.exp(-drag_k * run_time_))
|
|
1263
|
+
)
|
|
1264
|
+
|
|
1265
|
+
kwargs.setdefault("run_time", 3.5)
|
|
1266
|
+
kwargs.setdefault("rate_func", rate_functions.linear)
|
|
1267
|
+
super().__init__(spinner.needle, **kwargs)
|
|
1268
|
+
|
|
1269
|
+
def interpolate_mobject(self, alpha: float):
|
|
1270
|
+
# ω(t) = ω₀·e^(−k·t) → θ(t) = ω₀/k·(1−e^(−k·t))
|
|
1271
|
+
swept = (self.omega_0 / self.drag_k
|
|
1272
|
+
* (1 - np.exp(-self.drag_k * alpha * self.run_time)))
|
|
1273
|
+
new_angle = self.start_angle - swept
|
|
1274
|
+
|
|
1275
|
+
self.spinner.needle.become(self.starting_mobject.copy())
|
|
1276
|
+
delta = new_angle - self.start_angle
|
|
1277
|
+
self.spinner.needle.rotate(
|
|
1278
|
+
delta, axis=OUT,
|
|
1279
|
+
about_point=self.spinner.get_center(),
|
|
1280
|
+
)
|
|
1281
|
+
|
|
1282
|
+
if alpha >= 1.0:
|
|
1283
|
+
self.spinner._current_angle = new_angle % TAU
|
|
1284
|
+
|
|
1285
|
+
|
|
1286
|
+
class FlickSpin(Animation):
|
|
1287
|
+
"""
|
|
1288
|
+
Short sharp impulse — needle travels only 1–3 sector widths.
|
|
1289
|
+
Fast ease-in, slow ease-out. Good for illustrating a single trial.
|
|
1290
|
+
|
|
1291
|
+
Parameters
|
|
1292
|
+
----------
|
|
1293
|
+
spinner : Spinner3D
|
|
1294
|
+
outcome : int — target sector index
|
|
1295
|
+
run_time : float
|
|
1296
|
+
"""
|
|
1297
|
+
|
|
1298
|
+
def __init__(
|
|
1299
|
+
self,
|
|
1300
|
+
spinner: Spinner3D,
|
|
1301
|
+
outcome: int,
|
|
1302
|
+
**kwargs,
|
|
1303
|
+
):
|
|
1304
|
+
self.spinner = spinner
|
|
1305
|
+
self.outcome = outcome % spinner.n_sectors
|
|
1306
|
+
self.start_angle = spinner._current_angle
|
|
1307
|
+
target = spinner.sector_target_angle(outcome)
|
|
1308
|
+
delta = (self.start_angle - target) % TAU
|
|
1309
|
+
# At most 1.5 rotations
|
|
1310
|
+
self.total_sweep = delta % TAU + TAU * 0.5
|
|
1311
|
+
|
|
1312
|
+
kwargs.setdefault("run_time", 0.9)
|
|
1313
|
+
kwargs.setdefault("rate_func", rate_functions.ease_in_out_expo)
|
|
1314
|
+
super().__init__(spinner.needle, **kwargs)
|
|
1315
|
+
|
|
1316
|
+
def interpolate_mobject(self, alpha: float):
|
|
1317
|
+
swept = alpha * self.total_sweep
|
|
1318
|
+
new_angle = self.start_angle - swept
|
|
1319
|
+
|
|
1320
|
+
self.spinner.needle.become(self.starting_mobject.copy())
|
|
1321
|
+
self.spinner.needle.rotate(
|
|
1322
|
+
new_angle - self.start_angle,
|
|
1323
|
+
axis=OUT,
|
|
1324
|
+
about_point=self.spinner.get_center(),
|
|
1325
|
+
)
|
|
1326
|
+
|
|
1327
|
+
if alpha >= 1.0:
|
|
1328
|
+
self.spinner._current_angle = new_angle % TAU
|
|
1329
|
+
|
|
1330
|
+
|
|
1331
|
+
class RicochetSpin(Succession):
|
|
1332
|
+
"""
|
|
1333
|
+
Needle lands near the boundary of a sector, ticks slightly past it,
|
|
1334
|
+
then bounces back to settle in the correct sector.
|
|
1335
|
+
|
|
1336
|
+
Simulates the "click-stop" ratchet feel of a physical spinner.
|
|
1337
|
+
|
|
1338
|
+
Parameters
|
|
1339
|
+
----------
|
|
1340
|
+
spinner : Spinner3D
|
|
1341
|
+
outcome : int — final target sector
|
|
1342
|
+
overshoot_frac : float — fraction of sector width to overshoot (0.2–0.4)
|
|
1343
|
+
run_time : float
|
|
1344
|
+
"""
|
|
1345
|
+
|
|
1346
|
+
def __init__(
|
|
1347
|
+
self,
|
|
1348
|
+
spinner: Spinner3D,
|
|
1349
|
+
outcome: int,
|
|
1350
|
+
overshoot_frac: float = 0.28,
|
|
1351
|
+
**kwargs,
|
|
1352
|
+
):
|
|
1353
|
+
n = spinner.n_sectors
|
|
1354
|
+
outcome = outcome % n
|
|
1355
|
+
total_w = sum(spinner.weights)
|
|
1356
|
+
# Sector angular width
|
|
1357
|
+
sec_w = (spinner.weights[outcome] / total_w) * TAU
|
|
1358
|
+
overshoot = sec_w * overshoot_frac
|
|
1359
|
+
|
|
1360
|
+
# Phase 1: main spin, lands just past the sector boundary
|
|
1361
|
+
boundary_angle = spinner._sector_end_angles[outcome]
|
|
1362
|
+
phase1 = SpinToOutcome(
|
|
1363
|
+
spinner, outcome,
|
|
1364
|
+
n_full_rotations=3,
|
|
1365
|
+
wobble_amplitude=0.0,
|
|
1366
|
+
run_time=2.0,
|
|
1367
|
+
)
|
|
1368
|
+
# Override target to boundary
|
|
1369
|
+
phase1.total_sweep += overshoot
|
|
1370
|
+
|
|
1371
|
+
# Phase 2: bounce back
|
|
1372
|
+
def _bounce(sp=spinner, ov=overshoot):
|
|
1373
|
+
return ApplyMethod(
|
|
1374
|
+
sp.needle.rotate,
|
|
1375
|
+
ov * 0.80, # bounce back ~80% of overshoot
|
|
1376
|
+
about_point=sp.get_center(),
|
|
1377
|
+
run_time=0.20,
|
|
1378
|
+
rate_func=rate_functions.ease_out_bounce,
|
|
1379
|
+
)
|
|
1380
|
+
|
|
1381
|
+
# Phase 3: settle
|
|
1382
|
+
def _settle(sp=spinner, ov=overshoot):
|
|
1383
|
+
return ApplyMethod(
|
|
1384
|
+
sp.needle.rotate,
|
|
1385
|
+
-ov * 0.80,
|
|
1386
|
+
about_point=sp.get_center(),
|
|
1387
|
+
run_time=0.12,
|
|
1388
|
+
rate_func=rate_functions.ease_in_out_sine,
|
|
1389
|
+
)
|
|
1390
|
+
|
|
1391
|
+
kwargs.setdefault("run_time", 2.32)
|
|
1392
|
+
super().__init__(phase1, _bounce(), _settle(), **kwargs)
|
|
1393
|
+
|
|
1394
|
+
|
|
1395
|
+
class SpinSequence(Succession):
|
|
1396
|
+
"""
|
|
1397
|
+
Animate ``n_trials`` successive spins of the spinner, yielding
|
|
1398
|
+
a list of outcomes.
|
|
1399
|
+
|
|
1400
|
+
Parameters
|
|
1401
|
+
----------
|
|
1402
|
+
spinner : Spinner3D
|
|
1403
|
+
n_trials : int
|
|
1404
|
+
outcomes : list[int] | None — specify outcomes; random if None
|
|
1405
|
+
spin_cls : Animation class — which spin animation to use
|
|
1406
|
+
spin_kwargs : dict — forwarded to each spin animation
|
|
1407
|
+
pause : float — wait time between spins
|
|
1408
|
+
"""
|
|
1409
|
+
|
|
1410
|
+
def __init__(
|
|
1411
|
+
self,
|
|
1412
|
+
spinner: Spinner3D,
|
|
1413
|
+
n_trials: int = 5,
|
|
1414
|
+
outcomes: Optional[list[int]] = None,
|
|
1415
|
+
spin_cls=None,
|
|
1416
|
+
spin_kwargs: Optional[dict] = None,
|
|
1417
|
+
pause: float = 0.3,
|
|
1418
|
+
**kwargs,
|
|
1419
|
+
):
|
|
1420
|
+
if spin_cls is None:
|
|
1421
|
+
spin_cls = SpinToOutcome
|
|
1422
|
+
if spin_kwargs is None:
|
|
1423
|
+
spin_kwargs = {"n_full_rotations": 3, "run_time": 2.0}
|
|
1424
|
+
if outcomes is None:
|
|
1425
|
+
outcomes = [spinner.random_spin_outcome()
|
|
1426
|
+
for _ in range(n_trials)]
|
|
1427
|
+
|
|
1428
|
+
self.outcomes = outcomes[:n_trials]
|
|
1429
|
+
anims = []
|
|
1430
|
+
for outcome in self.outcomes:
|
|
1431
|
+
anims.append(spin_cls(spinner, outcome, **spin_kwargs))
|
|
1432
|
+
|
|
1433
|
+
kwargs.setdefault("run_time",
|
|
1434
|
+
sum(a.run_time for a in anims) + pause * len(anims))
|
|
1435
|
+
super().__init__(*anims, **kwargs)
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1439
|
+
# Convenience factories
|
|
1440
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1441
|
+
|
|
1442
|
+
def make_bernoulli_spinner(
|
|
1443
|
+
p: float = 0.5,
|
|
1444
|
+
labels: tuple[str, str] = ("Success", "Failure"),
|
|
1445
|
+
colors: tuple[str, str] = ("#2A9D8F", "#E63946"),
|
|
1446
|
+
**spinner_kwargs,
|
|
1447
|
+
) -> Spinner3D:
|
|
1448
|
+
"""
|
|
1449
|
+
Two-sector spinner for Bernoulli / coin-flip demonstrations.
|
|
1450
|
+
|
|
1451
|
+
Parameters
|
|
1452
|
+
----------
|
|
1453
|
+
p : probability of success (sector 0)
|
|
1454
|
+
labels : names for the two sectors
|
|
1455
|
+
colors : colours for the two sectors
|
|
1456
|
+
"""
|
|
1457
|
+
return Spinner3D(
|
|
1458
|
+
weights=[p, 1 - p],
|
|
1459
|
+
sector_names=list(labels),
|
|
1460
|
+
colors=list(colors),
|
|
1461
|
+
label_style="name",
|
|
1462
|
+
**spinner_kwargs,
|
|
1463
|
+
)
|
|
1464
|
+
|
|
1465
|
+
|
|
1466
|
+
def make_die_spinner(
|
|
1467
|
+
n: int = 6,
|
|
1468
|
+
**spinner_kwargs,
|
|
1469
|
+
) -> Spinner3D:
|
|
1470
|
+
"""
|
|
1471
|
+
Uniform n-sector spinner mimicking a fair die.
|
|
1472
|
+
|
|
1473
|
+
Parameters
|
|
1474
|
+
----------
|
|
1475
|
+
n : number of faces (2–20)
|
|
1476
|
+
"""
|
|
1477
|
+
spinner_kwargs.setdefault("label_style", "name")
|
|
1478
|
+
return Spinner3D(
|
|
1479
|
+
weights=[1] * n,
|
|
1480
|
+
sector_names=[str(i + 1) for i in range(n)],
|
|
1481
|
+
**spinner_kwargs,
|
|
1482
|
+
)
|
|
1483
|
+
|
|
1484
|
+
|
|
1485
|
+
def make_markov_spinner(
|
|
1486
|
+
state_names: Sequence[str],
|
|
1487
|
+
transition_row: Sequence[float],
|
|
1488
|
+
current_state: int = 0,
|
|
1489
|
+
**spinner_kwargs,
|
|
1490
|
+
) -> Spinner3D:
|
|
1491
|
+
"""
|
|
1492
|
+
Spinner representing one row of a Markov transition matrix.
|
|
1493
|
+
Used to visualise the probability of transitioning from
|
|
1494
|
+
``current_state`` to each other state.
|
|
1495
|
+
|
|
1496
|
+
Parameters
|
|
1497
|
+
----------
|
|
1498
|
+
state_names : names of all states
|
|
1499
|
+
transition_row : transition probabilities from the current state
|
|
1500
|
+
current_state : index of the "from" state (used only for display)
|
|
1501
|
+
"""
|
|
1502
|
+
spinner_kwargs.setdefault("label_style", "name")
|
|
1503
|
+
return Spinner3D(
|
|
1504
|
+
weights=list(transition_row),
|
|
1505
|
+
sector_names=list(state_names),
|
|
1506
|
+
**spinner_kwargs,
|
|
1507
|
+
)
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1511
|
+
# Demo Scene (run with: manim -pql spinner.py SpinnerDemo)
|
|
1512
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
1513
|
+
|
|
1514
|
+
try:
|
|
1515
|
+
from manim import ThreeDScene, DEGREES, Wait
|
|
1516
|
+
|
|
1517
|
+
class SpinnerDemo(ThreeDScene):
|
|
1518
|
+
"""Showcase scene for Spinner3D and all animations."""
|
|
1519
|
+
|
|
1520
|
+
def construct(self):
|
|
1521
|
+
self.set_camera_orientation(phi=72 * DEGREES, theta=-45 * DEGREES)
|
|
1522
|
+
self.begin_ambient_camera_rotation(rate=0.02)
|
|
1523
|
+
|
|
1524
|
+
# ── Four-sector uniform spinner (wood board) ──────────────
|
|
1525
|
+
s4 = Spinner3D.uniform(
|
|
1526
|
+
n=4,
|
|
1527
|
+
radius=2.0,
|
|
1528
|
+
board_palette="wood",
|
|
1529
|
+
hub_palette="brass",
|
|
1530
|
+
needle_palette="red_chrome",
|
|
1531
|
+
label_style="both",
|
|
1532
|
+
)
|
|
1533
|
+
s4.shift(LEFT * 3.5)
|
|
1534
|
+
self.add(s4)
|
|
1535
|
+
|
|
1536
|
+
# ── Named Bernoulli spinner (acrylic dark) ────────────────
|
|
1537
|
+
bern = make_bernoulli_spinner(
|
|
1538
|
+
p=0.65,
|
|
1539
|
+
labels=("Win", "Lose"),
|
|
1540
|
+
colors=("#2A9D8F", "#E63946"),
|
|
1541
|
+
radius=1.6,
|
|
1542
|
+
board_palette="acrylic_dark",
|
|
1543
|
+
hub_palette="chrome",
|
|
1544
|
+
needle_palette="gold",
|
|
1545
|
+
)
|
|
1546
|
+
bern.shift(RIGHT * 2.5)
|
|
1547
|
+
self.add(bern)
|
|
1548
|
+
self.wait(0.8)
|
|
1549
|
+
|
|
1550
|
+
# ── Spin the 4-sector spinner to sector 2 ─────────────────
|
|
1551
|
+
self.play(
|
|
1552
|
+
SpinToOutcome(s4, outcome=2, n_full_rotations=5,
|
|
1553
|
+
wobble_amplitude=0.07, run_time=3.2),
|
|
1554
|
+
run_time=3.2,
|
|
1555
|
+
)
|
|
1556
|
+
self.wait(0.5)
|
|
1557
|
+
|
|
1558
|
+
# ── Flick the Bernoulli spinner ───────────────────────────
|
|
1559
|
+
self.play(FlickSpin(bern, outcome=0, run_time=1.1))
|
|
1560
|
+
self.wait(0.4)
|
|
1561
|
+
|
|
1562
|
+
# ── Ricochet on the 4-sector spinner ─────────────────────
|
|
1563
|
+
self.play(
|
|
1564
|
+
RicochetSpin(s4, outcome=3, overshoot_frac=0.30,
|
|
1565
|
+
run_time=2.4),
|
|
1566
|
+
)
|
|
1567
|
+
self.wait(0.5)
|
|
1568
|
+
|
|
1569
|
+
# ── 6-sector die spinner, run 4 trials ───────────────────
|
|
1570
|
+
d6_spin = make_die_spinner(
|
|
1571
|
+
n=6,
|
|
1572
|
+
radius=1.8,
|
|
1573
|
+
board_palette="casino_red",
|
|
1574
|
+
hub_palette="brass",
|
|
1575
|
+
needle_palette="white",
|
|
1576
|
+
label_style="name",
|
|
1577
|
+
)
|
|
1578
|
+
d6_spin.shift(DOWN * 0.5 + LEFT * 0.5)
|
|
1579
|
+
self.play(FadeIn(d6_spin, shift=UP * 0.3), run_time=0.6)
|
|
1580
|
+
|
|
1581
|
+
self.play(SpinSequence(
|
|
1582
|
+
d6_spin,
|
|
1583
|
+
n_trials=4,
|
|
1584
|
+
outcomes=[5, 2, 5, 1],
|
|
1585
|
+
spin_kwargs={"n_full_rotations": 3, "run_time": 1.8},
|
|
1586
|
+
pause=0.25,
|
|
1587
|
+
))
|
|
1588
|
+
self.wait(2.0)
|
|
1589
|
+
|
|
1590
|
+
except ImportError:
|
|
1591
|
+
pass # Manim not installed; skip demo scene definition
|