Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Add fields and orbital examples

apoogdkcbeba1b8b58f
diff --git a/examples/lagrange_points.py b/examples/lagrange_points.py
new file mode 100644
index 00000000..71a5d2c0
--- /dev/null
+++ b/examples/lagrange_points.py
@@ -0,0 +1,319 @@
+"""The hilltops where spacecraft park: Lagrange points on the rotating Earth–Moon landscape.
+
+In the frame turning with the Earth and the Moon, a small body feels gravity and the centrifugal
+force as one landscape, the effective potential Ω = −(1−μ)/r₁ − μ/r₂ − ½(x² + y²) (μ = 0.0121,
+the Earth–Moon mass ratio). It has five flat spots: three saddles L1, L2, L3 on the axis and two
+hilltops, L4 and L5, 60° ahead of and behind the Moon. A ball on a hilltop should roll off — but
+in a turning frame the Coriolis force (ẍ − 2ẏ = −∂Ω/∂x, ÿ + 2ẋ = −∂Ω/∂y) bends every slide into a
+loop, and a probe released near L4 circles it forever on a "tadpole" orbit, while one released
+at the L1 saddle falls away. The height is drawn log-compressed so that the flat spots are
+visible; the Jacobi constant C = −2Ω − v², measured along the orbit, stays fixed.
+"""
+
+import numpy as np
+
+import manimgx as m
+
+MU = 0.0121
+SIZE = 2.35 # screen units per unit of distance
+L4 = np.array([0.5 - MU, np.sqrt(3) / 2])
+
+
+def potential(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ r1 = np.hypot(x + MU, y)
+ r2 = np.hypot(x - 1 + MU, y)
+ return -(1 - MU) / r1 - MU / r2 - 0.5 * (x * x + y * y)
+
+
+def slope(x: float, y: float) -> tuple[float, float]:
+ """∂Ω/∂x, ∂Ω/∂y."""
+ r1 = np.hypot(x + MU, y) ** 3
+ r2 = np.hypot(x - 1 + MU, y) ** 3
+ gx = (1 - MU) * (x + MU) / r1 + MU * (x - 1 + MU) / r2 - x
+ gy = (1 - MU) * y / r1 + MU * y / r2 - y
+ return float(gx), float(gy)
+
+
+TOP = float(potential(np.array(L4[0]), np.array(L4[1])))
+
+
+def height(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ """The landscape as drawn: 0 at the hilltops L4 and L5, log-compressed below, floored."""
+ below = np.maximum(TOP - potential(x, y), 0)
+ return np.maximum(-0.55 * np.log1p(below / 0.004), -4.2)
+
+
+def collinear_points() -> list[float]:
+ """x of L1, L2, L3: where the slope along the axis vanishes (bisection)."""
+
+ def root(a: float, b: float) -> float:
+ for _ in range(100):
+ c = 0.5 * (a + b)
+ if np.sign(slope(a, 0)[0]) == np.sign(slope(c, 0)[0]):
+ a = c
+ else:
+ b = c
+ return 0.5 * (a + b)
+
+ return [root(0.5, 1 - MU - 1e-3), root(1 - MU + 1e-3, 2.0), root(-2.0, -MU - 1e-3)]
+
+
+def orbit(start: np.ndarray, span: float, steps: int) -> np.ndarray:
+ """(x, y, vx, vy) along the rotating-frame equations of motion, RK4."""
+
+ def rate(s: np.ndarray) -> np.ndarray:
+ gx, gy = slope(s[0], s[1])
+ return np.array([s[2], s[3], -gx + 2 * s[3], -gy - 2 * s[2]])
+
+ dt = span / steps
+ states = [start]
+ s = start.copy()
+ for _ in range(steps):
+ k1 = rate(s)
+ k2 = rate(s + dt / 2 * k1)
+ k3 = rate(s + dt / 2 * k2)
+ k4 = rate(s + dt * k3)
+ s = s + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
+ states.append(s)
+ return np.array(states)
+
+
+def to_scene(x: np.ndarray, y: np.ndarray, lift: float = 0.0) -> np.ndarray:
+ return np.stack([SIZE * x, SIZE * y, height(x, y) + lift], axis=-1)
+
+
+def colormap(values: np.ndarray, stops: list[str]) -> np.ndarray:
+ rgb = np.array([m.ManimColor(s).to_rgb() for s in stops])
+ x = np.clip(values, 0, 1) * (len(stops) - 1)
+ i = np.minimum(x.astype(int), len(stops) - 2)
+ f = (x - i)[:, None]
+ out = np.ones((len(values), 4))
+ out[:, :3] = rgb[i] * (1 - f) + rgb[i + 1] * f
+ return out
+
+
+def grid_mesh(nu: int, nv: int, fill_color: str = "#ffffff") -> m.MeshMobject:
+ """A smooth lit mesh over an (nu + 1) × (nv + 1) grid of vertices (vertex i·(nv + 1) + j),
+ each cell two triangles; its points are set by whoever shapes it."""
+ idx = np.arange((nu + 1) * (nv + 1)).reshape(nu + 1, nv + 1)
+ a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]
+ cells = np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 2)
+ return m.MeshMobject(
+ np.zeros(((nu + 1) * (nv + 1), 3)),
+ cells.reshape(-1, 3),
+ shade_in_3d=True,
+ fill_color=fill_color,
+ )
+
+
+def camera_axes(phi: float, theta: float, gamma: float) -> np.ndarray:
+ """The camera's axes for its orbit angles, as rows: right, up, and toward the viewer."""
+
+ def spin(a: float) -> np.ndarray: # a turn about z
+ return np.array(
+ [[np.cos(a), -np.sin(a), 0.0], [np.sin(a), np.cos(a), 0.0], [0.0, 0.0, 1.0]]
+ )
+
+ c, s = np.cos(phi), np.sin(phi)
+ tilt = np.array(
+ [[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]]
+ ) # a turn by −φ about x
+ return spin(gamma) @ tilt @ spin(-theta - np.pi / 2)
+
+
+def billboard(label: m.Mobject, camera: m.Camera, shown: m.ValueTracker) -> m.Mobject:
+ """Keep `label` where it is, turned every frame to face the camera, at opacity `shown` (fade it
+ by animating `shown`: a FadeIn would fight the turning)."""
+ anchor = label.get_center()
+ parts = [
+ (part, part.points - anchor) for part in label.family_members_with_points()
+ ]
+
+ def face(_: m.Mobject) -> None:
+ axes = camera_axes(camera.get_phi(), camera.get_theta(), camera.get_gamma())
+ for part, flat in parts:
+ part.points = anchor + flat[:, :1] * axes[0] + flat[:, 1:2] * axes[1]
+ label.set_opacity(shown.get_value())
+
+ label.add_updater(face)
+ face(label)
+ return label
+
+
+class LagrangePoints(m.ThreeDScene):
+ def construct(self) -> None:
+ # the landscape on a polar grid around the barycenter
+ radial = np.linspace(0.04, 1.62, 230) ** 1.0
+ angular = np.linspace(0, m.TAU, 361)
+ rr, aa = np.meshgrid(radial, angular, indexing="ij")
+ gx, gy = rr * np.cos(aa), rr * np.sin(aa)
+ grown = m.ValueTracker(0.0)
+ land = grid_mesh(229, 360)
+ z_full = height(gx, gy)
+ land.paint = land.paint.but(
+ fill=colormap(
+ (z_full.ravel() + 4.2) / 4.2,
+ ["#08101f", "#133c63", "#1d7a8c", "#6cc4a1", "#f2e8a0", "#fffbe6"],
+ )
+ )
+
+ def rise(mob: m.Mobject) -> None:
+ mob.points = np.stack(
+ [SIZE * gx, SIZE * gy, grown.get_value() * z_full], -1
+ ).reshape(-1, 3)
+
+ rise(land)
+ land.add_updater(rise)
+
+ # the five Lagrange points
+ l1, l2, l3 = collinear_points()
+ spots = {
+ "L1": (l1, 0.0),
+ "L2": (l2, 0.0),
+ "L3": (l3, 0.0),
+ "L4": tuple(L4),
+ "L5": (L4[0], -L4[1]),
+ }
+ markers = m.Group()
+ labels = m.VGroup()
+ for name, (x, y) in spots.items():
+ p = to_scene(np.array(x), np.array(y), 0.06)
+ markers.add(m.Dot3D(p, radius=0.07, color=m.WHITE))
+ labels.add(
+ m.MathTex(name.replace("L", r"L_"), font_size=30).move_to(
+ p + np.array([0, 0, 0.45])
+ )
+ )
+
+ labels_shown = [m.ValueTracker(0.0) for _ in spots]
+ for label, shown in zip(labels, labels_shown, strict=True):
+ billboard(label, self.camera, shown)
+
+ # two probes, released at rest: near the L4 hilltop, and at the L1 saddle
+ span, steps = 62.0, 6200
+ tadpole = orbit(np.array([L4[0] + 0.02, L4[1], 0.0, 0.0]), span, steps)
+ falling = orbit(np.array([l1 - 0.004, 0.0, 0.0, 0.0]), 10.0, 1000)
+ clock = m.ValueTracker(0.0)
+
+ def probe_track(
+ states: np.ndarray, duration: float, color: str
+ ) -> tuple[m.VMobject, m.Dot3D]:
+ trail = m.VMobject(stroke_color=color, stroke_width=3.5, shade_in_3d=True)
+ dot = m.Dot3D(radius=0.075, color=color)
+ count = len(states) - 1
+
+ def follow(_: m.Mobject) -> None:
+ k = max(2, int(min(clock.get_value(), duration) / duration * count))
+ path = to_scene(states[:k, 0], states[:k, 1], 0.05)
+ trail.set_points_as_corners(
+ path[:: max(1, k // 1500)] if k > 1500 else path
+ )
+ dot.move_to(path[-1])
+
+ trail.add_updater(follow)
+ follow(trail)
+ return trail, dot
+
+ tad_trail, tad_dot = probe_track(tadpole, span, "#ffd166")
+ fall_trail, fall_dot = probe_track(falling, 10.0, "#ff5d8f")
+
+ def jacobi() -> float:
+ k = min(int(clock.get_value() / span * steps), steps)
+ x, y, vx, vy = tadpole[k]
+ return float(-2 * potential(np.array(x), np.array(y)) - (vx * vx + vy * vy))
+
+ title = m.Text("The hilltops where spacecraft park", font_size=34).to_corner(
+ m.UL
+ )
+ subtitle = m.Text(
+ "the Earth–Moon system, seen from the frame that turns with it",
+ font_size=22,
+ )
+ subtitle.set_color(m.GREY_B).next_to(
+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.12
+ )
+ c_value = m.DecimalNumber(jacobi(), num_decimal_places=5, font_size=30)
+ c_value.add_updater(lambda d: d.set_value(jacobi()))
+ c_row = m.VGroup(
+ m.MathTex(r"C = -2\Omega - v^2 =", font_size=30), c_value
+ ).arrange(m.RIGHT, buff=0.15)
+ c_row.to_corner(m.UR)
+ closing = m.Text(
+ "L4 is a hilltop; the Coriolis force keeps the probe on it.", font_size=26
+ )
+ closing.to_edge(m.DOWN, buff=0.35)
+ for text in (title, subtitle, c_row, closing): # readable over the landscape
+ text.add_background_rectangle(color=m.BLACK, opacity=0.85, buff=0.08)
+ self.add_fixed_in_frame_mobjects(title, subtitle, c_row, closing)
+ self.remove(c_row, closing)
+
+ self.set_camera_orientation(
+ phi=58 * m.DEGREES,
+ theta=-78 * m.DEGREES,
+ zoom=0.92,
+ frame_center=np.array([0.3, 0.4, -1.2]),
+ )
+ self.add(land)
+ # 0–4 s: the landscape rises out of the plane (the camera drifting round, slowly)
+ self.play(
+ grown.animate.set_value(1.0),
+ self.camera.theta_tracker.animate(rate_func=m.linear).set_value(
+ -70 * m.DEGREES
+ ),
+ run_time=3.5,
+ )
+ # 4–9 s: the five flat spots
+ self.add(labels)
+ self.play(
+ m.LaggedStart(
+ *[
+ m.AnimationGroup(m.FadeIn(d), s.animate.set_value(1.0))
+ for d, s in zip(markers, labels_shown, strict=True)
+ ],
+ lag_ratio=0.3,
+ ),
+ self.camera.theta_tracker.animate(rate_func=m.linear).set_value(
+ -62 * m.DEGREES
+ ),
+ run_time=3.5,
+ )
+ # 9–25 s: release two probes at rest; follow the one near L4 up close
+ self.add(tad_trail, tad_dot, fall_trail, fall_dot)
+ self.play(m.FadeIn(c_row), run_time=0.5)
+ self.move_camera(
+ phi=50 * m.DEGREES,
+ theta=35 * m.DEGREES,
+ zoom=1.3,
+ frame_center=np.array([SIZE * 0.42, SIZE * 0.72, 0.5]),
+ added_anims=[clock.animate.set_value(6.0)],
+ run_time=3,
+ rate_func=m.linear,
+ )
+ self.play(clock.animate.set_value(12.0), run_time=2.5, rate_func=m.linear)
+ self.play(
+ m.FadeOut(fall_trail),
+ m.FadeOut(fall_dot),
+ clock.animate.set_value(15.0),
+ run_time=1,
+ rate_func=m.linear,
+ )
+ self.play(
+ clock.animate.set_value(span),
+ self.camera.theta_tracker.animate.set_value(75 * m.DEGREES),
+ run_time=10,
+ rate_func=m.linear,
+ )
+ # 26–30 s: step back: why it stays
+ self.move_camera(
+ phi=52 * m.DEGREES,
+ theta=20 * m.DEGREES,
+ zoom=0.95,
+ frame_center=np.array([0.3, 0.4, -1.2]),
+ added_anims=[m.FadeIn(closing)],
+ run_time=3.5,
+ )
+ self.wait(1.8)
+
+
+if __name__ == "__main__":
+ LagrangePoints().render("lagrange_points.mp4")
diff --git a/examples/taylor_poles.py b/examples/taylor_poles.py
new file mode 100644
index 00000000..985bf42e
--- /dev/null
+++ b/examples/taylor_poles.py
@@ -0,0 +1,327 @@
+"""Why the Taylor series of 1/(1 + x²) gives up at |x| = 1.
+
+On the real line f(x) = 1/(1 + x²) is as smooth as a function can be, yet its Taylor series
+1 − x² + x⁴ − x⁶ + ⋯ explodes as soon as |x| > 1. The reason is off the line: in the complex
+plane f(z) = 1/(1 + z²) has poles at z = ±i, and a power series converges exactly in the largest
+disk around its center that avoids every singularity. Seen from the side, the bell curve is a
+slice of the landscape |f(z)|, colored by arg f(z); the disk |z| < 1 runs into the two towers. Move
+the center to a and the radius becomes the distance to ±i, √(1 + a²).
+"""
+
+import numpy as np
+
+import manimgx as m
+
+UNIT = 1.45 # screen units per unit of x, y and |f|
+X_RANGE = (-2.4, 2.4)
+Y_RANGE = (-1.9, 1.9)
+CLIP = 2.3 # |f| is cut off here (the poles go to infinity)
+
+
+def f(z: np.ndarray) -> np.ndarray:
+ return 1 / (1 + z * z)
+
+
+def domain_colors(z: np.ndarray) -> np.ndarray:
+ """RGBA rows: hue from arg f(z), a little brighter where |f| is large."""
+ w = f(z)
+ hue = (np.angle(w) / m.TAU) % 1.0
+ k = np.arange(3)[None, :]
+ rgb = 0.5 + 0.5 * np.cos(m.TAU * (hue[:, None] - k / 3)) # a smooth hue wheel
+ light = np.clip(0.55 + 0.25 * np.tanh(np.log(np.abs(w) + 1e-9)), 0, 1)
+ rows = np.ones((len(z), 4))
+ rows[:, :3] = 0.25 + 0.75 * rgb * light[:, None]
+ return rows
+
+
+def partial_sum(x: np.ndarray, terms: int) -> np.ndarray:
+ return sum((-1) ** k * x ** (2 * k) for k in range(terms))
+
+
+def grid_mesh(nu: int, nv: int, fill_color: str = "#ffffff") -> m.MeshMobject:
+ """A smooth lit mesh over an (nu + 1) × (nv + 1) grid of vertices (vertex i·(nv + 1) + j),
+ each cell two triangles; its points are set by whoever shapes it."""
+ idx = np.arange((nu + 1) * (nv + 1)).reshape(nu + 1, nv + 1)
+ a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]
+ cells = np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 2)
+ return m.MeshMobject(
+ np.zeros(((nu + 1) * (nv + 1), 3)),
+ cells.reshape(-1, 3),
+ shade_in_3d=True,
+ fill_color=fill_color,
+ )
+
+
+def camera_axes(phi: float, theta: float, gamma: float) -> np.ndarray:
+ """The camera's axes for its orbit angles, as rows: right, up, and toward the viewer."""
+
+ def spin(a: float) -> np.ndarray: # a turn about z
+ return np.array(
+ [[np.cos(a), -np.sin(a), 0.0], [np.sin(a), np.cos(a), 0.0], [0.0, 0.0, 1.0]]
+ )
+
+ c, s = np.cos(phi), np.sin(phi)
+ tilt = np.array(
+ [[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]]
+ ) # a turn by −φ about x
+ return spin(gamma) @ tilt @ spin(-theta - np.pi / 2)
+
+
+def billboard(label: m.Mobject, camera: m.Camera, shown: m.ValueTracker) -> m.Mobject:
+ """Keep `label` where it is, turned every frame to face the camera, at opacity `shown` (fade it
+ by animating `shown`: a FadeIn would fight the turning)."""
+ anchor = label.get_center()
+ parts = [
+ (part, part.points - anchor) for part in label.family_members_with_points()
+ ]
+
+ def face(_: m.Mobject) -> None:
+ axes = camera_axes(camera.get_phi(), camera.get_theta(), camera.get_gamma())
+ for part, flat in parts:
+ part.points = anchor + flat[:, :1] * axes[0] + flat[:, 1:2] * axes[1]
+ label.set_opacity(shown.get_value())
+
+ label.add_updater(face)
+ face(label)
+ return label
+
+
+class TaylorPoles(m.ThreeDScene):
+ def construct(self) -> None:
+ # the side view: the x–z plane seen face on, nearly orthographic (a 2D plot)
+ self.set_camera_orientation(
+ phi=90 * m.DEGREES,
+ theta=-90 * m.DEGREES,
+ focal_distance=60,
+ zoom=1.0,
+ frame_center=np.array([0.0, 0.0, 1.0]),
+ )
+ real_axis = m.Line(
+ UNIT * X_RANGE[0] * m.RIGHT, UNIT * X_RANGE[1] * m.RIGHT, stroke_width=2
+ )
+ height_axis = m.Line(m.ORIGIN, UNIT * CLIP * m.OUT, stroke_width=2)
+ ticks = m.VGroup(
+ *[
+ m.Line(
+ UNIT * x * m.RIGHT + 0.08 * m.IN,
+ UNIT * x * m.RIGHT + 0.08 * m.OUT,
+ stroke_width=2,
+ )
+ for x in (-2, -1, 1, 2)
+ ]
+ )
+ tick_labels = m.VGroup(
+ *[
+ m.MathTex(str(x), font_size=28)
+ .move_to(UNIT * x * m.RIGHT + 0.35 * m.IN)
+ .rotate(m.PI / 2, m.RIGHT)
+ for x in (-2, -1, 1, 2)
+ ]
+ )
+
+ def graph(
+ values: np.ndarray, xs: np.ndarray, color: str, width: float = 4
+ ) -> m.VMobject:
+ keep = np.abs(values) < CLIP + 0.4
+ mob = m.VMobject(stroke_color=color, stroke_width=width)
+ points = np.stack(
+ [UNIT * xs, 0 * xs, UNIT * np.clip(values, -1.0, CLIP + 0.4)], 1
+ )
+ mob.set_points_smoothly(points[keep])
+ return mob
+
+ xs = np.linspace(*X_RANGE, 400)
+ bell = graph(f(xs.astype(complex)).real, xs, m.WHITE, 5)
+ edges = m.VGroup(
+ *[
+ m.DashedLine(
+ UNIT * x * m.RIGHT,
+ UNIT * x * m.RIGHT + UNIT * CLIP * m.OUT,
+ stroke_width=2,
+ color=m.GREY_B,
+ )
+ for x in (-1, 1)
+ ]
+ )
+
+ title = m.Text(
+ "Why does this Taylor series stop at 1?", font_size=34
+ ).to_corner(m.UL)
+ series = m.MathTex(
+ r"\frac{1}{1+x^2} = 1 - x^2 + x^4 - x^6 + \cdots", font_size=34
+ )
+ series.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.25)
+ terms_label = m.MathTex(r"n =", font_size=32)
+ terms_value = m.Integer(1, font_size=32)
+ terms_row = (
+ m.VGroup(terms_label, terms_value)
+ .arrange(m.RIGHT, buff=0.15)
+ .to_corner(m.UR)
+ )
+ self.add_fixed_in_frame_mobjects(title, series, terms_row)
+ self.remove(series, terms_row)
+
+ self.add(real_axis, height_axis, ticks, tick_labels)
+ self.play(m.Create(bell), m.FadeIn(series), run_time=2)
+ # 2–9 s: partial sums hug the curve inside (−1, 1) and fly off outside
+ partial = graph(partial_sum(xs, 1), xs, m.YELLOW, 3.5)
+ self.play(m.FadeIn(partial), m.FadeIn(terms_row), m.Create(edges), run_time=1)
+ for terms in range(2, 13):
+ terms_value.set_value(terms)
+ self.play(
+ m.Transform(partial, graph(partial_sum(xs, terms), xs, m.YELLOW, 3.5)),
+ run_time=0.5,
+ )
+ # 9–13 s: tilt the camera: the real line lies in the complex plane
+ plane = m.NumberPlane(
+ x_range=(*X_RANGE, 0.5),
+ y_range=(*Y_RANGE, 0.5),
+ x_length=UNIT * 4.8,
+ y_length=UNIT * 3.8,
+ background_line_style={
+ "stroke_color": m.BLUE_E,
+ "stroke_width": 1,
+ "stroke_opacity": 0.6,
+ },
+ axis_config={"stroke_opacity": 0},
+ )
+ self.play(
+ m.FadeOut(partial), m.FadeOut(edges), m.FadeOut(terms_row), run_time=1
+ )
+ self.add(plane)
+ self.move_camera(
+ phi=62 * m.DEGREES,
+ theta=-62 * m.DEGREES,
+ focal_distance=20,
+ zoom=0.95,
+ frame_center=np.array([-1.1, 0.4, 0.9]),
+ added_anims=[m.FadeIn(plane)],
+ run_time=3,
+ )
+
+ # 13–19 s: the landscape |f(z)| rises, colored by arg f
+ nu, nv = 241, 191 # odd: no grid point lands exactly on a pole
+ xg = np.linspace(*X_RANGE, nu + 1)
+ yg = np.linspace(*Y_RANGE, nv + 1)
+ zz = xg[:, None] + 1j * yg[None, :]
+ height = np.minimum(np.abs(f(zz)), CLIP)
+ base_colors = domain_colors(zz.ravel())
+ rise = m.ValueTracker(0.0)
+ center = m.ValueTracker(0.0) # the center of the expansion
+ spotlight = m.ValueTracker(
+ 0.0
+ ) # 0: all lit; 1: only the disk of convergence lit
+ land = grid_mesh(nu, nv)
+
+ def lift(mob: m.Mobject) -> None:
+ xx, yy = np.meshgrid(xg, yg, indexing="ij")
+ mob.points = UNIT * np.stack(
+ [xx, yy, rise.get_value() * height], -1
+ ).reshape(-1, 3)
+ a = center.get_value()
+ inside = np.abs(zz.ravel() - a) < np.hypot(a, 1.0)
+ shade = 1 - spotlight.get_value() * 0.6 * ~inside
+ rows = base_colors.copy()
+ rows[:, :3] *= shade[:, None]
+ rows[:, 3] = min(1.0, 4 * rise.get_value())
+ mob.paint = mob.paint.but(fill=rows)
+
+ lift(land)
+ land.add_updater(lift)
+ poles = m.VGroup(
+ *[
+ m.MathTex(t, font_size=36).move_to(
+ UNIT * np.array([0.35, y, CLIP + 0.25])
+ )
+ for t, y in ((r"i", 1), (r"-i", -1))
+ ]
+ )
+ poles_shown = m.ValueTracker(0.0)
+ for pole in poles:
+ billboard(pole, self.camera, poles_shown)
+ complex_series = m.MathTex(
+ r"f(z) = \frac{1}{1+z^2}\ \text{has poles at } z = \pm i", font_size=32
+ )
+ complex_series.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.25)
+ self.add_fixed_in_frame_mobjects(complex_series)
+ self.remove(complex_series)
+ self.add(land)
+ self.play(
+ rise.animate.set_value(1.0),
+ m.FadeOut(series),
+ m.FadeIn(complex_series),
+ run_time=3.5,
+ rate_func=m.smooth,
+ )
+ self.add(poles)
+ self.play(
+ poles_shown.animate.set_value(1.0),
+ self.camera.theta_tracker.animate.set_value(-40 * m.DEGREES),
+ run_time=2,
+ )
+
+ # 19–30 s: the disk of convergence, drawn on the landscape, and moving its center
+ def on_surface(z: np.ndarray, lift_by: float = 0.03) -> np.ndarray:
+ h = np.minimum(np.abs(f(z)), CLIP) + lift_by
+ return UNIT * np.stack([z.real, z.imag, h], 1)
+
+ def ring_points() -> np.ndarray:
+ a = center.get_value()
+ t = np.linspace(0, m.TAU, 361)
+ return on_surface(a + np.hypot(a, 1.0) * np.exp(1j * t) + 1e-4j)
+
+ ring = m.VMobject(stroke_color=m.YELLOW, stroke_width=6, shade_in_3d=True)
+ ring.set_points_as_corners(ring_points())
+ ring.add_updater(lambda mob: mob.set_points_as_corners(ring_points()))
+
+ def interval_points() -> np.ndarray:
+ a = center.get_value()
+ r = np.hypot(a, 1.0)
+ x = np.linspace(max(a - r, X_RANGE[0]), min(a + r, X_RANGE[1]), 200)
+ return on_surface(x + 0j, 0.04)
+
+ interval = m.VMobject(stroke_color=m.YELLOW, stroke_width=9, shade_in_3d=True)
+ interval.set_points_smoothly(interval_points())
+ interval.add_updater(lambda mob: mob.set_points_smoothly(interval_points()))
+
+ radius_value = m.DecimalNumber(1.0, num_decimal_places=2, font_size=32)
+ center_value = m.DecimalNumber(0.0, num_decimal_places=2, font_size=32)
+ readout = m.VGroup(
+ m.VGroup(m.MathTex(r"a =", font_size=32), center_value).arrange(
+ m.RIGHT, buff=0.15
+ ),
+ m.VGroup(
+ m.MathTex(r"\text{radius} =", font_size=32),
+ radius_value,
+ m.MathTex(r"= |a \mp i| = \sqrt{1+a^2}", font_size=32),
+ ).arrange(m.RIGHT, buff=0.15),
+ ).arrange(m.DOWN, aligned_edge=m.LEFT)
+ readout.next_to(complex_series, m.DOWN, aligned_edge=m.LEFT, buff=0.35)
+ center_value.add_updater(lambda d: d.set_value(center.get_value()))
+ # measured: the distance from the center to the nearest pole
+ radius_value.add_updater(
+ lambda d: d.set_value(
+ float(min(abs(center.get_value() - p) for p in (1j, -1j)))
+ )
+ )
+ closing = m.Text(
+ "A power series converges out to the nearest singularity.", font_size=28
+ )
+ closing.to_edge(m.DOWN, buff=0.3)
+ self.add_fixed_in_frame_mobjects(readout, closing)
+ self.remove(readout, closing)
+ self.play(
+ m.Create(ring),
+ m.FadeIn(interval),
+ m.FadeIn(readout),
+ spotlight.animate.set_value(1.0),
+ run_time=2.5,
+ )
+ self.wait(0.5)
+ self.play(center.animate.set_value(1.5), run_time=4)
+ self.play(center.animate.set_value(0.0), m.FadeIn(closing), run_time=3.5)
+ self.wait(1.5)
+
+
+if __name__ == "__main__":
+ TaylorPoles().render("taylor_poles.mp4")
diff --git a/examples/van_allen.py b/examples/van_allen.py
new file mode 100644
index 00000000..8382baca
--- /dev/null
+++ b/examples/van_allen.py
@@ -0,0 +1,504 @@
+"""A magnetic bottle around the Earth: how the Van Allen belts trap particles.
+
+A charged particle in the Earth's dipole field does three things at once. It gyrates around a
+field line. It slides along the line toward a pole until the growing field turns it back: its
+magnetic moment μ = m v⊥²/2B stays constant while its speed cannot change, so it runs out of
+parallel speed exactly where B = B_eq / sin²α (α: its pitch angle at the equator) — and bounces
+to the other hemisphere and back. And it drifts slowly around the planet: protons west, electrons
+east. The drift paints a doughnut-shaped shell, a radiation belt. Particles whose pitch angle is
+too small (the loss cone) reach the atmosphere before they can turn, and rain down near the poles.
+The motion is integrated exactly (Boris pusher); the time scales are stretched for visibility.
+"""
+
+import functools
+import math
+
+import numpy as np
+
+import manimgx as m
+
+K = 1500.0 # the dipole's strength, charge-to-mass ratio folded in: gyrofrequency K / r³ at the equator
+SPEED = 5.0 # every particle's speed, Earth radii per second
+DT = 1 / 540 # integration step: 9 steps per tick of the 60 Hz simulation clock
+STEPS = 9
+MOMENT = np.array([0.0, 0.0, -1.0]) # the Earth's dipole points south
+PITCH = 30.0 # the first proton's equatorial pitch angle, degrees
+ORANGE, CYAN = np.array([1.0, 0.68, 0.25]), np.array([0.35, 0.85, 1.0])
+
+
+def field(x: np.ndarray, sign: np.ndarray) -> np.ndarray:
+ """(charge sign) × the dipole field at points x (rows): each particle's rotation vector Ω."""
+ r2 = (x * x).sum(-1, keepdims=True)
+ r = np.sqrt(r2)
+ rhat = x / r
+ return sign[:, None] * K * (3 * (rhat @ MOMENT)[:, None] * rhat - MOMENT) / (r2 * r)
+
+
+def field_at(x: float, y: float, z: float, qk: float) -> tuple[float, float, float]:
+ """`field` at one point for charge sign × K = qk, in plain floats and operation for
+ operation (so to the bit): numpy's per-call overhead would dwarf the arithmetic of three
+ numbers."""
+ r2 = x * x + y * y + z * z
+ r = math.sqrt(r2)
+ x, y, z = x / r, y / r, z / r
+ c = -3 * z # 3 (r̂ · m), with m = MOMENT = −ẑ
+ d = r2 * r
+ return qk * (c * x) / d, qk * (c * y) / d, qk * (c * z + 1) / d
+
+
+def boris(particles: list[list[float]]) -> None:
+ """A step of DT in a pure magnetic field (the Boris rotation: speed is conserved exactly),
+ split so that no particle turns more than 0.25 rad per substep — near the planet, where
+ the field is hundreds of times stronger, the gyration stays resolved. Each particle is
+ [x, y, z, vx, vy, vz, sign × K], stepped in place."""
+ omegas = [field_at(p[0], p[1], p[2], p[6]) for p in particles]
+ fastest = math.sqrt(max(a * a + b * b + c * c for a, b, c in omegas))
+ parts = max(1, math.ceil(fastest * DT / 0.25))
+ h = DT / parts
+ for p, (o0, o1, o2) in zip(particles, omegas, strict=True):
+ x0, x1, x2, v0, v1, v2, qk = p
+ for part in range(parts):
+ if part: # the first substep's field is the one just measured
+ o0, o1, o2 = field_at(x0, x1, x2, qk)
+ t0, t1, t2 = 0.5 * h * o0, 0.5 * h * o1, 0.5 * h * o2
+ q = 1 + (t0 * t0 + t1 * t1 + t2 * t2)
+ s0, s1, s2 = 2 * t0 / q, 2 * t1 / q, 2 * t2 / q
+ u0 = v0 + (v1 * t2 - v2 * t1) # u = v + v × t, then v += u × s
+ u1 = v1 + (v2 * t0 - v0 * t2)
+ u2 = v2 + (v0 * t1 - v1 * t0)
+ v0 += u1 * s2 - u2 * s1
+ v1 += u2 * s0 - u0 * s2
+ v2 += u0 * s1 - u1 * s0
+ x0 += h * v0
+ x1 += h * v1
+ x2 += h * v2
+ p[:6] = x0, x1, x2, v0, v1, v2
+
+
+def fly(
+ x: np.ndarray, v: np.ndarray, sign: np.ndarray, steps: int, every: int
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """`steps` Boris steps of the particles (rows): their final positions and velocities, and
+ both after every `every`-th step from the first (a row per particle per sample)."""
+ particles = [
+ [*p, *u, s * K]
+ for p, u, s in zip(x.tolist(), v.tolist(), sign.tolist(), strict=True)
+ ]
+ seen: list[list[float]] = []
+ for step in range(steps):
+ boris(particles)
+ if step % every == 0:
+ seen += [p[:6] for p in particles]
+ final, states = np.array(particles)[:, :6], np.array(seen)
+ return final[:, :3], final[:, 3:], states[:, :3], states[:, 3:]
+
+
+def guiding_center(x: np.ndarray, v: np.ndarray, sign: np.ndarray) -> np.ndarray:
+ """The center of each particle's gyration: x + (v × Ω) / Ω²."""
+ omega = field(x, sign)
+ return x + np.cross(v, omega) / (omega * omega).sum(-1, keepdims=True)
+
+
+def launch(
+ L: np.ndarray,
+ pitch: np.ndarray,
+ azimuth: np.ndarray,
+ sign: np.ndarray,
+ speed: np.ndarray | float = SPEED,
+) -> tuple[np.ndarray, np.ndarray]:
+ """Particles whose gyration centers sit at the equator of the field line L, with the given
+ equatorial pitch angles (the field is vertical there)."""
+ center = np.stack([L * np.cos(azimuth), L * np.sin(azimuth), np.zeros_like(L)], 1)
+ around = np.stack([-np.sin(azimuth), np.cos(azimuth), np.zeros_like(L)], 1)
+ direction = np.sin(pitch)[:, None] * around + np.cos(pitch)[:, None] * np.array(
+ [0.0, 0.0, 1.0]
+ )
+ v = np.reshape(speed, (-1, 1)) * direction
+ return center - (guiding_center(center, v, sign) - center), v
+
+
+def field_line(L: float, azimuth: float, count: int = 160) -> np.ndarray:
+ """The dipole field line r = L cos²λ in the meridian at `azimuth`, above the surface."""
+ top = np.arccos(np.sqrt(1 / L))
+ lat = np.linspace(-top, top, count)
+ r = L * np.cos(lat) ** 2
+ return np.stack(
+ [
+ r * np.cos(lat) * np.cos(azimuth),
+ r * np.cos(lat) * np.sin(azimuth),
+ r * np.sin(lat),
+ ],
+ 1,
+ )
+
+
+def tube(
+ points: np.ndarray, radius: np.ndarray, sides: int = 8
+) -> tuple[np.ndarray, np.ndarray]:
+ """A tube along a polyline with a radius per point (parallel-transport frames)."""
+ tangent = np.gradient(points, axis=0)
+ tangent /= np.linalg.norm(tangent, axis=1, keepdims=True) + 1e-12
+ seed = np.cross(tangent[0], [0.3, 0.5, 0.8])
+ n0, n1, n2 = (seed / np.linalg.norm(seed)).tolist()
+ normals = [n0, n1, n2]
+ for t0, t1, t2 in tangent[1:].tolist(): # plain floats: one short step per point
+ d = n0 * t0 + n1 * t1 + n2 * t2
+ n0, n1, n2 = n0 - d * t0, n1 - d * t1, n2 - d * t2
+ norm = math.sqrt(n0 * n0 + n1 * n1 + n2 * n2) + 1e-12
+ n0, n1, n2 = n0 / norm, n1 / norm, n2 / norm
+ normals += n0, n1, n2
+ n_ = np.array(normals).reshape(-1, 3)
+ b_ = np.cross(tangent, n_)
+ a = np.linspace(0, m.TAU, sides, endpoint=False)
+ ring = (
+ np.cos(a)[None, :, None] * n_[:, None] + np.sin(a)[None, :, None] * b_[:, None]
+ )
+ verts = (points[:, None] + radius[:, None, None] * ring).reshape(-1, 3)
+ return verts, tube_triangles(len(points), sides)
+
+
[email protected]_cache(maxsize=1)
+def tube_triangles(rings: int, sides: int) -> np.ndarray:
+ """A tube's triangles, two per side between neighboring rings: the same for every tube
+ of its size (kept, read-only, while a trail's length holds)."""
+ i = np.arange(rings - 1)[:, None]
+ j = np.arange(sides)[None, :]
+ k = (j + 1) % sides
+ tris = np.stack(
+ [
+ np.stack([i * sides + j, (i + 1) * sides + j, (i + 1) * sides + k], -1),
+ np.stack([i * sides + j, (i + 1) * sides + k, i * sides + k], -1),
+ ],
+ 2,
+ ).reshape(-1, 3)
+ tris.flags.writeable = False
+ return tris
+
+
[email protected]_cache(maxsize=1)
+def trail_look(samples: int) -> tuple[np.ndarray, np.ndarray]:
+ """A trail's radius per sample and color per vertex, fading toward its oldest end: the
+ same for every trail of its length (kept while the length holds)."""
+ fade = np.linspace(0, 1, samples)
+ rows = np.ones((samples * 8, 4))
+ rows[:, :3] = ORANGE
+ rows[:, 3] = np.repeat(0.15 + 0.85 * fade, 8)
+ return 0.004 + 0.016 * fade, rows
+
+
+def globe_colors(points: np.ndarray) -> np.ndarray:
+ """A deep-blue planet, a little lighter toward the equator."""
+ z = points[:, 2] / np.linalg.norm(points, axis=1)
+ rows = np.ones((len(points), 4))
+ rows[:, :3] = np.array([0.05, 0.16, 0.38]) + 0.12 * (1 - np.abs(z))[
+ :, None
+ ] * np.array([0.3, 0.6, 1.0])
+ return rows
+
+
+class Proton:
+ """The first particle: its state, and the trail it leaves (its path, or in fast time its
+ guiding center)."""
+
+ def __init__(self) -> None:
+ sign = np.ones(1)
+ self.sign = sign
+ self.x, self.v = launch(
+ np.array([3.0]), np.radians([PITCH]), np.array([-0.35]), sign
+ )
+ self.samples: np.ndarray = self.x.copy()
+ self.speedup = 1
+ self.keep = 1400
+
+ def advance(self) -> None:
+ fast = self.speedup > 1
+ self.x, self.v, xs, vs = fly(
+ self.x, self.v, self.sign, STEPS * self.speedup, STEPS if fast else 1
+ )
+ new = guiding_center(xs, vs, self.sign.repeat(len(xs))) if fast else xs
+ self.samples = np.concatenate([self.samples, new])[-self.keep :]
+
+
+def unit_sphere(nu: int, nv: int) -> m.MeshMobject:
+ """A smooth lit unit sphere over an (nu + 1) × (nv + 1) grid of longitude u ∈ [0, 2π] and
+ colatitude v ∈ [0, π] (vertex i·(nv + 1) + j), each cell two triangles."""
+ u, v = np.meshgrid(
+ np.linspace(0, m.TAU, nu + 1), np.linspace(0, m.PI, nv + 1), indexing="ij"
+ )
+ points = np.stack([np.cos(u) * np.sin(v), np.sin(u) * np.sin(v), np.cos(v)], -1)
+ idx = np.arange((nu + 1) * (nv + 1)).reshape(nu + 1, nv + 1)
+ a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]
+ cells = np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 2)
+ return m.MeshMobject(points.reshape(-1, 3), cells.reshape(-1, 3), shade_in_3d=True)
+
+
+class VanAllen(m.ThreeDScene):
+ def construct(self) -> None:
+ rng = np.random.default_rng(1958)
+ globe = unit_sphere(96, 48)
+ globe.paint = globe.paint.but(fill=globe_colors(globe.points))
+ lines = m.VGroup(
+ *[
+ m.VMobject(
+ stroke_color="#8fb8ff",
+ stroke_width=1.2,
+ stroke_opacity=0.3,
+ shade_in_3d=True,
+ ).set_points_smoothly(field_line(L, a))
+ for L in (2.0, 3.0, 4.4)
+ for a in np.linspace(0, m.TAU, 8, endpoint=False)
+ ]
+ )
+
+ proton = Proton()
+ dot = m.Dot3D(proton.x[0], radius=0.06, color=m.WHITE)
+ trail = m.MeshMobject(
+ *tube(
+ np.array([[3.0, 0, 0], [3.0, 0.001, 0], [3.0, 0.002, 0]]),
+ np.full(3, 0.01),
+ ),
+ shade_in_3d=True,
+ )
+
+ def advance(_: m.Mobject, dt: float) -> None:
+ proton.advance()
+
+ def draw(_: m.Mobject) -> None:
+ dot.move_to(proton.x[0])
+ points = proton.samples
+ if len(points) > 2:
+ radius, rows = trail_look(len(points))
+ trail.points, trail.triangles = tube(points, radius)
+ trail.paint = trail.paint.but(fill=rows)
+
+ driver = m.Mobject()
+ driver.add_updater(advance)
+ driver.add_updater(draw)
+
+ b_eq = float(np.linalg.norm(field(np.array([[3.0, 0.0, 0.0]]), np.ones(1))))
+ b_value = m.DecimalNumber(1.0, num_decimal_places=2, font_size=30)
+ b_value.add_updater(
+ lambda d: d.set_value(
+ float(
+ np.linalg.norm(
+ field(
+ guiding_center(proton.x, proton.v, proton.sign), np.ones(1)
+ )
+ )
+ )
+ / b_eq
+ )
+ )
+ mirror = 1 / np.sin(np.radians(PITCH)) ** 2
+ readout = (
+ m.VGroup(
+ m.VGroup(
+ m.MathTex(r"B / B_{\text{eq}} =", font_size=30), b_value
+ ).arrange(m.RIGHT, buff=0.15),
+ m.MathTex(
+ rf"\text{{it turns back at }} 1/\sin^2\alpha = {mirror:.2f}",
+ font_size=28,
+ ).set_color(m.GREY_A),
+ )
+ .arrange(m.DOWN, aligned_edge=m.LEFT)
+ .to_corner(m.UR)
+ )
+ law = m.MathTex(
+ r"\mu = \frac{m v_\perp^2}{2B} = \text{const},\quad v = \text{const}",
+ font_size=30,
+ ).to_corner(m.DL)
+
+ title = m.Text("A magnetic bottle around the Earth", font_size=36).to_corner(
+ m.UL
+ )
+ subtitle = m.Text(
+ "gyrate, bounce, drift: how the radiation belts trap particles",
+ font_size=22,
+ )
+ subtitle.set_color(m.GREY_B).next_to(
+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.12
+ )
+ self.add_fixed_in_frame_mobjects(title, subtitle, readout, law)
+ self.remove(readout, law)
+
+ # 0–10 s: close to one proton: it gyrates, slides toward a pole, turns back, bounces
+ self.set_camera_orientation(
+ phi=76 * m.DEGREES,
+ theta=-112 * m.DEGREES,
+ zoom=1.55,
+ frame_center=np.array([2.2, -1.0, 0.1]),
+ )
+ self.add(globe, lines, driver, trail, dot)
+ self.play(m.FadeIn(readout), m.FadeIn(law), run_time=1.2)
+ self.wait(5.3)
+ self.move_camera(
+ phi=64 * m.DEGREES,
+ theta=-80 * m.DEGREES,
+ zoom=1.0,
+ frame_center=np.array([0.8, 0.0, 0.0]),
+ run_time=3.5,
+ )
+
+ # 10–18 s: time × 12: the bounce and the slow drift wrap a shell around the planet
+ fast = m.Text(
+ "time × 12 (the trail follows the gyration's center)", font_size=24
+ ).set_color(m.YELLOW)
+ fast.next_to(subtitle, m.DOWN, aligned_edge=m.LEFT, buff=0.2)
+ self.add_fixed_in_frame_mobjects(fast)
+ self.remove(fast)
+ proton.speedup, proton.keep = 12, 4000
+ proton.samples = guiding_center(proton.x, proton.v, proton.sign)
+ self.play(m.FadeOut(readout), m.FadeOut(law), m.FadeIn(fast), run_time=1)
+ self.begin_ambient_camera_rotation(rate=0.07)
+ self.move_camera(
+ phi=56 * m.DEGREES, zoom=0.92, frame_center=np.zeros(3), run_time=7
+ )
+
+ # 18–30 s: time × 30. An inner-belt proton and an outer-belt electron weave shells of their
+ # own, drifting opposite ways; electrons knocked into the loss cone off the equator (as
+ # waves do) stream down their field lines into the atmosphere, near the poles
+ GREEN = np.array([0.45, 1.0, 0.55])
+ proton.speedup, proton.keep = 30, 5000
+ belts = [(2.0, 60.0, 1.2, 1.0, 5.0, ORANGE), (4.2, 55.0, 2.6, -1.0, 2.6, CYAN)]
+ L = np.array([b_[0] for b_ in belts])
+ xs, vs = launch(
+ L,
+ np.radians([b_[1] for b_ in belts]),
+ np.array([b_[2] for b_ in belts]),
+ np.array([b_[3] for b_ in belts]),
+ np.array([b_[4] for b_ in belts]),
+ )
+ # the rain: a latitude of ±25° on lines L = 5 … 6, heading down the line, pitch 2° (inside
+ # the local loss cone, ~5°), released one after another
+ rain_count = 64
+ rain_L = rng.uniform(5.0, 6.0, rain_count)
+ hemisphere = np.where(np.arange(rain_count) % 2 == 0, 1.0, -1.0)
+ lat0 = np.radians(25.0) * hemisphere
+ azim = rng.uniform(0, m.TAU, rain_count)
+ r0 = rain_L * np.cos(lat0) ** 2
+ start = np.stack(
+ [
+ r0 * np.cos(lat0) * np.cos(azim),
+ r0 * np.cos(lat0) * np.sin(azim),
+ r0 * np.sin(lat0),
+ ],
+ 1,
+ )
+ b_hat = field(start, np.ones(rain_count))
+ b_hat /= np.linalg.norm(b_hat, axis=1, keepdims=True)
+ b_hat *= -np.sign((b_hat * start).sum(1))[:, None] # along the line, inward
+ side = np.cross(b_hat, np.array([0.0, 0.0, 1.0]))
+ side /= np.linalg.norm(side, axis=1, keepdims=True)
+ tilt = np.radians(2.0)
+ rain_v = 1.2 * (np.cos(tilt) * b_hat + np.sin(tilt) * side)
+ swarm_x = np.concatenate([xs, start])
+ swarm_v = np.concatenate([vs, rain_v])
+ sign = np.array([b_[3] for b_ in belts] + [-1.0] * rain_count)
+ count = len(sign)
+ release = np.concatenate(
+ [np.zeros(len(belts), int), np.sort(rng.integers(0, 480, rain_count))]
+ )
+ alive = np.ones(count, bool)
+ landed_at = np.full(
+ count, -1
+ ) # the tick each rain electron reached the atmosphere
+ clock = {"tick": 0}
+ tracks: list[list[np.ndarray]] = [[swarm_x[k]] for k in range(count)]
+ colors = [b_[5] for b_ in belts] + [GREEN] * rain_count
+ strands = [
+ m.VMobject(
+ stroke_color=m.ManimColor(c),
+ stroke_width=2.4 if k < len(belts) else 2.0,
+ stroke_opacity=0.9,
+ shade_in_3d=True,
+ )
+ for k, c in enumerate(colors)
+ ]
+ paths = m.VGroup(*strands)
+ landed = m.Group()
+
+ def weave(_: m.Mobject, dt: float) -> None:
+ clock["tick"] += 1
+ idx = np.flatnonzero(alive & (release <= clock["tick"]))
+ if not len(idx):
+ return
+ x, v, xs, vs = fly(swarm_x[idx], swarm_v[idx], sign[idx], STEPS * 30, 15)
+ centers = guiding_center(xs, vs, np.tile(sign[idx], len(xs) // len(idx)))
+ for j, k in enumerate(idx):
+ tracks[k].extend(centers[j :: len(idx)])
+ swarm_x[idx], swarm_v[idx] = x, v
+ for j, k in enumerate(idx):
+ if np.linalg.norm(x[j]) < 1.03: # it reached the atmosphere
+ alive[k] = False
+ landed_at[k] = clock["tick"]
+ spot = 1.012 * x[j] / np.linalg.norm(x[j])
+ landed.add(m.Dot3D(spot, radius=0.05, color=m.ManimColor(GREEN)))
+
+ def redraw(_: m.Mobject) -> None:
+ for k, (path, track) in enumerate(zip(strands, tracks, strict=True)):
+ if k < len(belts):
+ if len(track) > 1:
+ path.set_points_as_corners(np.array(track[-3000:]))
+ continue
+ # a rain electron: a bright streak down its line, fading once it has landed
+ since = clock["tick"] - landed_at[k] if landed_at[k] >= 0 else 0
+ if release[k] <= clock["tick"] and len(track) > 1 and since < 24:
+ path.set_points_as_corners(np.array(track[-160:]))
+ path.set_stroke(opacity=0.95 * (1 - since / 24))
+ elif path.has_points():
+ path.set_stroke(opacity=0.0)
+
+ weaver = m.Mobject()
+ weaver.add_updater(weave)
+ weaver.add_updater(redraw)
+ outer_lines = m.VGroup(
+ *[
+ m.VMobject(
+ stroke_color="#8fb8ff",
+ stroke_width=1.0,
+ stroke_opacity=0.22,
+ shade_in_3d=True,
+ ).set_points_smoothly(field_line(5.6, a_))
+ for a_ in np.linspace(0, m.TAU, 8, endpoint=False)
+ ]
+ )
+ legend = (
+ m.VGroup(
+ m.VGroup(
+ m.Dot(color=m.ManimColor(ORANGE)),
+ m.Text("protons drift west", font_size=22),
+ ).arrange(m.RIGHT, buff=0.15),
+ m.VGroup(
+ m.Dot(color=m.ManimColor(CYAN)),
+ m.Text("electrons drift east", font_size=22),
+ ).arrange(m.RIGHT, buff=0.15),
+ m.VGroup(
+ m.Dot(color=m.ManimColor(GREEN)),
+ m.Text("in the loss cone: down into the atmosphere", font_size=22),
+ ).arrange(m.RIGHT, buff=0.15),
+ )
+ .arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.15)
+ .to_corner(m.DL)
+ )
+ faster = (
+ m.Text("time × 30", font_size=24)
+ .set_color(m.YELLOW)
+ .next_to(subtitle, m.DOWN, aligned_edge=m.LEFT, buff=0.2)
+ )
+ self.add_fixed_in_frame_mobjects(legend, faster)
+ self.remove(legend, faster)
+ self.add(weaver, paths, landed)
+ self.play(
+ m.FadeOut(fast),
+ m.FadeIn(faster),
+ m.FadeIn(legend),
+ m.FadeIn(outer_lines),
+ dot.animate.set_opacity(0),
+ run_time=1.5,
+ )
+ self.move_camera(phi=64 * m.DEGREES, zoom=0.8, run_time=5.5)
+ self.move_camera(phi=46 * m.DEGREES, zoom=0.86, run_time=5)
+
+
+if __name__ == "__main__":
+ VanAllen().render("van_allen.mp4")