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

Expand spatial, physical and computational gallery films

Sina Atalaycf6f5f6131bd
diff --git a/examples/README.md b/examples/README.md
index 84801560..2ce9137f 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -1,14 +1,75 @@
# Examples
-Thirty short films made with manimgx, each one Python file that needs only numpy. Every
+Forty-eight short films made with manimgx, each one Python file that needs only numpy. Every
number on screen is computed as the film plays.
Render one at 1920×1080, 60 fps:
```sh
-uv run python examples/hopf_fibration.py # writes hopf_fibration.mp4 to the current directory
+uv run --frozen python examples/quadratic_formula.py # writes quadratic_formula.mp4 to the current directory
```
+## Equations and proofs
+
+- [The quadratic formula](quadratic_formula.py): Completing the square turns an equation
+ into a picture. Each term keeps its color as rectangles move and the quadratic formula
+ emerges.
+- [Pythagoras by rearrangement](pythagoras.py): Moving four right triangles reveals why
+ a² + b² = c². The triangles and their enclosing square keep the same area throughout.
+- [Unrolling a circle](circle_area.py): Thin rings unroll into strips that stack into a
+ triangle. Its base is 2πr and its height is r, so its area is πr².
+- [Euler's identity as a walk](euler_identity.py): The terms of the exponential series
+ spiral toward −1 in the complex plane. Letting the angle vary carries their sum around
+ the unit circle.
+
+## Calculus
+
+- [What a derivative measures](derivative.py): A secant becomes a tangent as two points on
+ a curve come together. The tangent's changing slope traces the derivative's graph.
+- [Rectangles become an integral](riemann_sums.py): Thinner rectangles bring a sum closer
+ to the area under a curve. Each refinement splits the rectangles and updates the
+ measured area.
+- [Polynomials become the sine](taylor_series.py): Each new Taylor term makes a polynomial
+ follow more of the sine wave. The growing formula and its graph change together.
+- [A circle draws sine and cosine](unit_circle.py): A rotating radius traces sine and
+ cosine from its height and reach. The right triangle inside the circle also shows why
+ sin²θ + cos²θ = 1.
+
+## Planes and surfaces
+
+- [A matrix moves the plane](linear_maps.py): A matrix carries a grid, its basis arrows
+ and a unit square together. The determinant measures the changing area as the plane
+ shears, rotates, flattens and turns over.
+- [Complex functions bend the plane](complex_maps.py): A grid bends under z², the
+ exponential and the sine. Straight lines become parabolas, circles and rays as each
+ point travels to its image.
+- [Landscapes from formulas](surface_plots.py): A flat grid rises into an egg crate, a
+ saddle and a bell. Each surface is computed from its formula and bends into the next
+ as the camera turns.
+
+## Patterns and surprises
+
+- [Circles draw π](fourier_pi.py): A chain of rotating arrows traces the outline of π.
+ The arrows' lengths and phases come from the letter's Fourier coefficients, and the
+ camera follows the pen for a closer look.
+- [Times tables on a circle](times_tables.py): Joining numbers to their multiples around
+ a circle draws cardioids and other curves. Changing the multiplier continuously makes
+ the pattern turn, split and fold.
+- [Two blocks count π](colliding_blocks.py): Elastic collisions between two blocks and
+ a wall count out digits of π. Every collision is simulated, with the mass ratio setting
+ how many digits appear.
+- [Prime spirals](prime_spirals.py): Plotting primes at distance p and angle p reveals
+ spirals that become rays as the camera pulls back. Close approximations to 2π explain
+ the changing patterns.
+- [Hilbert's space-filling curve](hilbert_curve.py): A path visits every cell of a finer
+ and finer square grid. Four smaller copies, turned and joined, form the next order of
+ the Hilbert curve.
+- [A Galton board](galton_board.py): Repeated left-or-right bounces build a bell-shaped
+ pile of balls. The measured counts approach the binomial distribution beneath the pegs.
+- [The Lorenz attractor](lorenz_attractor.py): Eight nearly identical starting points
+ trace a butterfly and then drift apart. Both paths follow the Lorenz equations, showing
+ how a deterministic system can be chaotic.
+
## Geometry and topology
- [The Hopf fibration](hopf_fibration.py): The 3-sphere is made of circles, and every two of
diff --git a/examples/cherenkov_cone.py b/examples/cherenkov_cone.py
index eaa9608d..22a69bd5 100644
--- a/examples/cherenkov_cone.py
+++ b/examples/cherenkov_cone.py
@@ -225,7 +225,8 @@ class CherenkovCone(m.ThreeDScene):
rows = colormap(age, CHERENKOV)
# brighter bands (photons emitted together) slide down the cone: each is where one
# wavelet touches it
- pulse = 0.65 + 0.35 * np.cos(2 * np.pi * 2.5 * tank.photon_t)
+ emitted = np.where(tank.alive, tank.photon_t, 0)
+ pulse = 0.65 + 0.35 * np.cos(2 * np.pi * 2.5 * emitted)
fade = np.clip((1 - age) / 0.3, 0, 1) * tank.photon_w * pulse
shown = np.where(tank.alive, fade, 0) * glow.get_value()
for layer, alpha in ((mob, 1.0), (photon_halo, 0.07)):
diff --git a/examples/colliding_blocks.py b/examples/colliding_blocks.py
new file mode 100644
index 00000000..d8918fdf
--- /dev/null
+++ b/examples/colliding_blocks.py
@@ -0,0 +1,150 @@
+"""Two blocks count the digits of π.
+
+A small block rests between a wall and a big block sliding toward it. Every collision is
+perfectly elastic and there is no friction: the small block bounces between the wall and the
+big block until the big one turns back and nothing can catch it. Count the clacks. If the big
+block is 100ᵈ times heavier, the count is the first d + 1 digits of π: 3, 31, 314, 3141, …
+(Galperin, 2003). The reason is a circle: in the coordinates √m₁v₁ and √m₂v₂ the energy keeps
+the state on a circle, and each collision steps it along by the same angle, arctan √(m₁/m₂).
+Every clack here is simulated, and the counter counts them.
+"""
+
+import numpy as np
+
+import manimgx as m
+
+WALL = 11.8 # the README wall's 5 seconds start here
+FLOOR = -1.6
+WALL_X = -5.6
+SPEED = 2.2 # the big block's starting speed, screen units a second
+RUNS = [
+ (1, 1.0, 1.4),
+ (100, 1.4, 1.6),
+ (10_000, 1.9, 1.6),
+ (1_000_000, 2.3, 1.6),
+] # (ratio, its side, gap)
+
+
+def simulate(
+ ratio: float, small: float, big: float, gap: float
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """The collisions' times, and the blocks' left edges and velocities just after each
+ (the start counted as one), small block first."""
+ m1, m2 = 1.0, ratio
+ x1, x2 = WALL_X + 1.2, WALL_X + 1.2 + small + gap
+ v1, v2 = 0.0, -SPEED
+ t = 0.0
+ times, positions, velocities = [0.0], [(x1, x2)], [(v1, v2)]
+ while True:
+ # the next collision: the blocks meeting, or the small block reaching the wall
+ meet = (x2 - x1 - small) / (v1 - v2) if v1 > v2 else np.inf
+ wall = (x1 - WALL_X) / -v1 if v1 < 0 else np.inf
+ dt = min(meet, wall)
+ if not np.isfinite(dt):
+ break
+ t += dt
+ x1, x2 = x1 + v1 * dt, x2 + v2 * dt
+ if meet <= wall:
+ v1, v2 = (
+ ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2),
+ ((m2 - m1) * v2 + 2 * m1 * v1) / (m1 + m2),
+ )
+ else:
+ v1 = -v1
+ times.append(t)
+ positions.append((x1, x2))
+ velocities.append((v1, v2))
+ return np.array(times), np.array(positions), np.array(velocities), np.array([0])
+
+
+class CollidingBlocks(m.Scene):
+ def construct(self) -> None:
+ floor = m.Line([WALL_X, FLOOR, 0], [7.2, FLOOR, 0], stroke_width=3)
+ wall = m.Line([WALL_X, FLOOR, 0], [WALL_X, 3.0, 0], stroke_width=3)
+ hatches = m.VGroup(
+ *(
+ m.Line([WALL_X, y, 0], [WALL_X - 0.3, y - 0.3, 0], stroke_width=2)
+ for y in np.arange(FLOOR + 0.3, 3.0, 0.3)
+ )
+ )
+ counter_label = m.Tex("collisions:", font_size=60)
+ counter = m.Integer(0, font_size=72, color=m.YELLOW)
+ readout = m.VGroup(counter_label, counter).arrange(m.RIGHT, buff=0.3)
+ readout.move_to([0.8, 3.0, 0])
+ counter_place = counter.get_left()
+ self.play(
+ m.Create(floor),
+ m.Create(wall),
+ m.Create(hatches),
+ m.FadeIn(readout),
+ run_time=1,
+ )
+
+ record = m.VGroup() # the counts so far, under the counter
+ for ratio, side, gap in RUNS:
+ small_side = 0.7
+ times, positions, velocities, _ = simulate(ratio, small_side, side, gap)
+ clock = m.ValueTracker(0.0)
+ small = m.Square(
+ small_side,
+ fill_color=m.BLUE_E,
+ fill_opacity=1,
+ stroke_color=m.BLUE_B,
+ stroke_width=3,
+ )
+ big = m.Square(
+ side,
+ fill_color=m.BLUE_D,
+ fill_opacity=1,
+ stroke_color=m.BLUE_B,
+ stroke_width=3,
+ )
+ small.add(m.MathTex("1", font_size=36).move_to(small))
+ mass = f"{ratio:,}".replace(",", r"{,}")
+ big.add(m.MathTex(mass, font_size=40 if ratio < 10**6 else 32).move_to(big))
+
+ def place(
+ _: m.Mobject,
+ small: m.Mobject = small,
+ big: m.Mobject = big,
+ times: np.ndarray = times,
+ positions: np.ndarray = positions,
+ velocities: np.ndarray = velocities,
+ clock: m.ValueTracker = clock,
+ ) -> None:
+ t = clock.get_value()
+ k = int(np.searchsorted(times, t, side="right")) - 1
+ x1, x2 = positions[k] + velocities[k] * (t - times[k])
+ small.move_to([x1 + small.width / 2, FLOOR + small.height / 2, 0])
+ big.move_to([x2 + big.width / 2, FLOOR + big.height / 2, 0])
+ counter.set_value(k)
+ counter.move_to(counter_place, aligned_edge=m.LEFT)
+
+ blocks = m.VGroup(small, big)
+ blocks.add_updater(place)
+ place(blocks)
+ self.play(m.FadeIn(blocks, shift=0.3 * m.DOWN), run_time=0.6)
+ # until the big block has left the frame, or the last clack and a moment after
+ last = times[-1]
+ leave = (7.4 - positions[-1][1]) / max(velocities[-1][1], 1e-9) + last
+ duration = min(leave, last + 1.6)
+ self.play(
+ clock.animate.set_value(duration), run_time=duration, rate_func=m.linear
+ )
+ blocks.clear_updaters()
+ count = len(times) - 1
+ entry = m.MathTex(rf"{mass} : {count}", font_size=40, color=m.GREY_A)
+ record.add(entry)
+ record.arrange(m.DOWN, aligned_edge=m.RIGHT, buff=0.22)
+ record.move_to([WALL_X + 0.6, 2.75, 0], aligned_edge=m.UL)
+ self.play(
+ m.FadeOut(blocks), m.TransformFromCopy(counter, entry), run_time=0.8
+ )
+ digits = m.MathTex(r"\pi = 3.14159\ldots", font_size=64, color=m.YELLOW)
+ digits.next_to(readout, m.DOWN, buff=0.5)
+ self.play(m.Write(digits), run_time=1.2)
+ self.wait(2)
+
+
+if __name__ == "__main__":
+ CollidingBlocks().render("colliding_blocks.mp4")
diff --git a/examples/galton_board.py b/examples/galton_board.py
new file mode 100644
index 00000000..b82ddf70
--- /dev/null
+++ b/examples/galton_board.py
@@ -0,0 +1,209 @@
+"""Randomness that adds up to a bell: the Galton board.
+
+Every ball meets a peg in each of the board's rows and bounces left or right, at random, as
+if by a coin toss. The bin it lands in counts how many times it went right, so a ball's bin is
+a sum of coin tosses, and the number of balls in bin k follows the binomial distribution: of
+the 2ⁿ ways down, C(n, k) end in bin k. A few balls make a ragged pile; many make a bell, the
+normal curve with the binomial's mean n/2 and variance n/4 (de Moivre, 1733; Galton, 1889).
+"""
+
+import numpy as np
+
+import manimgx as m
+
+ROWS = 10 # rows of pegs; there are ROWS + 1 bins
+BALLS = 480
+DX, DY = 0.7, 0.34 # between pegs in a row, and between rows
+TOP = 3.1 # the first peg's height
+FLOOR = -3.75 # the bins' floor
+PEG, BALL = 0.05, 0.06 # radii
+GAP = 2.04 * BALL # between the centers of two balls side by side in a pile
+GRAVITY = 25.0 # scene units per second², in the board's own time
+HOP = 0.26 # seconds from one peg to the next, in the board's own time
+RELEASE = TOP + 0.62 # where balls are let go, in the funnel's neck
+SEED = 7
+WALL = 8.2
+
+
+def peg(row: int, k: int) -> np.ndarray:
+ """The k-th peg (from the left) of a row."""
+ return np.array([(k - row / 2) * DX, TOP - row * DY, 0.0])
+
+
+def pile(count: int) -> np.ndarray:
+ """Where the balls of a bin come to rest, relative to its floor's middle: rows of five
+ and of four in turn, packed, each row filled in a scattered order."""
+ fives = np.array([0.0, -2.0, 2.0, -1.0, 1.0]) * GAP
+ fours = np.array([-0.5, 1.5, 0.5, -1.5]) * GAP
+ places = np.empty((count, 2))
+ for s in range(count):
+ pair, r = divmod(s, 9)
+ layer, x = (2 * pair, fives[r]) if r < 5 else (2 * pair + 1, fours[r - 5])
+ places[s] = [x, BALL + layer * GAP * np.sqrt(3) / 2]
+ return places
+
+
+def release_times() -> np.ndarray:
+ """When each ball is let go, in board time: three alone, then faster and faster."""
+ first = [0.0, 1.4, 2.8]
+ times, s = list(first), 0.0
+ while len(times) < BALLS:
+ times.append(4.2 + s)
+ s += 1 / min(2 + 9 * s**2, 70) # balls per second, s seconds into the rush
+ return np.array(times)
+
+
+class Board:
+ """Every ball's way down, worked out in advance: its release, its bounces, its rest."""
+
+ def __init__(self, releases: np.ndarray, rng: np.random.Generator) -> None:
+ count = len(releases)
+ self.releases = releases
+ rights = rng.integers(0, 2, size=(count, ROWS)) # 1: it bounced right
+ self.bins = rights.sum(1)
+ before = np.concatenate([np.zeros((count, 1), int), np.cumsum(rights, 1)], 1)
+ rows = np.arange(ROWS)
+ # where it touches the peg of each row: above its center, by the two radii
+ self.contacts = np.stack(
+ [
+ (before[:, :ROWS] - rows / 2) * DX,
+ np.broadcast_to(TOP - rows * DY + PEG + BALL, (count, ROWS)),
+ ],
+ -1,
+ )
+ self.fall = float(np.sqrt(2 * (RELEASE - self.contacts[0, 0, 1]) / GRAVITY))
+ self.kick = (
+ GRAVITY * HOP**2 / 2 - DY
+ ) / HOP # up, off a peg: each hop drops DY
+ # it comes to rest in its bin on top of those that came before it
+ rank = np.zeros(count, int)
+ self.counts = np.zeros(ROWS + 1, int)
+ for i in np.argsort(releases, kind="stable"):
+ rank[i] = self.counts[self.bins[i]]
+ self.counts[self.bins[i]] += 1
+ places = pile(int(self.counts.max()))
+ self.rest = places[rank] + np.column_stack(
+ [(self.bins - ROWS / 2) * DX, np.full(count, FLOOR)]
+ )
+ drop = self.contacts[:, -1, 1] - self.rest[:, 1]
+ self.last = (self.kick + np.sqrt(self.kick**2 + 2 * GRAVITY * drop)) / GRAVITY
+ self.landed = releases + self.fall + (ROWS - 1) * HOP + self.last
+
+ def positions(self, t: float) -> np.ndarray:
+ """Where the balls let go by board time t are then, as rows (x, y, 0)."""
+ shown = self.releases <= t
+ u = t - self.releases[shown]
+ contacts, rest, last = self.contacts[shown], self.rest[shown], self.last[shown]
+ xy = np.empty((len(u), 2))
+ # falling onto the first peg
+ a = u < self.fall
+ xy[a, 0] = contacts[a, 0, 0]
+ xy[a, 1] = RELEASE - GRAVITY * u[a] ** 2 / 2
+ # hopping from peg to peg
+ bouncing = u - self.fall
+ h = (bouncing >= 0) & (bouncing < (ROWS - 1) * HOP)
+ hop = np.minimum((bouncing[h] // HOP).astype(int), ROWS - 2)
+ w = bouncing[h] - hop * HOP
+ here, there = contacts[h, hop], contacts[h, hop + 1]
+ xy[h, 0] = here[:, 0] + (there[:, 0] - here[:, 0]) * w / HOP
+ xy[h, 1] = here[:, 1] + self.kick * w - GRAVITY * w**2 / 2
+ # the last bounce, into the bin, onto the pile
+ f = bouncing >= (ROWS - 1) * HOP
+ w = np.minimum(bouncing[f] - (ROWS - 1) * HOP, last[f])
+ here = contacts[f, -1]
+ xy[f, 0] = here[:, 0] + (rest[f, 0] - here[:, 0]) * w / last[f]
+ flying = here[:, 1] + self.kick * w - GRAVITY * w**2 / 2
+ xy[f, 1] = np.where(w >= last[f], rest[f, 1], flying)
+ return np.column_stack([xy, np.zeros(len(u))])
+
+
+class GaltonBoard(m.Scene):
+ def construct(self) -> None:
+ board = Board(release_times(), np.random.default_rng(SEED))
+
+ pegs = m.VGroup(
+ *(
+ m.Dot(peg(r, k), radius=PEG, color=m.GREY_B)
+ for r in range(ROWS)
+ for k in range(r + 1)
+ )
+ )
+ wall_top = TOP - (ROWS - 1) * DY - 0.45
+ edges = (np.arange(ROWS + 2) - (ROWS + 1) / 2) * DX
+ bins = m.VGroup(
+ m.Line([edges[0], FLOOR, 0], [edges[-1], FLOOR, 0]),
+ *(m.Line([x, FLOOR, 0], [x, wall_top, 0]) for x in edges),
+ ).set_stroke(m.GREY_B, width=3)
+
+ funnel = m.VGroup(
+ m.Line([-0.5, RELEASE + 0.22, 0], [-0.1, RELEASE - 0.05, 0]),
+ m.Line([0.5, RELEASE + 0.22, 0], [0.1, RELEASE - 0.05, 0]),
+ ).set_stroke(m.GREY_B, width=3)
+
+ clock = m.ValueTracker(0.0) # the board's own time
+ balls = m.PMobject(stroke_width=200 * BALL)
+ blue = m.BLUE.to_rgba()
+
+ def place(cloud: m.Mobject) -> None:
+ points = board.positions(clock.get_value())
+ cloud.points = points
+ cloud.paint = cloud.paint.but(fill=np.tile(blue, (len(points), 1)))
+
+ balls.add_updater(place)
+ place(balls)
+
+ landed = m.Integer(0, font_size=56)
+ landed_row = m.VGroup(m.Tex("balls", font_size=44), landed)
+ landed_row.arrange(m.RIGHT, buff=0.3).to_corner(m.UL)
+ landed.add_updater(
+ lambda d: d.set_value(int(np.sum(board.landed <= clock.get_value())))
+ )
+
+ self.add(balls)
+ self.play(
+ m.LaggedStart(*(m.FadeIn(p, scale=0.5) for p in pegs), lag_ratio=0.02),
+ m.Create(bins),
+ m.Create(funnel),
+ m.FadeIn(landed_row),
+ run_time=1.2,
+ )
+
+ # the board's clock against the film's: 0.8 of life while three balls fall alone,
+ # then speeding up to twice life as the rest pour in
+ end = float(board.landed.max()) + 0.2
+ film = np.linspace(0, 30, 3001)
+ speed = np.interp(film, [0, 5.0, 8.0], [0.8, 0.8, 2.0])
+ board_time = np.concatenate(
+ [[0], np.cumsum((speed[1:] + speed[:-1]) / 2 * np.diff(film))]
+ )
+ seconds = float(np.interp(end, board_time, film))
+
+ def pace(alpha: float) -> float:
+ return float(np.interp(alpha * seconds, film, board_time)) / end
+
+ self.play(clock.animate.set_value(end), run_time=seconds, rate_func=pace)
+
+ # the bell: the normal curve with the binomial's mean and variance, over the bins
+ mean, variance = ROWS / 2, ROWS / 4
+ per_ball = GAP * np.sqrt(3) / 9 # a pile's height, per ball in it
+
+ def bell(x: float) -> float:
+ k = x / DX + ROWS / 2 # x, in bins
+ density = np.exp(-((k - mean) ** 2) / (2 * variance)) / np.sqrt(
+ 2 * np.pi * variance
+ )
+ return FLOOR + BALLS * density * per_ball
+
+ curve = m.FunctionGraph(bell, x_range=[edges[0], edges[-1]], color=m.YELLOW)
+ curve.set_stroke(width=6)
+ label = m.VGroup(
+ m.MathTex(rf"\mu = {mean:g}", font_size=52),
+ m.MathTex(rf"\sigma^2 = {variance:g}", font_size=52),
+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.25)
+ label.set_color(m.YELLOW).move_to(np.array([edges[-1] + 1.6, FLOOR + 2.2, 0.0]))
+ self.play(m.Create(curve), m.FadeIn(label), run_time=2.0)
+ self.wait(2.0)
+
+
+if __name__ == "__main__":
+ GaltonBoard().render("galton_board.mp4")
diff --git a/examples/life_spacetime.py b/examples/life_spacetime.py
new file mode 100644
index 00000000..8115b08a
--- /dev/null
+++ b/examples/life_spacetime.py
@@ -0,0 +1,240 @@
+"""The Game of Life in spacetime: stack the generations and gliders become staircases.
+
+Conway's Game of Life: a live cell survives with two or three live neighbours, a dead one comes
+alive with exactly three. Bill Gosper's glider gun (1970) is a pattern that fires a glider every
+30 generations — the first proof that a finite pattern can grow forever. Stack each generation
+on top of the one before, so height is time, and every cell becomes a column that lasts as long
+as the cell does: the gun is a tower that repeats every 30 layers, the blocks that hold it in
+place are pillars, and each glider is a staircase leaning away at one cell per four generations
+in each direction — the speed of light of this universe is one cell per generation; gliders
+travel at a quarter of it, diagonally.
+"""
+
+import numpy as np
+
+import manimgx as m
+
+GUN = [
+ (5, 1),
+ (5, 2),
+ (6, 1),
+ (6, 2),
+ (5, 11),
+ (6, 11),
+ (7, 11),
+ (4, 12),
+ (8, 12),
+ (3, 13),
+ (9, 13),
+ (3, 14),
+ (9, 14),
+ (6, 15),
+ (4, 16),
+ (8, 16),
+ (5, 17),
+ (6, 17),
+ (7, 17),
+ (6, 18),
+ (3, 21),
+ (4, 21),
+ (5, 21),
+ (3, 22),
+ (4, 22),
+ (5, 22),
+ (2, 23),
+ (6, 23),
+ (1, 25),
+ (2, 25),
+ (6, 25),
+ (7, 25),
+ (3, 35),
+ (4, 35),
+ (3, 36),
+ (4, 36),
+]
+SIZE = 64 # the board
+GENERATIONS = 126
+CELL = 0.105 # a cell's side on screen
+LAYER = 0.042 # the height of one generation
+STOPS = ["#9d4edd", "#4361ee", "#4cc9f0", "#80ffdb", "#ffd166", "#ff7b54"]
+FOCUS = np.array([-0.2, 1.05, 0.0]) # the middle of the action: the gun and its gliders
+
+
+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 history() -> np.ndarray:
+ """Every generation of the gun on the board: (GENERATIONS, SIZE, SIZE) booleans."""
+ board = np.zeros((SIZE, SIZE), bool)
+ for r, c in GUN:
+ board[r + 3, c + 2] = True
+ frames = []
+ for _ in range(GENERATIONS):
+ frames.append(board.copy())
+ padded = np.pad(board, 1)
+ neighbours = sum(
+ padded[1 + dy : SIZE + 1 + dy, 1 + dx : SIZE + 1 + dx].astype(int)
+ for dy in (-1, 0, 1)
+ for dx in (-1, 0, 1)
+ if (dy, dx) != (0, 0)
+ )
+ board = (neighbours == 3) | (board & (neighbours == 2))
+ return np.array(frames)
+
+
+def runs(frames: np.ndarray) -> np.ndarray:
+ """Every stretch of generations a cell stays alive: rows (row, column, first, last)."""
+ alive = np.pad(frames, ((1, 1), (0, 0), (0, 0)))
+ starts = np.argwhere(alive[1:-1] & ~alive[:-2])
+ ends = np.argwhere(alive[1:-1] & ~alive[2:])
+ starts = starts[np.lexsort((starts[:, 0], starts[:, 2], starts[:, 1]))]
+ ends = ends[np.lexsort((ends[:, 0], ends[:, 2], ends[:, 1]))]
+ return np.column_stack([starts[:, 1], starts[:, 2], starts[:, 0], ends[:, 0]])
+
+
+# the six faces of a unit box, as corner indices (bit 0: x, bit 1: y, bit 2: z), outward
+BOX_FACES = np.array(
+ [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]]
+)
+
+
+def columns(
+ spans: np.ndarray, now: float, depth: float
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """The columns alive between generations now − depth and now, the oldest shown at height 0:
+ vertices, triangles, colors (by generation)."""
+ first = np.maximum(spans[:, 2], now - depth)
+ last = np.minimum(spans[:, 3] + 1, now + 1)
+ keep = last > first
+ s, first, last = spans[keep], first[keep], last[keep]
+ base = max(now - depth, 0.0)
+ x0 = (s[:, 1] - SIZE / 2) * CELL
+ y0 = (SIZE / 2 - s[:, 0]) * CELL
+ inset = 0.08 * CELL
+ lo = np.stack([x0 + inset, y0 - CELL + inset, (first - base) * LAYER], 1)
+ hi = np.stack(
+ [
+ x0 + CELL - inset,
+ y0 - inset,
+ np.maximum((last - base) * LAYER, (first - base) * LAYER + 0.012),
+ ],
+ 1,
+ )
+ bits = np.array([[(k >> 0) & 1, (k >> 1) & 1, (k >> 2) & 1] for k in range(8)])
+ corners = lo[:, None, :] + bits[None] * (hi - lo)[:, None, :] # (columns, 8, 3)
+ quads = corners[:, BOX_FACES] # (columns, 6, 4, 3)
+ verts = quads.reshape(-1, 3)
+ faces = np.arange(len(s) * 6)[:, None] * 4
+ tris = np.concatenate([faces + [0, 1, 2], faces + [0, 2, 3]])
+ generation = np.where(
+ bits[BOX_FACES][..., 2] == 1, last[:, None, None] - 1, first[:, None, None]
+ )
+ rows = colormap((generation / GENERATIONS).reshape(-1), STOPS)
+ return verts, tris, rows
+
+
+class LifeSpacetime(m.ThreeDScene):
+ def construct(self) -> None:
+ spans = runs(history())
+ now = m.ValueTracker(0.0)
+ depth = m.ValueTracker(
+ 0.0
+ ) # how many past generations stand below the present one
+ stack = m.MeshMobject(*columns(spans, 0.0, 0.0)[:2], shade_in_3d=True)
+
+ def rebuild(mob: m.Mobject) -> None:
+ assert isinstance(mob, m.MeshMobject)
+ g = float(np.floor(now.get_value()))
+ verts, tris, rows = columns(spans, g, float(np.floor(depth.get_value())))
+ mob.points, mob.triangles = verts, tris
+ mob.paint = mob.paint.but(fill=rows)
+
+ rebuild(stack)
+ stack.add_updater(rebuild)
+ board = m.Square(
+ side_length=SIZE * CELL,
+ stroke_color=m.GREY_D,
+ stroke_width=1.5,
+ fill_color="#0b0f1a",
+ fill_opacity=1,
+ )
+ board.shift(0.001 * m.IN)
+
+ title = m.Text("The Game of Life in spacetime", font_size=38).to_corner(m.UL)
+ subtitle = m.Text(
+ "Gosper's glider gun: a glider every 30 generations", font_size=22
+ ).set_color(m.GREY_B)
+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)
+ generation = m.Integer(0, font_size=30)
+ generation.add_updater(lambda d: d.set_value(int(now.get_value())))
+ counter = (
+ m.VGroup(m.Text("generation", font_size=26), generation)
+ .arrange(m.RIGHT, buff=0.15)
+ .to_corner(m.UR)
+ )
+ self.add_fixed_in_frame_mobjects(title, subtitle, counter)
+
+ # 0–6 s: from above: the gun, one generation at a time
+ self.set_camera_orientation(
+ phi=0,
+ theta=-90 * m.DEGREES,
+ focal_distance=60,
+ zoom=1.9,
+ frame_center=np.array([-1.3, 2.35, 0.0]),
+ )
+ self.add(board, stack)
+ self.play(now.animate.set_value(34), run_time=5.5, rate_func=m.linear)
+
+ # 6–11 s: keep every generation, each one on top of the last: height is time
+ up = (
+ m.Text("height = time", font_size=26)
+ .set_color(m.YELLOW)
+ .next_to(counter, m.DOWN, aligned_edge=m.RIGHT, buff=0.25)
+ )
+ self.add_fixed_in_frame_mobjects(up)
+ self.remove(up)
+ self.move_camera(
+ phi=62 * m.DEGREES,
+ theta=-65 * m.DEGREES,
+ focal_distance=18,
+ zoom=1.0,
+ frame_center=FOCUS + np.array([0, 0, 1.2]),
+ added_anims=[
+ now.animate.set_value(54),
+ depth.animate.set_value(54),
+ m.FadeIn(up),
+ ],
+ run_time=5,
+ rate_func=m.linear,
+ )
+
+ # 11–24 s: the tower grows; gliders lean away as staircases
+ self.begin_ambient_camera_rotation(rate=0.12)
+ self.play(
+ now.animate.set_value(GENERATIONS - 1),
+ depth.animate.set_value(GENERATIONS - 1),
+ self.camera.frame.animate.move_to(FOCUS + np.array([0, 0, 2.7])),
+ self.camera.zoom_tracker.animate.set_value(0.88),
+ run_time=12,
+ rate_func=m.linear,
+ )
+
+ # 24–30 s: the poster
+ closing = m.Text(
+ "each glider climbs one cell every four generations: c/4", font_size=26
+ ).to_edge(m.DOWN, buff=0.35)
+ self.add_fixed_in_frame_mobjects(closing)
+ self.remove(closing)
+ self.play(m.FadeIn(closing), run_time=1)
+ self.wait(5.8)
+
+
+if __name__ == "__main__":
+ LifeSpacetime().render("life_spacetime.mp4")
diff --git a/examples/lorenz_attractor.py b/examples/lorenz_attractor.py
new file mode 100644
index 00000000..5855e0fc
--- /dev/null
+++ b/examples/lorenz_attractor.py
@@ -0,0 +1,112 @@
+"""Chaos: the Lorenz attractor.
+
+In 1963 Edward Lorenz cut a model of convection down to three equations, ẋ = σ(y − x),
+ẏ = x(ρ − z) − y, ż = xy − βz, and found that it never settles and never repeats: a point winds
+around one lobe, then the other, in an order no one can predict. Here eight points start a
+ten-thousandth apart. For a while they travel as one curve; then the difference doubles about
+every three quarters of a unit of time, they split, and each weaves the same butterfly its own
+way. The paths are integrated as they are drawn (fourth-order Runge–Kutta, σ = 10, ρ = 28,
+β = 8/3).
+"""
+
+import numpy as np
+
+import manimgx as m
+
+WALL = 7.5 # the README wall's 5 seconds start here
+SIGMA, RHO, BETA = 10.0, 28.0, 8.0 / 3.0
+DT, STEPS = 0.004, 6500 # 26 units of time
+SETTLE = 3000 # steps run before the paths start, so that they start on the attractor
+PATHS = 8
+SCALE = 0.115 # screen units per unit of the system
+GROW = 22.0 # seconds the paths take to grow
+
+
+def lorenz(p: np.ndarray) -> np.ndarray:
+ x, y, z = p[..., 0], p[..., 1], p[..., 2]
+ return np.stack([SIGMA * (y - x), x * (RHO - z) - y, x * y - BETA * z], axis=-1)
+
+
+def step(p: np.ndarray) -> np.ndarray:
+ """One step of fourth-order Runge–Kutta."""
+ a = lorenz(p)
+ b = lorenz(p + DT / 2 * a)
+ c = lorenz(p + DT / 2 * b)
+ d = lorenz(p + DT * c)
+ return p + DT / 6 * (a + 2 * b + 2 * c + d)
+
+
+def integrate(starts: np.ndarray) -> np.ndarray:
+ """Each start's path, (paths, STEPS + 1, 3)."""
+ out = np.empty((len(starts), STEPS + 1, 3))
+ p = starts.astype(float)
+ out[:, 0] = p
+ for k in range(STEPS):
+ p = step(p)
+ out[:, k + 1] = p
+ return out
+
+
+class LorenzAttractor(m.ThreeDScene):
+ def construct(self) -> None:
+ settled = np.array([0.0, 1.0, 1.05])
+ for _ in range(SETTLE):
+ settled = step(settled)
+ starts = settled + np.outer(np.arange(PATHS), [1e-4, 0, 0])
+ paths = integrate(starts)
+ center = np.array([0.0, 0.0, 25.0])
+ colors = m.color_gradient(
+ [m.BLUE, m.TEAL, m.GREEN, m.YELLOW, m.GOLD, m.RED, m.MAROON, m.PURPLE],
+ PATHS,
+ )
+
+ def to_screen(points: np.ndarray) -> np.ndarray:
+ return (points - center) * SCALE
+
+ clock = m.ValueTracker(0.0) # how much of the paths is drawn, 0 to 1
+ fulls, curves, heads = [], m.VGroup(), m.VGroup()
+ for path, color in zip(paths, colors, strict=True):
+ full = m.VMobject(stroke_color=color, stroke_width=2.2, stroke_opacity=0.85)
+ full.set_points_as_corners(to_screen(path))
+ fulls.append(full)
+ curve = full.copy()
+ curve.pointwise_become_partial(full, 0, 0)
+ curves.add(curve)
+ heads.add(m.Dot3D(to_screen(path[0]), radius=0.07, color=color))
+
+ def grow(group: m.VGroup) -> None:
+ t = clock.get_value()
+ k = min(int(t * STEPS), STEPS)
+ for curve, full, head, path in zip(
+ curves, fulls, heads, paths, strict=True
+ ):
+ assert isinstance(curve, m.VMobject)
+ curve.pointwise_become_partial(full, 0, max(t, 1e-6))
+ head.move_to(to_screen(path[k]))
+
+ everything = m.VGroup(curves, heads)
+ everything.add_updater(grow)
+
+ equations = m.MathTex(
+ r"\dot x &= \sigma (y - x) \\ \dot y &= x(\rho - z) - y \\ \dot z &= xy - \beta z",
+ font_size=44,
+ ).to_corner(m.UL, buff=0.5)
+ self.add_fixed_in_frame_mobjects(equations)
+ self.remove(equations)
+
+ # the lobes lie along x = y: the camera swings slowly through the view that shows
+ # them side by side (θ = −45°)
+ self.set_camera_orientation(
+ phi=68 * m.DEGREES, theta=-88 * m.DEGREES, zoom=1.05
+ )
+ self.begin_ambient_camera_rotation(rate=0.05)
+ self.play(m.FadeIn(heads), m.Write(equations), run_time=1.5)
+ self.add(everything)
+ self.play(clock.animate.set_value(1.0), run_time=GROW, rate_func=m.linear)
+ everything.clear_updaters()
+ self.play(m.FadeOut(heads), run_time=1)
+ self.wait(2.5)
+
+
+if __name__ == "__main__":
+ LorenzAttractor().render("lorenz_attractor.mp4")
diff --git a/examples/neural_untangle.py b/examples/neural_untangle.py
new file mode 100644
index 00000000..a292bdf2
--- /dev/null
+++ b/examples/neural_untangle.py
@@ -0,0 +1,270 @@
+"""How a neural network untangles two spirals.
+
+No straight line separates two interleaved spirals, and no smooth deformation of the plane can pull
+them apart: in 2D one arm would have to pass through the other. A small residual network lifts
+the plane into 3D instead. Each of its four layers nudges every point, h ↦ h + V tanh(Uh + c), and
+training pays for how far points move, so the network learns the cheapest way to untangle. Here
+that means raising one arm above the other, until one flat plane cuts the two colors apart (after
+Olah, "Neural Networks, Manifolds, and Topology", 2014). Carried back through the layers, that
+flat cut becomes the winding boundary between the arms in the input plane.
+"""
+
+from dataclasses import dataclass
+
+import numpy as np
+
+import manimgx as m
+
+LAYERS, HIDDEN = 4, 16
+TURNS = 1.25 # of each spiral
+ENERGY = 0.3 # the price of moving points: small, direct moves win
+SEED = 0
+SCALE = 2.4 # screen units per unit of the network's space
+COLORS = ["#ff9f1c", "#2ec4b6"]
+
+
+def two_spirals(count: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
+ """Two interleaved spirals of TURNS turns in the unit disk, and their labels (0, 1)."""
+ turn = np.sqrt(rng.uniform(0.04, 1, count)) * TURNS * m.TAU
+ arm = np.stack([np.cos(turn), np.sin(turn)], 1) * (turn / (TURNS * m.TAU))[:, None]
+ arm += 0.02 * rng.normal(size=arm.shape)
+ return np.concatenate([arm, -arm]), np.repeat([0.0, 1.0], count)
+
+
+@dataclass
+class Network:
+ u: list[np.ndarray] # (HIDDEN, 3) per layer
+ c: list[np.ndarray] # (HIDDEN,)
+ v: list[np.ndarray] # (3, HIDDEN)
+ w: np.ndarray # the classifier's normal
+ b: np.ndarray # and offset, shape (1,)
+
+ def run(self, x: np.ndarray) -> tuple[list[np.ndarray], list[np.ndarray]]:
+ """The points at every stage (the input in the plane z = 0, then after each layer) and
+ each layer's hidden activations."""
+ h = np.column_stack([x, np.zeros(len(x))])
+ stages, hidden = [h], []
+ for u, c, v in zip(self.u, self.c, self.v):
+ a = np.tanh(h @ u.T + c)
+ h = h + a @ v.T
+ stages.append(h)
+ hidden.append(a)
+ return stages, hidden
+
+ def stages(self, x: np.ndarray) -> list[np.ndarray]:
+ return self.run(x)[0]
+
+ def logit(self, x: np.ndarray) -> np.ndarray:
+ return self.stages(x)[-1] @ self.w + self.b[0]
+
+
+def train(
+ x: np.ndarray, y: np.ndarray, rng: np.random.Generator, steps: int = 6000
+) -> Network:
+ """Logistic loss plus ENERGY × the mean squared move of each layer; full-batch Adam, with
+ backpropagation written out."""
+ net = Network(
+ [0.5 * rng.normal(size=(HIDDEN, 3)) for _ in range(LAYERS)],
+ [0.5 * rng.normal(size=HIDDEN) for _ in range(LAYERS)],
+ [0.1 * rng.normal(size=(3, HIDDEN)) for _ in range(LAYERS)],
+ rng.normal(size=3),
+ np.zeros(1),
+ )
+ params = [*net.u, *net.c, *net.v, net.w, net.b]
+ first = [np.zeros_like(p) for p in params]
+ second = [np.zeros_like(p) for p in params]
+ n = len(x)
+ for step in range(1, steps + 1):
+ stages, hidden = net.run(x)
+ prob = 1 / (1 + np.exp(-(stages[-1] @ net.w + net.b[0])))
+ g = (prob - y) / n # d loss / d logit
+ grad_u: list[np.ndarray] = [np.zeros(0)] * LAYERS
+ grad_c: list[np.ndarray] = [np.zeros(0)] * LAYERS
+ grad_v: list[np.ndarray] = [np.zeros(0)] * LAYERS
+ grad_w, grad_b = stages[-1].T @ g, np.array([g.sum()])
+ back = np.outer(g, net.w) # d loss / d h, from the top down
+ for k in reversed(range(LAYERS)):
+ move = hidden[k] @ net.v[k].T
+ through = back + 2 * ENERGY * move / n
+ grad_v[k] = through.T @ hidden[k]
+ pre = (through @ net.v[k]) * (1 - hidden[k] ** 2)
+ grad_u[k], grad_c[k] = pre.T @ stages[k], pre.sum(0)
+ back = (
+ back + pre @ net.u[k]
+ ) # h passes through each layer unchanged, plus its move
+ for i, (p, grad) in enumerate(
+ zip(params, [*grad_u, *grad_c, *grad_v, grad_w, grad_b])
+ ):
+ first[i] = 0.9 * first[i] + 0.1 * grad
+ second[i] = 0.999 * second[i] + 0.001 * grad**2
+ p -= (
+ 0.02
+ * (first[i] / (1 - 0.9**step))
+ / (np.sqrt(second[i] / (1 - 0.999**step)) + 1e-8)
+ )
+ return net
+
+
+def boundary(net: Network, size: float = 1.15, n: int = 240) -> np.ndarray:
+ """The network's decision boundary in the input plane (logit = 0), by marching squares:
+ segments as (count, 2, 2)."""
+ s = np.linspace(-size, size, n)
+ gx, gy = np.meshgrid(s, s, indexing="ij")
+ f = net.logit(np.column_stack([gx.ravel(), gy.ravel()])).reshape(n, n)
+ segments = []
+ corners = [(0, 0), (1, 0), (1, 1), (0, 1)]
+ for i in range(n - 1):
+ for j in range(n - 1):
+ values = [f[i + di, j + dj] for di, dj in corners]
+ crossings = []
+ for k in range(4):
+ (ai, aj), (bi, bj) = corners[k], corners[(k + 1) % 4]
+ fa, fb = values[k], values[(k + 1) % 4]
+ if (fa < 0) != (fb < 0):
+ t = fa / (fa - fb)
+ crossings.append(
+ [
+ s[i + ai] + t * (s[i + bi] - s[i + ai]),
+ s[j + aj] + t * (s[j + bj] - s[j + aj]),
+ ]
+ )
+ if len(crossings) == 2:
+ segments.append(crossings)
+ return np.array(segments)
+
+
+class NeuralUntangle(m.ThreeDScene):
+ def construct(self) -> None:
+ rng = np.random.default_rng(SEED)
+ x, y = two_spirals(300, rng)
+ net = train(x, y, rng)
+ accuracy = float(np.mean((net.logit(x) > 0) == (y == 1)))
+ # 0: the input plane; k: after layer k (in between: a blend of the two)
+ stage = m.ValueTracker(0.0)
+
+ def at(stages: list[np.ndarray]) -> np.ndarray:
+ s = stage.get_value()
+ k = min(int(s), LAYERS - 1)
+ f = s - k
+ return SCALE * ((1 - f) * stages[k] + f * stages[k + 1])
+
+ # the grid of the input plane, and the data, carried through every layer
+ # (the grid's lines are cut off at radius 1.2: far from the data the layers are wild)
+ grid_inputs = []
+ for t in np.linspace(-1.1, 1.1, 13):
+ half = np.sqrt(1.2**2 - t**2)
+ along = np.linspace(-half, half, 90)
+ grid_inputs += [
+ np.column_stack([np.full(90, t), along]),
+ np.column_stack([along, np.full(90, t)]),
+ ]
+ grid_stages = [net.stages(g) for g in grid_inputs]
+ grid = m.VGroup(
+ *[
+ m.VMobject(stroke_color="#5c677d", stroke_width=1.4, shade_in_3d=True)
+ for _ in grid_inputs
+ ]
+ )
+
+ def bend_grid(group: m.Mobject) -> None:
+ for line, stages in zip(group.submobjects, grid_stages):
+ assert isinstance(line, m.VMobject)
+ line.set_points_as_corners(at(stages))
+
+ bend_grid(grid)
+ grid.add_updater(bend_grid)
+ data_stages = net.stages(x)
+ rows = np.ones((len(x), 4))
+ rows[:, :3] = np.array([m.ManimColor(c).to_rgb() for c in COLORS])[
+ y.astype(int)
+ ]
+ data = m.PMobject(stroke_width=7)
+ data.add_points(at(data_stages), rgbas=rows)
+
+ def carry(mob: m.Mobject) -> None:
+ mob.points = at(data_stages)
+
+ data.add_updater(carry)
+
+ # the classifier: a plane in the last layer's space, w·h + b = 0
+ normal = net.w / np.linalg.norm(net.w)
+ foot = -net.b[0] * net.w / float(net.w @ net.w)
+ u = np.cross(normal, [0.3, 0.5, 0.8])
+ u /= np.linalg.norm(u)
+ v = np.cross(normal, u)
+ cut = m.Polygon(
+ *[
+ SCALE * (foot + 1.3 * (a * u + b * v))
+ for a, b in [(-1, -1), (1, -1), (1, 1), (-1, 1)]
+ ],
+ stroke_width=1.5,
+ stroke_color=m.WHITE,
+ fill_color=m.WHITE,
+ fill_opacity=0.18,
+ shade_in_3d=True,
+ )
+ # the boundary it cuts: a curve on the sheet, drawn back to the input plane at the end
+ pieces = boundary(net)
+ piece_stages = net.stages(pieces.reshape(-1, 2))
+ edge = m.VMobject(stroke_color=m.WHITE, stroke_width=3.5, shade_in_3d=True)
+
+ def trace_edge(mob: m.Mobject) -> None:
+ assert isinstance(mob, m.VMobject)
+ ends = at(piece_stages).reshape(-1, 2, 3)
+ mob.reset_points()
+ for a, b in zip(ends[:, 0], ends[:, 1]):
+ mob.start_new_path(a)
+ mob.add_line_to(b)
+
+ trace_edge(edge)
+ edge.add_updater(trace_edge)
+
+ # HUD
+ title = m.Text("How a network untangles two spirals", font_size=38).to_corner(
+ m.UL
+ )
+ subtitle = m.Text(
+ "four residual layers, each nudging space: h ↦ h + V tanh(Uh + c)",
+ font_size=22,
+ ).set_color(m.GREY_B)
+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)
+ layer_value = m.Integer(0, font_size=30)
+ layer_value.add_updater(lambda d: d.set_value(int(round(stage.get_value()))))
+ layer_row = m.VGroup(m.Text("layer", font_size=28), layer_value).arrange(
+ m.RIGHT, buff=0.15
+ )
+ layer_row.to_corner(m.UR)
+ score = m.Text(
+ f"one flat cut separates them: {100 * accuracy:.0f}% of points",
+ font_size=24,
+ ).to_edge(m.DOWN, buff=0.35)
+ back = m.Text(
+ "carried back to the input, the flat cut winds between the arms",
+ font_size=24,
+ ).to_edge(m.DOWN, buff=0.35)
+ self.add_fixed_in_frame_mobjects(title, subtitle, layer_row, score, back)
+ self.remove(score, back)
+
+ self.set_camera_orientation(phi=35 * m.DEGREES, theta=-90 * m.DEGREES, zoom=1.0)
+ self.add(grid, data)
+ self.wait(1.5)
+ self.begin_ambient_camera_rotation(rate=0.12)
+ self.move_camera(phi=64 * m.DEGREES, run_time=2)
+ for k in range(1, LAYERS + 1):
+ self.play(stage.animate.set_value(k), run_time=3.2)
+ self.wait(0.3)
+ self.play(m.FadeIn(cut), m.FadeIn(score), m.Create(edge), run_time=1.5)
+ self.wait(2.5)
+ self.play(m.FadeOut(cut), m.FadeOut(score), run_time=0.6)
+ self.play(
+ stage.animate.set_value(0),
+ m.FadeIn(back, rate_func=m.rush_from),
+ run_time=4.4,
+ )
+ self.stop_ambient_camera_rotation()
+ self.move_camera(phi=20 * m.DEGREES, theta=-90 * m.DEGREES, run_time=2)
+ self.wait(1.5)
+
+
+if __name__ == "__main__":
+ NeuralUntangle().render("neural_untangle.mp4")
diff --git a/examples/riemann_surfaces.py b/examples/riemann_surfaces.py
new file mode 100644
index 00000000..e2ba60d5
--- /dev/null
+++ b/examples/riemann_surfaces.py
@@ -0,0 +1,248 @@
+"""Where √z lives: two sheets — and log z, an endless staircase.
+
+Walk once around 0 and √z comes back negated: √(r e^{iθ}) = √r e^{iθ/2}, and θ → θ + 2π flips
+e^{iθ/2}. Walk around twice and it returns. So √z is not a function on the plane but on a
+surface with two sheets over it (Riemann, 1851): here the height is Re √z and the color is the
+angle of √z, and the walker's value — measured from the surface it stands on — flips sign after
+one loop and comes back after two. The same plane grid then bends into log z = ln r + iθ, whose
+height Im log z climbs 2π with every loop: an infinite spiral staircase.
+"""
+
+import numpy as np
+
+import manimgx as m
+
+R_MAX = 2.5
+TURNS = 2 # the grid covers θ ∈ [0, 4π): both sheets of √z, two floors of log z
+NR, NT = 40, 360
+WALK = 1.8 # the walker's |z|
+FLOOR = 1.6 # the staircase rises this much per turn (on screen)
+
+
+def lifted(r: np.ndarray, theta: np.ndarray, blend: float) -> np.ndarray:
+ """The surface: height Re √z (blend 0) bending into Im log z (blend 1), over z = r e^{iθ}."""
+ root = np.sqrt(r) * np.cos(theta / 2)
+ stairs = FLOOR * (theta / m.TAU - TURNS / 2)
+ return np.stack(
+ [r * np.cos(theta), r * np.sin(theta), (1 - blend) * root + blend * stairs], -1
+ )
+
+
+def hues(theta: np.ndarray, r: np.ndarray) -> np.ndarray:
+ """Color by the angle of the lifted point (θ/2 for √z: once around the rainbow over two
+ turns), with soft rings in |z| for texture."""
+ hue = (theta / (TURNS * m.TAU)) % 1.0
+ k = np.arange(3)[None, :]
+ rgb = 0.5 + 0.5 * np.cos(m.TAU * (hue[:, None] - k / 3))
+ shade = 0.72 + 0.28 * np.cos(m.TAU * 2.5 * np.log(r + 0.05))[:, None]
+ rows = np.ones((len(hue), 4))
+ rows[:, :3] = np.clip(0.15 + 0.8 * rgb * shade, 0, 1)
+ return rows
+
+
+def tube(
+ points: np.ndarray, radius: float, sides: int = 10
+) -> tuple[np.ndarray, np.ndarray]:
+ """A lit tube along a polyline (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])
+ 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) + 1e-12))
+ 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 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,
+ )
+
+
+class RiemannSurfaces(m.ThreeDScene):
+ def construct(self) -> None:
+ rr, tt = np.meshgrid(
+ np.linspace(0.02, R_MAX, NR + 1),
+ np.linspace(0, TURNS * m.TAU, NT + 1),
+ indexing="ij",
+ )
+ blend = m.ValueTracker(0.0)
+ sheet = grid_mesh(NR, NT)
+ sheet.paint = sheet.paint.but(fill=hues(tt.ravel(), rr.ravel()))
+
+ def bend(mob: m.Mobject) -> None:
+ mob.points = lifted(rr, tt, blend.get_value()).reshape(-1, 3)
+
+ bend(sheet)
+ sheet.add_updater(bend)
+
+ # the walker goes around 0 at |z| = WALK; its path on the surface is a glowing tube
+ angle = m.ValueTracker(0.0)
+ walker = m.Dot3D(radius=0.09, color=m.WHITE)
+
+ def on_surface(theta: np.ndarray) -> np.ndarray:
+ return lifted(
+ np.full_like(theta, WALK), theta, blend.get_value()
+ ) + np.array([0, 0, 0.03])
+
+ def place(dot: m.Mobject) -> None:
+ dot.move_to(on_surface(np.array([angle.get_value()]))[0])
+
+ walker.add_updater(place)
+ path = m.MeshMobject(
+ *tube(on_surface(np.linspace(0, 0.01, 3)), 0.035),
+ shade_in_3d=True,
+ fill_color=m.WHITE,
+ )
+
+ def trace(mob: m.Mobject) -> None:
+ span = max(angle.get_value(), 0.02)
+ verts, tris = tube(
+ on_surface(np.linspace(0, span, max(3, int(span * 40)))), 0.035
+ )
+ assert isinstance(mob, m.MeshMobject)
+ mob.points, mob.triangles = verts, tris
+
+ path.add_updater(trace)
+
+ # the walker's value, read from where it stands (√z, then log z)
+ title = m.Text("Where √z lives", font_size=40).to_corner(m.UL)
+ subtitle = m.Text(
+ "height: Re √z · color: the angle of √z", font_size=22
+ ).set_color(m.GREY_B)
+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)
+ real_part = m.DecimalNumber(
+ np.sqrt(WALK), num_decimal_places=2, include_sign=True, font_size=32
+ )
+ imag_part = m.DecimalNumber(
+ 0, num_decimal_places=2, include_sign=True, font_size=32
+ )
+ real_part.add_updater(
+ lambda d: d.set_value(np.sqrt(WALK) * np.cos(angle.get_value() / 2))
+ )
+ imag_part.add_updater(
+ lambda d: d.set_value(np.sqrt(WALK) * np.sin(angle.get_value() / 2))
+ )
+ value_row = m.VGroup(
+ m.MathTex(r"\sqrt z =", font_size=32),
+ real_part,
+ imag_part,
+ m.MathTex("i", font_size=32),
+ ).arrange(m.RIGHT, buff=0.12)
+ loops = m.DecimalNumber(0, num_decimal_places=2, font_size=32)
+ loops.add_updater(lambda d: d.set_value(angle.get_value() / m.TAU))
+ loop_row = m.VGroup(m.Text("loops around 0:", font_size=26), loops).arrange(
+ m.RIGHT, buff=0.15
+ )
+ hud = (
+ m.VGroup(value_row, loop_row)
+ .arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.2)
+ .to_corner(m.UR)
+ )
+ self.add_fixed_in_frame_mobjects(title, subtitle, hud)
+ self.remove(hud)
+
+ self.set_camera_orientation(
+ phi=62 * m.DEGREES,
+ theta=-60 * m.DEGREES,
+ zoom=1.05,
+ frame_center=np.array([0, 0, 0.2]),
+ )
+ self.begin_ambient_camera_rotation(rate=0.1)
+ self.add(sheet)
+ self.wait(1.5)
+ self.add(path, walker)
+ self.play(m.FadeIn(hud), m.FadeIn(walker), run_time=1)
+ # one loop: the walker ends on the other sheet, and √z has flipped sign
+ self.play(angle.animate.set_value(m.TAU), run_time=5, rate_func=m.linear)
+ flipped = (
+ m.Text("one loop: √z → −√z", font_size=26)
+ .set_color(m.YELLOW)
+ .next_to(hud, m.DOWN, aligned_edge=m.LEFT, buff=0.3)
+ )
+ self.add_fixed_in_frame_mobjects(flipped)
+ self.remove(flipped)
+ self.play(m.FadeIn(flipped), run_time=0.8)
+ # a second loop brings it home
+ self.play(
+ angle.animate.set_value(2 * m.TAU - 0.02), run_time=5, rate_func=m.linear
+ )
+ home = (
+ m.Text("two loops: home again", font_size=26)
+ .set_color(m.YELLOW)
+ .move_to(flipped, aligned_edge=m.LEFT)
+ )
+ self.play(m.Transform(flipped, home), run_time=0.8)
+ self.wait(0.6)
+
+ # log z: the same grid bends into an endless staircase
+ log_title = m.Text("…and log z, an endless staircase", font_size=40).to_corner(
+ m.UL
+ )
+ log_sub = m.Text(
+ "height: Im log z · every loop climbs 2π", font_size=22
+ ).set_color(m.GREY_B)
+ log_sub.next_to(log_title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)
+ climb = m.DecimalNumber(0, num_decimal_places=2, font_size=32)
+ climb.add_updater(lambda d: d.set_value(angle.get_value()))
+ climb_row = m.VGroup(
+ m.MathTex(r"\operatorname{Im}\log z =", font_size=32), climb
+ ).arrange(m.RIGHT, buff=0.15)
+ climb_row.move_to(value_row, aligned_edge=m.LEFT)
+ self.add_fixed_in_frame_mobjects(log_title, log_sub, climb_row)
+ self.remove(log_title, log_sub, climb_row)
+ self.play(
+ m.FadeOut(title),
+ m.FadeOut(subtitle),
+ m.FadeOut(value_row),
+ m.FadeOut(flipped),
+ run_time=0.8,
+ )
+ self.play(
+ blend.animate.set_value(1.0),
+ angle.animate.set_value(0.0),
+ m.FadeIn(log_title),
+ m.FadeIn(log_sub),
+ m.FadeIn(climb_row),
+ run_time=2.5,
+ )
+ self.play(
+ angle.animate.set_value(2 * m.TAU - 0.02), run_time=7, rate_func=m.linear
+ )
+ closing = m.Text(
+ "√z needs two sheets; log z needs infinitely many.", font_size=28
+ ).to_edge(m.DOWN, buff=0.35)
+ self.add_fixed_in_frame_mobjects(closing)
+ self.remove(closing)
+ self.play(m.FadeIn(closing), run_time=1)
+ self.wait(3.3)
+
+
+if __name__ == "__main__":
+ RiemannSurfaces().render("riemann_surfaces.mp4")
diff --git a/examples/score_diffusion.py b/examples/score_diffusion.py
new file mode 100644
index 00000000..c57900ba
--- /dev/null
+++ b/examples/score_diffusion.py
@@ -0,0 +1,245 @@
+"""Noise into a word: a diffusion model, run with the exact score.
+
+A diffusion model generates data by running noise backwards through time along the "score"
+∇ₓ log p_t(x), the direction in which the noised data distribution p_t grows fastest. Here the
+data is a mixture of narrow Gaussians sitting on the outlines of a word, so p_t (the data blurred
+by the variance-preserving forward process, x_t = α_t x₀ + σ_t ε) is a mixture too, and its score
+is exact — no neural network. 2,400 points of pure noise follow the probability-flow ODE
+dx/dt = −½β(t)(x + ∇ₓ log p_t(x)) from t = 1 down to t ≈ 0 (Song et al., 2021), and land on the
+letters. Height is the noise level σ_t; each point is colored by where it ends up, so the noise
+at the top is visibly sorted into the letters on the way down.
+"""
+
+import itertools
+
+import numpy as np
+
+import manimgx as m
+
+N_POINTS = 2400
+N_CENTERS = 900
+SPREAD = 0.012 # the width of each Gaussian on the outline
+BETA = (0.1, 20.0) # β(t) runs linearly between these
+STEPS = 240
+SCALE = 1.45 # screen units per data unit
+HEIGHT = 4.2 # screen height of σ = 1
+N_TRAILS = 110
+BLOCK = 100 # points at a time in the score, so that its arrays stay in cache
+RAINBOW = ["#ff595e", "#ff924c", "#ffca3a", "#8ac926", "#1982c4", "#6a4c93", "#c77dff"]
+
+
+def colormap(values: np.ndarray, stops: list[str], opacity: float = 1.0) -> 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.full((len(values), 4), opacity)
+ out[:, :3] = rgb[i] * (1 - f) + rgb[i + 1] * f
+ return out
+
+
+def word_centers(text: str, count: int) -> np.ndarray:
+ """Points spread evenly along the outlines of a word, in data units (width 4.4)."""
+ word = m.Text(text, font_size=96).scale_to_fit_width(4.4).move_to(m.ORIGIN)
+ leaves = [
+ leaf
+ for leaf in word.family_members_with_points()
+ if isinstance(leaf, m.VMobject)
+ ]
+ lengths = np.array([leaf.get_arc_length() for leaf in leaves])
+ points = []
+ for leaf, share in zip(
+ leaves,
+ np.maximum(3, np.round(count * lengths / lengths.sum())).astype(int),
+ strict=True,
+ ):
+ points += [
+ leaf.point_from_proportion(a)[:2]
+ for a in np.linspace(0, 1, share, endpoint=False)
+ ]
+ return np.array(points)
+
+
+def alpha(t: float) -> float:
+ lo, hi = BETA
+ return float(np.exp(-0.5 * (lo * t + 0.5 * (hi - lo) * t * t)))
+
+
+def sigma(t: float) -> float:
+ return float(np.sqrt(1 - alpha(t) ** 2))
+
+
+def velocity(x: np.ndarray, t: float, centers: np.ndarray) -> np.ndarray:
+ """The probability-flow ODE's velocity, with the mixture's exact score."""
+ a = alpha(t)
+ var = a * a * SPREAD**2 + 1 - a * a
+ cx, cy = (a * centers).T[:, :, None] # (centers, 1) each
+ score = np.empty_like(x)
+ for i in range(0, len(x), BLOCK):
+ px, py = x[i : i + BLOCK].T.copy()
+ dx, dy = cx - px, cy - py # the offsets: (centers, points) each
+ log_weight = -(dx * dx + dy * dy) / (2 * var)
+ log_weight -= log_weight.max(axis=0)
+ weight = np.exp(log_weight)
+ weight /= weight.T.copy().sum(axis=1) # each point's weights, summed pairwise
+ score[i : i + BLOCK, 0] = (weight * dx).sum(axis=0)
+ score[i : i + BLOCK, 1] = (weight * dy).sum(axis=0)
+ score /= var
+ beta = BETA[0] + t * (BETA[1] - BETA[0])
+ return -0.5 * beta * (x + score)
+
+
+def time_at_noise(level: np.ndarray) -> np.ndarray:
+ """t with σ_t = level: −2 log α_t = β₀t + ½(β₁ − β₀)t² is a quadratic in t."""
+ lo, hi = BETA
+ c = -np.log(1 - level**2) # = −2 log α
+ half = 0.5 * (hi - lo)
+ return (-lo + np.sqrt(lo * lo + 4 * half * c)) / (2 * half)
+
+
+def flow(start: np.ndarray, centers: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Heun steps from t = 1 to t = 0.002, evenly spaced in the noise level σ_t (so the
+ descent is steady, and the steps are fine near the data): (times, positions per time).
+ """
+ levels = np.linspace(sigma(1.0), sigma(0.002), STEPS + 1)
+ times = np.concatenate([[1.0], time_at_noise(levels[1:])])
+ x = start.copy()
+ path = [x.copy()]
+ for t, t_next in itertools.pairwise(times):
+ h = t_next - t
+ v1 = velocity(x, t, centers)
+ v2 = velocity(x + h * v1, t_next, centers)
+ x = x + 0.5 * h * (v1 + v2)
+ path.append(x.copy())
+ return times, np.array(path)
+
+
+class ScoreDiffusion(m.ThreeDScene):
+ def construct(self) -> None:
+ rng = np.random.default_rng(2021)
+ centers = word_centers("manimgx", N_CENTERS)
+ times, path = flow(rng.standard_normal((N_POINTS, 2)), centers)
+ heights = HEIGHT * np.array([sigma(t) for t in times])
+ final = path[-1]
+ colors = colormap(
+ (final[:, 0] - final[:, 0].min()) / np.ptp(final[:, 0]), RAINBOW, 0.95
+ )
+ progress = m.ValueTracker(0.0) # 0: t = 1 (noise) … 1: t ≈ 0 (data)
+
+ def at(p: float) -> tuple[np.ndarray, float]:
+ """Positions (screen units, xy) and height at progress p, interpolated between steps."""
+ f = p * STEPS
+ k = min(int(f), STEPS - 1)
+ w = f - k
+ xy = (1 - w) * path[k] + w * path[k + 1]
+ return SCALE * xy, (1 - w) * heights[k] + w * heights[k + 1]
+
+ cloud = m.PMobject(stroke_width=4.2)
+ xy0, z0 = at(0.0)
+ cloud.add_points(np.column_stack([xy0, np.full(N_POINTS, z0)]), rgbas=colors)
+
+ def descend(mob: m.Mobject) -> None:
+ xy, z = at(progress.get_value())
+ mob.points = np.column_stack([xy, np.full(N_POINTS, z)])
+
+ cloud.add_updater(descend)
+
+ # the paths of a few points, all in one path object (a subpath each)
+ chosen = rng.choice(N_POINTS, N_TRAILS, replace=False)
+ trail_xyz = np.concatenate(
+ [
+ SCALE * path[:, chosen, :],
+ np.broadcast_to(heights[:, None, None], (STEPS + 1, N_TRAILS, 1)),
+ ],
+ axis=2,
+ )
+ trails = m.VMobject(stroke_width=1.3)
+ trail_colors = [
+ m.ManimColor(c).to_hex() for c in colors[chosen, :3].tolist()
+ ] # by destination
+ trails.set_stroke(color=trail_colors, opacity=0.6)
+
+ # each step of each trail, a straight cubic Bézier: (trails, steps, 4, 3)
+ start, end = trail_xyz[:-1].transpose(1, 0, 2), trail_xyz[1:].transpose(1, 0, 2)
+ third = (end - start) / 3
+ segments = np.stack([start, start + third, start + 2 * third, end], axis=2)
+ shown = 0 # the steps the trails show
+
+ def grow(mob: m.Mobject) -> None:
+ nonlocal shown
+ upto = max(1, int(progress.get_value() * STEPS))
+ if upto != shown:
+ shown = upto
+ mob.set_points(segments[:, :upto].reshape(-1, 3))
+
+ grow(trails)
+ trails.add_updater(grow)
+
+ title = m.Text(
+ "Noise into a word, by following the score", font_size=34
+ ).to_corner(m.UL)
+ subtitle = m.Text(
+ "a diffusion model with the exact score of the data (no neural network)",
+ font_size=21,
+ )
+ subtitle.set_color(m.GREY_B).next_to(
+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.12
+ )
+ ode = m.MathTex(
+ r"\frac{dx}{dt} = -\tfrac12\,\beta(t)\,\bigl(x + \nabla_x \log"
+ r" p_t(x)\bigr)",
+ font_size=32,
+ ).to_corner(m.DL)
+ axis_note = (
+ m.Text("height: noise level σ", font_size=22)
+ .set_color(m.GREY_B)
+ .to_corner(m.DR)
+ )
+ closing = m.Text(
+ "2,400 points of noise, each carried down the score onto the data.",
+ font_size=26,
+ )
+ closing.to_edge(m.DOWN, buff=0.35)
+ self.add_fixed_in_frame_mobjects(title, subtitle, ode, axis_note, closing)
+ self.remove(ode, closing)
+
+ self.set_camera_orientation(
+ phi=58 * m.DEGREES,
+ theta=-72 * m.DEGREES,
+ zoom=0.82,
+ frame_center=np.array([0.0, 0.0, 2.3]),
+ )
+ self.add(trails, cloud)
+ self.begin_ambient_camera_rotation(rate=0.05)
+ self.wait(1.5)
+ # 1.5–16 s: t from 1 down to 0: the noise is carried onto the letters
+ self.play(
+ progress.animate.set_value(1.0),
+ m.FadeIn(ode, run_time=2),
+ self.camera.frame.animate.move_to(np.array([0.0, 0.0, 1.4])),
+ run_time=14,
+ rate_func=m.smooth,
+ )
+ self.stop_ambient_camera_rotation()
+ # 16–22 s: the whole bundle of paths
+ self.move_camera(
+ phi=76 * m.DEGREES,
+ theta=-40 * m.DEGREES,
+ zoom=0.9,
+ frame_center=np.array([0.0, 0.0, 1.8]),
+ run_time=5,
+ )
+ # 22–30 s: from above: the word
+ self.move_camera(
+ phi=0,
+ theta=-90 * m.DEGREES,
+ zoom=1.5,
+ frame_center=np.zeros(3),
+ run_time=4.5,
+ )
+ self.play(m.FadeIn(closing), m.FadeOut(axis_note), m.FadeOut(ode), run_time=1)
+ self.play(self.camera.zoom_tracker.animate.set_value(1.6), run_time=4)
+
+
+if __name__ == "__main__":
+ ScoreDiffusion().render("score_diffusion.mp4")
diff --git a/examples/sugihara_cylinder.py b/examples/sugihara_cylinder.py
new file mode 100644
index 00000000..9112bb24
--- /dev/null
+++ b/examples/sugihara_cylinder.py
@@ -0,0 +1,242 @@
+"""Circle or square? Kokichi Sugihara's ambiguous cylinder, built from two projections.
+
+Looked at from 40° above, the tube's rim is a perfect circle; its reflection in the mirror behind
+it — the same tube seen from the back — is a square. Turn it around and they swap. The trick:
+seen from the front, a rim point (x, y, z) sits at height v_f = y sin α + z cos α on the screen;
+seen from the back it sits at v_b = −y sin α + z cos α. Ask for a circle in front
+(x, v_f) = (cos t, sin t) and a rounded square behind (x, v_b) = (cos t, ±(1 − |cos t|⁶)^⅙), and
+solve: y = (v_f − v_b)/(2 sin α), z = (v_f + v_b)/(2 cos α). The walls are vertical, so from
+both sides they look like the sides of a cylinder. From anywhere else it is a wavy tube with a
+bow-tie footprint (Sugihara, 2016).
+"""
+
+import math
+
+import numpy as np
+
+import manimgx as m
+
+ALPHA = 40 * m.DEGREES # the elevation of both views
+SQUARENESS = 6.0
+WALL = 1.1 # wall height
+MIRROR_Y = 2.6 # the mirror is the plane y = MIRROR_Y
+SAMPLES = 480
+
+
+def rim() -> np.ndarray:
+ """The rim, unturned: (SAMPLES + 1, 3)."""
+ t = np.linspace(0, m.TAU, SAMPLES + 1)
+ front = np.sin(t)
+ back = np.sign(np.sin(t)) * (1 - np.abs(np.cos(t)) ** SQUARENESS) ** (
+ 1 / SQUARENESS
+ )
+ y = (front - back) / (2 * np.sin(ALPHA))
+ z = (front + back) / (2 * np.cos(ALPHA))
+ return np.stack([np.cos(t), y, z], axis=1)
+
+
+def turned(points: np.ndarray, turn: float) -> np.ndarray:
+ """The points, turned about the vertical axis by `turn`."""
+ c, s = np.cos(turn), np.sin(turn)
+ return points @ np.array([[c, s, 0], [-s, c, 0], [0, 0, 1]])
+
+
+def mirrored(points: np.ndarray) -> np.ndarray:
+ return points * np.array([1, -1, 1]) + np.array([0, 2 * MIRROR_Y, 0])
+
+
+def wall(top: np.ndarray) -> np.ndarray:
+ """A vertical wall hanging WALL below the rim: the rim's points, then its foot's."""
+ return np.concatenate([top, top - np.array([0, 0, WALL])])
+
+
+def wall_triangles(n: int) -> np.ndarray:
+ """The wall's triangles, below a rim of n points: a strip of quads."""
+ i = np.arange(n - 1)
+ return np.concatenate(
+ [np.stack([i, i + 1, n + i + 1], 1), np.stack([i, n + i + 1, n + i], 1)]
+ )
+
+
+def tube(points: np.ndarray, radius: float, sides: int = 10) -> np.ndarray:
+ """A lit tube along a closed polyline (parallel-transport frames): a ring of
+ `sides` vertices around each point."""
+ 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])
+ x, y, z = (seed / np.linalg.norm(seed)).tolist()
+ normals = [(x, y, z)]
+ # point by point, in floats: numpy's overhead would dwarf the work on 3-vectors
+ for tx, ty, tz in tangent[1:].tolist():
+ d = x * tx + y * ty + z * tz
+ x, y, z = x - d * tx, y - d * ty, z - d * tz
+ length = math.sqrt(x * x + y * y + z * z)
+ x, y, z = x / length, y / length, z / length
+ normals.append((x, y, z))
+ 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]
+ )
+ return (points[:, None] + radius * ring).reshape(-1, 3)
+
+
+def tube_triangles(n: int, sides: int = 10) -> np.ndarray:
+ """The tube's triangles, along a polyline of n points: quads between the rings."""
+ i = np.arange(n - 1)[:, None]
+ j = np.arange(sides)[None, :]
+ k = (j + 1) % sides
+ return 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)
+
+
+class SugiharaCylinder(m.ThreeDScene):
+ def construct(self) -> None:
+ turn = m.ValueTracker(0.0)
+ upright = rim()
+ triangles = [
+ wall_triangles(SAMPLES + 1),
+ tube_triangles(SAMPLES + 1),
+ tube_triangles(SAMPLES + 1),
+ ]
+
+ def object_parts(reflect: bool) -> list[np.ndarray]:
+ top = turned(upright, turn.get_value())
+ if reflect:
+ top = mirrored(top)
+ return [
+ wall(top),
+ tube(top, 0.045),
+ tube(top - np.array([0, 0, WALL]), 0.02),
+ ]
+
+ def build(reflect: bool, colors: tuple[str, str, str]) -> m.Group:
+ parts = m.Group(
+ *(
+ m.MeshMobject(verts, tris, shade_in_3d=True, fill_color=color)
+ for verts, tris, color in zip(
+ object_parts(reflect), triangles, colors, strict=True
+ )
+ )
+ )
+ shown = turn.get_value()
+
+ # only a turn moves the parts: between turns they keep their points
+ def follow(parts: m.Mobject) -> None:
+ nonlocal shown
+ if turn.get_value() != shown:
+ shown = turn.get_value()
+ for part, verts in zip(
+ parts.submobjects, object_parts(reflect), strict=True
+ ):
+ part.set_points(verts)
+
+ parts.add_updater(follow)
+ return parts
+
+ tube_obj = build(False, ("#ff6b4a", "#ffe08a", "#ffd0b0"))
+ reflection = build(True, ("#b8493a", "#c9ad63", "#b89a88"))
+ mirror = m.Polygon(
+ [-2.5, MIRROR_Y, -2.4],
+ [2.5, MIRROR_Y, -2.4],
+ [2.5, MIRROR_Y, 3.0],
+ [-2.5, MIRROR_Y, 3.0],
+ fill_color="#8fb8ff",
+ fill_opacity=0.10,
+ stroke_color="#dfe8ff",
+ stroke_width=2,
+ shade_in_3d=True,
+ )
+
+ # the magic view: 40° above, nearly orthographic
+ self.set_camera_orientation(
+ phi=90 * m.DEGREES - ALPHA,
+ theta=-90 * m.DEGREES,
+ zoom=0.9,
+ focal_distance=120,
+ frame_center=np.array([0.0, 1.6, 0.0]),
+ )
+ title = m.Text("Circle or square?", font_size=40).to_corner(m.UL)
+ subtitle = m.Text("one tube in front of a mirror", font_size=24).set_color(
+ m.GREY_B
+ )
+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)
+ views = m.VGroup(
+ m.MathTex(r"v_f = \phantom{-}y\sin\alpha + z\cos\alpha", font_size=32),
+ m.MathTex(r"v_b = -y\sin\alpha + z\cos\alpha", font_size=32),
+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.2)
+ solve = m.VGroup(
+ m.MathTex(r"y = \frac{v_f - v_b}{2\sin\alpha}", font_size=32),
+ m.MathTex(r"z = \frac{v_f + v_b}{2\cos\alpha}", font_size=32),
+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.25)
+ m.VGroup(views, solve).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.45).to_edge(
+ m.RIGHT, buff=0.5
+ )
+ in_front = (
+ m.Text("the tube", font_size=24)
+ .set_color(m.GREY_B)
+ .move_to([-3.4, -2.2, 0])
+ )
+ behind = (
+ m.Text("its reflection", font_size=24)
+ .set_color(m.GREY_B)
+ .move_to([-3.9, 1.6, 0])
+ )
+ truth = m.Text("neither: a wavy tube with a bow-tie footprint", font_size=28)
+ truth.to_corner(m.DR)
+ self.add_fixed_in_frame_mobjects(
+ title, subtitle, solve, views, truth, in_front, behind
+ )
+ self.remove(solve, views, truth, in_front, behind)
+
+ self.add(reflection, mirror, tube_obj)
+ self.play(
+ m.FadeIn(in_front),
+ m.FadeIn(behind),
+ self.camera.zoom_tracker.animate.set_value(0.94),
+ run_time=3,
+ )
+ # 3–10 s: turn the tube half a turn: circle ↔ square
+ self.play(turn.animate.set_value(np.pi), run_time=6, rate_func=m.smooth)
+ self.wait(1)
+ # 10–18 s: leave the magic view: the truth
+ self.play(m.FadeOut(in_front), m.FadeOut(behind), run_time=0.5)
+ self.move_camera(
+ phi=62 * m.DEGREES,
+ theta=-50 * m.DEGREES,
+ focal_distance=16,
+ zoom=1.15,
+ frame_center=np.array([0.0, 0.6, -0.4]),
+ run_time=3.5,
+ )
+ self.play(m.FadeIn(truth), turn.animate.set_value(2 * np.pi), run_time=4)
+ # 18–22 s: from straight above: the footprint is a lens
+ self.move_camera(
+ phi=6 * m.DEGREES,
+ theta=-90 * m.DEGREES,
+ zoom=2.2,
+ frame_center=np.array([0.0, 0.0, 0.0]),
+ run_time=3.5,
+ )
+ self.play(m.FadeOut(truth), run_time=0.5)
+ # 22–30 s: back to the magic view, and how it is made
+ self.move_camera(
+ phi=90 * m.DEGREES - ALPHA,
+ theta=-90 * m.DEGREES,
+ zoom=0.9,
+ focal_distance=120,
+ frame_center=np.array([0.0, 1.6, 0.0]),
+ run_time=3.5,
+ )
+ self.play(m.Write(views), m.Write(solve), run_time=2)
+ self.play(self.camera.zoom_tracker.animate.set_value(0.94), run_time=2.5)
+
+
+if __name__ == "__main__":
+ SugiharaCylinder().render("sugihara_cylinder.mp4")
diff --git a/examples/surface_plots.py b/examples/surface_plots.py
new file mode 100644
index 00000000..257c57f1
--- /dev/null
+++ b/examples/surface_plots.py
@@ -0,0 +1,101 @@
+"""Graphs of functions of two variables, one becoming the next.
+
+The graph of z = f(x, y) is a landscape over the plane: above each point (x, y), the height
+f(x, y). sin x cos y is an egg crate of peaks and pits. (x² − y²)/4 is a saddle: it curves up
+along one axis and down along the other, so its center is flat yet neither a peak nor a pit.
+2e^{−(x² + y²)/2} is a single bell, the shape of the normal distribution in two dimensions.
+Each surface is drawn from its formula, and each one bends into the next.
+"""
+
+from collections.abc import Callable
+
+import numpy as np
+
+import manimgx as m
+
+WALL = 4.2 # the README wall's 5 seconds start here
+RESOLUTION = 48
+COLORS = [
+ (m.BLUE_E, -2.0),
+ (m.BLUE, -1.0),
+ (m.TEAL, 0.0),
+ (m.GREEN, 1.0),
+ (m.YELLOW, 2.0),
+]
+
+FUNCTIONS: list[tuple[str, Callable[[float, float], float]]] = [
+ (r"z = \sin x \cos y", lambda x, y: np.sin(x) * np.cos(y)),
+ (r"z = \frac{x^2 - y^2}{4}", lambda x, y: (x * x - y * y) / 4),
+ (r"z = 2e^{-(x^2 + y^2)/2}", lambda x, y: 2 * np.exp(-(x * x + y * y) / 2)),
+]
+
+
+class SurfacePlots(m.ThreeDScene):
+ def construct(self) -> None:
+ axes = m.ThreeDAxes(
+ x_range=[-3, 3, 1],
+ y_range=[-3, 3, 1],
+ z_range=[-2, 2, 1],
+ x_length=6.6,
+ y_length=6.6,
+ z_length=4.4,
+ )
+
+ def surface(f: Callable[[float, float], float]) -> m.Surface:
+ graph = m.Surface(
+ lambda u, v: axes.c2p(u, v, f(u, v)),
+ u_range=[-3, 3],
+ v_range=[-3, 3],
+ resolution=(RESOLUTION, RESOLUTION),
+ fill_opacity=0.95,
+ stroke_color=m.WHITE,
+ stroke_width=0.4,
+ stroke_opacity=0.35,
+ )
+ graph.set_fill_by_value(axes=axes, colorscale=COLORS, axis=2)
+ return graph
+
+ def label(tex: str) -> m.MathTex:
+ formula = m.MathTex(tex, font_size=60).to_corner(m.UL, buff=0.5)
+ self.add_fixed_in_frame_mobjects(formula)
+ self.remove(formula)
+ return formula
+
+ self.set_camera_orientation(
+ phi=64 * m.DEGREES, theta=-55 * m.DEGREES, zoom=0.95
+ )
+ self.begin_ambient_camera_rotation(rate=0.16)
+ graph = surface(lambda x, y: 0.0)
+ heights = [graph.points.copy()] + [
+ surface(f).points.copy() for _, f in FUNCTIONS
+ ]
+ labels = [label(tex) for tex, _ in FUNCTIONS]
+
+ def bend(k: int) -> m.Animation:
+ """From the k-th surface to the next (the 0th is flat), recolored by height as
+ it goes."""
+
+ def step(mob: m.Mobject, alpha: float) -> None:
+ assert isinstance(mob, m.Surface)
+ mob.points = (1 - alpha) * heights[k] + alpha * heights[k + 1]
+ mob.set_fill_by_value(axes=axes, colorscale=COLORS, axis=2)
+
+ return m.UpdateFromAlphaFunc(graph, step)
+
+ self.play(m.Create(axes), run_time=1.2)
+ self.play(m.FadeIn(graph), m.Write(labels[0]), run_time=0.8)
+ self.play(bend(0), run_time=2)
+ self.wait(1)
+ for k in (1, 2):
+ self.play(
+ bend(k),
+ m.FadeOut(labels[k - 1], shift=0.4 * m.UP),
+ m.FadeIn(labels[k], shift=0.4 * m.UP),
+ run_time=2.6,
+ )
+ self.wait(1.4)
+ self.wait(2)
+
+
+if __name__ == "__main__":
+ SurfacePlots().render("surface_plots.mp4")
diff --git a/examples/traffic_helix.py b/examples/traffic_helix.py
new file mode 100644
index 00000000..772d2448
--- /dev/null
+++ b/examples/traffic_helix.py
@@ -0,0 +1,212 @@
+"""A traffic jam from nowhere, seen in spacetime.
+
+Twenty-two cars drive around a ring road with no bottleneck, no merge, no accident — and within
+a minute a jam appears out of nothing, just as it did in Sugiyama and colleagues' experiment on
+a real track (New J. Phys., 2008). Each driver speeds toward the speed their gap allows and reacts
+with a lag: the optimal-velocity model ẍₙ = a [V(xₙ₊₁ − xₙ) − ẋₙ], V(h) = tanh(h − 2) + tanh 2
+(Bando et al., 1995). With the gap at 2 and a = 1, smooth flow is unstable: a tiny wobble grows
+into a stop-and-go wave. Lift time into the third dimension (the last 70 time units, the present
+on top) and each car's worldline winds up a cylinder; the jam is where worldlines flatten and
+crowd — and that knot leans back, moving against the traffic while every car keeps going forward.
+"""
+
+import numpy as np
+
+import manimgx as m
+
+N = 22
+LENGTH = 44.0 # the ring's length (gap 2 per car)
+SENSITIVITY = 1.0
+RADIUS = 2.6 # the ring on screen
+TIME_SCALE = 12.5 # model time per second of video
+RISE = 0.05 # height per unit of model time
+WINDOW = 70.0 # how much of the past the cylinder shows (model time)
+SPEED_STOPS = ["#e63946", "#f4a261", "#e9c46a", "#8ac926", "#2ec4b6"] # stopped … fast
+V_MAX = 1.0 + np.tanh(2.0)
+
+
+def optimal_velocity(gap: np.ndarray) -> np.ndarray:
+ return np.tanh(gap - 2) + np.tanh(2)
+
+
+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 Road:
+ """The cars' positions and speeds, integrated with RK4; their histories for the worldlines."""
+
+ def __init__(self) -> None:
+ self.x = np.arange(N) * LENGTH / N
+ self.x[0] += 0.1 # one driver a little out of place
+ self.v = np.full(N, optimal_velocity(np.array(2.0)))
+ self.t = 0.0
+ self.times: list[float] = [0.0]
+ self.xs: list[np.ndarray] = [self.x.copy()]
+ self.vs: list[np.ndarray] = [self.v.copy()]
+
+ def rates(self, x: np.ndarray, v: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ gap = (np.roll(x, -1) - x) % LENGTH
+ return v, SENSITIVITY * (optimal_velocity(gap) - v)
+
+ def advance(self, duration: float, dt: float = 0.05) -> None:
+ for _ in range(max(1, round(duration / dt))):
+ k1 = self.rates(self.x, self.v)
+ k2 = self.rates(self.x + dt / 2 * k1[0], self.v + dt / 2 * k1[1])
+ k3 = self.rates(self.x + dt / 2 * k2[0], self.v + dt / 2 * k2[1])
+ k4 = self.rates(self.x + dt * k3[0], self.v + dt * k3[1])
+ self.x = self.x + dt / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
+ self.v = self.v + dt / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
+ self.t += dt
+ self.times.append(self.t)
+ self.xs.append(self.x.copy())
+ self.vs.append(self.v.copy())
+
+
+def on_ring(x: np.ndarray, height: np.ndarray, radius: float = RADIUS) -> np.ndarray:
+ angle = m.TAU * x / LENGTH
+ return np.stack([radius * np.cos(angle), radius * np.sin(angle), height], -1)
+
+
+def worldlines(
+ road: Road, lift: float, sides: int = 6
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Every car's worldline over the last WINDOW of model time, as a thin tube on the cylinder
+ (the present on top), colored by the car's speed: vertices, triangles, colors. A curve on a
+ cylinder has a natural frame — the outward radial direction and its cross with the tangent —
+ so no transport along the curve is needed."""
+ times = np.array(road.times)
+ keep = times >= road.t - WINDOW
+ xs, vs = np.array(road.xs)[keep], np.array(road.vs)[keep] # (samples, cars)
+ z = lift * RISE * (times[keep] - (road.t - WINDOW))[:, None] * np.ones((1, N))
+ centers = on_ring(xs, z).transpose(1, 0, 2) # (cars, samples, 3)
+ angle = m.TAU * xs.T / LENGTH
+ radial = np.stack([np.cos(angle), np.sin(angle), np.zeros_like(angle)], -1)
+ tangent = np.gradient(centers, axis=1)
+ tangent /= np.linalg.norm(tangent, axis=-1, keepdims=True) + 1e-12
+ across = np.cross(tangent, radial)
+ across /= np.linalg.norm(across, axis=-1, keepdims=True) + 1e-12
+ out = np.cross(across, tangent)
+ a = np.linspace(0, m.TAU, sides, endpoint=False)
+ ring = (
+ np.cos(a)[:, None] * out[:, :, None, :]
+ + np.sin(a)[:, None] * across[:, :, None, :]
+ )
+ verts = (centers[:, :, None, :] + 0.028 * ring).reshape(-1, 3)
+ cars, samples = centers.shape[:2]
+ i = np.arange(samples - 1)[:, None]
+ j = np.arange(sides)[None, :]
+ k = (j + 1) % sides
+ one = 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 = (one[None] + (np.arange(cars) * samples * sides)[:, None, None]).reshape(
+ -1, 3
+ )
+ speed = np.repeat(vs.T.reshape(-1), sides)
+ return verts, tris, colormap(speed / V_MAX, SPEED_STOPS)
+
+
+class TrafficHelix(m.ThreeDScene):
+ def construct(self) -> None:
+ road = Road()
+ lift = m.ValueTracker(0.0) # 0: the present only (a flat ring); 1: time rises
+
+ def step(_: m.Mobject, dt: float) -> None:
+ road.advance(TIME_SCALE * dt)
+
+ clock = m.Mobject()
+ clock.add_updater(step)
+
+ lines = m.MeshMobject(
+ np.zeros((3, 3)), np.array([[0, 1, 2]]), shade_in_3d=True
+ ) # drawn once time rises
+
+ def redraw(mob: m.Mobject) -> None:
+ assert isinstance(mob, m.MeshMobject)
+ if lift.get_value() > 0 and len(road.times) > 2:
+ verts, tris, rows = worldlines(road, lift.get_value())
+ mob.points, mob.triangles = verts, tris
+ mob.paint = mob.paint.but(fill=rows)
+
+ lines.add_updater(redraw)
+ cars = m.Group(*[m.Dot3D(radius=0.12, color=m.WHITE) for _ in range(N)])
+
+ def drive(group: m.Mobject) -> None:
+ height = lift.get_value() * RISE * WINDOW
+ colors = colormap(road.v / V_MAX, SPEED_STOPS)
+ for k, car in enumerate(group.submobjects):
+ car.move_to(on_ring(road.x[k : k + 1], np.array([height]))[0])
+ car.set_color(m.ManimColor(colors[k, :3]))
+
+ cars.add_updater(drive)
+ track = m.Circle(radius=RADIUS, color=m.GREY_D, stroke_width=10)
+
+ title = m.Text("A traffic jam from nowhere", font_size=38).to_corner(m.UL)
+ subtitle = m.Text(
+ "22 cars on a ring road; no bottleneck (Sugiyama et al., 2008)",
+ font_size=22,
+ ).set_color(m.GREY_B)
+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)
+ model = m.MathTex(
+ r"\ddot x_n = a\,\bigl[V(x_{n+1} - x_n) - \dot x_n\bigr]", font_size=32
+ ).to_corner(m.UR)
+ bar = m.Rectangle(
+ width=2.4, height=0.18, stroke_width=0, fill_opacity=1
+ ).set_fill(color=SPEED_STOPS, opacity=1)
+ bar.set_sheen_direction(m.RIGHT)
+ legend = (
+ m.VGroup(m.Text("stopped", font_size=20), bar, m.Text("fast", font_size=20))
+ .arrange(m.RIGHT, buff=0.15)
+ .next_to(model, m.DOWN, aligned_edge=m.RIGHT, buff=0.3)
+ )
+ self.add_fixed_in_frame_mobjects(title, subtitle, model, legend)
+
+ # 0–8 s: from above: smooth flow, then a wobble grows into a jam
+ self.set_camera_orientation(
+ phi=0, theta=-90 * m.DEGREES, focal_distance=40, zoom=1.0
+ )
+ self.add(track, clock, lines, cars)
+ self.wait(8)
+
+ # 8–14 s: lift time into the third dimension: worldlines wind up a cylinder
+ up = (
+ m.Text("height = time", font_size=26)
+ .set_color(m.YELLOW)
+ .next_to(legend, m.DOWN, aligned_edge=m.RIGHT, buff=0.25)
+ )
+ self.add_fixed_in_frame_mobjects(up)
+ self.remove(up)
+ self.move_camera(
+ phi=66 * m.DEGREES,
+ theta=-70 * m.DEGREES,
+ focal_distance=20,
+ zoom=0.9,
+ frame_center=np.array([0.0, 0.0, 1.75]),
+ added_anims=[lift.animate.set_value(1.0), m.FadeIn(up)],
+ run_time=6,
+ )
+ # 14–30 s: the jam is the band of flat, crowded, red worldlines — and it leans backward
+ self.begin_ambient_camera_rotation(rate=0.08)
+ self.wait(10)
+ closing = m.Text(
+ "The jam moves backward while every car moves forward.", font_size=28
+ ).to_edge(m.DOWN, buff=0.35)
+ self.add_fixed_in_frame_mobjects(closing)
+ self.remove(closing)
+ self.play(m.FadeIn(closing), run_time=1)
+ self.wait(5)
+
+
+if __name__ == "__main__":
+ TrafficHelix().render("traffic_helix.mp4")
diff --git a/examples/turing_torus.py b/examples/turing_torus.py
new file mode 100644
index 00000000..4b45c132
--- /dev/null
+++ b/examples/turing_torus.py
@@ -0,0 +1,187 @@
+"""Turing patterns growing on a torus.
+
+Two chemicals react and diffuse over the surface of a doughnut (the Gray–Scott model):
+u̇ = D_u Δu − uv² + F(1 − u), v̇ = D_v Δv + uv² − (F + k)v, with D_u = 2 D_v. The Laplacian Δ is
+the torus's own (Laplace–Beltrami) operator,
+Δf = f_φφ/ρ² + (1/(ρ r²)) ∂_θ(ρ f_θ), ρ = R + r cos θ,
+so spots come out round on the curved surface — smaller on the inside of the hole than they
+would be on a flat map. From a few seeds, spots grow and divide until they tile the torus; then
+F and k are changed and the same equations grow a labyrinth instead. Alan Turing (1952): diffusion,
+which should smooth everything out, can create pattern.
+"""
+
+import numpy as np
+
+import manimgx as m
+
+R, r = 2.0, 0.95 # the torus's radii (screen units)
+NU, NV = 288, 128 # the simulation grid: around the ring, around the tube
+CELL = 0.045 # the classic Gray–Scott unit cell, in screen units
+D_U, D_V = 0.16 * CELL**2, 0.08 * CELL**2
+DT = 0.5
+PHASES = {"spots": (0.0367, 0.0649), "labyrinth": (0.0545, 0.062)}
+STOPS = ["#07213a", "#0f4c5c", "#2a9d8f", "#e9c46a", "#f4a261", "#fff3d6"]
+
+
+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 GrayScott:
+ """The two concentrations on the torus's (φ, θ) grid, stepped by explicit Euler."""
+
+ def __init__(self, rng: np.random.Generator) -> None:
+ theta = np.linspace(0, m.TAU, NV, endpoint=False)
+ self.dphi, self.dtheta = m.TAU / NU, m.TAU / NV
+ self.rho = (R + r * np.cos(theta))[None, :]
+ self.rho_half = (R + r * np.cos(theta + self.dtheta / 2))[
+ None, :
+ ] # ρ between cells
+ self.u = np.ones((NU, NV))
+ self.v = np.zeros((NU, NV))
+ for _ in range(7): # a few seeds
+ i, j = rng.integers(0, NU), rng.integers(0, NV)
+ rows, cols = np.arange(i - 3, i + 3) % NU, np.arange(j - 3, j + 3) % NV
+ self.u[np.ix_(rows, cols)] = 0.5
+ self.v[np.ix_(rows, cols)] = 0.25
+ self.v += 0.01 * rng.random((NU, NV))
+ self.feed, self.kill = PHASES["spots"]
+
+ def laplacian(self, f: np.ndarray) -> np.ndarray:
+ along_ring = (np.roll(f, -1, 0) - 2 * f + np.roll(f, 1, 0)) / (
+ self.dphi * self.rho
+ ) ** 2
+ flux = self.rho_half * (
+ np.roll(f, -1, 1) - f
+ ) # conservative: ρ f_θ between cells
+ around_tube = (flux - np.roll(flux, 1, 1)) / (r * r * self.dtheta**2 * self.rho)
+ return along_ring + around_tube
+
+ def step(self, count: int) -> None:
+ for _ in range(count):
+ uvv = self.u * self.v * self.v
+ self.u += DT * (
+ D_U * self.laplacian(self.u) - uvv + self.feed * (1 - self.u)
+ )
+ self.v += DT * (
+ D_V * self.laplacian(self.v) + uvv - (self.feed + self.kill) * self.v
+ )
+
+
+def torus_points(bump: np.ndarray) -> np.ndarray:
+ """Vertices of the torus, pushed out along the normal by `bump` (grid-shaped)."""
+ phi = np.linspace(0, m.TAU, NU, endpoint=False)[:, None]
+ theta = np.linspace(0, m.TAU, NV, endpoint=False)[None, :]
+ tube = r + bump
+ rho = R + tube * np.cos(theta)
+ return np.stack(
+ [rho * np.cos(phi), rho * np.sin(phi), tube * np.sin(theta)], -1
+ ).reshape(-1, 3)
+
+
+def torus_triangles() -> np.ndarray:
+ """A welded periodic grid: every vertex shared, so the surface has no seam."""
+ i, j = np.meshgrid(np.arange(NU), np.arange(NV), indexing="ij")
+ a = i * NV + j
+ b = ((i + 1) % NU) * NV + j
+ c = ((i + 1) % NU) * NV + (j + 1) % NV
+ d = i * NV + (j + 1) % NV
+ return np.concatenate(
+ [np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)]
+ )
+
+
+class TuringTorus(m.ThreeDScene):
+ def construct(self) -> None:
+ chem = GrayScott(np.random.default_rng(1952))
+ speed = {"steps": 16} # simulation steps per tick of the 60 Hz simulation clock
+ surface = m.MeshMobject(
+ torus_points(np.zeros((NU, NV))),
+ torus_triangles(),
+ vertex_colors=colormap(np.zeros(NU * NV), STOPS),
+ shade_in_3d=True,
+ )
+
+ def grow(mob: m.Mobject, dt: float) -> None:
+ chem.step(speed["steps"])
+ level = np.clip(chem.v * 3.2, 0, 1)
+ mob.points = torus_points(0.035 * level)
+ mob.paint = mob.paint.but(fill=colormap(level.ravel(), STOPS))
+
+ surface.add_updater(grow)
+
+ title = m.Text("Turing patterns on a torus", font_size=38).to_corner(m.UL)
+ subtitle = m.Text(
+ "two chemicals reacting and diffusing (Gray–Scott)", font_size=22
+ )
+ subtitle.set_color(m.GREY_B).next_to(
+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.12
+ )
+ equations = (
+ m.VGroup(
+ m.MathTex(r"\dot u = D_u \Delta u - u v^2 + F(1 - u)", font_size=30),
+ m.MathTex(r"\dot v = D_v \Delta v + u v^2 - (F + k)\,v", font_size=30),
+ )
+ .arrange(m.DOWN, aligned_edge=m.LEFT)
+ .to_corner(m.DL)
+ )
+ feed_value = m.DecimalNumber(chem.feed, num_decimal_places=4, font_size=30)
+ kill_value = m.DecimalNumber(chem.kill, num_decimal_places=4, font_size=30)
+ feed_value.add_updater(lambda d: d.set_value(chem.feed))
+ kill_value.add_updater(lambda d: d.set_value(chem.kill))
+ knobs = (
+ m.VGroup(
+ m.VGroup(m.MathTex("F =", font_size=30), feed_value).arrange(
+ m.RIGHT, buff=0.15
+ ),
+ m.VGroup(m.MathTex("k =", font_size=30), kill_value).arrange(
+ m.RIGHT, buff=0.15
+ ),
+ )
+ .arrange(m.DOWN, aligned_edge=m.LEFT)
+ .to_corner(m.UR)
+ )
+ closing = m.Text(
+ "Diffusion, which smooths, can also create pattern (Turing, 1952)",
+ font_size=26,
+ )
+ closing.to_edge(m.DOWN, buff=0.35)
+ self.add_fixed_in_frame_mobjects(title, subtitle, equations, knobs, closing)
+ self.remove(equations, knobs, closing)
+
+ self.set_camera_orientation(
+ phi=62 * m.DEGREES, theta=-60 * m.DEGREES, zoom=1.05
+ )
+ self.begin_ambient_camera_rotation(rate=0.1)
+ self.add(surface)
+ # 0–16 s: seeds grow into spots that divide until they tile the torus
+ self.play(m.FadeIn(equations), m.FadeIn(knobs), run_time=2)
+ self.wait(6)
+ self.move_camera(
+ phi=40 * m.DEGREES,
+ zoom=1.1,
+ frame_center=np.array([0.0, 0.25, 0.0]),
+ run_time=4,
+ )
+ self.wait(3.5)
+ # 16–27 s: new F and k: the same equations grow a labyrinth
+ chem.feed, chem.kill = PHASES["labyrinth"]
+ speed["steps"] = 5 # slower: watch the spots stretch into worms
+ self.play(m.Indicate(knobs, color=m.YELLOW, scale_factor=1.1), run_time=1.2)
+ self.move_camera(
+ phi=66 * m.DEGREES, zoom=1.05, frame_center=np.zeros(3), run_time=5
+ )
+ self.wait(3.3)
+ self.play(m.FadeOut(equations), m.FadeIn(closing), run_time=1)
+ speed["steps"] = 12
+ self.wait(4)
+
+
+if __name__ == "__main__":
+ TuringTorus().render("turing_torus.mp4")
diff --git a/examples/voronoi_cones.py b/examples/voronoi_cones.py
new file mode 100644
index 00000000..a4775656
--- /dev/null
+++ b/examples/voronoi_cones.py
@@ -0,0 +1,237 @@
+"""Voronoi cells are crystals grown from seeds — and mountains of cones seen from above.
+
+Plant sixteen seeds at once and let each grow a crystal at the same speed. A point belongs to
+the grain that reaches it first, so the grains meet along the Voronoi diagram: every point goes
+to its nearest seed. Draw arrival time as depth and each grain becomes a cone; the diagram is the
+lower envelope of the cones, which the GPU's depth buffer computes exactly, pixel by pixel. A
+dark plane marks the present moment and hides whatever has not been reached yet, so from above
+you watch the grains grow. Then time runs back, and one seed gets a head start: its cone rises,
+and its borders bend into hyperbolas (a Johnson–Mehl tessellation, as when metal crystallizes
+from nuclei that appear at different times).
+"""
+
+import numpy as np
+
+import manimgx as m
+
+N_SEEDS = 16
+TOP = 3.0 # the height of time zero
+SLOPE = (
+ 1.6 # height lost per unit of growth: arrival time t is drawn at TOP − SLOPE · t
+)
+WIDTH, HEIGHT = 12.4, 6.6 # the dish the crystals grow in
+GRID = (248, 132)
+PALETTE = [
+ "#ef476f",
+ "#ffd166",
+ "#06d6a0",
+ "#118ab2",
+ "#8338ec",
+ "#ff9f1c",
+ "#2ec4b6",
+ "#e76f51",
+ "#a7c957",
+ "#f15bb5",
+ "#00bbf9",
+ "#fee440",
+ "#9b5de5",
+ "#00f5d4",
+ "#f77f00",
+ "#4cc9f0",
+]
+DARK = "#0b0f14"
+
+
+def seeds(rng: np.random.Generator) -> np.ndarray:
+ """Well-spread seeds: each the best of 30 random candidates (Mitchell's best candidate)."""
+ low, high = (
+ [-WIDTH / 2 + 0.7, -HEIGHT / 2 + 0.7],
+ [WIDTH / 2 - 0.7, HEIGHT / 2 - 0.7],
+ )
+ points = [rng.uniform(low, high)]
+ while len(points) < N_SEEDS:
+ candidates = rng.uniform(low, high, (30, 2))
+ distance = np.linalg.norm(
+ candidates[:, None] - np.array(points)[None], axis=2
+ ).min(axis=1)
+ points.append(candidates[np.argmax(distance)])
+ return np.array(points)
+
+
+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,
+ )
+
+
+class Grains(m.Group):
+ """The cones of all the grains, z = TOP − SLOPE · (tᵢ + |p − sᵢ|) over the dish, each cut down
+ to the cell it wins (plus one triangle of margin, hidden under its neighbours) — so only the
+ envelope exists, from any side. The cells are recomputed when a start changes.
+ """
+
+ def __init__(self, sites: np.ndarray, starts: list[m.ValueTracker]) -> None:
+ xs = np.linspace(-WIDTH / 2, WIDTH / 2, GRID[0] + 1)
+ ys = np.linspace(-HEIGHT / 2, HEIGHT / 2, GRID[1] + 1)
+ self.gx, self.gy = np.meshgrid(xs, ys, indexing="ij")
+ self.distance = np.hypot(
+ self.gx[None] - sites[:, 0, None, None],
+ self.gy[None] - sites[:, 1, None, None],
+ )
+ self.starts = starts
+ self.drawn: list[float] = [] # the starts the cells were last made for
+ self.cones = [
+ grid_mesh(*GRID, fill_color=color) for color in PALETTE[: len(sites)]
+ ]
+ self.all_triangles = self.cones[0].triangles
+ super().__init__(*self.cones)
+ self.add_updater(lambda g: g.refresh())
+ self.refresh()
+
+ def refresh(self) -> None:
+ starts = [s.get_value() for s in self.starts]
+ if starts == self.drawn:
+ return
+ self.drawn = starts
+ arrival = np.array(starts)[:, None, None] + self.distance
+ owner = np.argmin(arrival, axis=0).ravel()[self.all_triangles] # (triangles, 3)
+ for k, mesh in enumerate(self.cones):
+ z = TOP - SLOPE * arrival[k]
+ mesh.points = np.stack([self.gx, self.gy, z], -1).reshape(-1, 3)
+ mesh.triangles = self.all_triangles[(owner == k).any(axis=1)]
+
+
+class VoronoiCones(m.ThreeDScene):
+ def construct(self) -> None:
+ rng = np.random.default_rng(1644)
+ sites = seeds(rng)
+ starts = [m.ValueTracker(0.0) for _ in sites]
+ cones = Grains(sites, starts)
+ dots = m.Group(
+ *[m.Dot3D(np.array([*s, TOP]), radius=0.06, color=m.WHITE) for s in sites]
+ )
+ for dot, start, site in zip(dots, starts, sites, strict=True):
+ dot.add_updater(
+ lambda d, site=site, start=start: d.move_to(
+ np.array([*site, TOP - SLOPE * start.get_value() + 0.02])
+ )
+ )
+
+ # the present moment: a dark plane at the height of time T hides every point not yet reached
+ now = m.ValueTracker(0.0)
+ shown = m.ValueTracker(
+ 1.0
+ ) # the plane's opacity (it is hidden while the camera is tilted)
+ present = m.Rectangle(
+ width=WIDTH + 0.02,
+ height=HEIGHT + 0.02,
+ stroke_width=0,
+ fill_color=DARK,
+ fill_opacity=1,
+ )
+
+ def settle(plane: m.Mobject) -> None:
+ plane.move_to(np.array([0.0, 0.0, TOP - SLOPE * now.get_value()]))
+ plane.set_fill(opacity=shown.get_value())
+
+ present.add_updater(settle)
+
+ title = m.Text("Crystals grown from seeds", font_size=36).to_corner(m.UL)
+ subtitle = m.Text(
+ "every point joins the grain that reaches it first", font_size=22
+ )
+ subtitle.set_color(m.GREY_B).next_to(
+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.12
+ )
+ header = m.VGroup(title, subtitle)
+ backing = m.BackgroundRectangle(header, color=DARK, fill_opacity=0.9, buff=0.12)
+ self.add_fixed_in_frame_mobjects(backing, header)
+
+ def note(tex: str) -> m.VGroup:
+ label = m.MathTex(tex, font_size=32).to_corner(m.UR)
+ group = m.VGroup(
+ m.BackgroundRectangle(label, color=DARK, fill_opacity=0.9, buff=0.1),
+ label,
+ )
+ self.add_fixed_in_frame_mobjects(group)
+ self.remove(group)
+ return group
+
+ # 0–7 s: from above: the grains grow at equal speed and meet along the Voronoi diagram
+ self.set_camera_orientation(
+ phi=0,
+ theta=-90 * m.DEGREES,
+ focal_distance=40,
+ zoom=1.08,
+ frame_center=np.array([0, -0.25, 0]),
+ )
+ self.add(cones, present, dots)
+ self.play(now.animate.set_value(3.2), run_time=6.5, rate_func=m.linear)
+ self.wait(0.5)
+
+ # 7–14 s: tilt: time is depth, and every grain is a cone
+ equal = note(r"\text{arrival time} = |p - s_i|")
+ self.move_camera(
+ phi=55 * m.DEGREES,
+ theta=-62 * m.DEGREES,
+ focal_distance=24,
+ zoom=0.8,
+ frame_center=np.array([0, 0, 0.4]),
+ added_anims=[shown.animate.set_value(0.0), m.FadeIn(equal)],
+ run_time=4,
+ )
+ self.play(
+ self.camera.theta_tracker.animate.set_value(-30 * m.DEGREES), run_time=3
+ )
+
+ # 14–18 s: back to the top; time runs back to zero; one seed gets a head start
+ chosen = int(np.argmin(np.linalg.norm(sites - np.array([0.5, 0.3]), axis=1)))
+ head = note(r"\text{arrival} = t_i + |p - s_i|")
+ self.move_camera(
+ phi=0,
+ theta=-90 * m.DEGREES,
+ focal_distance=40,
+ zoom=1.08,
+ frame_center=np.array([0, -0.25, 0]),
+ added_anims=[
+ now.animate.set_value(0.0),
+ shown.animate.set_value(1.0),
+ m.FadeOut(equal),
+ ],
+ run_time=3.5,
+ )
+ self.play(
+ starts[chosen].animate.set_value(-1.15),
+ m.FadeIn(head),
+ m.Flash(dots[chosen], color=m.WHITE),
+ run_time=1,
+ )
+
+ # 18–25 s: grow again: the early grain wins more ground, with curved borders
+ self.play(now.animate.set_value(3.3), run_time=6.5, rate_func=m.linear)
+
+ # 25–30 s: the poster
+ closing = m.Text(
+ "equal starts: straight borders · a head start: hyperbolas", font_size=26
+ ).to_edge(m.DOWN, buff=0.3)
+ self.add_fixed_in_frame_mobjects(
+ m.BackgroundRectangle(closing, color=DARK, fill_opacity=0.9, buff=0.1),
+ closing,
+ )
+ self.play(
+ m.FadeIn(closing),
+ self.camera.zoom_tracker.animate.set_value(1.12),
+ run_time=4.5,
+ )
+
+
+if __name__ == "__main__":
+ VoronoiCones().render("voronoi_cones.mp4")
diff --git a/tests/docs/test_gallery.py b/tests/docs/test_gallery.py
index 4d48e2a1..351655f4 100644
--- a/tests/docs/test_gallery.py
+++ b/tests/docs/test_gallery.py
@@ -4,6 +4,7 @@ shows and its code, folded under the film."""
import re
+from docs import examples
from scripts.docs import gallery
@@ -41,3 +42,17 @@ def test_a_card_says_one_sentence() -> None:
assert re.fullmatch(r"[A-Z0-9√].*[.?!]", film.lead), film.name
assert len(film.lead.split()) <= 24, film.name
assert film.words.startswith(film.lead), film.name
+
+
+def test_gallery_scene_names_do_not_clash_with_other_examples() -> None:
+ """Scene names identify films across the entire site, including narrated lessons."""
+ scenes = {
+ example.scene: example.where
+ for example in examples.examples()
+ if not example.where.startswith(("docs/content/gallery/", "examples/"))
+ }
+ _, groups = gallery.readme()
+ for _, films in groups:
+ for film in films:
+ assert film.scene not in scenes, (film.name, scenes.get(film.scene))
+ scenes[film.scene] = f"examples/{film.name}.py"