The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add geometry and topology examples
Sina Atalayc85f5da926e0
diff --git a/examples/README.md b/examples/README.mdnew file mode 100644index 00000000..84801560--- /dev/null+++ b/examples/README.md@@ -0,0 +1,90 @@+# Examples++Thirty 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+```++## Geometry and topology++- [The Hopf fibration](hopf_fibration.py): The 3-sphere is made of circles, and every two of+ them link once. Each circle lies over one point of the ordinary sphere, and the film+ measures how every pair links.+- [A torus turned inside out](clifford_torus.py): A quarter turn in four dimensions turns a+ torus inside out. Halfway, it passes through infinity as a plane with a handle.+- [Bending without stretching](catenoid_helicoid.py): A helicoid rolls up into a catenoid+ without stretching. Distances and curvature stay the same at every step (Gauss's Theorema+ Egregium).+- [A kaleidoscope on the sphere](kaleidoscope_sphere.py): Three mirrors tile the sphere with+ 120 triangles. One point and its reflections make the icosahedron, the dodecahedron and the+ solids between them.+- [Stars in the Menger sponge](menger_slice.py): Cut through its center, the Menger sponge+ is full of six-pointed stars. The cut, across a long diagonal, is a hexagon.+- [Cubes and the arctic circle](lozenge_cubes.py): A random tiling by rhombi is a pile of+ cubes seen along a diagonal. Outside a circle, the tiling freezes.+- [Where √z lives](riemann_surfaces.py): The square root changes sign after one loop around+ 0, so it lives on two sheets. The logarithm climbs with every loop: an endless staircase.+- [Prince Rupert's cube](rupert_cube.py): A cube can pass through a hole in an identical cube+ (Prince Rupert, 1693). In 2025, the Noperthedron became the first convex solid that cannot.+- [Why a Taylor series stops](taylor_poles.py): The Taylor series of 1/(1 + x²) stops+ converging at |x| = 1. Two poles at ±i are the reason, and only the complex plane shows+ them.+- [Crystals and cones](voronoi_cones.py): Voronoi cells are crystals grown from seeds. Seen+ from above, they are also a field of cones.+- [Period doubling in the Mandelbrot set](bifurcation_mandelbrot.py): The logistic map's+ period doubling rises out of the Mandelbrot set. Each doubling sits on a pinch between two+ bulbs.+- [Circle or square?](sugihara_cylinder.py): A tube's rim is a circle from the front and a+ square in the mirror (Sugihara, 2016). It is one 3D curve, solved from the two views.+- [Stacking oranges](sphere_packing.py): Oranges stack in two ways, and one is a cube standing+ on its corner. A knife through both piles measures that each fills 74.05% of space, the most+ any stack of spheres can (Kepler, 1611; Hales, 1998).++## Physics++- [A spinning top](heavy_top.py): A spinning top doesn't fall: it precesses and nods. Its tip+ traces cusps, loops or waves, depending on how it is launched.+- [The tennis racket flip](tennis_racket.py): A handle spun about its middle axis flips over+ and over (the Dzhanibekov effect). The curves of constant energy show why.+- [Lagrange points](lagrange_points.py): Seen turning with the Earth and the Moon, the+ Lagrange points L4 and L5 are hilltops. Yet the Coriolis force keeps a probe parked on them.+- [The Van Allen belts](van_allen.py): Charged particles spin, bounce and drift in Earth's+ magnetic field. The field is a magnetic bottle, and it holds the radiation belts.+- [Leapfrogging smoke rings](vortex_rings.py): Two smoke rings take turns passing through+ each other (Helmholtz, 1858). Kelvin's impulse, r₁² + r₂², stays the same.+- [Quantum tunneling](wave_packet.py): A quantum particle tunnels through a wall it can't+ cross classically. The measured transmission matches the formula.+- [Cherenkov light](cherenkov_cone.py): A charge moving faster than light does in water+ leaves a cone of blue light. The film measures the cone's angle against the formula.+- [Turing patterns on a torus](turing_torus.py): Two chemicals react and spread on a doughnut,+ and paint it with spots and stripes (Gray–Scott; Turing, 1952).+- [Fireflies in sync](kuramoto_fireflies.py): Past a critical coupling, 2,000 fireflies fall+ into step. How in step they are matches the exact curve.+- [A coral of random walkers](dla_coral.py): 18,000 random walkers wander until they touch+ the cluster and stick. The coral they build has fractal dimension 2.5, measured from how its+ mass grows.++## Engineering++- [Steering a beam with phase](phased_array.py): Fixed antennas steer a beam by phase alone.+ The film shows the live wave field, then the beam in 3D.+- [Miura-ori](miura_ori.py): One pull folds the whole sheet, and no facet bends. It opens in+ both directions at once (a negative Poisson ratio).+- [A harmonic drive](harmonic_drive.py): Strain-wave gearing makes a 30:1 reduction in one+ flat ring. A flexible ring of 60 teeth, inside one of 62, creeps back two teeth per turn.+- [A traffic jam from nowhere](traffic_helix.py): With time as a third dimension, a traffic+ jam is a knot of paths. It moves backward while every car moves forward.++## Computing and learning++- [Noise into a word](score_diffusion.py): Noise flows into a word along the exact score of+ the data. It is a diffusion model with no neural network.+- [A network untangles spirals](neural_untangle.py): A small network, trained as the scene+ starts, lifts one spiral over the other. Then a flat plane separates them.+- [The Game of Life in spacetime](life_spacetime.py): Stack the Game of Life's generations,+ and the glider gun's gliders are staircases. They climb at c/4, a quarter of Life's top+ speed.diff --git a/examples/catenoid_helicoid.py b/examples/catenoid_helicoid.pynew file mode 100644index 00000000..d98b1a7e--- /dev/null+++ b/examples/catenoid_helicoid.py@@ -0,0 +1,222 @@+"""Bending without stretching: the helicoid rolls up into the catenoid.++The associate family X_θ = cos θ · H + sin θ · C bends a helicoid H into a catenoid C through+minimal surfaces that all share one metric, ds² = cosh² v (du² + dv²). Gauss's Theorema+Egregium says curvature is intrinsic: the color, K = −sech⁴ v, stays painted on the same+material while the shape changes completely, and the two marked curves keep their lengths.+"""++import numpy as np++import manimgx as m++U = (-np.pi, np.pi)+V = (-1.25, 1.25)+RES = (120, 48)+SCALE = 0.9+STOPS = ["#1b2a6b", "#2f6fdb", "#39c5bb", "#f4d35e", "#f25c54"]+++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 surface(theta: float, u: np.ndarray, v: np.ndarray) -> np.ndarray:+ """The associate family: θ = 0 is the helicoid, θ = π/2 the catenoid."""+ c, s = np.cos(theta), np.sin(theta)+ x = c * np.sinh(v) * np.sin(u) + s * np.cosh(v) * np.cos(u)+ y = -c * np.sinh(v) * np.cos(u) + s * np.cosh(v) * np.sin(u)+ z = u * c + v * s+ return SCALE * np.stack([x, y, z], axis=-1)+++def tube(+ points: np.ndarray, radius: float, sides: int = 12+) -> tuple[np.ndarray, np.ndarray]:+ """Vertices and triangles of a 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 grid_mesh(points: np.ndarray) -> m.MeshMobject:+ """A smooth lit mesh over an (nu + 1, nv + 1, 3) grid of points (vertex i·(nv + 1) + j), its+ cells in order along u and both triangles of a cell together, so `Create` sweeps it along u.+ """+ nu, nv = points.shape[0] - 1, points.shape[1] - 1+ idx = np.arange((nu + 1) * (nv + 1)).reshape(nu + 1, nv + 1)+ a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]+ cells = np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 2)+ return m.MeshMobject(points.reshape(-1, 3), cells.reshape(-1, 3), shade_in_3d=True)+++class CatenoidHelicoid(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(+ phi=72 * m.DEGREES, theta=-50 * m.DEGREES, zoom=0.78+ )+ theta = m.ValueTracker(0.0)++ us = np.linspace(*U, RES[0] + 1)+ vs = np.linspace(*V, RES[1] + 1)+ uu, vv = np.meshgrid(us, vs, indexing="ij")+ curvature = 1 / np.cosh(vv.ravel()) ** 4 # |K| = sech⁴ v, the same at every θ++ sheet = grid_mesh(surface(0.0, uu, vv))+ sheet.paint = sheet.paint.but(fill=colormap(curvature, STOPS))+ sheet.add_updater(+ lambda mob: mob.set_points(+ surface(theta.get_value(), uu, vv).reshape(-1, 3)+ )+ )++ # two material curves: a v-line (u = 0.9) and a u-line (v = 0.55)+ line_v = np.linspace(*V, 160)+ line_u = np.linspace(*U, 240)++ def curve_points(which: str) -> np.ndarray:+ t = theta.get_value()+ if which == "v":+ return surface(t, np.full_like(line_v, 0.9), line_v)+ return surface(t, line_u, np.full_like(line_u, 0.55))++ def make_tube(which: str, color: str) -> m.MeshMobject:+ verts, tris = tube(curve_points(which), 0.035)+ mob = m.MeshMobject(verts, tris, shade_in_3d=True, fill_color=color)++ def follow(mob: m.Mobject) -> None:+ mob.set_points(tube(curve_points(which), 0.035)[0])++ mob.add_updater(follow)+ return mob++ white_tube = make_tube("v", "#ffffff")+ black_tube = make_tube("u", "#111111")++ def length(which: str) -> float:+ p = curve_points(which)+ return float(np.linalg.norm(np.diff(p, axis=0), axis=1).sum() / SCALE)++ # heads-up display+ title = m.Text("Bending without stretching", font_size=34).to_corner(m.UL)+ subtitle = m.Text(+ "helicoid → catenoid, one family of minimal surfaces", font_size=22+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ family = m.MathTex(+ r"X_\theta = \cos\theta\,H + \sin\theta\,C", font_size=38+ ).to_corner(m.UR)+ theta_label = m.MathTex(r"\theta =", font_size=38)+ theta_value = m.DecimalNumber(0, num_decimal_places=2, font_size=38)+ theta_row = m.VGroup(theta_label, theta_value).arrange(m.RIGHT, buff=0.15)+ theta_row.next_to(family, m.DOWN, aligned_edge=m.LEFT, buff=0.3)+ theta_value.add_updater(lambda d: d.set_value(theta.get_value()))++ metric = m.MathTex(r"ds^2 = \cosh^2 v\,(du^2 + dv^2)", font_size=32).to_corner(+ m.DL+ )+ gauss = m.MathTex(r"K = -\operatorname{sech}^4 v", font_size=34)+ gauss.next_to(metric, m.UP, aligned_edge=m.LEFT, buff=0.3)++ bar = m.Rectangle(width=0.3, height=2.6, stroke_width=0, fill_opacity=1)+ bar.set_fill(color=STOPS, opacity=1)+ bar.set_sheen_direction(m.UP)+ bar.to_corner(m.DR).shift(0.6 * m.UP + 0.2 * m.LEFT)+ bar_top = m.MathTex(r"K=-1", font_size=28).next_to(bar, m.LEFT, buff=0.15)+ bar_top.align_to(bar, m.UP)+ bar_bottom = m.MathTex(r"K=-0.08", font_size=28).next_to(bar, m.LEFT, buff=0.15)+ bar_bottom.align_to(bar, m.DOWN)++ def length_row(color: str, which: str) -> m.VGroup:+ swatch = m.RoundedRectangle(+ corner_radius=0.05,+ width=0.5,+ height=0.1,+ fill_color=color,+ fill_opacity=1,+ stroke_color=m.WHITE,+ stroke_width=1,+ )+ label = m.MathTex(r"\ell =", font_size=32)+ value = m.DecimalNumber(length(which), num_decimal_places=3, font_size=32)+ value.add_updater(lambda d: d.set_value(length(which)))+ return m.VGroup(swatch, label, value).arrange(m.RIGHT, buff=0.15)++ lengths = m.VGroup(+ length_row("#ffffff", "v"), length_row("#111111", "u")+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.2)+ lengths.next_to(theta_row, m.DOWN, aligned_edge=m.LEFT, buff=0.35)++ hud = [family, theta_row, metric, gauss, bar, bar_top, bar_bottom]+ self.add_fixed_in_frame_mobjects(title, subtitle, *hud, lengths)+ self.remove(*hud, lengths)++ # 0–3 s: the helicoid sweeps in+ self.play(m.Create(sheet), run_time=3, rate_func=m.smooth)+ # 4–8 s: what stays: curvature and the metric+ self.play(+ m.FadeIn(bar),+ m.FadeIn(bar_top),+ m.FadeIn(bar_bottom),+ m.Write(gauss),+ m.Write(metric),+ run_time=2,+ )+ self.play(+ m.FadeIn(white_tube),+ m.FadeIn(black_tube),+ m.Write(family),+ m.FadeIn(theta_row),+ m.FadeIn(lengths),+ run_time=1.5,+ )+ self.begin_ambient_camera_rotation(rate=0.12)+ # 8–22 s: bend helicoid → catenoid+ self.play(theta.animate.set_value(np.pi / 2), run_time=9, rate_func=m.smooth)+ self.wait(1.0)+ self.move_camera(phi=60 * m.DEGREES, zoom=0.86, run_time=2.5)+ self.wait(0.5)+ # and on, to the mirror image of the helicoid+ self.play(theta.animate.set_value(np.pi), run_time=6, rate_func=m.smooth)+ closing = (+ m.Text("Same metric, same curvature, different shape.", font_size=28)+ .to_edge(m.DOWN, buff=0.3)+ .shift(1.2 * m.RIGHT)+ )+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(m.FadeIn(closing, shift=0.2 * m.UP), run_time=1.2)+ self.wait(2.6)+++if __name__ == "__main__":+ CatenoidHelicoid().render("catenoid_helicoid.mp4")diff --git a/examples/clifford_torus.py b/examples/clifford_torus.pynew file mode 100644index 00000000..1149be2b--- /dev/null+++ b/examples/clifford_torus.py@@ -0,0 +1,408 @@+"""Turning a torus inside out: a quarter turn in four dimensions.++The Clifford torus X(u, v) = (cos u, sin u, cos v, sin v)/√2 lies in the 3-sphere and splits it+into two congruent solid tori. Stereographic projection P(x) = (x1, x2, x3)/(1 − x4) shows it as+an ordinary torus, slate outside and wine inside (a wedge is cut away to see in). Rotating S³ by t+in the x1x3- and x2x4-planes at once, the torus has to pass through the pole x4 = 1, the point at+infinity: at t = 45° it is a plane with a handle. At t = 90° it is the same torus again, with its+gold and blue circles exchanged and its wine side facing out: the inside has become the outside.+"""++from collections.abc import Callable++import numpy as np++import manimgx as m+++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)+++S = 1.15 # scale of the projected picture+NU, NV = (+ 144,+ 160,+) # surface cells: u spans the torus minus a 30° wedge, v the full circle+LINES, RING, SIDES = (+ 12,+ 128,+ 8,+) # circles per family (30° apart), points per circle, tube sides+WEDGE = np.radians(-105.0), np.radians(-75.0) # the cut-away cell+RC = 10.0 # geometry farther than this from the origin is cut away (it runs off to infinity)+TUBE = 0.05+SLATE, WINE = "#2f3648", "#781d38"+GOLD, BLUE = "#ffbe3b", "#4aa8ff"+++# ── the torus in S³ and its shadow ─────────────────────────────────────────────────────────────+++def rotation(t: float, s: float) -> np.ndarray:+ """The quarter turn (x1x3- and x2x4-planes by t), then the smoke-ring roll (x3x4-plane by+ s), which slides the torus along itself through its hole."""+ c, d = np.cos(t), np.sin(t)+ swap = np.array([[c, 0, d, 0], [0, c, 0, -d], [-d, 0, c, 0], [0, d, 0, c]])+ c, d = np.cos(s), np.sin(s)+ roll = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, c, -d], [0, 0, d, c]])+ return roll @ swap+++def project(+ u: np.ndarray, v: np.ndarray, turn: np.ndarray+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """Projected points of the turned torus, their unit normals (pointing into the tube at+ rest), and the height x4 of each point in S³."""+ x = np.stack([np.cos(u), np.sin(u), np.cos(v), np.sin(v)], -1) @ turn.T / np.sqrt(2)+ n = (+ np.stack([np.cos(u), np.sin(u), -np.cos(v), -np.sin(v)], -1)+ @ turn.T+ / np.sqrt(2)+ )+ d = np.maximum(1 - x[..., 3:], 1e-9)+ normal = (+ n[..., :3] / d + x[..., :3] * n[..., 3:] / d**2+ ) # the differential of P, applied to n+ normal /= np.linalg.norm(normal, axis=-1, keepdims=True)+ return S * x[..., :3] / d, normal, x[..., 3]+++# ── meshes ─────────────────────────────────────────────────────────────────────────────────────+++def grid_triangles(nu: int, nv: int) -> np.ndarray:+ """Triangles of an (nu + 1) × nv grid, open in u and periodic in v, ordered along u."""+ i = np.arange(nu)[:, None]+ j = np.arange(nv)[None, :]+ a, b = i * nv + j, (i + 1) * nv + j+ c, d = (i + 1) * nv + (j + 1) % nv, i * nv + (j + 1) % nv+ return np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 2).reshape(+ -1, 3+ )+++def tube_triangles(lines: int, n: int, sides: int) -> np.ndarray:+ """Triangles of closed tubes, shaped (lines, n segments, 2·sides, 3)."""+ li = np.arange(lines)[:, None, None]+ i = np.arange(n)[None, :, None]+ j = np.arange(sides)[None, None, :]+ base = li * n * sides+ a, b = base + i * sides + j, base + (i + 1) % n * sides + j+ c, d = (+ base + (i + 1) % n * sides + (j + 1) % sides,+ base + i * sides + (j + 1) % sides,+ )+ tris = np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 3)+ return tris.reshape(lines, n, 2 * sides, 3)+++def tubes(points: np.ndarray, normals: np.ndarray) -> np.ndarray:+ """Vertices of closed tubes around curves (lines, n, 3) lying on the surface."""+ tangent = np.roll(points, -1, 1) - np.roll(points, 1, 1)+ tangent /= np.maximum(np.linalg.norm(tangent, axis=-1, keepdims=True), 1e-12)+ side = np.cross(tangent, normals)+ a = np.linspace(0, m.TAU, SIDES, endpoint=False)[:, None]+ ring = np.cos(a) * normals[:, :, None] + np.sin(a) * side[:, :, None]+ return (points[:, :, None] + TUBE * ring).reshape(-1, 3)+++def clip(+ values: np.ndarray, triangles: np.ndarray, far: np.ndarray+) -> tuple[np.ndarray, np.ndarray]:+ """Keep the part of a mesh where far < 0, cutting triangles along far = 0 so the edge is+ smooth instead of a staircase. `values` are per-vertex rows (position, normal, ...),+ interpolated at the cuts; returns them (cut rows appended) and the kept triangles.+ """+ out = far[triangles] >= 0+ count = out.sum(axis=1)+ pieces, rows = [triangles[count == 0]], [values]+ total = len(values)++ def cut(a: np.ndarray, b: np.ndarray) -> np.ndarray:+ nonlocal total+ lam = (far[a] / (far[a] - far[b]))[:, None]+ rows.append(values[a] * (1 - lam) + values[b] * lam)+ total += len(a)+ return np.arange(total - len(a), total)++ for k in (1, 2):+ tri, o = triangles[count == k], out[count == k]+ # turn each triangle (keeping its winding) so the odd vertex is last (k = 1) or first+ first = (np.argmax(o, axis=1) + 1) % 3 if k == 1 else np.argmin(o, axis=1)+ a, b, c = np.take_along_axis(tri, (first[:, None] + np.arange(3)) % 3, 1).T+ if k == 1: # c is out: a quad remains+ bc, ac = cut(b, c), cut(a, c)+ pieces += [np.stack([a, b, bc], 1), np.stack([a, bc, ac], 1)]+ else: # only a is in: a small triangle remains+ pieces.append(np.stack([a, cut(a, b), cut(a, c)], 1))+ return np.concatenate(rows), np.concatenate(pieces)+++def linger(x: float) -> float:+ """A smooth 0 → 1 that slows down in the middle, where the torus passes infinity."""+ ease = x / 2 - np.sin(4 * np.pi * x) / (+ 8 * np.pi+ ) # speed sin²(2πx): rests at 0, ½, 1+ through = x / 2 - np.sin(2 * np.pi * x) / (+ 4 * np.pi+ ) # speed sin²(πx): keeps it moving+ return float((ease + 0.3 * through) / 0.65)+++def passage(t: float) -> float:+ """0 while the torus is small; 1 while it is near infinity (t within 15° of 45°)."""+ x = float(np.clip((np.radians(25) - abs(t - np.pi / 4)) / np.radians(10), 0, 1))+ return x * x * (3 - 2 * x)+++def live(number: m.DecimalNumber, value: Callable[[], float]) -> m.DecimalNumber:+ """Keep a number showing value(), re-typesetting it only when its digits change."""++ def update(d: m.DecimalNumber) -> None:+ v, places = value(), d.num_decimal_places+ if round(v, places) != round(d.get_value(), places):+ d.set_value(v)++ number.add_updater(update)+ return number+++def vignette() -> m.ImageMobject:+ """A screen-sized frame that darkens the edges, so the HUD stays legible when the torus+ fills the screen (invisible against the background otherwise)."""+ h, w = 180, 320+ y, x = np.mgrid[-1 : 1 : h * 1j, -1 : 1 : w * 1j]+ d = np.clip(((np.abs(x) ** 3 + np.abs(y) ** 3) ** (1 / 3) - 0.55) / 0.4, 0, 1)+ image = np.zeros((h, w, 4), np.uint8) # black, like the background+ image[..., 3] = (230 * d * d * (3 - 2 * d)).astype(np.uint8)+ mob = m.ImageMobject(image)+ mob.stretch_to_fit_width(m.config.frame_width)+ mob.stretch_to_fit_height(m.config.frame_height)+ return mob+++class Shadow:+ """Everything drawn, for the current angles and camera: recomputed once per frame."""++ def __init__(+ self, scene: m.ThreeDScene, t: m.ValueTracker, s: m.ValueTracker+ ) -> None:+ self.scene, self.t, self.s = scene, t, s+ self.grow = m.ValueTracker(0.04)+ self.key: tuple[float, ...] = ()+ us = np.linspace(WEDGE[1], WEDGE[0] + m.TAU, NU + 1)+ # v is offset by half a cell, so that no vertex ever lands exactly on the pole+ vs = (np.arange(NV) + 0.5) * m.TAU / NV+ self.u, self.v = np.meshgrid(us, vs, indexing="ij")+ self.surface_triangles = grid_triangles(NU, NV)+ ring = np.linspace(0, m.TAU, RING, endpoint=False)+ levels = WEDGE[0] + np.arange(LINES) * m.TAU / LINES+ ones = np.ones((LINES, RING))+ # gold circles: v fixed, u runs; blue circles: u fixed (both wedge edges among them)+ self.circles = {+ "gold": (ring * ones, (levels + np.pi / 12)[:, None] * ones),+ "blue": (levels[:, None] * ones, ring * ones),+ }+ self.tube_triangles = tube_triangles(LINES, RING, SIDES)+ self.meshes: dict[str, tuple[np.ndarray, np.ndarray]] = {}+ self.colors = np.zeros((0, 4))+ self.points = self.normals = np.zeros((0, 3))+ self.height = 0.0+ self.slate, self.wine = (+ np.array(m.ManimColor(c).to_rgba()) for c in (SLATE, WINE)+ )++ def update(self) -> None:+ cam = self.scene.camera+ angles = (cam.get_phi(), cam.get_theta(), cam.get_gamma())+ key = (self.t.get_value(), self.s.get_value(), self.grow.get_value(), *angles)+ if key == self.key:+ return+ self.key = key+ turn = rotation(key[0], key[1])+ p, n, x4 = project(self.u, self.v, turn)+ self.points, self.normals = p.reshape(-1, 3), n.reshape(-1, 3)+ self.height = float(x4.max())+ # the sweep that builds the torus: a front at angle `front` past the wedge+ front = key[2] * (m.TAU + 2.2)+ cells = int(np.clip(front / (m.TAU - (WEDGE[1] - WEDGE[0])), 0, 1) * NU)+ shown = self.surface_triangles[: 2 * NV * cells]+ far = np.linalg.norm(self.points, axis=1) - RC+ rows, tris = clip(np.hstack([self.points, self.normals]), shown, far)+ # two-sided paint: slate where the outer side faces the eye, wine where the inner does+ eye = cam.frame_center + cam.get_focal_distance() * camera_axes(*angles)[2]+ inner = np.sum(rows[:, 3:] * (eye - rows[:, :3]), axis=1) > 0+ self.colors = np.where(inner[:, None], self.wine, self.slate)+ self.meshes["surface"] = rows[:, :3], tris+ for name, (cu, cv) in self.circles.items():+ cp, cn, _ = project(cu, cv, turn)+ # how long ago the front passed each point of the circle+ passed = front - (cu - WEDGE[1]) % m.TAU+ # a gold circle is laid down with the front; a blue one then draws itself round+ drawn = passed >= 0 if name == "gold" else cv <= 3 * passed+ near = np.linalg.norm(cp, axis=-1) < RC+ keep = drawn & np.roll(drawn, -1, 1) & near & np.roll(near, -1, 1)+ self.meshes[name] = (+ tubes(cp, cn),+ self.tube_triangles[keep].reshape(-1, 3),+ )++ def mesh(self, name: str, color: str) -> m.MeshMobject:+ mob = m.MeshMobject(+ np.zeros((3, 3)), np.array([[0, 1, 2]]), shade_in_3d=True, fill_color=color+ )++ def follow(mob: m.MeshMobject) -> None:+ self.update()+ mob.points, mob.triangles = self.meshes[name]+ if name == "surface":+ mob.paint = mob.paint.but(fill=self.colors)++ mob.add_updater(follow)+ return mob++ def outside_is_slate(self) -> bool:+ """Measured: at the torus's farthest point, is the slate side the one facing away?"""+ self.update()+ k = int(np.argmax(np.linalg.norm(self.points, axis=1)))+ return float(self.points[k] @ self.normals[k]) < 0+++class CliffordTorus(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(+ phi=66 * m.DEGREES, theta=-116 * m.DEGREES, zoom=1.0, focal_distance=40+ )+ self.begin_ambient_camera_rotation(rate=0.045)+ t, s = m.ValueTracker(0.0), m.ValueTracker(-np.pi / 2)+ shadow = Shadow(self, t, s)+ colors = {"surface": SLATE, "gold": GOLD, "blue": BLUE}+ self.add(*(shadow.mesh(name, color) for name, color in colors.items()))++ # heads-up display+ title = m.Text("Turning a torus inside out", font_size=36).to_corner(m.UL)+ subtitle = m.Text(+ "the Clifford torus, rotated in four dimensions", font_size=22+ )+ subtitle.set_color(m.GREY_B).next_to(+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.15+ )+ formulas = m.VGroup(+ m.MathTex(+ r"X(u,v) = \frac{1}{\sqrt{2}}\,(\cos u,\ \sin u,\ \cos v,\ \sin v)",+ font_size=30,+ ),+ m.MathTex(r"P(x) = \frac{(x_1,\ x_2,\ x_3)}{1 - x_4}", font_size=30),+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.25)+ formulas.to_corner(m.UR)++ def swatch(outside: bool) -> m.Square:+ box = m.Square(0.26, fill_opacity=1, stroke_color=m.WHITE, stroke_width=1)+ box.add_updater(+ lambda b: b.set_fill(+ SLATE if shadow.outside_is_slate() == outside else WINE+ )+ )+ return box++ legend = m.VGroup(+ m.VGroup(swatch(True), m.Text("outside", font_size=24)),+ m.VGroup(swatch(False), m.Text("inside", font_size=24)),+ )+ for row in legend:+ row.arrange(m.RIGHT, buff=0.2)+ legend.arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.2).to_corner(m.DL)++ plane_note = m.MathTex(+ r"\text{rotating the } x_1x_3 \text{ and } x_2x_4 \text{ planes}",+ font_size=26,+ ).set_color(m.GREY_B)+ angle = live(+ m.DecimalNumber(0, num_decimal_places=1, unit=r"^\circ", font_size=30),+ lambda: float(np.degrees(t.get_value())),+ )+ height = live(+ m.DecimalNumber(shadow.height, num_decimal_places=3, font_size=30),+ lambda: shadow.height,+ )+ readouts = m.VGroup(+ m.VGroup(m.MathTex(r"t =", font_size=30), angle),+ m.VGroup(m.MathTex(r"\max x_4 =", font_size=30), height),+ )+ for row in readouts:+ row.arrange(m.RIGHT, buff=0.15)+ readouts.arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.2)+ hud_br = m.VGroup(plane_note, readouts).arrange(+ m.DOWN, aligned_edge=m.RIGHT, buff=0.2+ )+ hud_br.to_corner(m.DR)++ caption = m.MathTex(+ r"x_4 = 1 \text{ is the point at infinity, and the torus passes"+ r" through it}",+ font_size=28,+ )+ caption.to_edge(m.DOWN, buff=0.3)+ # while the torus fills the screen, the caption replaces the formulas and the subtitle+ formulas_on = m.ValueTracker(0.0)+ caption.add_updater(lambda c: c.set_opacity(passage(t.get_value())))+ subtitle.add_updater(lambda c: c.set_opacity(1 - passage(t.get_value())))+ formulas.add_updater(+ lambda f: f.set_opacity(+ formulas_on.get_value() * (1 - passage(t.get_value()))+ )+ )++ self.add_fixed_in_frame_mobjects(vignette(), title, subtitle)+ self.add_fixed_in_frame_mobjects(formulas, legend, hud_br, caption)+ self.remove(legend, hud_br)++ # 0–2.5 s: the torus is swept in; its open end shows the wine inside+ self.play(shadow.grow.animate.set_value(1.0), run_time=2.5, rate_func=m.smooth)+ # 2.5–7 s: the smoke ring: the gold circles roll through the hole+ self.play(+ s.animate.set_value(0.0),+ m.Succession(+ formulas_on.animate(run_time=1.2).set_value(1.0),+ m.FadeIn(legend, run_time=1.2),+ ),+ run_time=4.5,+ rate_func=m.linear,+ )+ # 7–18 s: the quarter turn in 4D, through the point at infinity+ self.play(m.FadeIn(hud_br), run_time=0.6)+ self.play(t.animate.set_value(np.pi / 2), run_time=10.5, rate_func=linger)+ # 18–24 s: the smoke ring again: now the blue circles roll through the hole+ self.move_camera(+ phi=54 * m.DEGREES,+ zoom=1.1,+ run_time=6,+ added_anims=[s.animate(rate_func=m.linear).set_value(np.pi / 2)],+ )+ closing = m.Text("A quarter turn in 4D swaps inside and outside.", font_size=28)+ closing.to_edge(m.DOWN, buff=0.3)+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(+ m.FadeIn(closing, shift=0.2 * m.UP),+ s.animate.set_value(0.6 * np.pi),+ run_time=1.5,+ rate_func=m.linear,+ )+ self.play(s.animate.set_value(0.9 * np.pi), run_time=4.4, rate_func=m.linear)+++if __name__ == "__main__":+ CliffordTorus().render("clifford_torus.mp4")diff --git a/examples/hopf_fibration.py b/examples/hopf_fibration.pynew file mode 100644index 00000000..dfa9225e--- /dev/null+++ b/examples/hopf_fibration.py@@ -0,0 +1,471 @@+"""The Hopf fibration: the 3-sphere is made of circles, one over each point of the 2-sphere.++The Hopf map h(z1, z2) = (2 z1 z̄2, |z1|² − |z2|²) sends the unit 3-sphere in C² onto the 2-sphere,+and the points sent to p = (θ, φ) form a great circle: (cos(θ/2) e^{iξ}, sin(θ/2) e^{i(ξ − φ)}).+Stereographic projection P(x) = (x1, x2, x3)/(1 − x4) keeps circles circles. A point on the small+sphere (lower left) lights up its circle; a point sweeping a latitude sweeps out a torus of+Villarceau circles; four latitudes nest four tori around the circle over the north pole, and the+circle over the south pole runs through infinity as the vertical axis. Every two circles link once:+the Gauss linking integral of every drawn pair is measured, not assumed.+"""++from collections.abc import Callable++import numpy as np++import manimgx as m+++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)+++S = 0.8 # scale of the projected picture+LATITUDES = np.radians([30.0, 60.0, 90.0, 120.0]) # polar angles of the four tori+COLORS = ["#ffc94a", "#ff8a3d", "#f0506e", "#6f8cff"]+PER_TORUS = 16 # circles per torus+RING, SIDES, TUBE = 128, 8, 0.032 # points per circle, tube sides, tube radius+BALL = 0.9 # radius of the base sphere, pinned to the lower left of the screen+BALL_AT = np.array([-5.25, -2.3])+++# ── the fibration ──────────────────────────────────────────────────────────────────────────────+++def hopf_circle(+ theta: float | np.ndarray, phi: float | np.ndarray, xi: np.ndarray+) -> np.ndarray:+ """The projected points ξ of the circle over the base point (θ, φ) (arrays broadcast)."""+ z1 = np.cos(theta / 2) * np.exp(1j * xi)+ z2 = np.sin(theta / 2) * np.exp(1j * (xi - phi))+ x = np.stack([z1.real, z1.imag, z2.real, z2.imag], -1)+ return S * x[..., :3] / (1 - x[..., 3:])+++def fibre(theta: float, phi: float) -> np.ndarray:+ """Three points of the projected circle over the base point (θ, φ)."""+ return hopf_circle(theta, phi, np.array([0.0, 2 * np.pi / 3, 4 * np.pi / 3]))+++def circle(three: np.ndarray, n: int = RING) -> np.ndarray:+ """n evenly spaced points of the circle through three points, from the first one on."""+ a, b, c = three+ ab, ac = b - a, c - a+ normal = np.cross(ab, ac)+ center = a + (+ np.dot(ac, ac) * np.cross(normal, ab) + np.dot(ab, ab) * np.cross(ac, normal)+ ) / (2 * np.dot(normal, normal))+ radius = np.linalg.norm(a - center)+ e1 = (a - center) / radius+ e2 = np.cross(normal / np.linalg.norm(normal), e1)+ angle = np.linspace(0, m.TAU, n, endpoint=False)[:, None]+ return center + radius * (np.cos(angle) * e1 + np.sin(angle) * e2)+++def ring_tubes(+ curves: np.ndarray, radius: float = TUBE+) -> tuple[np.ndarray, np.ndarray]:+ """A lit tube around each closed planar curve in (count, n, 3): vertices, and triangles+ shaped (count, n, 2·SIDES, 3) so each curve can be revealed segment by segment."""+ count, n, _ = curves.shape+ tangent = np.roll(curves, -1, 1) - np.roll(curves, 1, 1)+ tangent /= np.linalg.norm(tangent, axis=-1, keepdims=True)+ chord = np.cross(+ curves[:, n // 3] - curves[:, 0], curves[:, 2 * n // 3] - curves[:, 0]+ )+ plane = (chord / np.linalg.norm(chord, axis=-1, keepdims=True))[:, None, :]+ inward = np.cross(tangent, plane)+ a = np.linspace(0, m.TAU, SIDES, endpoint=False)[:, None]+ ring = np.cos(a) * inward[:, :, None] + np.sin(a) * plane[:, :, None]+ verts = (curves[:, :, None] + radius * ring).reshape(-1, 3)+ f = np.arange(count)[:, None, None]+ i = np.arange(n)[None, :, None]+ j = np.arange(SIDES)[None, None, :]+ base = f * n * SIDES+ p, q = base + i * SIDES + j, base + (i + 1) % n * SIDES + j+ r, s = (+ base + (i + 1) % n * SIDES + (j + 1) % SIDES,+ base + i * SIDES + (j + 1) % SIDES,+ )+ tris = np.stack([np.stack([p, q, r], -1), np.stack([p, r, s], -1)], 3)+ return verts, tris.reshape(count, n, 2 * SIDES, 3)+++def linking(a: np.ndarray, b: np.ndarray, edges: int | None = None) -> np.ndarray:+ """Gauss linking integrals of closed polygons a (k, n, 3) with the polygon b (n', 3), or+ with its first `edges` edges only: (1/4π) ∮∮ (r_a − r_b)·(dr_a × dr_b)/|r_a − r_b|³, summed+ exactly over pairs of edges as the signed solid angles of the quadrilaterals they span+ (Klenin & Langowski 2000). For two closed polygons it is their linking number."""++ def unit(v: np.ndarray) -> np.ndarray:+ return v / np.linalg.norm(v, axis=-1, keepdims=True)++ p1, p2 = a[:, :, None], np.roll(a, -1, 1)[:, :, None]+ p3, p4 = b[None, None], np.roll(b, -1, 0)[None, None]+ r13, r14, r23, r24 = p3 - p1, p4 - p1, p3 - p2, p4 - p2+ corners = [unit(np.cross(r13, r14)), unit(np.cross(r14, r24))]+ corners += [unit(np.cross(r24, r23)), unit(np.cross(r23, r13))]+ omega = sum(+ np.arcsin(np.clip(np.sum(corners[i] * corners[(i + 1) % 4], -1), -1, 1))+ for i in range(4)+ )+ sign = np.sign(np.sum(np.cross(p4 - p3, p2 - p1) * r13, -1))+ return np.sum((omega * sign)[:, :, :edges], axis=(1, 2)) / (4 * np.pi)+++def live(number: m.DecimalNumber, value: Callable[[], float]) -> m.DecimalNumber:+ """Keep a number showing value(), re-typesetting it only when its digits change."""++ def update(d: m.DecimalNumber) -> None:+ v, places = value(), d.num_decimal_places+ if round(v, places) != round(d.get_value(), places):+ d.set_value(v)++ number.add_updater(update)+ return number+++def beads(centers: np.ndarray, radius: float) -> tuple[np.ndarray, np.ndarray]:+ """Vertices and triangles of small lit spheres at the given centers (one mesh)."""+ lon, lat = np.meshgrid(+ np.linspace(0, m.TAU, 9)[:-1], np.linspace(0, np.pi, 6), indexing="ij"+ )+ ball = np.stack(+ [np.sin(lat) * np.cos(lon), np.sin(lat) * np.sin(lon), np.cos(lat)], -1+ )+ ball = ball.reshape(-1, 3)+ i, j = np.meshgrid(np.arange(8), np.arange(5), indexing="ij")+ a, b = i * 6 + j, (i + 1) % 8 * 6 + j+ tris = np.concatenate(+ [np.stack([a, b, b + 1], -1), np.stack([a, b + 1, a + 1], -1)]+ )+ tris = tris.reshape(-1, 3)+ verts = (centers[:, None] + radius * ball[None]).reshape(-1, 3)+ offsets = len(ball) * np.arange(len(centers))[:, None, None]+ return verts, (tris[None] + offsets).reshape(-1, 3)+++# ── the scene ──────────────────────────────────────────────────────────────────────────────────+++def base_point(theta: float, phi: float) -> np.ndarray:+ return np.array(+ [np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)]+ )+++def parametric_mesh(+ func: Callable[[float, float], np.ndarray],+ u_range: tuple[float, float],+ v_range: tuple[float, float],+ resolution: tuple[int, int],+ fill_color: str,+) -> m.MeshMobject:+ """A smooth lit mesh of func over a (u, v) grid: vertex i·(nv + 1) + j is at (u_i, v_j),+ each cell two triangles."""+ nu, nv = resolution+ us, vs = np.linspace(*u_range, nu + 1), np.linspace(*v_range, nv + 1)+ points = np.array([[func(u, v) for v in vs] for u in us], dtype=float)+ idx = np.arange((nu + 1) * (nv + 1)).reshape(nu + 1, nv + 1)+ a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]+ cells = np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 2)+ return m.MeshMobject(+ points.reshape(-1, 3),+ cells.reshape(-1, 3),+ shade_in_3d=True,+ fill_color=fill_color,+ )+++class Torus:+ """The circles over one latitude, all computed up front and laid down as a point sweeps+ past them (its own circle, moving with it, is the brush)."""++ def __init__(self, theta: float, color: str) -> None:+ self.theta, self.color = theta, color+ self.phis = np.arange(PER_TORUS) * m.TAU / PER_TORUS+ self.curves = np.stack([circle(fibre(theta, phi)) for phi in self.phis])+ self.verts, self.tris = ring_tubes(self.curves)+ self.sweep = m.ValueTracker(-1.0) # the sweeping point's φ (negative: not yet)+ self.count = 0+ self.mob = m.MeshMobject(+ self.verts, self.tris[:0].reshape(-1, 3), shade_in_3d=True+ )+ self.mob.set_fill(color)+ self.mob.add_updater(lambda mob: self.lay_down(mob))++ def laid(self) -> np.ndarray:+ return np.greater_equal(self.sweep.get_value(), self.phis - 1e-9)++ def lay_down(self, mob: m.MeshMobject) -> None:+ laid = self.laid()+ if laid.sum() != self.count:+ self.count = int(laid.sum())+ # points are assigned too: a change of triangles alone is not redrawn+ mob.points, mob.triangles = self.verts, self.tris[laid].reshape(-1, 3)+++class HopfFibration(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(+ phi=68 * m.DEGREES, theta=-128 * m.DEGREES, zoom=1.0, focal_distance=30+ )+ cam = self.camera+ ball_size = m.ValueTracker(0.0)++ def pinned(p: np.ndarray) -> np.ndarray:+ """World position of the point p of the unit base sphere, which sits at a fixed+ spot of the screen but keeps the world's orientation (it turns as the camera+ orbits, like everything else)."""+ axes = camera_axes(cam.get_phi(), cam.get_theta(), cam.get_gamma())+ at = BALL_AT / cam.get_zoom()+ size = BALL * ball_size.get_value()+ return cam.frame_center + at[0] * axes[0] + at[1] * axes[1] + size * p++ def dot(where: Callable[[], np.ndarray], color: str, radius: float) -> m.Dot3D:+ """A point on the base sphere; where() is its unit vector (0: hidden inside)."""+ d = m.Dot3D(radius=radius, color=color)+ d.add_updater(lambda d: d.move_to(pinned(1.01 * where())))+ return d++ # the base sphere S²+ ball = parametric_mesh(base_point, (0, np.pi), (0, m.TAU), (24, 48), "#1d2436")+ unit = ball.points.copy()+ ball.add_updater(lambda mob: mob.set_points(pinned(unit)))++ # the four tori, and a dot under every circle laid down+ tori = [Torus(th, c) for th, c in zip(LATITUDES, COLORS)]+ trail = [+ dot(+ lambda t=t, k=k: base_point(t.theta, t.phis[k]) * t.laid()[k],+ t.color,+ 0.04,+ )+ for t in tori+ for k in range(PER_TORUS)+ ]++ # moving points (θ, φ, how much of its circle is drawn): one per latitude, whose+ # circles are the brushes, and the north pole, whose circle is the core of every torus+ points = [+ (m.ValueTracker(th), m.ValueTracker(0.0), m.ValueTracker(0.0))+ for th in [*LATITUDES, 0.0]+ ]++ def brush(k: int, color: str) -> tuple[m.Dot3D, m.MeshMobject]:+ theta, phi, drawn = points[k]++ def shape() -> tuple[np.ndarray, np.ndarray]:+ verts, tris = ring_tubes(+ circle(fibre(theta.get_value(), phi.get_value()))[None]+ )+ return verts, tris[0, : int(drawn.get_value() * RING)].reshape(-1, 3)++ mob = m.MeshMobject(*shape(), shade_in_3d=True, fill_color=color)++ def update(mob: m.MeshMobject) -> None:+ mob.points, mob.triangles = shape()++ mob.add_updater(update)++ def where() -> np.ndarray:+ return base_point(theta.get_value(), phi.get_value())++ return dot(where, color, 0.065), mob++ brushes = [brush(k, c) for k, c in enumerate([*COLORS, "#e8ebf2"])]+ (a_theta, a_phi, a_drawn), (b_theta, b_phi, b_drawn) = points[1], points[3]+ b_phi.set_value(np.radians(110))++ # the circle over the south pole runs through infinity: the axis, grown both ways+ axis_length = m.ValueTracker(0.0)+ axis = parametric_mesh(+ lambda u, z: np.array(+ [+ TUBE * np.sqrt(1 - abs(z) ** 3) * np.cos(u),+ TUBE * np.sqrt(1 - abs(z) ** 3) * np.sin(u),+ z,+ ]+ ),+ (0, m.TAU),+ (-1, 1),+ (SIDES, 80),+ "#c8ccd8",+ )+ spindle = axis.points.copy()++ def axis_scale() -> np.ndarray:+ grown = (+ axis_length.get_value()+ ) # 0 → 1: thickens at once, lengthens steadily+ return np.array([min(1.0, 4 * grown), min(1.0, 4 * grown), 3.1 * grown])++ axis.add_updater(lambda mob: mob.set_points(spindle * axis_scale()))+ south = dot(+ lambda: base_point(np.pi, 0.0) * (axis_length.get_value() > 0),+ "#e8ebf2",+ 0.065,+ )++ # beads riding the circles: the circle action (z1, z2) ↦ e^{is}(z1, z2), a rotation of S³+ base = np.array([(t.theta, phi) for t in tori for phi in t.phis] + [(0.0, 0.0)])+ per_circle = 6+ bead_theta, bead_phi = (np.repeat(base[:, k], per_circle) for k in (0, 1))+ bead_xi = np.tile(np.arange(per_circle) * m.TAU / per_circle, len(base))+ flow, bead_size = m.ValueTracker(0.0), m.ValueTracker(0.0)++ def bead_mesh() -> tuple[np.ndarray, np.ndarray]:+ centers = hopf_circle(bead_theta, bead_phi, bead_xi + flow.get_value())+ return beads(centers, 0.06 * bead_size.get_value())++ bead_mob = m.MeshMobject(*bead_mesh(), shade_in_3d=True)+ tints = [+ m.interpolate_color(m.ManimColor(c), m.WHITE, 0.6)+ for c in [*COLORS, "#fff"]+ ]+ rows = np.array(+ [tints[min(i // PER_TORUS, 4)].to_rgba() for i in range(len(base))]+ )+ per_bead = len(bead_mob.points) // len(bead_theta)+ bead_mob.paint = bead_mob.paint.but(+ fill=np.repeat(rows, per_circle * per_bead, axis=0)+ )+ bead_mob.add_updater(lambda mob: mob.set_points(bead_mesh()[0]))++ # heads-up display+ title = m.Text("The fibration", font_size=38).to_corner(m.UL)+ subtitle = m.Text(+ "S³ is made of circles, one over each point of S²", font_size=22+ )+ subtitle.set_color(m.GREY_B).next_to(+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.15+ )+ closing = m.Text("Circle links every other exactly once.", font_size=24)+ closing.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ hopf = m.MathTex(+ r"h(z_1, z_2) = \big(2 z_1 \bar z_2,\ \lvert z_1\rvert^2 - \lvert"+ r" z_2\rvert^2\big)",+ font_size=32,+ ).to_corner(m.UR)+ base_label = m.MathTex(r"S^2", font_size=34)+ base_label.move_to([BALL_AT[0] + 1.2, BALL_AT[1] + 0.9, 0])++ def two_circles() -> float:+ """The Gauss integral of A's circle with the part of B's circle drawn so far."""+ a = circle(fibre(a_theta.get_value(), a_phi.get_value()), RING // 2)+ b = circle(fibre(b_theta.get_value(), b_phi.get_value()), RING // 2)+ return float(linking(a[None], b, int(b_drawn.get_value() * RING // 2))[0])++ link_value = m.DecimalNumber(two_circles(), num_decimal_places=3, font_size=30)+ link_row = m.VGroup(+ m.Text("Gauss linking integral", font_size=24),+ live(link_value, two_circles),+ )+ link_row.arrange(m.RIGHT, buff=0.2).to_corner(m.DR)++ # every pair of the 65 circles drawn in the end, measured once (on every other vertex)+ drawn = np.concatenate(+ [t.curves for t in tori] + [circle(fibre(0.0, 0.0))[None]]+ )+ drawn = drawn[:, ::2]+ pairs = np.concatenate(+ [linking(drawn[i + 1 :], drawn[i]) for i in range(len(drawn) - 1)]+ )+ all_row = m.VGroup(+ m.Text(f"all {len(pairs)} pairs of circles", font_size=24),+ m.VGroup(+ m.Text("linking numbers from", font_size=24),+ m.DecimalNumber(pairs.min(), num_decimal_places=3, font_size=30),+ m.Text("to", font_size=24),+ m.DecimalNumber(pairs.max(), num_decimal_places=3, font_size=30),+ ).arrange(m.RIGHT, buff=0.15),+ ).arrange(m.DOWN, aligned_edge=m.RIGHT, buff=0.15)+ all_row.to_corner(m.DR)++ self.add_fixed_in_frame_mobjects(title, subtitle, base_label, hopf, link_row)+ self.add_fixed_in_frame_mobjects(all_row, closing)+ self.remove(base_label, hopf, link_row, all_row, closing)+ self.add(ball, *(t.mob for t in tori), axis, bead_mob, *trail, *brushes[1])+ self.begin_ambient_camera_rotation(rate=0.06)++ # 0–1.8 s: one point, one circle+ self.play(+ ball_size.animate(run_time=0.6).set_value(1.0),+ a_drawn.animate(run_time=1.8).set_value(1.0),+ m.FadeIn(base_label, run_time=0.6),+ m.FadeIn(hopf, run_time=1.2),+ )+ # 1.8–3.8 s: a second point, a second circle: the integral grows to 1 as it closes+ self.add(*brushes[3])+ self.play(m.FadeIn(link_row), run_time=0.4)+ self.play(b_drawn.animate.set_value(1.0), run_time=1.6, rate_func=m.linear)+ # 3.8–7 s: the second point wanders; its circle stays linked, and the integral says so+ self.play(+ b_theta.animate.set_value(np.radians(70)),+ b_phi.animate.set_value(np.radians(250)),+ run_time=1.6,+ )+ self.play(+ b_theta.animate.set_value(LATITUDES[3]),+ b_phi.animate.set_value(m.TAU),+ run_time=1.6,+ )+ # 7–11 s: B sweeps its latitude, leaving circles behind: a torus+ b_phi.set_value(0.0)+ self.play(+ b_phi.animate.set_value(m.TAU),+ tori[3].sweep.animate.set_value(m.TAU),+ run_time=4.0,+ rate_func=m.linear,+ )+ self.remove(*brushes[3])+ # 11–15.6 s: three more points sweep three more latitudes at once: nested tori+ self.add(*brushes[0], *brushes[2])+ self.play(*(points[k][2].animate.set_value(1.0) for k in (0, 2)), run_time=0.6)+ self.play(+ *(points[k][1].animate.set_value(m.TAU) for k in range(3)),+ *(tori[k].sweep.animate.set_value(m.TAU) for k in range(3)),+ run_time=4.0,+ rate_func=m.linear,+ )+ self.remove(*brushes[0], *brushes[1], *brushes[2])+ # 15.6–17.2 s: the circles over the poles: the core, and a line through infinity+ self.add(*brushes[4], south)+ self.play(+ points[4][2].animate.set_value(1.0),+ axis_length.animate.set_value(1.0),+ run_time=1.6,+ )+ # 17.2–30 s: every pair measured; the beads ride their circles; the closing line+ flow.add_updater(lambda v, dt: v.increment_value(m.TAU / 7 * dt))+ self.add(flow)+ self.play(+ m.FadeOut(link_row),+ m.FadeIn(all_row),+ bead_size.animate.set_value(1.0),+ run_time=1.0,+ )+ self.wait(2.0)+ self.play(+ m.FadeOut(subtitle, shift=0.15 * m.UP),+ m.FadeIn(closing, shift=0.15 * m.UP),+ run_time=1.2,+ )+ self.play(+ cam.zoom_tracker.animate.set_value(1.12), run_time=8.6, rate_func=m.smooth+ )+++if __name__ == "__main__":+ HopfFibration().render("hopf_fibration.mp4")