statanim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. statanim/__init__.py +0 -0
  2. statanim/animations/__init__.py +0 -0
  3. statanim/animations/clt_demo.py +1852 -0
  4. statanim/animations/flip_roll.py +1851 -0
  5. statanim/animations/sampling.py +2291 -0
  6. statanim/animations/transitions.py +1857 -0
  7. statanim/axes/__init__.py +0 -0
  8. statanim/axes/axes3d.py +1989 -0
  9. statanim/axes/grid3d.py +1127 -0
  10. statanim/axes/number_plane3d.py +1526 -0
  11. statanim/charts/__init__.py +0 -0
  12. statanim/charts/bar_chart3d.py +1572 -0
  13. statanim/charts/box_plot3d.py +1977 -0
  14. statanim/charts/heat_map3d.py +1639 -0
  15. statanim/charts/histogram3d.py +1019 -0
  16. statanim/charts/line_plot3d.py +1891 -0
  17. statanim/charts/scatter_plot3d.py +1469 -0
  18. statanim/charts/violin_plot3d.py +1567 -0
  19. statanim/core/__init__.py +0 -0
  20. statanim/core/base.py +1585 -0
  21. statanim/core/colors.py +1373 -0
  22. statanim/core/math_utils.py +2081 -0
  23. statanim/core/tex_utils.py +2111 -0
  24. statanim/distributions/__init__.py +0 -0
  25. statanim/distributions/base_dist.py +1936 -0
  26. statanim/distributions/cdf_viz.py +1773 -0
  27. statanim/distributions/continuous_dists.py +1769 -0
  28. statanim/distributions/discrete_dists.py +1734 -0
  29. statanim/distributions/normal3d.py +1877 -0
  30. statanim/distributions/pdf_viz.py +2247 -0
  31. statanim/distributions/pmf_viz.py +1936 -0
  32. statanim/inference/__init__.py +0 -0
  33. statanim/inference/confidence_interval.py +1693 -0
  34. statanim/inference/error_types.py +1825 -0
  35. statanim/inference/hypothesis.py +1821 -0
  36. statanim/inference/sampling_dist.py +1933 -0
  37. statanim/probability/__init__.py +0 -0
  38. statanim/probability/bayes.py +1682 -0
  39. statanim/probability/prob_tree.py +1478 -0
  40. statanim/probability/sample_space.py +1642 -0
  41. statanim/probability/venn3d.py +1857 -0
  42. statanim/props/__init__.py +0 -0
  43. statanim/props/card.py +2259 -0
  44. statanim/props/coin.py +1011 -0
  45. statanim/props/die.py +1391 -0
  46. statanim/props/spinner.py +1591 -0
  47. statanim/props/urn.py +1531 -0
  48. statanim/regression/__init__.py +0 -0
  49. statanim/regression/correlation.py +2805 -0
  50. statanim/regression/regression_plane.py +2286 -0
  51. statanim/regression/residuals.py +2599 -0
  52. statanim/scenes/__init__.py +0 -0
  53. statanim/scenes/demo_bayes.py +2056 -0
  54. statanim/scenes/demo_clt.py +1756 -0
  55. statanim/scenes/demo_distributions.py +1905 -0
  56. statanim/scenes/demo_hypothesis.py +1791 -0
  57. statanim/ui/__init__.py +0 -0
  58. statanim/ui/labels.py +1844 -0
  59. statanim/ui/panels.py +1937 -0
  60. statanim/ui/table3d.py +1745 -0
  61. statanim/ui/ticker.py +2007 -0
  62. statanim-0.1.0.dist-info/METADATA +463 -0
  63. statanim-0.1.0.dist-info/RECORD +66 -0
  64. statanim-0.1.0.dist-info/WHEEL +5 -0
  65. statanim-0.1.0.dist-info/licenses/LICENSE +21 -0
  66. statanim-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2291 @@
