The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add nonlinear systems examples
apoogdk84224cb31c73
diff --git a/examples/bifurcation_mandelbrot.py b/examples/bifurcation_mandelbrot.pynew file mode 100644index 00000000..5a19773c--- /dev/null+++ b/examples/bifurcation_mandelbrot.py@@ -0,0 +1,211 @@+"""The Mandelbrot set knows about period doubling.++The logistic map x → r x (1 − x) and z → z² + c are the same dynamics in different clothes:+c = r/2 − r²/4. So the logistic bifurcation diagram (the long-run values of x for each r) can be+stood up on the real axis of the Mandelbrot set, above the c that matches each r. Every+period-doubling lands on a pinch between two bulbs — period 2 at c = −3/4, period 4 at −5/4, the+cascade piling up at the Feigenbaum point −1.4012 — and the period-3 window sits exactly over the+little copy of the Mandelbrot set at c = −1.75.+"""++import numpy as np++import manimgx as m++UNIT = 2.6 # screen units per unit of c+HEIGHT = 3.0 # screen height of x ∈ [0, 1]+RE = (-2.15, 0.65)+IM = (-1.2, 1.2)+PIXELS = (1120, 960) # (columns, rows) of the Mandelbrot picture+N_PARAMS = 2400+KEEP = 120 # iterates kept per parameter (after a transient)+++def mandelbrot_pixels() -> np.ndarray:+ """The set in deep ink, its outside glowing by smooth escape time: (rows, cols, 4) uint8."""+ cols, rows = PIXELS+ re = np.linspace(*RE, cols)+ im = np.linspace(IM[1], IM[0], rows) # the picture's rows go down+ c = re[None, :] + 1j * im[:, None]+ z = np.zeros_like(c)+ escape = np.full(c.shape, np.nan)+ for n in range(240):+ z = np.where(np.isnan(escape), z * z + c, z)+ out = np.isnan(escape) & (np.abs(z) > 4)+ escape[out] = n + 1 - np.log2(np.log2(np.abs(z[out])))+ t = np.nan_to_num(np.sqrt(np.nan_to_num(escape) / 40), nan=0)+ inside = np.isnan(escape)+ rgb = np.stack([0.10 + 0.9 * t**1.6, 0.18 + 0.6 * t, 0.45 + 0.55 * np.sqrt(t)], -1)+ rgb = np.clip(rgb * np.clip(t * 3, 0, 1)[..., None], 0, 1)+ rgb[inside] = [0.02, 0.02, 0.05]+ alpha = np.ones(t.shape)+ return (np.concatenate([rgb, alpha[..., None]], -1) * 255).astype(np.uint8)+++def attractor() -> tuple[np.ndarray, np.ndarray]:+ """(c, x) of the logistic map's long-run values, r from 1 to 4, sorted by c from right to left."""+ r = np.linspace(1.0, 4.0, N_PARAMS)+ x = np.full(N_PARAMS, 0.5)+ for _ in range(600):+ x = r * x * (1 - x)+ xs = []+ for _ in range(KEEP):+ x = r * x * (1 - x)+ xs.append(x.copy())+ c = np.repeat(r / 2 - r * r / 4, KEEP).reshape(N_PARAMS, KEEP).T.ravel()+ values = np.array(xs).ravel()+ order = np.argsort(-c, kind="stable")+ return c[order], values[order]+++def to_scene(c: np.ndarray, x: np.ndarray) -> np.ndarray:+ return np.stack([UNIT * (c + 0.75), 0 * c, HEIGHT * x], 1)+++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 BifurcationMandelbrot(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(phi=0, theta=-90 * m.DEGREES, zoom=0.95)++ # the Mandelbrot set lying on the floor, the real axis along x+ floor = m.ImageMobject(mandelbrot_pixels())+ x0, x1 = UNIT * (RE[0] + 0.75), UNIT * (RE[1] + 0.75)+ y0, y1 = UNIT * IM[0], UNIT * IM[1]+ floor.points = np.array(+ [[x0, y1, 0], [x1, y1, 0], [x0, y0, 0], [x1, y0, 0]], dtype=float+ )++ # the logistic map's long-run values, revealed by a scan line moving in c at constant speed+ c, x = attractor()+ colors = np.ones((len(c), 4))+ colors[:, :3] = [1.0, 0.82, 0.35]+ diagram = m.PMobject(stroke_width=1.4)+ diagram.add_points(to_scene(c, x), rgbas=colors)+ scan = m.ValueTracker(0.3)++ def reveal(mob: m.Mobject) -> None:+ rows = colors.copy()+ rows[:, 3] = np.where(c >= scan.get_value(), 0.55, 0.0)+ mob.paint = mob.paint.but(fill=rows)++ reveal(diagram)+ diagram.add_updater(reveal)+ scanline = m.always_redraw(+ lambda: m.Line(+ to_scene(np.array([scan.get_value()]), np.array([0.0]))[0],+ to_scene(np.array([scan.get_value()]), np.array([1.05]))[0],+ stroke_width=3,+ color=m.WHITE,+ stroke_opacity=0.8 if -2.0 < scan.get_value() < 0.26 else 0.0,+ )+ )++ title = m.Text(+ "The Mandelbrot set knows about period doubling", font_size=30+ ).to_corner(m.UL)+ relation = m.MathTex(+ r"x \mapsto r x(1-x)\ \sim\ z \mapsto z^2 + c",+ r"\quad c = \tfrac{r}{2} - \tfrac{r^2}{4}",+ font_size=30,+ )+ relation.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.2)+ self.add_fixed_in_frame_mobjects(title, relation)+ self.remove(relation)++ # 0–3 s: the set from above+ self.add(floor)+ self.play(self.camera.zoom_tracker.animate.set_value(1.0), run_time=2.5)+ # 3–7 s: tilt; the real axis becomes a stage+ self.move_camera(+ phi=72 * m.DEGREES,+ theta=-90 * m.DEGREES,+ zoom=1.0,+ frame_center=np.array([-0.9, 0.0, 1.35]),+ added_anims=[m.FadeIn(relation)],+ run_time=4,+ )+ # 7–17 s: sweep c from 1/4 to −2; above each c its logistic attractor appears+ self.add(diagram, scanline)+ self.play(scan.animate.set_value(-2.02), run_time=10, rate_func=m.linear)+ diagram.clear_updaters() # all revealed: nothing changes any more+ self.remove(scanline)++ # 17–25 s: the landmarks line up with the bulbs+ marks = [+ (-0.75, "period 2", 1.08),+ (-1.25, "period 4", 1.08),+ (-1.75, "period 3", 1.08),+ ]+ reveals = []+ for c_mark, name, reach in marks:+ top = to_scene(np.array([c_mark]), np.array([reach]))[0]+ drop = m.DashedLine(+ top,+ top * np.array([1, 1, 0]),+ stroke_width=2.5,+ color=m.WHITE,+ dash_length=0.1,+ )+ label = m.Text(name, font_size=20).move_to(top + 0.25 * m.OUT)+ shown = m.ValueTracker(0.0)+ self.add(billboard(label, self.camera, shown))+ reveals.append(+ m.AnimationGroup(+ m.Create(drop), shown.animate.set_value(1.0), run_time=1.4+ )+ )+ # one at a time, while the camera swings round to look along the drops+ self.play(+ m.Succession(*reveals, m.Wait(3.8)),+ self.camera.phi_tracker.animate.set_value(66 * m.DEGREES),+ self.camera.theta_tracker.animate.set_value(-74 * m.DEGREES),+ run_time=8,+ )+ closing = m.Text(+ "Each doubling sits on a pinch between bulbs.", font_size=28+ ).to_edge(m.DOWN, buff=0.3)+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(+ m.FadeIn(closing),+ self.camera.theta_tracker.animate.set_value(-84 * m.DEGREES),+ run_time=3.5,+ )+ self.wait(1)+++if __name__ == "__main__":+ BifurcationMandelbrot().render("bifurcation_mandelbrot.mp4")diff --git a/examples/dla_coral.py b/examples/dla_coral.pynew file mode 100644index 00000000..793f6d0c--- /dev/null+++ b/examples/dla_coral.py@@ -0,0 +1,270 @@+"""Diffusion-limited aggregation: random walkers build a coral.++Start with one particle. Release another far away and let it wander at random, one lattice step at+a time, until it touches the cluster, where it sticks. Repeat 18,000 times (Witten & Sander,+1981). The walkers almost never reach the fjords: the tips catch them first, so the tips grow and+branch while the inside stays empty. The cluster is a fractal: its mass grows like its radius to+a power D, measured here from the cluster itself (radius of gyration against particle count, on+log–log axes), close to the known D ≈ 2.5 for three dimensions, between a surface (2) and a solid (3).+Walkers far from the cluster take long jumps to the cluster's bounding sphere, which changes nothing+about where they land but saves most of the walking.+"""++import numpy as np++import manimgx as m++COUNT = 18000+SIZE = 200 # the lattice, SIZE³ cells+CELL = 0.052 # screen units per lattice cell+STOPS = ["#3c096c", "#7b2cbf", "#c9184a", "#ff5d8f", "#ff9e00", "#ffe066"] # old → new+MOVES = np.array([[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -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+++class Cluster:+ """The growing cluster on a cubic lattice, and the walkers wandering toward it."""++ def __init__(self, rng: np.random.Generator) -> None:+ self.rng = rng+ self.center = SIZE // 2+ self.taken = np.zeros((SIZE,) * 3, bool)+ # the cells next to the cluster: a walker that steps onto one sticks+ self.sticky = np.zeros((SIZE,) * 3, bool)+ self.cells: list[tuple[int, int, int]] = []+ self.radius = 1.0+ self.stick((self.center, self.center, self.center))++ def stick(self, cell: tuple[int, int, int]) -> None:+ self.taken[cell] = True+ for dx, dy, dz in MOVES.tolist():+ self.sticky[cell[0] + dx, cell[1] + dy, cell[2] + dz] = True+ self.cells.append(cell)+ self.radius = max(+ self.radius, float(np.linalg.norm(np.array(cell) - self.center))+ )++ def launch(self, n: int) -> np.ndarray:+ v = self.rng.normal(size=(n, 3))+ v /= np.linalg.norm(v, axis=1, keepdims=True)+ return np.round(self.center + (self.radius + 8) * v).astype(np.int64)++ def step(self, walkers: np.ndarray) -> np.ndarray:+ """One move for every walker: a lattice step, or, when the cluster's bounding sphere is+ far, a jump straight toward it through the free room (its landing spot is uniform).+ """+ room = np.linalg.norm(walkers - self.center, axis=1) - self.radius - 3+ moves = MOVES[self.rng.integers(0, 6, len(walkers))]+ far = np.flatnonzero(room > 2)+ v = self.rng.normal(size=(len(far), 3))+ v /= np.linalg.norm(v, axis=1, keepdims=True)+ moves[far] = np.round(room[far, None] * v).astype(np.int64)+ walkers = walkers + moves+ lost = np.linalg.norm(walkers - self.center, axis=1) > min(+ 2 * self.radius + 25, SIZE / 2 - 3+ )+ walkers[lost] = self.launch(int(lost.sum()))+ return walkers++ def grow(self, count: int) -> None:+ walkers = self.launch(20)+ while len(self.cells) < count:+ want = min(3000, 20 + len(self.cells) // 5) # more walkers as it grows+ if len(walkers) < want:+ walkers = np.concatenate([walkers, self.launch(want - len(walkers))])+ walkers = self.step(walkers)+ x, y, z = walkers.T+ hit = np.flatnonzero(self.sticky[x, y, z] & ~self.taken[x, y, z])+ for i in hit:+ cell = (int(walkers[i, 0]), int(walkers[i, 1]), int(walkers[i, 2]))+ if not self.taken[cell] and len(self.cells) < count:+ self.stick(cell)+ walkers[hit] = self.launch(len(hit))++ def wander(self) -> np.ndarray:+ """One more walker's whole path, from launch to where it would stick (lattice steps+ only; it is not stuck: see `stick`)."""+ walker = self.launch(1)+ path = [walker[0].copy()]+ while not self.sticky[tuple(walker[0])]:+ walker = walker + MOVES[self.rng.integers(0, 6, 1)]+ if np.linalg.norm(walker[0] - self.center) > self.radius + 12:+ walker = self.launch(1)+ path = []+ path.append(walker[0].copy())+ return np.array(path, float)+++def beads(centers: np.ndarray, radius: float) -> tuple[np.ndarray, np.ndarray]:+ """A small octahedron at every center, in order (smooth-shaded, it reads as a bead):+ vertices and triangles, wound outward."""+ corners = np.concatenate([np.eye(3), -np.eye(3)]) # +x +y +z −x −y −z+ faces = []+ for sx, sy, sz in np.ndindex(2, 2, 2):+ a, b, c = 3 * sx, 1 + 3 * sy, 2 + 3 * sz+ faces.append([a, b, c] if (sx + sy + sz) % 2 == 0 else [a, c, b])+ verts = (centers[:, None, :] + radius * corners[None]).reshape(-1, 3)+ tris = (np.array(faces)[None] + 6 * np.arange(len(centers))[:, None, None]).reshape(+ -1, 3+ )+ return verts, tris+++class DlaCoral(m.ThreeDScene):+ def construct(self) -> None:+ cluster = Cluster(np.random.default_rng(5))+ cluster.grow(COUNT)+ cells = np.array(cluster.cells, float) - cluster.center+ centers = CELL * cells+ verts, tris = beads(centers, 0.62 * CELL)+ coral = m.MeshMobject(verts, tris, shade_in_3d=True)+ coral.paint = coral.paint.but(+ fill=np.repeat(colormap(np.linspace(0, 1, COUNT), STOPS), 6, axis=0)+ )++ # the mass–radius law, measured: radius of gyration of the first n particles+ counts = np.unique(np.geomspace(50, COUNT, 24).astype(int))+ spread = np.array(+ [+ np.sqrt(((cells[:n] - cells[:n].mean(0)) ** 2).sum(1).mean())+ for n in counts+ ]+ )+ scaling = counts >= 300 # past the first few hundred, where the law has set in+ slope = 1 / np.polyfit(np.log(counts[scaling]), np.log(spread[scaling]), 1)[0]+ grown = m.ValueTracker(1.0)+ plot = (+ m.Axes(+ x_range=(0.8, 3.6, 1),+ y_range=(3.5, 10.0, 1),+ x_length=2.8,+ y_length=2.4,+ tips=False,+ axis_config={"stroke_width": 1.5, "include_ticks": False},+ )+ .to_corner(m.DR)+ .shift(0.4 * m.UP + 0.2 * m.LEFT)+ )+ plot_names = m.VGroup(+ m.MathTex(r"\log R_g", font_size=24).next_to(+ plot.x_axis, m.DOWN, buff=0.12+ ),+ m.MathTex(r"\log N", font_size=24).next_to(plot.y_axis, m.UP, buff=0.1),+ )++ hud = m.ValueTracker(+ 1.0+ ) # the plot's opacity (it steps aside for the close-up)++ def measured() -> m.VGroup:+ shown = counts <= grown.get_value()+ return m.VGroup(+ *[+ m.Dot(+ plot.c2p(float(np.log(s)), float(np.log(n))),+ radius=0.045,+ color=m.GOLD,+ )+ for n, s in zip(counts[shown], spread[shown])+ ]+ ).set_opacity(hud.get_value())++ dots = m.always_redraw(measured)+ fit_value = m.DecimalNumber(slope, num_decimal_places=2, font_size=30)+ fit_row = m.VGroup(+ m.MathTex(r"N \propto R_g^{D},\ D =", font_size=30), fit_value+ )+ fit_row.arrange(m.RIGHT, buff=0.12).next_to(plot, m.UP, buff=0.45)+ unit = m.Text("particles", font_size=24).to_corner(m.UR)+ tally = m.Integer(1, font_size=30)++ def count_up(d: m.Mobject) -> None:+ assert isinstance(d, m.Integer)+ d.set_value(int(grown.get_value()))+ d.next_to(unit, m.LEFT, buff=0.15) # (set_value re-centers the number)++ tally.add_updater(count_up)+ tally_row = m.VGroup(tally, unit)++ title = m.Text("Random walkers build a coral", font_size=38).to_corner(m.UL)+ subtitle = m.Text(+ "each wanders until it touches the cluster, then sticks (Witten & Sander,"+ " 1981)",+ font_size=22,+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)+ self.add_fixed_in_frame_mobjects(+ title, subtitle, tally_row, plot, plot_names, dots, fit_row+ )+ self.remove(fit_row)++ self.set_camera_orientation(phi=70 * m.DEGREES, theta=-60 * m.DEGREES, zoom=2.4)+ self.begin_ambient_camera_rotation(rate=0.1)+ self.add(coral)+ # grow: particles in the order they stuck, the camera pulling back with the cluster+ self.play(+ m.Create(coral, rate_func=lambda u: u**1.6),+ grown.animate(rate_func=lambda u: u**1.6).set_value(COUNT),+ self.camera.zoom_tracker.animate.set_value(0.95),+ run_time=19,+ )+ self.play(m.FadeIn(fit_row), run_time=1)+ # one more walker, followed all the way in, up close: of a dozen, the one that lands on+ # the tip that faces the camera+ phi, theta = self.camera.get_phi(), self.camera.get_theta()+ toward = np.array(+ [np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi)]+ )+ paths = [cluster.wander() for _ in range(12)]+ chosen = max(paths, key=lambda p: float((p[-1] - cluster.center) @ toward))+ end = chosen[-1].astype(int)+ cluster.stick((int(end[0]), int(end[1]), int(end[2])))+ path = CELL * (chosen - cluster.center)+ trail = m.VMobject(stroke_color=m.WHITE, stroke_width=2, shade_in_3d=True)+ trail.set_points_as_corners(path[:: max(1, len(path) // 500)])+ bead_verts, bead_tris = beads(path[-1:], 0.75 * CELL)+ bead = m.MeshMobject(+ bead_verts, bead_tris, shade_in_3d=True, fill_color=m.WHITE+ )+ aside = m.VGroup(title, subtitle, plot, plot_names, fit_row)+ self.stop_ambient_camera_rotation()+ self.move_camera(+ frame_center=path[-1],+ zoom=3.0,+ added_anims=[aside.animate.set_opacity(0.0), hud.animate.set_value(0.0)],+ run_time=2,+ )+ self.play(m.Create(trail), run_time=3, rate_func=m.linear)+ self.add(bead)+ self.play(m.FadeOut(trail), run_time=0.6)+ self.move_camera(+ frame_center=m.ORIGIN,+ zoom=0.95,+ added_anims=[aside.animate.set_opacity(1.0), hud.animate.set_value(1.0)],+ run_time=2.4,+ )+ self.begin_ambient_camera_rotation(rate=0.1)+ closing = (+ m.Text(+ f"D = {slope:.2f}: more than a surface, less than a solid", font_size=26+ )+ .to_edge(m.DOWN, buff=0.35)+ .shift(1.5 * m.LEFT)+ )+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(m.FadeIn(closing), run_time=1)+ self.wait(2)+++if __name__ == "__main__":+ DlaCoral().render("dla_coral.mp4")diff --git a/examples/kuramoto_fireflies.py b/examples/kuramoto_fireflies.pynew file mode 100644index 00000000..eadea5c8--- /dev/null+++ b/examples/kuramoto_fireflies.py@@ -0,0 +1,384 @@+"""Fireflies fall into step: spontaneous synchrony past a critical coupling (Kuramoto 1975).++2000 fireflies flash whenever their phase θᵢ passes 0. Each has its own rhythm ωᵢ, drawn from a+Lorentzian of width γ, and each is nudged toward the swarm's average rhythm:+θ̇ᵢ = ωᵢ + K r sin(ψ − θᵢ), where r e^{iψ} = (1/N) Σ e^{iθⱼ} (drawn as the arrow in the HUD).+Below K_c = 2γ nothing happens: r is only finite-size noise, ~1/√N. Past it, a locked cluster+forms and grows, and r follows the exact result for a Lorentzian, r = √(1 − K_c/K) (Kuramoto+1984). Fireflies are placed by rhythm (slow on the left, fast on the right), so the locked+middle of the forest flashes as one wave while the extremes keep their own time.+"""++import numpy as np++import manimgx as m++N = 2000+OMEGA0 = 2 * np.pi * 0.75 # the swarm's median rhythm: a flash every 1.33 s+GAMMA = OMEGA0 / 1.5 # half-width of the Lorentzian of rhythms+KC = 2 * GAMMA # the critical coupling+STOPS = ["#ff8a3d", "#ffc94d", "#e2ff6a", "#8dff8a", "#46f0d2"] # slow → fast rhythm+GOLD = "#ffd166"+BACKGROUND = "#03060d"+++def colormap(values: np.ndarray, stops: list[str]) -> np.ndarray:+ """RGBA rows for values in [0, 1], interpolated through color stops."""+ 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 ease(x: float) -> float:+ x = min(max(x, 0.0), 1.0)+ return x * x * (3 - 2 * x)+++def coupling(t: float) -> float:+ """K / K_c against film time: slowly through the transition, then strong."""+ return (+ 0.9 * ease((t - 1.5) / 4.5) + 0.7 * ease((t - 6) / 9) + 1.4 * ease((t - 15) / 7)+ )+++def order(theta: np.ndarray) -> complex:+ """The order parameter r e^{iψ} = mean of e^{iθ}."""+ return complex(np.exp(1j * theta).mean())+++def tube(+ points: np.ndarray, radius: float, sides: int = 12+) -> tuple[np.ndarray, np.ndarray]:+ """Vertices and triangles of a lit tube along a polyline (parallel-transport frames)."""+ tangent = np.gradient(points, axis=0)+ tangent /= np.linalg.norm(tangent, axis=1, keepdims=True)+ seed = np.cross(tangent[0], [0.3, 0.5, 0.8])+ normals = [seed / np.linalg.norm(seed)]+ for t in tangent[1:]:+ n = normals[-1] - np.dot(normals[-1], t) * t+ normals.append(n / np.linalg.norm(n))+ n_ = np.array(normals)+ 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 * ring).reshape(-1, 3)+ i = np.arange(len(points) - 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)+ return verts, tris+++def cloud(points: np.ndarray, rows: np.ndarray, size: float) -> m.PMobject:+ mob = m.PMobject(stroke_width=size)+ mob.add_points(points, rgbas=rows)+ return mob+++class KuramotoFireflies(m.ThreeDScene):+ def construct(self) -> None:+ self.camera.background_color = BACKGROUND+ self.set_camera_orientation(phi=78 * m.DEGREES, theta=-100 * m.DEGREES)+ self.camera.light_source.move_to([-6.0, 30.0, 12.0]) # moonlight from behind+ rng = np.random.default_rng(7)++ # rhythms: the Lorentzian's quantiles, so the sample is as Lorentzian as it can be+ rank = (np.arange(N) + 0.5) / N+ omega = OMEGA0 + GAMMA * np.tan(np.pi * (rank - 0.5))+ theta = rng.uniform(0, m.TAU, N)+ paint = colormap(rank, STOPS)++ # the forest: fireflies placed by rhythm across it, scattered in depth and height+ home = np.stack(+ [+ 13.0 * (rank - 0.5) + 0.7 * rng.standard_normal(N),+ rng.uniform(-2.5, 6.0, N),+ rng.uniform(-3.3, 1.2, N),+ ],+ axis=1,+ )+ drift_f = rng.uniform(0.25, 0.7, (N, 3))+ drift_p = rng.uniform(0, m.TAU, (N, 3))+ trunks = []+ for k in range(16):+ x0, y0 = -8.0 + k + rng.uniform(-0.4, 0.4), rng.uniform(-1.0, 9.0)+ line = np.array([[x0, y0, -4.0], [x0 + 0.1, y0, 1.0], [x0, y0, 7.0]])+ verts, tris = tube(line, rng.uniform(0.07, 0.16))+ trunks.append(+ m.MeshMobject(verts, tris, shade_in_3d=True, fill_color="#0c1118")+ )++ state = {"theta": theta}+ clock = [0.0]++ def rhs(th: np.ndarray, k: float) -> np.ndarray:+ z = order(th)+ return omega + k * abs(z) * np.sin(np.angle(z) - th)++ def advance(mob: m.Mobject, dt: float) -> None:+ k = coupling(clock[0]) * KC+ th = state["theta"]+ h = dt / 4+ for _ in range(4): # RK4+ k1 = rhs(th, k)+ k2 = rhs(th + h / 2 * k1, k)+ k3 = rhs(th + h / 2 * k2, k)+ k4 = rhs(th + h * k3, k)+ th = th + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)+ state["theta"] = np.mod(th, m.TAU)+ clock[0] += dt++ driver = m.Mobject().add_updater(advance)++ def flash() -> np.ndarray:+ """Brightness: a short flash as the phase passes 0."""+ return np.exp(5.0 * (np.cos(state["theta"]) - 1))++ cores = cloud(home, paint, 5)+ glows = cloud(home, paint, 26)+ halos = cloud(home, paint, 64)++ def shine(mob: m.Mobject) -> None:+ t = clock[0]+ where = home + 0.16 * np.sin(drift_f * t + drift_p)+ b = flash()+ lit = paint.copy()+ lit[:, :3] *= (0.22 + 0.78 * b)[:, None]+ cores.points = where+ cores.paint = cores.paint.but(fill=lit)+ for layer, alpha in ((glows, 0.32), (halos, 0.05)):+ rows = paint.copy()+ rows[:, 3] = alpha * b+ layer.points = where+ layer.paint = layer.paint.but(fill=rows)++ shine(driver)+ cores.add_updater(shine)+ self.add(driver, *trunks, cores, glows, halos)++ # HUD, left: the phases on a circle (flash at the top) and the arrow r e^{iψ}+ at = np.array([-5.35, -2.35, 0.0])+ radius = 1.05+ panel_l = m.RoundedRectangle(+ corner_radius=0.15, width=3.1, height=3.05, stroke_width=1+ )+ panel_l.set_fill(BACKGROUND, opacity=0.8).set_stroke(m.GREY_D)+ panel_l.move_to(at + [0, 0.12, 0])+ ring = m.Circle(radius=radius, stroke_color=m.GREY_D, stroke_width=1.5)+ ring.move_to(at)+ spot = m.Line(+ at + [0, radius - 0.12, 0], at + [0, radius + 0.12, 0], stroke_width=3+ ).set_stroke(m.WHITE)+ lane = radius * (0.82 + 0.18 * rank) # slow rhythms inside, fast outside++ def on_circle(th: np.ndarray, r: np.ndarray) -> np.ndarray:+ angle = np.pi / 2 - th # phase 0 at the top, advancing clockwise+ flat = np.stack([r * np.cos(angle), r * np.sin(angle), 0 * r], axis=1)+ return flat + at++ dots = cloud(on_circle(theta, lane), paint, 4)+ arrow_line = m.Line(at, at + [0.01, 0, 0], stroke_width=4, stroke_color=m.WHITE)+ arrow_tip = m.Dot(at, radius=0.05, color=m.WHITE)+ # a ×10 magnifier at the centre, so the arrow shows while r is still only noise+ noise_ring = m.DashedVMobject(+ m.Circle(radius=10 * radius / np.sqrt(N), stroke_width=1.5), num_dashes=20+ ).move_to(at)+ noise_ring.set_stroke(m.GREY_B)+ zoom_arrow = m.Line(at, at + [0.01, 0, 0], stroke_width=2.5)+ zoom_label = m.MathTex(r"\times 10", font_size=20).set_color(m.GREY_B)+ zoom_label.next_to(noise_ring, m.DOWN, buff=0.05)++ def phases(mob: m.Mobject) -> None:+ b = flash()+ rows = paint.copy()+ rows[:, :3] *= (0.45 + 0.55 * b)[:, None]+ dots.points = on_circle(state["theta"], lane)+ dots.paint = dots.paint.but(fill=rows)+ z = order(state["theta"])+ tip = on_circle(np.array([np.angle(z)]), np.array([radius * abs(z)]))[0]+ arrow_line.put_start_and_end_on(at, tip + [1e-4, 0, 0])+ arrow_tip.move_to(tip)+ near = min(1.0, max(0.0, (0.1 - abs(z)) / 0.04)) # gone once r is real+ reach = min(10 * abs(z), 0.8)+ zoomed = on_circle(np.array([np.angle(z)]), np.array([radius * reach]))[0]+ zoom_arrow.put_start_and_end_on(at, zoomed + [1e-4, 0, 0])+ zoom_arrow.set_stroke(m.WHITE, opacity=0.85 * near)+ noise_ring.set_stroke(opacity=0.7 * near)+ zoom_label.set_opacity(near)++ dots.add_updater(phases)+ z_label = m.MathTex(r"r e^{i\psi} = \langle e^{i\theta} \rangle", font_size=26)+ z_label.next_to(ring, m.UP, buff=0.22)++ # HUD, right: r against K, measured, and the exact Lorentzian result+ plot = m.Axes(+ x_range=[0, 3.2, 1],+ y_range=[0, 1, 0.5],+ x_length=4.2,+ y_length=2.1,+ tips=False,+ axis_config={"stroke_width": 2, "color": m.GREY_B, "include_ticks": False},+ ).move_to([4.55, -2.45, 0])+ panel_r = m.RoundedRectangle(+ corner_radius=0.15, width=5.2, height=3.05, stroke_width=1+ )+ panel_r.set_fill(BACKGROUND, opacity=0.8).set_stroke(m.GREY_D)+ panel_r.move_to(plot.get_center() + [0.05, 0.12, 0])+ theory = m.VGroup(+ m.Line(plot.c2p(0, 0), plot.c2p(1, 0)),+ plot.plot(lambda k: float(np.sqrt(1 - 1 / k)), x_range=[1, 3.2, 0.005]),+ ).set_stroke(GOLD, 3)+ theory_label = m.MathTex(r"r = \sqrt{1 - K_c/K}", font_size=26).set_color(GOLD)+ theory_label.move_to(plot.c2p(2.35, 0.45))+ noise = m.DashedLine(+ plot.c2p(0, 1 / np.sqrt(N)), plot.c2p(1, 1 / np.sqrt(N)), dash_length=0.05+ ).set_stroke(m.GREY_B, 1.5)+ noise_label = m.MathTex(r"1/\sqrt{N}", font_size=22).set_color(m.GREY_B)+ noise_label.next_to(plot.c2p(0.5, 1 / np.sqrt(N)), m.UP, buff=0.08)+ kc_tick = m.MathTex(r"K_c = 2\gamma", font_size=24).next_to(+ plot.c2p(1, 0), m.DOWN, buff=0.12+ )+ k_axis = m.MathTex(r"K", font_size=26).next_to(plot.c2p(3.2, 0), m.RIGHT, 0.1)+ r_axis = m.MathTex(r"r", font_size=26).next_to(plot.c2p(0, 1), m.LEFT, 0.12)+ trace: list[np.ndarray] = []+ measured = m.VMobject(stroke_color=m.WHITE, stroke_width=2)+ now = m.Dot(plot.c2p(0, 0), radius=0.055, color=m.WHITE)++ def record(mob: m.Mobject) -> None:+ k, r = coupling(clock[0]), abs(order(state["theta"]))+ trace.append(plot.c2p(k, r))+ if len(trace) > 1:+ measured.set_points_as_corners(np.array(trace))+ now.move_to(trace[-1])++ measured.add_updater(record)++ # the legend: each firefly's own rhythm, which also sets where it sits+ legend_bar = m.Rectangle(width=3.0, height=0.1, stroke_width=0, fill_opacity=1)+ legend_bar.set_fill(color=STOPS, opacity=1).set_sheen_direction(m.RIGHT)+ legend_bar.move_to([-0.55, -3.62, 0])+ slow = m.Text("slower", font_size=20).set_color(m.GREY_B)+ slow.next_to(legend_bar, m.LEFT, buff=0.15)+ fast = m.Text("faster", font_size=20).set_color(m.GREY_B)+ fast.next_to(legend_bar, m.RIGHT, buff=0.15)+ legend_title = m.MathTex(+ r"\text{own rhythm } \omega_i \text{ (Lorentzian, width } \gamma)",+ font_size=24,+ ).set_color(m.GREY_B)+ legend_title.next_to(legend_bar, m.UP, buff=0.12)+ legend = m.VGroup(legend_bar, slow, fast, legend_title)+ backing = m.RoundedRectangle(+ corner_radius=0.12,+ width=legend.width + 0.35,+ height=legend.height + 0.25,+ stroke_width=1,+ )+ backing.set_fill(BACKGROUND, opacity=0.8).set_stroke(m.GREY_D)+ legend = m.VGroup(backing.move_to(legend), *legend)++ # readouts and titles+ title = m.Text("Fireflies fall into step", font_size=36).to_corner(m.UL)+ subtitle = m.Text(+ f"{N} flashing oscillators, each nudged toward the swarm's rhythm",+ font_size=22,+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ law = m.MathTex(+ r"\dot\theta_i = \omega_i + K r \sin(\psi - \theta_i)", font_size=32+ ).to_corner(m.UR)+ k_value = m.DecimalNumber(0, num_decimal_places=2, font_size=28)+ r_value = m.DecimalNumber(0, num_decimal_places=2, font_size=28)+ k_text = m.MathTex(r"K/K_c =", font_size=28)+ r_text = m.MathTex(r"r =", font_size=28)+ readout = m.VGroup(+ m.VGroup(k_text, k_value).arrange(m.RIGHT, buff=0.12),+ m.VGroup(r_text, r_value).arrange(m.RIGHT, buff=0.12),+ ).arrange(m.RIGHT, buff=0.5)+ readout.next_to(law, m.DOWN, buff=0.2).align_to(law, m.RIGHT)+ readout.set_opacity(0.0)++ shown = m.ValueTracker(0.0) # the readouts' opacity (live numbers can't FadeIn)++ def read(mob: m.Mobject) -> None:+ k_value.set_value(coupling(clock[0]))+ k_value.next_to(k_text, m.RIGHT, buff=0.12)+ r_value.set_value(abs(order(state["theta"])))+ r_value.next_to(r_text, m.RIGHT, buff=0.12)+ readout.set_opacity(shown.get_value())++ k_value.add_updater(read)++ hud = [+ panel_l,+ ring,+ spot,+ dots,+ noise_ring,+ zoom_label,+ zoom_arrow,+ arrow_line,+ arrow_tip,+ z_label,+ panel_r,+ plot,+ theory,+ k_axis,+ r_axis,+ measured,+ now,+ readout,+ ]+ later = [law, noise, noise_label, kc_tick, theory_label, legend]+ self.add_fixed_in_frame_mobjects(title, subtitle, *hud, *later)+ self.remove(*later)++ # 0–7 s: coupling too weak: every firefly keeps its own time, r is noise+ self.begin_ambient_camera_rotation(rate=0.012)+ self.wait(1.0)+ self.play(+ m.Write(law), shown.animate.set_value(1.0), m.FadeIn(legend), run_time=1.5+ )+ self.wait(1.5)+ self.play(m.Create(noise), m.FadeIn(noise_label), run_time=1)+ self.wait(1.5)+ self.play(m.FadeIn(kc_tick), run_time=1)+ # 7–16 s: past K_c a cluster locks and grows along the exact curve+ self.wait(5)+ self.play(m.FadeIn(theory_label), run_time=1)+ self.wait(2.5)+ # 16–25 s: strong coupling: into the forest as it flashes as one+ self.move_camera(zoom=1.3, phi=82 * m.DEGREES, run_time=6)+ self.wait(3)+ closing = m.MathTex(+ r"\text{Past } K_c = 2\gamma\text{, the swarm keeps one time.}",+ font_size=30,+ ).next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(+ m.FadeOut(subtitle, shift=0.12 * m.UP),+ m.FadeIn(closing, shift=0.12 * m.UP),+ run_time=1.2,+ )+ # hold, and end as the swarm flashes: when the average phase ψ comes round to 0+ self.wait(2.8)+ for _ in range(90): # at most one flash period+ if -0.1 < np.angle(order(state["theta"])) <= 0:+ break+ self.wait(1 / 60)+++if __name__ == "__main__":+ KuramotoFireflies().render("kuramoto_fireflies.mp4")