1
+ """
2
+ statanim/animations/sampling.py
3
+ =====================================
4
+ Animated sampling from distributions — visualising how samples are
5
+ drawn, how sampling methods differ, and how sample statistics vary.
6
+
7
+ Design philosophy
8
+ -----------------
9
+ Sampling is abstract. These animations make it concrete by treating
10
+ each population member as a visible 3D dot (``PopulationCloud3D``)
11
+ and showing the selection process explicitly: dots glow, float out
12
+ of the cloud, and regroup into a sample zone.
13
+
14
+ Four selection styles are supported for every sampler class:
15
+ ``"highlight"`` – selected dots enlarge and glow in place.
16
+ ``"extract"`` – selected dots float from the cloud to a
17
+ separate sample zone on the right.
18
+ ``"fade"`` – unselected dots dim; selected stay bright.
19
+ ``"draw"`` – an animated sweep line moves across the cloud,
20
+ picking dots as it passes (good for systematic).
21
+
22
+ Sampling methods
23
+ ----------------
24
+ ``SimpleRandomSampling3D``
25
+ Uniform random sample without replacement.
26
+
27
+ ``StratifiedSampling3D``
28
+ Population split into visible coloured strata; proportional
29
+ allocation within each stratum.
30
+
31
+ ``ClusterSampling3D``
32
+ Population grouped into spatial clusters; entire clusters selected.
33
+
34
+ ``SystematicSampling3D``
35
+ Every k-th member selected; sweep-line animation makes k visible.
36
+
37
+ ``BootstrapSampling3D``
38
+ Sample drawn with replacement; duplicate selections shown with
39
+ concentric rings; bootstrap distribution accumulated.
40
+
41
+ ``SamplingDistributionBuilder``
42
+ Generic: run any sampler m times, compute a statistic each time,
43
+ accumulate into a live 3D histogram to show the sampling distribution.
44
+
45
+ Classes
46
+ -------
47
+ SamplingConfig
48
+ PopulationCloud3D
49
+ SampleSelector
50
+ SimpleRandomSampling3D
51
+ StratifiedSampling3D
52
+ ClusterSampling3D
53
+ SystematicSampling3D
54
+ BootstrapSampling3D
55
+ SamplingDistributionBuilder
56
+
57
+ Helpers / internals
58
+ -------------------
59
+ _PopDot3D
60
+ _SampleZone3D
61
+ _SweepLine3D
62
+ _StrataRegion3D
63
+ _ClusterRegion3D
64
+ _SampleStatAnnotation3D
65
+
66
+ Ready-to-render scenes
67
+ ----------------------
68
+ SRSScene
69
+ StratifiedScene
70
+ ClusterScene
71
+ SystematicScene
72
+ BootstrapScene
73
+
74
+ Usage
75
+ -----
76
+ # Render a stratified sampling demo:
77
+ # manim -pql sampling.py StratifiedScene
78
+
79
+ # Embed in your own scene:
80
+ from statanim.animations.sampling import StratifiedSampling3D
81
+
82
+ class MyScene(ThreeDScene):
83
+ def construct(self):
84
+ demo = StratifiedSampling3D(N=120, n=24, n_strata=3)
85
+ demo.phase_population(self)
86
+ demo.phase_sample(self)
87
+ demo.phase_statistics(self)
88
+ """
89
+
90
+ from __future__ import annotations
91
+
92
+ from dataclasses import dataclass, field
93
+ from typing import List, Sequence, Tuple, Optional, Callable, Union, Dict, Set
94
+ import numpy as np
95
+
96
+ from manim import (
97
+ VGroup, VMobject, Polygon, Rectangle, Line, DashedLine,
98
+ Dot, Dot3D, Text, MathTex, Ellipse, Arrow, Circle,
99
+ ThreeDScene,
100
+ AnimationGroup, LaggedStart, Succession,
101
+ Create, FadeIn, FadeOut, Transform, MoveAlongPath,
102
+ UpdateFromAlphaFunc, Flash, Indicate, GrowFromCenter,
103
+ DEGREES, PI, TAU,
104
+ RIGHT, LEFT, UP, DOWN, OUT, IN, ORIGIN,
105
+ X_AXIS, Y_AXIS, Z_AXIS,
106
+ WHITE, BLACK, GRAY, BLUE, GREEN, RED, YELLOW,
107
+ ManimColor, color_to_rgb, rgba_to_color, color_to_rgba,
108
+ rate_functions, smooth,
109
+ )
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # Colour helpers
113
+ # ---------------------------------------------------------------------------
114
+
115
+ def _with_opacity(color: ManimColor, opacity: float) -> ManimColor:
116
+ r, g, b = color_to_rgb(color)
117
+ return rgba_to_color([r, g, b, max(0.0, min(1.0, opacity))])
118
+
119
+ def _darken(color: ManimColor, factor: float = 0.65) -> ManimColor:
120
+ r, g, b = color_to_rgb(color)
121
+ return ManimColor([r * factor, g * factor, b * factor])
122
+
123
+ def _lighten(color: ManimColor, factor: float = 1.35) -> ManimColor:
124
+ r, g, b = color_to_rgb(color)
125
+ return ManimColor([min(r * factor, 1.0), min(g * factor, 1.0), min(b * factor, 1.0)])
126
+
127
+ def _lerp_color(a: ManimColor, b: ManimColor, t: float) -> ManimColor:
128
+ ra, ga, ba = color_to_rgb(a)
129
+ rb, gb, bb = color_to_rgb(b)
130
+ return ManimColor([ra + (rb - ra) * t, ga + (gb - ga) * t, ba + (bb - ba) * t])
131
+
132
+ def _normal_pdf(x: np.ndarray, mu: float, sigma: float) -> np.ndarray:
133
+ return np.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * np.sqrt(TAU))
134
+
135
+
136
+ # ---------------------------------------------------------------------------
137
+ # SamplingConfig
138
+ # ---------------------------------------------------------------------------
139
+
140
+ @dataclass
141
+ class SamplingConfig:
142
+ """Complete visual configuration for all sampling animations.
143
+
144
+ Population display
145
+ ~~~~~~~~~~~~~~~~~~
146
+ ``pop_dot_radius`` : size of each population dot.
147
+ ``pop_dot_color`` : default colour before sampling.
148
+ ``pop_dot_opacity`` : default opacity.
149
+ ``pop_layout`` : ``"grid"`` | ``"random"`` | ``"hex"`` — how
150
+ dots are arranged in the cloud.
151
+ ``pop_width`` : x-extent of the population cloud.
152
+ ``pop_height`` : y-extent (depth) of the cloud.
153
+ ``pop_center`` : 3D centre of the population cloud.
154
+
155
+ Sampling display
156
+ ~~~~~~~~~~~~~~~~
157
+ ``selected_color`` : colour of selected dots.
158
+ ``selected_radius_mult`` : scale factor applied to selected dots.
159
+ ``unselected_opacity``: opacity of unselected dots after selection.
160
+ ``glow_radius_mult`` : radius of the glow halo around selected dots.
161
+ ``glow_opacity`` : opacity of glow halo.
162
+ ``selection_style`` : ``"highlight"`` | ``"extract"`` | ``"fade"`` | ``"draw"``.
163
+
164
+ Sample zone
165
+ ~~~~~~~~~~~
166
+ ``sample_zone_center``: where extracted dots land.
167
+ ``sample_zone_width`` : width of the sample zone layout.
168
+ ``sample_zone_height``: height of the sample zone layout.
169
+ ``show_sample_zone_box`` : draw a bounding box around the sample zone.
170
+ ``sample_zone_color`` : colour of sample zone box.
171
+
172
+ Statistics annotation
173
+ ~~~~~~~~~~~~~~~~~~~~~
174
+ ``show_stat_annotation`` : show x̄, s, n annotation after selection.
175
+ ``stat_font_size`` : font size for stat annotations.
176
+ ``stat_color`` : colour of stat text.
177
+ """
178
+
179
+ # Population
180
+ pop_dot_radius: float = 0.07
181
+ pop_dot_color: ManimColor = ManimColor("#4A90D9")
182
+ pop_dot_opacity: float = 0.70
183
+ pop_layout: str = "random" # grid | random | hex
184
+ pop_width: float = 5.0
185
+ pop_height: float = 4.0
186
+ pop_center: np.ndarray = field(default_factory=lambda: np.array([-1.5, 0.0, 0.0]))
187
+
188
+ # Selection
189
+ selected_color: ManimColor = ManimColor("#FFD700")
190
+ selected_radius_mult: float = 1.55
191
+ unselected_opacity: float = 0.18
192
+ glow_radius_mult: float = 2.8
193
+ glow_opacity: float = 0.20
194
+ selection_style: str = "extract" # highlight | extract | fade | draw
195
+
196
+ # Sample zone
197
+ sample_zone_center: np.ndarray = field(default_factory=lambda: np.array([3.5, 0.0, 0.0]))
198
+ sample_zone_width: float = 2.8
199
+ sample_zone_height: float = 3.5
200
+ show_sample_zone_box: bool = True
201
+ sample_zone_color: ManimColor = ManimColor("#2DAA6E")
202
+
203
+ # Stats
204
+ show_stat_annotation: bool = True
205
+ stat_font_size: int = 20
206
+ stat_color: ManimColor = WHITE
207
+
208
+ # Animation
209
+ lag_between_dots: float = 0.04
210
+ run_time_per_dot: float = 0.35
211
+ run_time_fade: float = 0.5
212
+
213
+
214
+ # ── Presets ──────────────────────────────────────────────────────────────
215
+
216
+ CLEAN_SAMPLING = SamplingConfig(
217
+ pop_dot_radius=0.065,
218
+ glow_opacity=0.0,
219
+ selection_style="highlight",
220
+ show_sample_zone_box=False,
221
+ show_stat_annotation=False,
222
+ )
223
+
224
+ DETAILED_SAMPLING = SamplingConfig(
225
+ pop_dot_radius=0.075,
226
+ selected_radius_mult=1.70,
227
+ glow_opacity=0.25,
228
+ selection_style="extract",
229
+ show_sample_zone_box=True,
230
+ show_stat_annotation=True,
231
+ )
232
+
233
+
234
+ # ---------------------------------------------------------------------------
235
+ # _PopDot3D — internal
236
+ # ---------------------------------------------------------------------------
237
+
238
+ class _PopDot3D(VGroup):
239
+ """A single population member dot with a glow halo.
240
+
241
+ Parameters
242
+ ----------
243
+ position : np.ndarray
244
+ 3D position of the dot.
245
+ value : float
246
+ Associated data value (used for colouring and statistics).
247
+ index : int
248
+ Index in the population (for selection tracking).
249
+ color : ManimColor
250
+ radius : float
251
+ glow_radius_mult : float
252
+ glow_opacity : float
253
+ stratum : int
254
+ Stratum label (0 = ungrouped).
255
+ cluster : int
256
+ Cluster label (0 = ungrouped).
257
+ """
258
+
259
+ def __init__(
260
+ self,
261
+ position: np.ndarray,
262
+ value: float = 0.0,
263
+ index: int = 0,
264
+ color: ManimColor = ManimColor("#4A90D9"),
265
+ radius: float = 0.07,
266
+ opacity: float = 0.70,
267
+ glow_radius_mult: float = 2.8,
268
+ glow_opacity: float = 0.18,
269
+ stratum: int = 0,
270
+ cluster: int = 0,
271
+ **kwargs,
272
+ ):
273
+ super().__init__(**kwargs)
274
+ self.dot_value = value
275
+ self.dot_index = index
276
+ self.dot_stratum = stratum
277
+ self.dot_cluster = cluster
278
+ self._radius = radius
279
+ self._pos = np.array(position, dtype=float)
280
+
281
+ self.glow = Dot3D(
282
+ point=self._pos,
283
+ radius=radius * glow_radius_mult,
284
+ color=_with_opacity(color, glow_opacity),
285
+ )
286
+ self.dot = Dot3D(
287
+ point=self._pos,
288
+ radius=radius,
289
+ color=_with_opacity(color, opacity),
290
+ )
291
+ self.add(self.glow, self.dot)
292
+
293
+ def select(
294
+ self,
295
+ selected_color: ManimColor,
296
+ radius_mult: float = 1.55,
297
+ glow_mult: float = 2.8,
298
+ glow_opacity: float = 0.25,
299
+ ) -> AnimationGroup:
300
+ """Return an animation that transforms this dot to its selected state."""
301
+ new_dot_color = _with_opacity(selected_color, 0.95)
302
+ new_glow_color = _with_opacity(selected_color, glow_opacity)
303
+ return AnimationGroup(
304
+ self.dot.animate.set_color(new_dot_color)
305
+ .scale(radius_mult),
306
+ self.glow.animate.set_color(new_glow_color)
307
+ .scale(glow_mult / 2.8),
308
+ run_time=0.25,
309
+ )
310
+
311
+ def deselect(
312
+ self,
313
+ original_color: ManimColor,
314
+ unselected_opacity: float = 0.18,
315
+ ) -> AnimationGroup:
316
+ """Dim this dot as an unselected member."""
317
+ return AnimationGroup(
318
+ self.dot.animate.set_color(_with_opacity(original_color, unselected_opacity)),
319
+ self.glow.animate.set_color(_with_opacity(original_color, 0.0)),
320
+ run_time=0.20,
321
+ )
322
+
323
+ def move_to_sample_zone(
324
+ self,
325
+ target: np.ndarray,
326
+ run_time: float = 0.45,
327
+ ) -> UpdateFromAlphaFunc:
328
+ """Arc the dot from its population position to the sample zone."""
329
+ start = self._pos.copy()
330
+ end = np.array(target, dtype=float)
331
+ mid = (start + end) / 2 + np.array([0, 0, 0.8])
332
+
333
+ def updater(mob: _PopDot3D, alpha: float) -> None:
334
+ t = smooth(alpha)
335
+ pos = (1 - t)**2 * start + 2 * (1 - t) * t * mid + t**2 * end
336
+ mob.dot.move_to(pos)
337
+ mob.glow.move_to(pos)
338
+
339
+ return UpdateFromAlphaFunc(self, updater, run_time=run_time)
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # PopulationCloud3D
344
+ # ---------------------------------------------------------------------------
345
+
346
+ class PopulationCloud3D(VGroup):
347
+ """A cloud of N 3D dots representing a finite population.
348
+
349
+ Each dot corresponds to one population member and stores a
350
+ ``value`` attribute (the measurement of interest), a ``stratum``
351
+ label, and a ``cluster`` label.
352
+
353
+ Layout algorithms
354
+ ~~~~~~~~~~~~~~~~~
355
+ ``"grid"`` – evenly spaced rectangular grid; clearest spatial
356
+ structure, good for systematic sampling demo.
357
+ ``"random"`` – uniform random scatter with a small z-jitter for
358
+ depth, giving a natural cloud appearance.
359
+ ``"hex"`` – hexagonal close-pack; maximises visible dot density.
360
+
361
+ Parameters
362
+ ----------
363
+ N : int
364
+ Population size.
365
+ values : np.ndarray or None
366
+ Data values for each member. If None, drawn from N(0, 1).
367
+ strata : np.ndarray or None
368
+ Integer stratum label for each member (0-based).
369
+ Shape (N,). If None all members are in stratum 0.
370
+ clusters : np.ndarray or None
371
+ Integer cluster label for each member (0-based).
372
+ Shape (N,). If None all members are in cluster 0.
373
+ config : SamplingConfig
374
+ rng_seed : int
375
+ scene : ThreeDScene or None
376
+
377
+ Attributes
378
+ ----------
379
+ dots : List[_PopDot3D]
380
+ Direct access to each dot object.
381
+ dot_group : VGroup
382
+ All dots as a single group.
383
+ N : int
384
+ values : np.ndarray
385
+ strata : np.ndarray
386
+ clusters : np.ndarray
387
+ """
388
+
389
+ # Palette for stratum / cluster colouring
390
+ _STRATUM_COLORS: List[ManimColor] = [
391
+ ManimColor("#4A90D9"), # blue
392
+ ManimColor("#E8593C"), # coral
393
+ ManimColor("#2DAA6E"), # emerald
394
+ ManimColor("#E0AA40"), # amber
395
+ ManimColor("#9B59B6"), # purple
396
+ ManimColor("#1ABC9C"), # teal
397
+ ]
398
+
399
+ def __init__(
400
+ self,
401
+ N: int = 100,
402
+ values: Optional[np.ndarray] = None,
403
+ strata: Optional[np.ndarray] = None,
404
+ clusters: Optional[np.ndarray] = None,
405
+ config: Optional[SamplingConfig] = None,
406
+ rng_seed: int = 42,
407
+ scene: Optional[ThreeDScene] = None,
408
+ **kwargs,
409
+ ):
410
+ super().__init__(**kwargs)
411
+
412
+ self.N = N
413
+ self.cfg = config if config is not None else SamplingConfig()
414
+ self._scene = scene
415
+ rng = np.random.default_rng(rng_seed)
416
+
417
+ # Values
418
+ self.values = (
419
+ values.copy() if values is not None
420
+ else rng.normal(0.0, 1.0, N).astype(float)
421
+ )
422
+
423
+ # Stratum labels
424
+ self.strata = (
425
+ strata.copy().astype(int) if strata is not None
426
+ else np.zeros(N, dtype=int)
427
+ )
428
+ self.n_strata = int(self.strata.max()) + 1
429
+
430
+ # Cluster labels
431
+ self.clusters = (
432
+ clusters.copy().astype(int) if clusters is not None
433
+ else np.zeros(N, dtype=int)
434
+ )
435
+ self.n_clusters = int(self.clusters.max()) + 1
436
+
437
+ # Generate positions
438
+ positions = self._generate_positions(rng)
439
+
440
+ # Build dots
441
+ self.dots: List[_PopDot3D] = []
442
+ self.dot_group = VGroup()
443
+
444
+ for i in range(N):
445
+ s = int(self.strata[i])
446
+ color = self._STRATUM_COLORS[s % len(self._STRATUM_COLORS)]
447
+
448
+ dot = _PopDot3D(
449
+ position=positions[i],
450
+ value=float(self.values[i]),
451
+ index=i,
452
+ color=color,
453
+ radius=self.cfg.pop_dot_radius,
454
+ opacity=self.cfg.pop_dot_opacity,
455
+ glow_radius_mult=self.cfg.glow_radius_mult,
456
+ glow_opacity=self.cfg.glow_opacity,
457
+ stratum=s,
458
+ cluster=int(self.clusters[i]),
459
+ )
460
+ self.dots.append(dot)
461
+ self.dot_group.add(dot)
462
+
463
+ self.add(self.dot_group)
464
+
465
+ # ------------------------------------------------------------------
466
+
467
+ def _generate_positions(self, rng: np.random.Generator) -> np.ndarray:
468
+ """Generate N 3D positions according to ``cfg.pop_layout``."""
469
+ cfg = self.cfg
470
+ cx, cy, cz = cfg.pop_center
471
+ hw = cfg.pop_width / 2
472
+ hh = cfg.pop_height / 2
473
+ N = self.N
474
+
475
+ if cfg.pop_layout == "grid":
476
+ cols = int(np.ceil(np.sqrt(N * cfg.pop_width / cfg.pop_height)))
477
+ rows = int(np.ceil(N / cols))
478
+ xs = np.linspace(cx - hw, cx + hw, cols)
479
+ ys = np.linspace(cy - hh, cy + hh, rows)
480
+ pts = []
481
+ for r in range(rows):
482
+ for c in range(cols):
483
+ if len(pts) < N:
484
+ z = cz + rng.uniform(-0.05, 0.05)
485
+ pts.append([xs[c], ys[r], z])
486
+ return np.array(pts[:N])
487
+
488
+ elif cfg.pop_layout == "hex":
489
+ # Hexagonal packing
490
+ cols = int(np.ceil(np.sqrt(N * cfg.pop_width / cfg.pop_height)))
491
+ rows = int(np.ceil(N / cols))
492
+ dx = cfg.pop_width / cols
493
+ dy = cfg.pop_height / rows
494
+ pts = []
495
+ for r in range(rows):
496
+ for c in range(cols):
497
+ if len(pts) < N:
498
+ x_off = dx / 2 if r % 2 else 0.0
499
+ x = cx - hw + c * dx + x_off
500
+ y = cy - hh + r * dy
501
+ z = cz + rng.uniform(-0.04, 0.04)
502
+ pts.append([x, y, z])
503
+ return np.array(pts[:N])
504
+
505
+ else: # "random" — default
506
+ xs = rng.uniform(cx - hw, cx + hw, N)
507
+ ys = rng.uniform(cy - hh, cy + hh, N)
508
+ zs = rng.uniform(cz - 0.12, cz + 0.12, N)
509
+ return np.column_stack([xs, ys, zs])
510
+
511
+ # ------------------------------------------------------------------
512
+
513
+ def animate_appear(
514
+ self,
515
+ lag: float = 0.008,
516
+ run_time_per: float = 0.18,
517
+ ) -> LaggedStart:
518
+ """Fade all dots in with a stagger."""
519
+ return LaggedStart(
520
+ *[FadeIn(d, scale=0.3, run_time=run_time_per)
521
+ for d in self.dots],
522
+ lag_ratio=lag,
523
+ )
524
+
525
+ def color_by_value(
526
+ self,
527
+ lo_color: ManimColor = ManimColor("#0C4478"),
528
+ hi_color: ManimColor = ManimColor("#A32D2D"),
529
+ ) -> AnimationGroup:
530
+ """Recolour all dots according to their value (low=lo_color, high=hi_color)."""
531
+ lo, hi = float(self.values.min()), float(self.values.max())
532
+ span = hi - lo if hi != lo else 1.0
533
+ anims = []
534
+ for dot in self.dots:
535
+ t = (dot.dot_value - lo) / span
536
+ col = _lerp_color(lo_color, hi_color, t)
537
+ anims.append(
538
+ dot.dot.animate.set_color(_with_opacity(col, self.cfg.pop_dot_opacity))
539
+ )
540
+ return AnimationGroup(*anims, run_time=0.6)
541
+
542
+ def get_indices_by_stratum(self, s: int) -> List[int]:
543
+ return [i for i in range(self.N) if self.strata[i] == s]
544
+
545
+ def get_indices_by_cluster(self, c: int) -> List[int]:
546
+ return [i for i in range(self.N) if self.clusters[i] == c]
547
+
548
+
549
+ # ---------------------------------------------------------------------------
550
+ # _SampleZone3D — internal
551
+ # ---------------------------------------------------------------------------
552
+
553
+ class _SampleZone3D(VGroup):
554
+ """The landing zone where extracted sample dots are displayed.
555
+
556
+ Draws an optional bounding box and a "Sample" label.
557
+
558
+ Parameters
559
+ ----------
560
+ center : np.ndarray
561
+ width, height : float
562
+ color : ManimColor
563
+ label : str
564
+ scene : ThreeDScene or None
565
+ """
566
+
567
+ def __init__(
568
+ self,
569
+ center: np.ndarray = ORIGIN,
570
+ width: float = 2.8,
571
+ height: float = 3.5,
572
+ color: ManimColor = ManimColor("#2DAA6E"),
573
+ label: str = "Sample",
574
+ show_box: bool = True,
575
+ scene: Optional[ThreeDScene] = None,
576
+ **kwargs,
577
+ ):
578
+ super().__init__(**kwargs)
579
+ cx, cy, cz = center
580
+ hw, hh = width / 2, height / 2
581
+ col = _with_opacity(color, 0.60)
582
+
583
+ if show_box:
584
+ # Draw a 3D bounding box (4 vertical edges + 4 base edges)
585
+ corners_bot = [
586
+ np.array([cx - hw, cy - hh, cz]),
587
+ np.array([cx + hw, cy - hh, cz]),
588
+ np.array([cx + hw, cy + hh, cz]),
589
+ np.array([cx - hw, cy + hh, cz]),
590
+ ]
591
+ corners_top = [p + np.array([0, 0, height]) for p in corners_bot]
592
+
593
+ edges = VGroup()
594
+ for i in range(4):
595
+ j = (i + 1) % 4
596
+ edges.add(Line(corners_bot[i], corners_bot[j], color=col, stroke_width=1.0))
597
+ edges.add(Line(corners_top[i], corners_top[j], color=col, stroke_width=1.0))
598
+ edges.add(Line(corners_bot[i], corners_top[i], color=col, stroke_width=0.7))
599
+ self.box = edges
600
+ self.add(edges)
601
+
602
+ # Label
603
+ lbl = Text(label, font_size=20, color=color)
604
+ lbl.move_to(center + np.array([0, -hh - 0.30, height / 2]))
605
+ self._label = VGroup(lbl)
606
+ if scene is not None:
607
+ scene.add_fixed_orientation_mobjects(lbl)
608
+ self.add(self._label)
609
+
610
+ def grid_positions(
611
+ self,
612
+ n: int,
613
+ width: float,
614
+ height: float,
615
+ center: np.ndarray,
616
+ ) -> List[np.ndarray]:
617
+ """Return n evenly-spaced positions inside the zone."""
618
+ cx, cy, cz = center
619
+ hw, hh = width / 2, height / 2
620
+ cols = int(np.ceil(np.sqrt(n * width / height)))
621
+ rows = int(np.ceil(n / cols))
622
+ xs = np.linspace(cx - hw * 0.8, cx + hw * 0.8, max(cols, 1))
623
+ ys = np.linspace(cy - hh * 0.8, cy + hh * 0.8, max(rows, 1))
624
+ pts = []
625
+ for r in range(rows):
626
+ for c in range(cols):
627
+ if len(pts) < n:
628
+ pts.append(np.array([xs[c], ys[r], cz + height * 0.2]))
629
+ return pts
630
+
631
+
632
+ # ---------------------------------------------------------------------------
633
+ # _SweepLine3D — internal
634
+ # ---------------------------------------------------------------------------
635
+
636
+ class _SweepLine3D(VGroup):
637
+ """A vertical sweep line that travels across the population cloud.
638
+
639
+ Used by ``SystematicSampling3D`` to visually show the selection
640
+ interval k.
641
+
642
+ Parameters
643
+ ----------
644
+ x_start, x_end : float
645
+ Horizontal travel range.
646
+ y_min, y_max : float
647
+ Vertical extent of the line.
648
+ z : float
649
+ Z position.
650
+ color : ManimColor
651
+ """
652
+
653
+ def __init__(
654
+ self,
655
+ x_start: float,
656
+ x_end: float,
657
+ y_min: float,
658
+ y_max: float,
659
+ z: float = 0.0,
660
+ color: ManimColor = ManimColor("#E0AA40"),
661
+ **kwargs,
662
+ ):
663
+ super().__init__(**kwargs)
664
+ self.x_start = x_start
665
+ self.x_end = x_end
666
+ col = _with_opacity(color, 0.65)
667
+
668
+ self.line = Line(
669
+ np.array([x_start, y_min, z]),
670
+ np.array([x_start, y_max, z]),
671
+ color=col, stroke_width=2.0,
672
+ )
673
+ self.glow_line = Line(
674
+ np.array([x_start, y_min, z]),
675
+ np.array([x_start, y_max, z]),
676
+ color=_with_opacity(color, 0.15), stroke_width=7.0,
677
+ )
678
+ self.add(self.glow_line, self.line)
679
+
680
+ def animate_sweep(
681
+ self,
682
+ run_time: float = 2.0,
683
+ ) -> UpdateFromAlphaFunc:
684
+ """Animate the line sweeping from x_start to x_end."""
685
+ x0, x1 = self.x_start, self.x_end
686
+
687
+ def updater(mob: _SweepLine3D, alpha: float) -> None:
688
+ x = x0 + (x1 - x0) * smooth(alpha)
689
+ mob.line.put_start_and_end_on(
690
+ mob.line.get_start() * 0 + np.array([x, mob.line.get_start()[1], mob.line.get_start()[2]]),
691
+ mob.line.get_end() * 0 + np.array([x, mob.line.get_end()[1], mob.line.get_end()[2]]),
692
+ )
693
+ mob.glow_line.put_start_and_end_on(
694
+ np.array([x, mob.glow_line.get_start()[1], mob.glow_line.get_start()[2]]),
695
+ np.array([x, mob.glow_line.get_end()[1], mob.glow_line.get_end()[2]]),
696
+ )
697
+
698
+ return UpdateFromAlphaFunc(self, updater, run_time=run_time)
699
+
700
+
701
+ # ---------------------------------------------------------------------------
702
+ # _StrataRegion3D — internal
703
+ # ---------------------------------------------------------------------------
704
+
705
+ class _StrataRegion3D(VGroup):
706
+ """A visual bounding box around one stratum in the population cloud.
707
+
708
+ Parameters
709
+ ----------
710
+ dots : list of _PopDot3D
711
+ Dots belonging to this stratum.
712
+ color : ManimColor
713
+ label : str
714
+ padding : float
715
+ scene : ThreeDScene or None
716
+ """
717
+
718
+ def __init__(
719
+ self,
720
+ dots: List[_PopDot3D],
721
+ color: ManimColor = ManimColor("#4A90D9"),
722
+ label: str = "",
723
+ padding: float = 0.20,
724
+ scene: Optional[ThreeDScene] = None,
725
+ **kwargs,
726
+ ):
727
+ super().__init__(**kwargs)
728
+ if not dots:
729
+ return
730
+
731
+ positions = np.array([d._pos for d in dots])
732
+ x_min, y_min = positions[:, 0].min() - padding, positions[:, 1].min() - padding
733
+ x_max, y_max = positions[:, 0].max() + padding, positions[:, 1].max() + padding
734
+ z = float(positions[:, 2].mean())
735
+
736
+ col = _with_opacity(color, 0.30)
737
+ fill_col = _with_opacity(color, 0.05)
738
+
739
+ # Flat rectangle in the xy-plane at z
740
+ rect = Polygon(
741
+ np.array([x_min, y_min, z]),
742
+ np.array([x_max, y_min, z]),
743
+ np.array([x_max, y_max, z]),
744
+ np.array([x_min, y_max, z]),
745
+ fill_color=fill_col,
746
+ fill_opacity=1.0,
747
+ stroke_color=col,
748
+ stroke_width=1.4,
749
+ )
750
+ self.rect = rect
751
+ self.add(rect)
752
+
753
+ if label:
754
+ lbl = Text(label, font_size=16, color=_with_opacity(color, 0.80))
755
+ lbl.move_to(np.array([
756
+ (x_min + x_max) / 2,
757
+ y_min - 0.25,
758
+ z,
759
+ ]))
760
+ self._label = VGroup(lbl)
761
+ if scene is not None:
762
+ scene.add_fixed_orientation_mobjects(lbl)
763
+ self.add(self._label)
764
+
765
+
766
+ # ---------------------------------------------------------------------------
767
+ # _ClusterRegion3D — internal
768
+ # ---------------------------------------------------------------------------
769
+
770
+ class _ClusterRegion3D(VGroup):
771
+ """A visual bounding circle / box around one cluster.
772
+
773
+ Parameters
774
+ ----------
775
+ dots : list of _PopDot3D
776
+ color : ManimColor
777
+ label : str
778
+ scene : ThreeDScene or None
779
+ """
780
+
781
+ def __init__(
782
+ self,
783
+ dots: List[_PopDot3D],
784
+ color: ManimColor = ManimColor("#4A90D9"),
785
+ label: str = "",
786
+ padding: float = 0.22,
787
+ scene: Optional[ThreeDScene] = None,
788
+ **kwargs,
789
+ ):
790
+ super().__init__(**kwargs)
791
+ if not dots:
792
+ return
793
+
794
+ positions = np.array([d._pos for d in dots])
795
+ centre = positions.mean(axis=0)
796
+ r = float(np.max(np.linalg.norm(positions - centre, axis=1))) + padding
797
+ z = float(centre[2])
798
+
799
+ col = _with_opacity(color, 0.35)
800
+
801
+ # Draw circle approximated as polygon in xy-plane
802
+ n = 32
803
+ angles = np.linspace(0, TAU, n, endpoint=False)
804
+ pts = [centre + np.array([r * np.cos(a), r * np.sin(a), 0]) for a in angles]
805
+ ring = Polygon(
806
+ *pts,
807
+ fill_color=_with_opacity(color, 0.06),
808
+ fill_opacity=1.0,
809
+ stroke_color=col,
810
+ stroke_width=1.5,
811
+ )
812
+ self.ring = ring
813
+ self.add(ring)
814
+
815
+ if label:
816
+ lbl = Text(label, font_size=15, color=_with_opacity(color, 0.75))
817
+ lbl.move_to(centre + np.array([0, -r - 0.22, 0]))
818
+ self._label = VGroup(lbl)
819
+ if scene is not None:
820
+ scene.add_fixed_orientation_mobjects(lbl)
821
+ self.add(self._label)
822
+
823
+
824
+ # ---------------------------------------------------------------------------
825
+ # _SampleStatAnnotation3D — internal
826
+ # ---------------------------------------------------------------------------
827
+
828
+ class _SampleStatAnnotation3D(VGroup):
829
+ """Floating annotation showing sample statistics after selection.
830
+
831
+ Displays: n, x̄ (mean), s (std dev), and optionally the population
832
+ mean μ for comparison.
833
+
834
+ Parameters
835
+ ----------
836
+ values : np.ndarray
837
+ Values of the selected sample members.
838
+ pop_mean : float or None
839
+ True population mean for comparison annotation.
840
+ position : np.ndarray
841
+ config : SamplingConfig
842
+ scene : ThreeDScene or None
843
+ """
844
+
845
+ def __init__(
846
+ self,
847
+ values: np.ndarray,
848
+ pop_mean: Optional[float] = None,
849
+ position: np.ndarray = ORIGIN,
850
+ config: Optional[SamplingConfig] = None,
851
+ scene: Optional[ThreeDScene] = None,
852
+ **kwargs,
853
+ ):
854
+ super().__init__(**kwargs)
855
+ cfg = config if config is not None else SamplingConfig()
856
+
857
+ n = len(values)
858
+ xbar = float(values.mean()) if n > 0 else 0.0
859
+ s = float(values.std(ddof=1)) if n > 1 else 0.0
860
+
861
+ lines = [
862
+ (f"n = {n}", ManimColor("#AABBCC")),
863
+ (f"x̄ = {xbar:.3f}", cfg.stat_color),
864
+ (f"s = {s:.3f}", cfg.stat_color),
865
+ ]
866
+ if pop_mean is not None:
867
+ bias = xbar - pop_mean
868
+ lines.append((f"μ = {pop_mean:.3f}", ManimColor("#E0AA40")))
869
+ lines.append((f"bias = {bias:+.3f}", ManimColor("#E8593C") if abs(bias) > 0.1 else ManimColor("#2DAA6E")))
870
+
871
+ pos = np.array(position, dtype=float)
872
+ for i, (txt, col) in enumerate(lines):
873
+ lbl = Text(txt, font_size=cfg.stat_font_size, color=col)
874
+ lbl.move_to(pos + np.array([0, 0, -i * 0.32]))
875
+ self.add(lbl)
876
+ if scene is not None:
877
+ scene.add_fixed_orientation_mobjects(lbl)
878
+
879
+
880
+ # ---------------------------------------------------------------------------
881
+ # SampleSelector — core animation engine
882
+ # ---------------------------------------------------------------------------
883
+
884
+ class SampleSelector:
885
+ """Animate the selection of a subset of dots from a population cloud.
886
+
887
+ This is the engine used by all sampling method classes. It handles
888
+ the four selection styles and the extract-to-sample-zone logic.
889
+
890
+ Parameters
891
+ ----------
892
+ population : PopulationCloud3D
893
+ selected_indices : list of int
894
+ Indices of dots to select.
895
+ config : SamplingConfig
896
+ scene : ThreeDScene or None
897
+ """
898
+
899
+ def __init__(
900
+ self,
901
+ population: PopulationCloud3D,
902
+ selected_indices: List[int],
903
+ config: Optional[SamplingConfig] = None,
904
+ scene: Optional[ThreeDScene] = None,
905
+ ):
906
+ self.pop = population
907
+ self.selected = list(selected_indices)
908
+ self.cfg = config if config is not None else population.cfg
909
+ self._scene = scene
910
+ self._selected_set: Set[int] = set(selected_indices)
911
+
912
+ # Sample zone (built lazily)
913
+ self._zone: Optional[_SampleZone3D] = None
914
+ self._zone_positions: Optional[List[np.ndarray]] = None
915
+
916
+ # ------------------------------------------------------------------
917
+
918
+ def build_sample_zone(
919
+ self,
920
+ scene: ThreeDScene,
921
+ label: str = "Sample",
922
+ ) -> _SampleZone3D:
923
+ """Add the sample zone bounding box to the scene."""
924
+ cfg = self.cfg
925
+ zone = _SampleZone3D(
926
+ center=cfg.sample_zone_center,
927
+ width=cfg.sample_zone_width,
928
+ height=cfg.sample_zone_height,
929
+ color=cfg.sample_zone_color,
930
+ label=label,
931
+ show_box=cfg.show_sample_zone_box,
932
+ scene=scene,
933
+ )
934
+ scene.add(zone)
935
+ scene.play(FadeIn(zone, run_time=0.4))
936
+ self._zone = zone
937
+
938
+ # Pre-compute target positions in sample zone
939
+ n = len(self.selected)
940
+ dummy_zone = _SampleZone3D.__new__(_SampleZone3D)
941
+ self._zone_positions = zone.grid_positions(
942
+ n,
943
+ cfg.sample_zone_width,
944
+ cfg.sample_zone_height,
945
+ cfg.sample_zone_center,
946
+ )
947
+ return zone
948
+
949
+ def animate_highlight(
950
+ self,
951
+ scene: ThreeDScene,
952
+ lag: float = 0.04,
953
+ ) -> None:
954
+ """Highlight selected dots in place; dim unselected."""
955
+ cfg = self.cfg
956
+
957
+ # Dim all first
958
+ dim_anims = [
959
+ self.pop.dots[i].deselect(
960
+ self.pop.cfg.pop_dot_color,
961
+ cfg.unselected_opacity,
962
+ )
963
+ for i in range(self.pop.N)
964
+ if i not in self._selected_set
965
+ ]
966
+ if dim_anims:
967
+ scene.play(AnimationGroup(*dim_anims, run_time=cfg.run_time_fade))
968
+
969
+ # Highlight selected with stagger
970
+ select_anims = [
971
+ self.pop.dots[i].select(
972
+ cfg.selected_color,
973
+ cfg.selected_radius_mult,
974
+ cfg.glow_radius_mult,
975
+ cfg.glow_opacity * 1.5,
976
+ )
977
+ for i in self.selected
978
+ ]
979
+ scene.play(LaggedStart(*select_anims, lag_ratio=lag))
980
+
981
+ def animate_extract(
982
+ self,
983
+ scene: ThreeDScene,
984
+ lag: float = 0.05,
985
+ ) -> None:
986
+ """Extract selected dots, arc them to the sample zone."""
987
+ cfg = self.cfg
988
+
989
+ if self._zone_positions is None:
990
+ self.build_sample_zone(scene)
991
+
992
+ # Dim unselected first
993
+ dim_anims = [
994
+ self.pop.dots[i].deselect(
995
+ self.pop.cfg.pop_dot_color,
996
+ cfg.unselected_opacity,
997
+ )
998
+ for i in range(self.pop.N)
999
+ if i not in self._selected_set
1000
+ ]
1001
+ if dim_anims:
1002
+ scene.play(AnimationGroup(*dim_anims, run_time=cfg.run_time_fade))
1003
+
1004
+ # Glow-up selected, then arc to zone
1005
+ select_anims = [
1006
+ self.pop.dots[i].select(
1007
+ cfg.selected_color,
1008
+ cfg.selected_radius_mult,
1009
+ cfg.glow_radius_mult,
1010
+ cfg.glow_opacity * 1.4,
1011
+ )
1012
+ for i in self.selected
1013
+ ]
1014
+ scene.play(LaggedStart(*select_anims, lag_ratio=lag * 0.5))
1015
+
1016
+ # Arc each selected dot to its target position
1017
+ arc_anims = []
1018
+ for j, idx in enumerate(self.selected):
1019
+ target = self._zone_positions[j] if self._zone_positions else cfg.sample_zone_center
1020
+ arc_anims.append(
1021
+ self.pop.dots[idx].move_to_sample_zone(
1022
+ target, run_time=cfg.run_time_per_dot
1023
+ )
1024
+ )
1025
+ scene.play(LaggedStart(*arc_anims, lag_ratio=lag))
1026
+
1027
+ def animate_fade(
1028
+ self,
1029
+ scene: ThreeDScene,
1030
+ ) -> None:
1031
+ """Fade unselected to near-invisible; selected stay bright."""
1032
+ cfg = self.cfg
1033
+ dim_anims = [
1034
+ self.pop.dots[i].deselect(
1035
+ self.pop.cfg.pop_dot_color,
1036
+ cfg.unselected_opacity,
1037
+ )
1038
+ for i in range(self.pop.N)
1039
+ if i not in self._selected_set
1040
+ ]
1041
+ bright_anims = [
1042
+ self.pop.dots[i].select(
1043
+ cfg.selected_color,
1044
+ cfg.selected_radius_mult,
1045
+ )
1046
+ for i in self._selected_set
1047
+ ]
1048
+ scene.play(
1049
+ AnimationGroup(
1050
+ AnimationGroup(*dim_anims),
1051
+ AnimationGroup(*bright_anims),
1052
+ run_time=cfg.run_time_fade,
1053
+ )
1054
+ )
1055
+
1056
+ def animate(
1057
+ self,
1058
+ scene: ThreeDScene,
1059
+ style: Optional[str] = None,
1060
+ zone_label: str = "Sample",
1061
+ ) -> None:
1062
+ """Dispatch to the correct animation style.
1063
+
1064
+ Parameters
1065
+ ----------
1066
+ style : str or None
1067
+ Override config style. ``"highlight"``, ``"extract"``,
1068
+ ``"fade"``, ``"draw"``.
1069
+ """
1070
+ s = style or self.cfg.selection_style
1071
+ if s == "extract":
1072
+ self.build_sample_zone(scene, label=zone_label)
1073
+ self.animate_extract(scene)
1074
+ elif s == "highlight":
1075
+ self.animate_highlight(scene)
1076
+ else:
1077
+ self.animate_fade(scene)
1078
+
1079
+
1080
+ # ---------------------------------------------------------------------------
1081
+ # SimpleRandomSampling3D
1082
+ # ---------------------------------------------------------------------------
1083
+
1084
+ class SimpleRandomSampling3D:
1085
+ """Animate simple random sampling without replacement.
1086
+
1087
+ Phase sequence:
1088
+ 1. ``phase_population`` — build and show the population cloud.
1089
+ 2. ``phase_sample`` — select n dots uniformly at random.
1090
+ 3. ``phase_statistics`` — annotate with x̄, s, n.
1091
+
1092
+ Parameters
1093
+ ----------
1094
+ N : int
1095
+ Population size.
1096
+ n : int
1097
+ Sample size.
1098
+ values : np.ndarray or None
1099
+ Population values. If None drawn from N(0,1).
1100
+ config : SamplingConfig
1101
+ rng_seed : int
1102
+ scene : ThreeDScene or None
1103
+ """
1104
+
1105
+ def __init__(
1106
+ self,
1107
+ N: int = 100,
1108
+ n: int = 20,
1109
+ values: Optional[np.ndarray] = None,
1110
+ config: Optional[SamplingConfig] = None,
1111
+ rng_seed: int = 42,
1112
+ scene: Optional[ThreeDScene] = None,
1113
+ ):
1114
+ self.N = N
1115
+ self.n = n
1116
+ self.cfg = config if config is not None else DETAILED_SAMPLING
1117
+ self._scene = scene
1118
+
1119
+ rng = np.random.default_rng(rng_seed)
1120
+ self.population = PopulationCloud3D(
1121
+ N=N, values=values, config=self.cfg,
1122
+ rng_seed=rng_seed, scene=scene,
1123
+ )
1124
+ self._sample_idx: List[int] = list(
1125
+ rng.choice(N, size=n, replace=False)
1126
+ )
1127
+ self._selector: Optional[SampleSelector] = None
1128
+
1129
+ def phase_population(
1130
+ self,
1131
+ scene: ThreeDScene,
1132
+ run_time: float = 1.2,
1133
+ title: bool = True,
1134
+ ) -> None:
1135
+ """Add population cloud to scene and animate its appearance."""
1136
+ scene.add(self.population)
1137
+ scene.play(
1138
+ self.population.animate_appear(
1139
+ lag=0.008, run_time_per=0.15
1140
+ ),
1141
+ run_time=run_time,
1142
+ )
1143
+ if title:
1144
+ lbl = Text(
1145
+ f"Population N = {self.N}",
1146
+ font_size=20,
1147
+ color=_with_opacity(self.cfg.pop_dot_color, 0.70),
1148
+ )
1149
+ lbl.move_to(self.cfg.pop_center + np.array([0, -self.cfg.pop_height / 2 - 0.35, 0]))
1150
+ scene.add_fixed_orientation_mobjects(lbl)
1151
+ scene.add(lbl)
1152
+ scene.play(FadeIn(lbl, run_time=0.3))
1153
+ scene.wait(0.4)
1154
+
1155
+ def phase_sample(
1156
+ self,
1157
+ scene: ThreeDScene,
1158
+ style: Optional[str] = None,
1159
+ ) -> None:
1160
+ """Animate the random selection of n members."""
1161
+ self._selector = SampleSelector(
1162
+ self.population, self._sample_idx, self.cfg, scene
1163
+ )
1164
+ self._selector.animate(scene, style=style, zone_label=f"SRS n = {self.n}")
1165
+
1166
+ def phase_statistics(
1167
+ self,
1168
+ scene: ThreeDScene,
1169
+ position: Optional[np.ndarray] = None,
1170
+ ) -> None:
1171
+ """Annotate the sample with x̄, s, n."""
1172
+ if not self.cfg.show_stat_annotation:
1173
+ return
1174
+ sample_values = self.population.values[self._sample_idx]
1175
+ pos = position if position is not None else (
1176
+ self.cfg.sample_zone_center + np.array([0, 0, 2.0])
1177
+ )
1178
+ ann = _SampleStatAnnotation3D(
1179
+ values=sample_values,
1180
+ pop_mean=float(self.population.values.mean()),
1181
+ position=pos,
1182
+ config=self.cfg,
1183
+ scene=scene,
1184
+ )
1185
+ scene.add(ann)
1186
+ scene.play(FadeIn(ann, run_time=0.5))
1187
+ scene.wait(0.8)
1188
+
1189
+ def run(self, scene: ThreeDScene, style: Optional[str] = None) -> None:
1190
+ self.phase_population(scene)
1191
+ self.phase_sample(scene, style=style)
1192
+ self.phase_statistics(scene)
1193
+
1194
+
1195
+ # ---------------------------------------------------------------------------
1196
+ # StratifiedSampling3D
1197
+ # ---------------------------------------------------------------------------
1198
+
1199
+ class StratifiedSampling3D:
1200
+ """Animate proportional stratified sampling.
1201
+
1202
+ Population is divided into ``n_strata`` visible strata (coloured
1203
+ bounding regions). Samples are drawn proportionally from each
1204
+ stratum. Shows clearly that each stratum contributes n × (N_h/N)
1205
+ members.
1206
+
1207
+ Parameters
1208
+ ----------
1209
+ N : int
1210
+ n : int
1211
+ Total sample size.
1212
+ n_strata : int
1213
+ Number of strata (2–6).
1214
+ stratum_sizes : list of int or None
1215
+ Size of each stratum. If None, N is divided equally.
1216
+ config : SamplingConfig
1217
+ rng_seed : int
1218
+ scene : ThreeDScene or None
1219
+ """
1220
+
1221
+ def __init__(
1222
+ self,
1223
+ N: int = 120,
1224
+ n: int = 30,
1225
+ n_strata: int = 3,
1226
+ stratum_sizes: Optional[List[int]] = None,
1227
+ config: Optional[SamplingConfig] = None,
1228
+ rng_seed: int = 42,
1229
+ scene: Optional[ThreeDScene] = None,
1230
+ ):
1231
+ self.N = N
1232
+ self.n = n
1233
+ self.n_strata = n_strata
1234
+ self.cfg = config if config is not None else DETAILED_SAMPLING
1235
+ self._scene = scene
1236
+
1237
+ rng = np.random.default_rng(rng_seed)
1238
+
1239
+ # Build strata labels
1240
+ if stratum_sizes is not None:
1241
+ assert sum(stratum_sizes) == N
1242
+ sizes = stratum_sizes
1243
+ else:
1244
+ base = N // n_strata
1245
+ sizes = [base] * n_strata
1246
+ sizes[-1] += N - sum(sizes)
1247
+
1248
+ strata_arr = np.concatenate([
1249
+ np.full(sz, s, dtype=int) for s, sz in enumerate(sizes)
1250
+ ])
1251
+ # Shuffle so strata are spatially mixed (then spatial layout will
1252
+ # separate them by y-band — override positions to be banded)
1253
+ rng.shuffle(strata_arr)
1254
+
1255
+ # Values: each stratum has a different mean
1256
+ strata_means = np.linspace(-1.5, 1.5, n_strata)
1257
+ values = np.array([
1258
+ rng.normal(strata_means[s], 0.6)
1259
+ for s in strata_arr
1260
+ ])
1261
+
1262
+ # Override layout to "grid" with y-bands per stratum
1263
+ cfg_copy = SamplingConfig(**self.cfg.__dict__)
1264
+ cfg_copy.pop_layout = "grid"
1265
+
1266
+ self.population = PopulationCloud3D(
1267
+ N=N, values=values, strata=strata_arr,
1268
+ config=cfg_copy, rng_seed=rng_seed, scene=scene,
1269
+ )
1270
+
1271
+ # Reposition dots into horizontal bands (one y-band per stratum)
1272
+ self._reposition_by_stratum(sizes)
1273
+
1274
+ # Proportional allocation
1275
+ nh_list = [max(1, round(n * sz / N)) for sz in sizes]
1276
+ # Adjust last to hit total n exactly
1277
+ nh_list[-1] = n - sum(nh_list[:-1])
1278
+
1279
+ # Draw proportional samples
1280
+ self._sample_idx: List[int] = []
1281
+ for s in range(n_strata):
1282
+ s_indices = self.population.get_indices_by_stratum(s)
1283
+ nh = nh_list[s]
1284
+ chosen = list(rng.choice(s_indices, size=min(nh, len(s_indices)), replace=False))
1285
+ self._sample_idx.extend(chosen)
1286
+
1287
+ self._nh_list = nh_list
1288
+ self._sizes = sizes
1289
+ self._strata_regions: List[_StrataRegion3D] = []
1290
+
1291
+ def _reposition_by_stratum(self, sizes: List[int]) -> None:
1292
+ """Move dots so each stratum occupies a horizontal y-band."""
1293
+ cfg = self.cfg
1294
+ cx, cy, cz = cfg.pop_center
1295
+ band_height = cfg.pop_height / self.n_strata
1296
+ for s in range(self.n_strata):
1297
+ indices = self.population.get_indices_by_stratum(s)
1298
+ y_center = cy - cfg.pop_height / 2 + (s + 0.5) * band_height
1299
+ for i, idx in enumerate(indices):
1300
+ dot = self.population.dots[idx]
1301
+ old_pos = dot._pos.copy()
1302
+ # Spread within band
1303
+ x_frac = (i % max(1, int(np.ceil(len(indices) ** 0.5)))) / max(1, int(np.ceil(len(indices) ** 0.5)) - 1 + 1e-9)
1304
+ new_x = cx - cfg.pop_width / 2 + x_frac * cfg.pop_width
1305
+ new_y = y_center + (i // max(1, int(np.ceil(len(indices) ** 0.5))) - 1) * 0.25
1306
+ new_pos = np.array([new_x, new_y, old_pos[2]])
1307
+ dot._pos = new_pos
1308
+ dot.dot.move_to(new_pos)
1309
+ dot.glow.move_to(new_pos)
1310
+
1311
+ def phase_population(self, scene: ThreeDScene) -> None:
1312
+ scene.add(self.population)
1313
+ scene.play(self.population.animate_appear(lag=0.007, run_time_per=0.12))
1314
+ scene.wait(0.3)
1315
+
1316
+ def phase_show_strata(
1317
+ self,
1318
+ scene: ThreeDScene,
1319
+ palette: Optional[List[ManimColor]] = None,
1320
+ ) -> None:
1321
+ """Draw bounding boxes around each stratum with labels."""
1322
+ colors = palette or PopulationCloud3D._STRATUM_COLORS
1323
+ self._strata_regions.clear()
1324
+
1325
+ for s in range(self.n_strata):
1326
+ indices = self.population.get_indices_by_stratum(s)
1327
+ dots = [self.population.dots[i] for i in indices]
1328
+ col = colors[s % len(colors)]
1329
+ region = _StrataRegion3D(
1330
+ dots=dots, color=col,
1331
+ label=f"Stratum {s+1} N={self._sizes[s]}",
1332
+ scene=scene,
1333
+ )
1334
+ self._strata_regions.append(region)
1335
+ scene.add(region)
1336
+
1337
+ scene.play(LaggedStart(
1338
+ *[FadeIn(r, run_time=0.35) for r in self._strata_regions],
1339
+ lag_ratio=0.15,
1340
+ ))
1341
+ scene.wait(0.5)
1342
+
1343
+ def phase_sample(self, scene: ThreeDScene) -> None:
1344
+ """Select proportional samples from each stratum, extract to zone."""
1345
+ selector = SampleSelector(
1346
+ self.population, self._sample_idx, self.cfg, scene
1347
+ )
1348
+ selector.build_sample_zone(
1349
+ scene, label=f"Stratified n = {self.n}"
1350
+ )
1351
+ selector.animate_extract(scene, lag=0.04)
1352
+
1353
+ def phase_statistics(self, scene: ThreeDScene) -> None:
1354
+ sample_values = self.population.values[np.array(self._sample_idx)]
1355
+ pos = self.cfg.sample_zone_center + np.array([0, 0, 2.2])
1356
+ ann = _SampleStatAnnotation3D(
1357
+ values=sample_values,
1358
+ pop_mean=float(self.population.values.mean()),
1359
+ position=pos, config=self.cfg, scene=scene,
1360
+ )
1361
+ scene.add(ann)
1362
+ scene.play(FadeIn(ann, run_time=0.5))
1363
+ scene.wait(0.8)
1364
+
1365
+ def run(self, scene: ThreeDScene) -> None:
1366
+ self.phase_population(scene)
1367
+ self.phase_show_strata(scene)
1368
+ self.phase_sample(scene)
1369
+ self.phase_statistics(scene)
1370
+
1371
+
1372
+ # ---------------------------------------------------------------------------
1373
+ # ClusterSampling3D
1374
+ # ---------------------------------------------------------------------------
1375
+
1376
+ class ClusterSampling3D:
1377
+ """Animate cluster sampling.
1378
+
1379
+ Population grouped into ``n_clusters`` spatial clusters. A random
1380
+ subset of ``n_selected_clusters`` clusters is chosen; all members of
1381
+ selected clusters form the sample.
1382
+
1383
+ Parameters
1384
+ ----------
1385
+ N : int
1386
+ n_clusters : int
1387
+ Total number of clusters.
1388
+ n_selected_clusters : int
1389
+ Number of clusters to select.
1390
+ config : SamplingConfig
1391
+ rng_seed : int
1392
+ scene : ThreeDScene or None
1393
+ """
1394
+
1395
+ def __init__(
1396
+ self,
1397
+ N: int = 120,
1398
+ n_clusters: int = 8,
1399
+ n_selected_clusters: int = 3,
1400
+ config: Optional[SamplingConfig] = None,
1401
+ rng_seed: int = 42,
1402
+ scene: Optional[ThreeDScene] = None,
1403
+ ):
1404
+ self.N = N
1405
+ self.n_clusters = n_clusters
1406
+ self.n_selected = n_selected_clusters
1407
+ self.cfg = config if config is not None else DETAILED_SAMPLING
1408
+ self._scene = scene
1409
+
1410
+ rng = np.random.default_rng(rng_seed)
1411
+
1412
+ # Assign cluster labels
1413
+ clusters_arr = np.repeat(np.arange(n_clusters), N // n_clusters)
1414
+ while len(clusters_arr) < N:
1415
+ clusters_arr = np.append(clusters_arr, n_clusters - 1)
1416
+ clusters_arr = clusters_arr[:N]
1417
+ rng.shuffle(clusters_arr)
1418
+
1419
+ values = rng.normal(0, 1, N).astype(float)
1420
+
1421
+ # Arrange clusters in a rough grid of circle-blobs
1422
+ cluster_centers = self._cluster_grid_centers(n_clusters)
1423
+
1424
+ self.population = PopulationCloud3D(
1425
+ N=N, values=values, clusters=clusters_arr,
1426
+ config=self.cfg, rng_seed=rng_seed, scene=scene,
1427
+ )
1428
+ # Reposition dots near cluster centres
1429
+ self._reposition_by_cluster(clusters_arr, cluster_centers, rng)
1430
+
1431
+ # Select clusters
1432
+ chosen_clusters = list(rng.choice(n_clusters, size=n_selected_clusters, replace=False))
1433
+ self._chosen_clusters: List[int] = chosen_clusters
1434
+ self._sample_idx: List[int] = [
1435
+ i for i in range(N) if int(clusters_arr[i]) in set(chosen_clusters)
1436
+ ]
1437
+
1438
+ self._cluster_regions: List[_ClusterRegion3D] = []
1439
+
1440
+ def _cluster_grid_centers(self, k: int) -> List[np.ndarray]:
1441
+ cfg = self.cfg
1442
+ cx, cy = cfg.pop_center[0], cfg.pop_center[1]
1443
+ cols = int(np.ceil(np.sqrt(k)))
1444
+ rows = int(np.ceil(k / cols))
1445
+ xs = np.linspace(cx - cfg.pop_width * 0.4, cx + cfg.pop_width * 0.4, cols)
1446
+ ys = np.linspace(cy - cfg.pop_height * 0.4, cy + cfg.pop_height * 0.4, rows)
1447
+ centres = []
1448
+ for r in range(rows):
1449
+ for c in range(cols):
1450
+ if len(centres) < k:
1451
+ centres.append(np.array([xs[c], ys[r], cfg.pop_center[2]]))
1452
+ return centres
1453
+
1454
+ def _reposition_by_cluster(
1455
+ self,
1456
+ clusters_arr: np.ndarray,
1457
+ centers: List[np.ndarray],
1458
+ rng: np.random.Generator,
1459
+ ) -> None:
1460
+ r_spread = 0.5
1461
+ for i, dot in enumerate(self.population.dots):
1462
+ c = int(clusters_arr[i])
1463
+ centre = centers[c]
1464
+ angle = rng.uniform(0, TAU)
1465
+ rad = rng.uniform(0, r_spread)
1466
+ new_pos = centre + np.array([rad * np.cos(angle), rad * np.sin(angle), 0])
1467
+ dot._pos = new_pos
1468
+ dot.dot.move_to(new_pos)
1469
+ dot.glow.move_to(new_pos)
1470
+
1471
+ def phase_population(self, scene: ThreeDScene) -> None:
1472
+ scene.add(self.population)
1473
+ scene.play(self.population.animate_appear(lag=0.008, run_time_per=0.13))
1474
+ scene.wait(0.3)
1475
+
1476
+ def phase_show_clusters(self, scene: ThreeDScene) -> None:
1477
+ colors = PopulationCloud3D._STRATUM_COLORS
1478
+ self._cluster_regions.clear()
1479
+ for c in range(self.n_clusters):
1480
+ indices = self.population.get_indices_by_cluster(c)
1481
+ dots = [self.population.dots[i] for i in indices]
1482
+ col = colors[c % len(colors)]
1483
+ region = _ClusterRegion3D(
1484
+ dots=dots, color=col,
1485
+ label=f"C{c+1}",
1486
+ scene=scene,
1487
+ )
1488
+ self._cluster_regions.append(region)
1489
+ scene.add(region)
1490
+
1491
+ scene.play(LaggedStart(
1492
+ *[FadeIn(r, run_time=0.30) for r in self._cluster_regions],
1493
+ lag_ratio=0.10,
1494
+ ))
1495
+ scene.wait(0.5)
1496
+
1497
+ def phase_select_clusters(self, scene: ThreeDScene) -> None:
1498
+ """Highlight selected clusters and dim rejected ones."""
1499
+ cfg = self.cfg
1500
+ colors = PopulationCloud3D._STRATUM_COLORS
1501
+ chosen_set = set(self._chosen_clusters)
1502
+
1503
+ for c, region in enumerate(self._cluster_regions):
1504
+ if c not in chosen_set:
1505
+ scene.play(region.animate.set_opacity(0.10), run_time=0.3)
1506
+ else:
1507
+ col = colors[c % len(colors)]
1508
+ scene.play(
1509
+ Flash(region, color=col, flash_radius=0.6, run_time=0.4),
1510
+ region.animate.set_stroke(
1511
+ color=_with_opacity(col, 0.90), width=2.5
1512
+ ),
1513
+ )
1514
+
1515
+ def phase_sample(self, scene: ThreeDScene) -> None:
1516
+ selector = SampleSelector(
1517
+ self.population, self._sample_idx, self.cfg, scene
1518
+ )
1519
+ n_sample = len(self._sample_idx)
1520
+ selector.build_sample_zone(
1521
+ scene, label=f"Cluster sample n = {n_sample}"
1522
+ )
1523
+ selector.animate_extract(scene, lag=0.03)
1524
+
1525
+ def run(self, scene: ThreeDScene) -> None:
1526
+ self.phase_population(scene)
1527
+ self.phase_show_clusters(scene)
1528
+ self.phase_select_clusters(scene)
1529
+ self.phase_sample(scene)
1530
+
1531
+
1532
+ # ---------------------------------------------------------------------------
1533
+ # SystematicSampling3D
1534
+ # ---------------------------------------------------------------------------
1535
+
1536
+ class SystematicSampling3D:
1537
+ """Animate systematic (every k-th) sampling.
1538
+
1539
+ Population is arranged in a ``"grid"`` layout so the selection
1540
+ interval k is visually obvious. A random start r ∈ [0, k) is
1541
+ chosen; then every k-th dot from r is selected.
1542
+
1543
+ The sweep-line animation ``phase_sweep`` shows the interval k
1544
+ explicitly before revealing the selected dots.
1545
+
1546
+ Parameters
1547
+ ----------
1548
+ N : int
1549
+ n : int
1550
+ Sample size (k = N // n).
1551
+ config : SamplingConfig
1552
+ rng_seed : int
1553
+ """
1554
+
1555
+ def __init__(
1556
+ self,
1557
+ N: int = 100,
1558
+ n: int = 20,
1559
+ config: Optional[SamplingConfig] = None,
1560
+ rng_seed: int = 42,
1561
+ scene: Optional[ThreeDScene] = None,
1562
+ ):
1563
+ self.N = N
1564
+ self.n = n
1565
+ self.k = max(1, N // n)
1566
+ self.cfg = config if config is not None else DETAILED_SAMPLING
1567
+ self._scene = scene
1568
+
1569
+ rng = np.random.default_rng(rng_seed)
1570
+ self.r = int(rng.integers(0, self.k)) # random start
1571
+ self._sample_idx = list(range(self.r, N, self.k))[:n]
1572
+
1573
+ values = rng.normal(0, 1, N)
1574
+
1575
+ # Force grid layout
1576
+ cfg_grid = SamplingConfig(**self.cfg.__dict__)
1577
+ cfg_grid.pop_layout = "grid"
1578
+
1579
+ self.population = PopulationCloud3D(
1580
+ N=N, values=values, config=cfg_grid,
1581
+ rng_seed=rng_seed, scene=scene,
1582
+ )
1583
+
1584
+ def phase_population(self, scene: ThreeDScene) -> None:
1585
+ scene.add(self.population)
1586
+ scene.play(self.population.animate_appear(lag=0.006, run_time_per=0.12))
1587
+
1588
+ # k annotation
1589
+ k_lbl = Text(f"k = N/n = {self.N}/{self.n} = {self.k}",
1590
+ font_size=20, color=ManimColor("#E0AA40"))
1591
+ k_lbl.move_to(self.cfg.pop_center + np.array([0, -self.cfg.pop_height / 2 - 0.38, 0]))
1592
+ scene.add_fixed_orientation_mobjects(k_lbl)
1593
+ scene.add(k_lbl)
1594
+ scene.play(FadeIn(k_lbl, run_time=0.4))
1595
+ scene.wait(0.4)
1596
+
1597
+ def phase_sweep(self, scene: ThreeDScene) -> None:
1598
+ """Animate a sweep line moving across the grid with step k."""
1599
+ cfg = self.cfg
1600
+ cx = cfg.pop_center[0]
1601
+ y_min = cfg.pop_center[1] - cfg.pop_height / 2
1602
+ y_max = cfg.pop_center[1] + cfg.pop_height / 2
1603
+
1604
+ # Build k interval markers as vertical dashed lines
1605
+ cols = int(np.ceil(np.sqrt(self.N * cfg.pop_width / cfg.pop_height)))
1606
+ dx = cfg.pop_width / cols
1607
+ k_width = dx * self.k
1608
+
1609
+ sweep = _SweepLine3D(
1610
+ x_start=cx - cfg.pop_width / 2,
1611
+ x_end=cx + cfg.pop_width / 2,
1612
+ y_min=y_min, y_max=y_max,
1613
+ z=cfg.pop_center[2],
1614
+ color=ManimColor("#E0AA40"),
1615
+ )
1616
+ scene.add(sweep)
1617
+ scene.play(FadeIn(sweep, run_time=0.3))
1618
+ scene.play(sweep.animate_sweep(run_time=1.8))
1619
+ scene.play(FadeOut(sweep, run_time=0.3))
1620
+
1621
+ def phase_sample(self, scene: ThreeDScene) -> None:
1622
+ # Label random start
1623
+ r_lbl = Text(f"Random start r = {self.r}",
1624
+ font_size=18, color=ManimColor("#E8593C"))
1625
+ r_lbl.move_to(self.cfg.pop_center + np.array([0, -self.cfg.pop_height / 2 - 0.70, 0]))
1626
+ scene.add_fixed_orientation_mobjects(r_lbl)
1627
+ scene.add(r_lbl)
1628
+ scene.play(FadeIn(r_lbl, run_time=0.3))
1629
+
1630
+ selector = SampleSelector(
1631
+ self.population, self._sample_idx, self.cfg, scene
1632
+ )
1633
+ selector.animate(scene, style="highlight",
1634
+ zone_label=f"Systematic n={self.n}")
1635
+
1636
+ def run(self, scene: ThreeDScene) -> None:
1637
+ self.phase_population(scene)
1638
+ self.phase_sweep(scene)
1639
+ self.phase_sample(scene)
1640
+
1641
+
1642
+ # ---------------------------------------------------------------------------
1643
+ # BootstrapSampling3D
1644
+ # ---------------------------------------------------------------------------
1645
+
1646
+ class BootstrapSampling3D:
1647
+ """Animate bootstrap resampling and build the bootstrap distribution.
1648
+
1649
+ Phase sequence:
1650
+ 1. ``phase_original_sample`` — show the n original sample dots.
1651
+ 2. ``phase_bootstrap_draw`` — draw one bootstrap sample WITH
1652
+ replacement; duplicates shown with
1653
+ concentric rings.
1654
+ 3. ``phase_accumulate`` — run B bootstrap trials, compute a
1655
+ statistic (default: mean), accumulate
1656
+ into a live histogram.
1657
+ 4. ``phase_ci`` — shade the central 95% of the
1658
+ bootstrap distribution as the CI.
1659
+
1660
+ Parameters
1661
+ ----------
1662
+ sample_values : np.ndarray
1663
+ The original sample (1-D array).
1664
+ B : int
1665
+ Number of bootstrap resamples.
1666
+ statistic : Callable[[np.ndarray], float]
1667
+ Statistic to compute on each resample. Default: np.mean.
1668
+ config : SamplingConfig
1669
+ rng_seed : int
1670
+ scene : ThreeDScene or None
1671
+ """
1672
+
1673
+ def __init__(
1674
+ self,
1675
+ sample_values: np.ndarray,
1676
+ B: int = 500,
1677
+ statistic: Optional[Callable[[np.ndarray], float]] = None,
1678
+ config: Optional[SamplingConfig] = None,
1679
+ rng_seed: int = 42,
1680
+ scene: Optional[ThreeDScene] = None,
1681
+ ):
1682
+ self.sample = np.asarray(sample_values, dtype=float)
1683
+ self.n = len(self.sample)
1684
+ self.B = B
1685
+ self.stat_fn = statistic if statistic is not None else np.mean
1686
+ self.cfg = config if config is not None else DETAILED_SAMPLING
1687
+ self._scene = scene
1688
+
1689
+ rng = np.random.default_rng(rng_seed)
1690
+
1691
+ # Pre-simulate all bootstrap statistics
1692
+ self._boot_stats: np.ndarray = np.array([
1693
+ self.stat_fn(rng.choice(self.sample, size=self.n, replace=True))
1694
+ for _ in range(B)
1695
+ ])
1696
+
1697
+ # Original sample as a population cloud
1698
+ orig_cfg = SamplingConfig(**self.cfg.__dict__)
1699
+ orig_cfg.pop_layout = "hex"
1700
+ orig_cfg.pop_width = 3.5
1701
+ orig_cfg.pop_height = 2.5
1702
+ orig_cfg.pop_center = np.array([-2.5, 0.0, 0.0])
1703
+ orig_cfg.pop_dot_color = ManimColor("#2DAA6E")
1704
+ orig_cfg.pop_dot_opacity = 0.85
1705
+
1706
+ self.sample_cloud = PopulationCloud3D(
1707
+ N=self.n,
1708
+ values=self.sample,
1709
+ config=orig_cfg,
1710
+ rng_seed=rng_seed,
1711
+ scene=scene,
1712
+ )
1713
+
1714
+ # Bootstrap histogram state
1715
+ self._boot_hist_counts: np.ndarray = None
1716
+ self._boot_hist_bins: np.ndarray = None
1717
+ self._hist_bar_mobs: Dict[int, VGroup] = {}
1718
+ self._max_count: int = 1
1719
+ self._boot_hist_group = VGroup()
1720
+
1721
+ self._init_bootstrap_hist()
1722
+
1723
+ def _init_bootstrap_hist(self) -> None:
1724
+ lo = float(self._boot_stats.min()) - 0.1
1725
+ hi = float(self._boot_stats.max()) + 0.1
1726
+ n_bins = 20
1727
+ self._boot_bins = np.linspace(lo, hi, n_bins + 1)
1728
+ self._boot_hist_counts = np.zeros(n_bins, dtype=int)
1729
+ self._boot_bar_w = (hi - lo) / n_bins
1730
+ self._boot_chart_x = 2.5
1731
+ self._boot_chart_scene_w = 4.0
1732
+ self._boot_n_bins = n_bins
1733
+ self._boot_lo = lo
1734
+ self._boot_hi = hi
1735
+
1736
+ def _boot_x_to_scene(self, val: float) -> float:
1737
+ t = (val - self._boot_lo) / (self._boot_hi - self._boot_lo)
1738
+ return self._boot_chart_x + (t - 0.5) * self._boot_chart_scene_w
1739
+
1740
+ def _build_boot_bar(self, bin_idx: int, height: float) -> VGroup:
1741
+ scene_x = self._boot_x_to_scene(
1742
+ self._boot_bins[bin_idx] + self._boot_bar_w / 2
1743
+ )
1744
+ scene_bar_w = self._boot_chart_scene_w / self._boot_n_bins
1745
+ hw = scene_bar_w / 2 * 0.88
1746
+ hd = 0.35
1747
+ y, z0, z1 = 0.0, 0.0, max(height, 0.01)
1748
+ x = scene_x
1749
+ col = ManimColor("#4A90D9")
1750
+ col_r = _darken(col, 0.60)
1751
+ col_t = _lighten(col, 1.28)
1752
+
1753
+ ff = Polygon(
1754
+ np.array([x-hw,y-hd,z0]), np.array([x+hw,y-hd,z0]),
1755
+ np.array([x+hw,y-hd,z1]), np.array([x-hw,y-hd,z1]),
1756
+ fill_color=_with_opacity(col, 0.88), fill_opacity=1.0, stroke_width=0,
1757
+ )
1758
+ fr = Polygon(
1759
+ np.array([x+hw,y-hd,z0]), np.array([x+hw,y+hd,z0]),
1760
+ np.array([x+hw,y+hd,z1]), np.array([x+hw,y-hd,z1]),
1761
+ fill_color=_with_opacity(col_r, 0.85), fill_opacity=1.0, stroke_width=0,
1762
+ )
1763
+ ft = Polygon(
1764
+ np.array([x-hw,y-hd,z1]), np.array([x+hw,y-hd,z1]),
1765
+ np.array([x+hw,y+hd,z1]), np.array([x-hw,y+hd,z1]),
1766
+ fill_color=_with_opacity(col_t, 0.78), fill_opacity=1.0, stroke_width=0,
1767
+ )
1768
+ return VGroup(ff, fr, ft)
1769
+
1770
+ def _update_boot_bar(self, bin_idx: int) -> None:
1771
+ h = (self._boot_hist_counts[bin_idx] / max(self._max_count, 1)) * 4.0
1772
+ scene_x = self._boot_x_to_scene(
1773
+ self._boot_bins[bin_idx] + self._boot_bar_w / 2
1774
+ )
1775
+ scene_bar_w = self._boot_chart_scene_w / self._boot_n_bins
1776
+ hw = scene_bar_w / 2 * 0.88
1777
+ hd = 0.35
1778
+ x, y, z0, z1 = scene_x, 0.0, 0.0, max(h, 0.01)
1779
+ bar = self._hist_bar_mobs[bin_idx]
1780
+ for face, pts in [
1781
+ (bar[0], [[x-hw,y-hd,z0],[x+hw,y-hd,z0],[x+hw,y-hd,z1],[x-hw,y-hd,z1],[x-hw,y-hd,z0]]),
1782
+ (bar[1], [[x+hw,y-hd,z0],[x+hw,y+hd,z0],[x+hw,y+hd,z1],[x+hw,y-hd,z1],[x+hw,y-hd,z0]]),
1783
+ (bar[2], [[x-hw,y-hd,z1],[x+hw,y-hd,z1],[x+hw,y+hd,z1],[x-hw,y+hd,z1],[x-hw,y-hd,z1]]),
1784
+ ]:
1785
+ face.set_points_as_corners([np.array(p) for p in pts])
1786
+
1787
+ def phase_original_sample(self, scene: ThreeDScene) -> None:
1788
+ """Show the original sample cloud."""
1789
+ scene.add(self.sample_cloud)
1790
+ scene.play(self.sample_cloud.animate_appear(lag=0.03, run_time_per=0.18))
1791
+
1792
+ # x̄ annotation
1793
+ xbar = float(self.sample.mean())
1794
+ lbl = Text(f"Original sample\nn = {self.n}, x̄ = {xbar:.3f}",
1795
+ font_size=18, color=ManimColor("#2DAA6E"))
1796
+ lbl.move_to(np.array([-2.5, 0, -1.6]))
1797
+ scene.add_fixed_orientation_mobjects(lbl)
1798
+ scene.add(lbl)
1799
+ scene.play(FadeIn(lbl, run_time=0.4))
1800
+ scene.wait(0.5)
1801
+
1802
+ def phase_bootstrap_draw(
1803
+ self,
1804
+ scene: ThreeDScene,
1805
+ n_show: int = 1,
1806
+ ) -> None:
1807
+ """Animate one bootstrap draw showing replacement.
1808
+
1809
+ Duplicate-selected members get concentric glow rings.
1810
+ """
1811
+ rng = np.random.default_rng(0)
1812
+ for _ in range(n_show):
1813
+ draw = rng.choice(self.n, size=self.n, replace=True)
1814
+ counts = np.bincount(draw, minlength=self.n)
1815
+
1816
+ # Show multiplicity rings on duplicates
1817
+ ring_anims = []
1818
+ for idx, cnt in enumerate(counts):
1819
+ if cnt > 1:
1820
+ dot = self.sample_cloud.dots[idx]
1821
+ for ring_n in range(1, cnt):
1822
+ ring_pos = dot._pos
1823
+ r_ring = self.cfg.pop_dot_radius * (1.8 + ring_n * 0.9)
1824
+ n_pts = 16
1825
+ angles = np.linspace(0, TAU, n_pts, endpoint=False)
1826
+ ring_pts = [
1827
+ ring_pos + r_ring * np.array([np.cos(a), 0, np.sin(a)])
1828
+ for a in angles
1829
+ ]
1830
+ ring = VMobject()
1831
+ ring.set_points_as_corners(ring_pts + [ring_pts[0]])
1832
+ ring.set_stroke(
1833
+ color=_with_opacity(ManimColor("#FFD700"), 0.70),
1834
+ width=1.5,
1835
+ )
1836
+ ring.set_fill(opacity=0)
1837
+ scene.add(ring)
1838
+ ring_anims.append(Create(ring, run_time=0.25))
1839
+
1840
+ if ring_anims:
1841
+ scene.play(LaggedStart(*ring_anims, lag_ratio=0.05))
1842
+ scene.wait(0.5)
1843
+
1844
+ def phase_accumulate(
1845
+ self,
1846
+ scene: ThreeDScene,
1847
+ n_visible: int = 50,
1848
+ run_time_per: float = 0.08,
1849
+ ) -> None:
1850
+ """Accumulate B bootstrap statistics into a histogram."""
1851
+ # Add histogram group
1852
+ scene.add(self._boot_hist_group)
1853
+
1854
+ for i, stat_val in enumerate(self._boot_stats):
1855
+ idx = np.searchsorted(self._boot_bins[1:], stat_val)
1856
+ idx = min(idx, self._boot_n_bins - 1)
1857
+ self._boot_hist_counts[idx] += 1
1858
+ self._max_count = max(self._max_count, int(self._boot_hist_counts.max()))
1859
+
1860
+ # Rescale existing bars
1861
+ for existing in self._hist_bar_mobs:
1862
+ self._update_boot_bar(existing)
1863
+
1864
+ if idx not in self._hist_bar_mobs:
1865
+ h = (self._boot_hist_counts[idx] / self._max_count) * 4.0
1866
+ bar = self._build_boot_bar(idx, max(h, 0.01))
1867
+ self._hist_bar_mobs[idx] = bar
1868
+ self._boot_hist_group.add(bar)
1869
+ if i < n_visible:
1870
+ scene.play(FadeIn(bar, run_time=run_time_per))
1871
+ elif i < n_visible:
1872
+ scene.wait(run_time_per * 0.3)
1873
+
1874
+ scene.wait(0.4)
1875
+
1876
+ def phase_ci(
1877
+ self,
1878
+ scene: ThreeDScene,
1879
+ alpha: float = 0.05,
1880
+ ) -> None:
1881
+ """Shade the (1-alpha) central bootstrap CI."""
1882
+ lo_ci = float(np.percentile(self._boot_stats, alpha / 2 * 100))
1883
+ hi_ci = float(np.percentile(self._boot_stats, (1 - alpha / 2) * 100))
1884
+
1885
+ lo_x = self._boot_x_to_scene(lo_ci)
1886
+ hi_x = self._boot_x_to_scene(hi_ci)
1887
+ hd = 0.35
1888
+
1889
+ ci_band = Polygon(
1890
+ np.array([lo_x, -hd, 0.0]),
1891
+ np.array([hi_x, -hd, 0.0]),
1892
+ np.array([hi_x, -hd, 4.2]),
1893
+ np.array([lo_x, -hd, 4.2]),
1894
+ fill_color=_with_opacity(ManimColor("#2DAA6E"), 0.18),
1895
+ fill_opacity=1.0, stroke_width=0,
1896
+ )
1897
+ ci_lo_line = DashedLine(
1898
+ np.array([lo_x, -hd, 0]), np.array([lo_x, -hd, 4.4]),
1899
+ dash_length=0.07, dashed_ratio=0.4,
1900
+ color=_with_opacity(ManimColor("#2DAA6E"), 0.75), stroke_width=1.8,
1901
+ )
1902
+ ci_hi_line = DashedLine(
1903
+ np.array([hi_x, -hd, 0]), np.array([hi_x, -hd, 4.4]),
1904
+ dash_length=0.07, dashed_ratio=0.4,
1905
+ color=_with_opacity(ManimColor("#2DAA6E"), 0.75), stroke_width=1.8,
1906
+ )
1907
+
1908
+ ci_lbl = Text(
1909
+ f"{int((1-alpha)*100)}% CI\n[{lo_ci:.3f}, {hi_ci:.3f}]",
1910
+ font_size=18, color=ManimColor("#2DAA6E"),
1911
+ )
1912
+ ci_lbl.move_to(np.array([self._boot_chart_x, 0, 4.8]))
1913
+ scene.add_fixed_orientation_mobjects(ci_lbl)
1914
+
1915
+ scene.add(ci_band, ci_lo_line, ci_hi_line, ci_lbl)
1916
+ scene.play(
1917
+ FadeIn(ci_band, run_time=0.5),
1918
+ Create(ci_lo_line, run_time=0.4),
1919
+ Create(ci_hi_line, run_time=0.4),
1920
+ FadeIn(ci_lbl, run_time=0.4),
1921
+ )
1922
+ scene.wait(1.0)
1923
+
1924
+ def run(self, scene: ThreeDScene) -> None:
1925
+ self.phase_original_sample(scene)
1926
+ self.phase_bootstrap_draw(scene, n_show=1)
1927
+ self.phase_accumulate(scene, n_visible=50)
1928
+ self.phase_ci(scene)
1929
+
1930
+
1931
+ # ---------------------------------------------------------------------------
1932
+ # SamplingDistributionBuilder
1933
+ # ---------------------------------------------------------------------------
1934
+
1935
+ class SamplingDistributionBuilder(VGroup):
1936
+ """Build and visualise the sampling distribution of any statistic.
1937
+
1938
+ Runs a sampler function m times, computing a statistic each time,
1939
+ and accumulates results into a live 3D bar histogram.
1940
+
1941
+ Parameters
1942
+ ----------
1943
+ sampler : Callable[[int], np.ndarray]
1944
+ Function that takes sample size n and returns a 1-D array.
1945
+ n : int
1946
+ Sample size passed to *sampler* each trial.
1947
+ m : int
1948
+ Number of sampling trials.
1949
+ statistic : Callable[[np.ndarray], float]
1950
+ Statistic to compute on each sample.
1951
+ true_value : float or None
1952
+ True population value (shown as reference line).
1953
+ chart_center : np.ndarray
1954
+ chart_width : float
1955
+ n_bins : int
1956
+ bar_color : ManimColor
1957
+ true_line_color : ManimColor
1958
+ rng_seed : int
1959
+ scene : ThreeDScene or None
1960
+
1961
+ Attributes
1962
+ ----------
1963
+ stat_values : np.ndarray
1964
+ All m pre-simulated statistic values.
1965
+ """
1966
+
1967
+ def __init__(
1968
+ self,
1969
+ sampler: Callable[[int], np.ndarray],
1970
+ n: int = 30,
1971
+ m: int = 500,
1972
+ statistic: Optional[Callable[[np.ndarray], float]] = None,
1973
+ true_value: Optional[float] = None,
1974
+ chart_center: np.ndarray = ORIGIN,
1975
+ chart_width: float = 5.0,
1976
+ n_bins: int = 25,
1977
+ z_scale: float = 0.80,
1978
+ bar_color: ManimColor = ManimColor("#4A90D9"),
1979
+ true_line_color: ManimColor = ManimColor("#E8593C"),
1980
+ rng_seed: int = 42,
1981
+ scene: Optional[ThreeDScene] = None,
1982
+ **kwargs,
1983
+ ):
1984
+ super().__init__(**kwargs)
1985
+
1986
+ self.n = n
1987
+ self.m = m
1988
+ self.true_value = true_value
1989
+ self.z_scale = z_scale
1990
+ self.bar_color = bar_color
1991
+ self.chart_center = np.array(chart_center, dtype=float)
1992
+ self.chart_width = chart_width
1993
+ self._scene = scene
1994
+
1995
+ stat_fn = statistic if statistic is not None else np.mean
1996
+
1997
+ rng = np.random.default_rng(rng_seed)
1998
+ self.stat_values = np.array([
1999
+ float(stat_fn(sampler(n))) for _ in range(m)
2000
+ ])
2001
+
2002
+ # Histogram parameters
2003
+ lo = float(self.stat_values.min()) - 0.05
2004
+ hi = float(self.stat_values.max()) + 0.05
2005
+ self._lo, self._hi = lo, hi
2006
+ self._bins = np.linspace(lo, hi, n_bins + 1)
2007
+ self._n_bins = n_bins
2008
+ self._bin_w = (hi - lo) / n_bins
2009
+ self._scene_bar_w = chart_width / n_bins
2010
+
2011
+ self._counts = np.zeros(n_bins, dtype=int)
2012
+ self._max_count = 1
2013
+ self._bar_mobs: Dict[int, VGroup] = {}
2014
+
2015
+ self.bars = VGroup()
2016
+ self.add(self.bars)
2017
+
2018
+ # Reference line at true value
2019
+ if true_value is not None:
2020
+ self._build_true_line(true_value, true_line_color, scene)
2021
+
2022
+ # Axis
2023
+ self._build_axis(scene)
2024
+
2025
+ # ------------------------------------------------------------------
2026
+
2027
+ def _val_to_scene_x(self, val: float) -> float:
2028
+ t = (val - self._lo) / (self._hi - self._lo)
2029
+ return self.chart_center[0] + (t - 0.5) * self.chart_width
2030
+
2031
+ def _build_true_line(
2032
+ self,
2033
+ val: float,
2034
+ color: ManimColor,
2035
+ scene: Optional[ThreeDScene],
2036
+ ) -> None:
2037
+ sx = self._val_to_scene_x(val)
2038
+ hd = 0.35
2039
+ y = self.chart_center[1]
2040
+ self.true_line = DashedLine(
2041
+ np.array([sx, y - hd, 0]),
2042
+ np.array([sx, y - hd, self.z_scale * 4.5]),
2043
+ dash_length=0.07, dashed_ratio=0.4,
2044
+ color=_with_opacity(color, 0.80), stroke_width=2.0,
2045
+ )
2046
+ lbl = Text(f"True value\n{val:.3f}", font_size=16, color=color)
2047
+ lbl.move_to(np.array([sx + 0.1, y, self.z_scale * 4.8]))
2048
+ self._true_lbl = VGroup(lbl)
2049
+ if scene is not None:
2050
+ scene.add_fixed_orientation_mobjects(lbl)
2051
+ self.add(self.true_line, self._true_lbl)
2052
+
2053
+ def _build_axis(self, scene: Optional[ThreeDScene]) -> None:
2054
+ """Draw 5 tick labels along the base."""
2055
+ hd = 0.35
2056
+ y = self.chart_center[1]
2057
+ self._axis_labels = VGroup()
2058
+ for i in range(6):
2059
+ t = i / 5
2060
+ val = self._lo + t * (self._hi - self._lo)
2061
+ sx = self._val_to_scene_x(val)
2062
+ lbl = Text(f"{val:.2f}", font_size=13, color=_with_opacity(WHITE, 0.45))
2063
+ lbl.move_to(np.array([sx, y - hd, -0.24]))
2064
+ self._axis_labels.add(lbl)
2065
+ if scene is not None:
2066
+ scene.add_fixed_orientation_mobjects(lbl)
2067
+ self.add(self._axis_labels)
2068
+
2069
+ def _build_bar(self, idx: int, height: float) -> VGroup:
2070
+ bin_centre = self._bins[idx] + self._bin_w / 2
2071
+ sx = self._val_to_scene_x(bin_centre)
2072
+ hw = self._scene_bar_w / 2 * 0.88
2073
+ hd = 0.35
2074
+ y = self.chart_center[1]
2075
+ x, z0, z1 = sx, 0.0, max(height, 0.01)
2076
+ col = self.bar_color
2077
+ col_r = _darken(col, 0.60)
2078
+ col_t = _lighten(col, 1.28)
2079
+
2080
+ ff = Polygon(
2081
+ np.array([x-hw,y-hd,z0]), np.array([x+hw,y-hd,z0]),
2082
+ np.array([x+hw,y-hd,z1]), np.array([x-hw,y-hd,z1]),
2083
+ fill_color=_with_opacity(col, 0.90), fill_opacity=1.0, stroke_width=0,
2084
+ )
2085
+ fr = Polygon(
2086
+ np.array([x+hw,y-hd,z0]), np.array([x+hw,y+hd,z0]),
2087
+ np.array([x+hw,y+hd,z1]), np.array([x+hw,y-hd,z1]),
2088
+ fill_color=_with_opacity(col_r, 0.88), fill_opacity=1.0, stroke_width=0,
2089
+ )
2090
+ ft = Polygon(
2091
+ np.array([x-hw,y-hd,z1]), np.array([x+hw,y-hd,z1]),
2092
+ np.array([x+hw,y+hd,z1]), np.array([x-hw,y+hd,z1]),
2093
+ fill_color=_with_opacity(col_t, 0.80), fill_opacity=1.0, stroke_width=0,
2094
+ )
2095
+ return VGroup(ff, fr, ft)
2096
+
2097
+ def _update_bar(self, idx: int) -> None:
2098
+ h = (self._counts[idx] / max(self._max_count, 1)) * self.z_scale * 4.0
2099
+ bin_centre = self._bins[idx] + self._bin_w / 2
2100
+ sx = self._val_to_scene_x(bin_centre)
2101
+ hw = self._scene_bar_w / 2 * 0.88
2102
+ hd = 0.35
2103
+ y = self.chart_center[1]
2104
+ x, z0, z1 = sx, 0.0, max(h, 0.01)
2105
+ bar = self._bar_mobs[idx]
2106
+ for face, pts in [
2107
+ (bar[0], [[x-hw,y-hd,z0],[x+hw,y-hd,z0],[x+hw,y-hd,z1],[x-hw,y-hd,z1],[x-hw,y-hd,z0]]),
2108
+ (bar[1], [[x+hw,y-hd,z0],[x+hw,y+hd,z0],[x+hw,y+hd,z1],[x+hw,y-hd,z1],[x+hw,y-hd,z0]]),
2109
+ (bar[2], [[x-hw,y-hd,z1],[x+hw,y-hd,z1],[x+hw,y+hd,z1],[x-hw,y+hd,z1],[x-hw,y-hd,z1]]),
2110
+ ]:
2111
+ face.set_points_as_corners([np.array(p) for p in pts])
2112
+
2113
+ def add_trial(
2114
+ self,
2115
+ trial_index: int,
2116
+ animate: bool = True,
2117
+ run_time: float = 0.08,
2118
+ ) -> Optional[AnimationGroup]:
2119
+ val = float(self.stat_values[trial_index])
2120
+ idx = np.searchsorted(self._bins[1:], val)
2121
+ idx = min(int(idx), self._n_bins - 1)
2122
+
2123
+ self._counts[idx] += 1
2124
+ self._max_count = max(self._max_count, int(self._counts.max()))
2125
+
2126
+ for existing in self._bar_mobs:
2127
+ self._update_bar(existing)
2128
+
2129
+ if idx not in self._bar_mobs:
2130
+ h = (self._counts[idx] / self._max_count) * self.z_scale * 4.0
2131
+ bar = self._build_bar(idx, max(h, 0.01))
2132
+ self._bar_mobs[idx] = bar
2133
+ self.bars.add(bar)
2134
+ if animate:
2135
+ return FadeIn(bar, run_time=run_time)
2136
+ return None
2137
+
2138
+ def run_accumulation(
2139
+ self,
2140
+ scene: ThreeDScene,
2141
+ n_visible: int = 60,
2142
+ run_time_per: float = 0.08,
2143
+ show_normal_after: bool = True,
2144
+ ) -> None:
2145
+ """Animate the full accumulation directly on *scene*."""
2146
+ scene.play(FadeIn(self._axis_labels, run_time=0.35))
2147
+ if hasattr(self, "true_line"):
2148
+ scene.play(Create(self.true_line, run_time=0.5))
2149
+ scene.play(FadeIn(self._true_lbl, run_time=0.3))
2150
+
2151
+ for i in range(min(n_visible, self.m)):
2152
+ anim = self.add_trial(i, animate=True, run_time=run_time_per)
2153
+ if anim is not None:
2154
+ scene.play(anim)
2155
+ else:
2156
+ scene.wait(run_time_per * 0.3)
2157
+
2158
+ for i in range(n_visible, self.m):
2159
+ self.add_trial(i, animate=False)
2160
+ scene.wait(0.4)
2161
+
2162
+ if show_normal_after:
2163
+ mu = float(self.stat_values.mean())
2164
+ sigma = float(self.stat_values.std())
2165
+ xs = np.linspace(self._lo, self._hi, 300)
2166
+ ys = _normal_pdf(xs, mu, sigma)
2167
+ ys_scaled = ys / ys.max() * self.z_scale * 4.0 if ys.max() > 0 else ys
2168
+
2169
+ hd = 0.35
2170
+ y = self.chart_center[1]
2171
+ curve_pts = [
2172
+ np.array([self._val_to_scene_x(x), y - hd, max(float(z), 0.0)])
2173
+ for x, z in zip(xs, ys_scaled)
2174
+ ]
2175
+ curve = VMobject()
2176
+ curve.set_points_as_corners(curve_pts)
2177
+ col = ManimColor("#E8593C")
2178
+ curve.set_stroke(color=_with_opacity(col, 0.88), width=2.5)
2179
+ curve.set_fill(opacity=0)
2180
+
2181
+ glow = VMobject()
2182
+ glow.set_points_as_corners(curve_pts)
2183
+ glow.set_stroke(color=_with_opacity(col, 0.13), width=8.0)
2184
+ glow.set_fill(opacity=0)
2185
+
2186
+ scene.add(glow, curve)
2187
+ scene.play(Create(curve, run_time=1.0))
2188
+ scene.wait(0.8)
2189
+
2190
+
2191
+ # ---------------------------------------------------------------------------
2192
+ # Ready-to-render ThreeDScene subclasses
2193
+ # ---------------------------------------------------------------------------
2194
+
2195
+ class SRSScene(ThreeDScene):
2196
+ """Simple random sampling demonstration.
2197
+
2198
+ Render: manim -pql sampling.py SRSScene
2199
+ """
2200
+
2201
+ def construct(self):
2202
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-45 * DEGREES)
2203
+ self.begin_ambient_camera_rotation(rate=0.03)
2204
+
2205
+ demo = SimpleRandomSampling3D(
2206
+ N=100, n=20,
2207
+ config=DETAILED_SAMPLING,
2208
+ rng_seed=42, scene=self,
2209
+ )
2210
+ demo.run(self)
2211
+ self.wait(2)
2212
+
2213
+
2214
+ class StratifiedScene(ThreeDScene):
2215
+ """Proportional stratified sampling with 3 strata.
2216
+
2217
+ Render: manim -pql sampling.py StratifiedScene
2218
+ """
2219
+
2220
+ def construct(self):
2221
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-45 * DEGREES)
2222
+ self.begin_ambient_camera_rotation(rate=0.025)
2223
+
2224
+ demo = StratifiedSampling3D(
2225
+ N=120, n=30, n_strata=3,
2226
+ config=DETAILED_SAMPLING,
2227
+ rng_seed=42, scene=self,
2228
+ )
2229
+ demo.run(self)
2230
+ self.wait(2)
2231
+
2232
+
2233
+ class ClusterScene(ThreeDScene):
2234
+ """Cluster sampling: 3 of 8 clusters selected.
2235
+
2236
+ Render: manim -pql sampling.py ClusterScene
2237
+ """
2238
+
2239
+ def construct(self):
2240
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-45 * DEGREES)
2241
+ self.begin_ambient_camera_rotation(rate=0.03)
2242
+
2243
+ demo = ClusterSampling3D(
2244
+ N=120, n_clusters=8, n_selected_clusters=3,
2245
+ config=DETAILED_SAMPLING,
2246
+ rng_seed=42, scene=self,
2247
+ )
2248
+ demo.run(self)
2249
+ self.wait(2)
2250
+
2251
+
2252
+ class SystematicScene(ThreeDScene):
2253
+ """Systematic (every k-th) sampling with sweep-line animation.
2254
+
2255
+ Render: manim -pql sampling.py SystematicScene
2256
+ """
2257
+
2258
+ def construct(self):
2259
+ self.set_camera_orientation(phi=62 * DEGREES, theta=-48 * DEGREES)
2260
+
2261
+ demo = SystematicSampling3D(
2262
+ N=100, n=20,
2263
+ config=DETAILED_SAMPLING,
2264
+ rng_seed=42, scene=self,
2265
+ )
2266
+ demo.run(self)
2267
+ self.wait(2)
2268
+
2269
+
2270
+ class BootstrapScene(ThreeDScene):
2271
+ """Bootstrap resampling with CI shading.
2272
+
2273
+ Render: manim -pql sampling.py BootstrapScene
2274
+ """
2275
+
2276
+ def construct(self):
2277
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-45 * DEGREES)
2278
+ self.begin_ambient_camera_rotation(rate=0.025)
2279
+
2280
+ rng = np.random.default_rng(7)
2281
+ sample = rng.normal(3.5, 1.2, 30)
2282
+
2283
+ demo = BootstrapSampling3D(
2284
+ sample_values=sample,
2285
+ B=600,
2286
+ statistic=np.mean,
2287
+ config=DETAILED_SAMPLING,
2288
+ rng_seed=42, scene=self,
2289
+ )
2290
+ demo.run(self)
2291
+ self.wait(2)