The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add classic mathematical explanation films
Sina Atalayc58cc0590475
diff --git a/examples/circle_area.py b/examples/circle_area.pynew file mode 100644index 00000000..29b2870a--- /dev/null+++ b/examples/circle_area.py@@ -0,0 +1,146 @@+"""Why a circle's area is πr²: unroll it.++Cut a disc of radius r into thin rings. Each ring, cut at the top and unrolled, is a thin strip+as long as its circumference, 2πρ for the ring of radius ρ, and as thick as the ring. Stack the+strips, the longest at the bottom: their lengths shrink evenly from 2πr to 0, so they make a+right triangle with base 2πr and height r. Its area is ½ · 2πr · r = πr², and so is the disc's:+the thinner the rings, the closer the stack to the triangle.+"""++import numpy as np++import manimgx as m++WALL = 3.4 # the rings unroll and stack++N = 24 # rings+R = 1.9 # the disc's radius, in scene units+DR = R / N # each ring's thickness+CENTER = np.array([-3.4, 1.75, 0]) # the disc's+CORNER = np.array([-5.55, -2.95, 0]) # the triangle's right angle, bottom left+RINGS = m.color_gradient([m.BLUE, m.TEAL, m.GREEN], N) # inside out+RADIUS = m.YELLOW # r, the radius and the triangle's height+ROUND = m.GREEN # 2πr, the outermost ring and the triangle's base+SAMPLES = 121+++def ring_points(rho: float, unrolled: float, bottom: np.ndarray) -> np.ndarray:+ """The ring of radius `rho`, `unrolled` from 0 (a circle) to 1 (a straight strip): an arc+ of radius rho/(1 − unrolled) and angle 2π(1 − unrolled), so as long as the circle, whose+ lowest point stays at `bottom`, with its tangent level there."""+ s = np.linspace(-np.pi * rho, np.pi * rho, SAMPLES) # arc length from the bottom+ k = (1 - unrolled) / rho # the curvature+ # sin(ks)/k and (1 − cos(ks))/k, written to stay exact as k → 0+ x = s * np.sinc(k * s / np.pi)+ y = 0.5 * k * s**2 * np.sinc(k * s / (2 * np.pi)) ** 2+ return bottom + np.stack([x, y, np.zeros_like(s)], axis=1)+++class CircleArea(m.Scene):+ def construct(self) -> None:+ radii = [(k + 0.5) * DR for k in range(N)]++ def ring(+ k: int, unrolled: float = 0.0, bottom: np.ndarray | None = None+ ) -> m.VMobject:+ rho = radii[k]+ where = CENTER - rho * m.UP if bottom is None else bottom+ mob = m.VMobject(stroke_color=RINGS[k], stroke_width=100 * DR * 0.88)+ mob.set_points_as_corners(ring_points(rho, unrolled, where))+ return mob++ disc = m.VGroup(*[ring(k) for k in range(N)])+ radius = m.Line(CENTER, CENTER + R * m.RIGHT, color=RADIUS, stroke_width=6)+ r_label = m.MathTex("r", color=RADIUS, font_size=56)+ r_label.next_to(radius, m.RIGHT, buff=0.18) # at its end, clear of the rings++ radius.set_z_index(1) # over the rings, and over their copies as they leave+ r_label.set_z_index(1)+ # 0–3 s: the disc, swept out+ self.play(*[m.Create(r) for r in disc], run_time=1.6)+ self.play(+ m.Create(radius), m.FadeIn(r_label, shift=0.2 * m.RIGHT), run_time=0.9+ )++ # 3–9 s: each ring, cut at the top, unrolls as it falls into its place in the+ # stack: the longest at the bottom, every strip starting at the triangle's left edge+ progress = [m.ValueTracker(0.0) for _ in range(N)]++ def strip(k: int) -> m.VMobject:+ u = progress[k].get_value()+ rho = radii[k]+ start = CENTER - rho * m.UP+ end = CORNER + np.pi * rho * m.RIGHT + (R - rho) * m.UP+ return ring(k, min(1.0, u / 0.75), start + u * (end - start))++ strips = m.VGroup(*[m.always_redraw(lambda k=k: strip(k)) for k in range(N)])+ self.add(strips)+ self.play(+ m.LaggedStart(+ *[progress[k].animate.set_value(1.0) for k in reversed(range(N))],+ lag_ratio=0.07,+ ),+ run_time=6.5,+ )++ # 9–11 s: the stack is a right triangle, 2πr wide and r tall+ top = CORNER + R * m.UP+ right = CORNER + 2 * np.pi * R * m.RIGHT+ outline = m.Polygon(CORNER, right, top, color=m.WHITE, stroke_width=3)+ base = m.Line(CORNER, right)+ height = m.Line(CORNER, top)+ base_brace = m.Brace(base, m.DOWN, buff=0.12, color=ROUND)+ base_label = m.MathTex(r"2\pi r", color=ROUND, font_size=52)+ base_label.next_to(base_brace, m.DOWN, buff=0.1)+ height_brace = m.Brace(height, m.LEFT, buff=0.12, color=RADIUS)+ height_label = m.MathTex("r", color=RADIUS, font_size=52)+ height_label.next_to(height_brace, m.LEFT, buff=0.12)+ self.play(m.Create(outline), run_time=1)+ self.play(+ m.GrowFromCenter(base_brace),+ m.FadeIn(base_label, shift=0.2 * m.DOWN),+ m.GrowFromCenter(height_brace),+ m.FadeIn(height_label, shift=0.2 * m.LEFT),+ run_time=1.2,+ )++ # 11–18 s: the area, half the base times the height+ area = m.MathTex(+ r"{{\text{Area} =}} {{\frac{1}{2} \cdot 2}} {{\pi}} {{r}} \cdot {{r}}",+ font_size=60,+ )+ area[1][-1].set_color(ROUND) # the 2 of 2πr (its glyphs: 1, 2, bar, dot, 2)+ m.VGroup(area[2], area[3]).set_color(ROUND)+ area[5].set_color(RADIUS)+ area.move_to(np.array([2.9, CENTER[1], 0]))+ cancelled = m.MathTex(+ r"{{\text{Area} =}} {{\pi}} {{r}} \cdot {{r}}", font_size=60+ )+ m.VGroup(cancelled[1], cancelled[2]).set_color(ROUND)+ cancelled[4].set_color(RADIUS)+ cancelled.move_to(area, aligned_edge=m.LEFT)+ result = m.MathTex(r"{{\text{Area} =}} {{\pi}} {{r}}^{ {{2}} }", font_size=72)+ m.VGroup(result[1], result[2]).set_color(ROUND)+ result.get_parts_by_tex("2", substring=False).set_color(RADIUS)+ result.move_to(area)++ self.play(m.Write(area), run_time=1.5)+ self.wait(0.5)+ # ½ and 2 cancel+ self.play(+ m.FadeOut(area[1], shift=0.3 * m.DOWN),+ *[+ m.ReplacementTransform(a, b)+ for a, b in zip([area[0], *area[2:]], cancelled, strict=True)+ ],+ run_time=1.2,+ )+ self.remove(*cancelled)+ self.add(cancelled)+ # r · r = r²+ self.play(m.TransformMatchingTex(cancelled, result), run_time=1.5)+ self.wait(2)+++if __name__ == "__main__":+ CircleArea().render("circle_area.mp4")diff --git a/examples/complex_maps.py b/examples/complex_maps.pynew file mode 100644index 00000000..eef30c32--- /dev/null+++ b/examples/complex_maps.py@@ -0,0 +1,99 @@+"""Complex functions bend the plane.++A complex function sends each point z of the plane to a point f(z). Carry a grid along and the+function's shape appears. z² doubles every angle about the origin and squares every distance:+the grid's lines become parabolas. e^{x+iy} = e^x · e^{iy}, so a vertical line wraps onto a+circle and a horizontal line straightens into a ray. sin z bends the lines into ellipses and+hyperbolas that share two foci. Whatever the function, the bent lines still cross at right+angles: a complex function keeps angles wherever its derivative isn't 0.+"""++from collections.abc import Callable++import numpy as np++import manimgx as m++WALL = 2.4 # the README wall's 5 seconds start here+UNIT = 1.75 # screen units per unit of the plane+HALF = 2.0 # the grid covers [−HALF, HALF] in both directions+STEP = 0.25 # between its lines+SAMPLES = 240 # points along each line+REAL, IMAGINARY = m.BLUE_D, m.YELLOW+++def grid() -> tuple[m.VGroup, list[np.ndarray]]:+ """The grid's lines, and each line's points as complex numbers."""+ lines = m.VGroup()+ points: list[np.ndarray] = []+ run = np.linspace(-HALF, HALF, SAMPLES)+ for k in np.arange(-HALF, HALF + STEP / 2, STEP):+ for z, color in ((k + 1j * run, REAL), (run + 1j * k, IMAGINARY)):+ axis = abs(k) < 1e-9+ line = m.VMobject(+ stroke_color=m.WHITE if axis else color,+ stroke_width=4.5 if axis else 3,+ )+ lines.add(line)+ points.append(z)+ return lines, points+++def place(+ lines: m.VGroup,+ points: list[np.ndarray],+ f: Callable[[np.ndarray], np.ndarray],+ t: float,+) -> None:+ """Each line at t of the way from z to f(z)."""+ for line, z in zip(lines, points, strict=True):+ assert isinstance(line, m.VMobject)+ w = (1 - t) * z + t * f(z)+ line.set_points_as_corners(+ UNIT * np.stack([w.real, w.imag, np.zeros(len(w))], axis=1)+ )+++class ComplexMaps(m.Scene):+ def construct(self) -> None:+ lines, points = grid()+ place(lines, points, lambda z: z, 0)+ ghost = lines.copy().set_stroke(opacity=0.18) # where the lines started+ corner = np.array([-6.6, 3.45, 0.0])+ shown = {"label": m.MathTex("f(z) = z", font_size=60)}+ shown["label"].move_to(corner, aligned_edge=m.LEFT)++ def relabel(tex: str, seconds: float) -> None:+ formula = m.MathTex(tex, font_size=60).move_to(corner, aligned_edge=m.LEFT)+ self.play(m.TransformMatchingTex(shown["label"], formula), run_time=seconds)+ shown["label"] = formula++ def bend(+ f: Callable[[np.ndarray], np.ndarray], back: bool, seconds: float+ ) -> None:+ self.play(+ m.UpdateFromAlphaFunc(+ lines, lambda mob, a: place(mob, points, f, 1 - a if back else a)+ ),+ run_time=seconds,+ )++ def show(f: Callable[[np.ndarray], np.ndarray], tex: str) -> None:+ relabel(tex, 0.8)+ bend(f, back=False, seconds=3)+ self.wait(1.2)+ bend(f, back=True, seconds=2)+ relabel("f(z) = z", 0.6)++ self.add(ghost)+ self.play(+ m.Create(lines, lag_ratio=0.01), m.Write(shown["label"]), run_time=1.5+ )+ show(lambda z: z * z, "f(z) = z^2")+ show(np.exp, "f(z) = e^z")+ show(np.sin, r"f(z) = \sin z")+ self.wait(1)+++if __name__ == "__main__":+ ComplexMaps().render("complex_maps.mp4")diff --git a/examples/derivative.py b/examples/derivative.pynew file mode 100644index 00000000..a894f9f7--- /dev/null+++ b/examples/derivative.py@@ -0,0 +1,293 @@+"""What a derivative is: the slope of a curve at one point.++Nudge x by dx and f changes by df; the ratio df/dx is the slope of the secant through the two+points, rise over run. Let dx shrink toward 0 and the secant turns into the tangent, whose slope+is the derivative: f′(x) = lim (f(x + dx) − f(x))/dx as dx → 0. Slide x along the curve and the+tangent's slope is positive where the curve rises, 0 where it is flat and negative where it+falls. Plotted against x, the slopes draw a curve of their own: the graph of f′.+"""++from collections.abc import Callable+from itertools import pairwise++import numpy as np++import manimgx as m++WALL = 17.6 # the tangent slides and f′ is traced++X_MIN, X_MAX = 0.3, 9.3 # the curve's stretch of x; the axes run from 0 to 9.6+Y_MAX = 2.1 # f's axes run from −Y_MAX to Y_MAX+X0 = 3.6 # where the secant becomes the tangent+DX0, DX1 = 1.6, 0.01 # the nudge, from wide to tiny+FLAT = 0.15 # slopes this close to 0 fade to white: flat+DF_COLOR = m.PURPLE_B # df, the rise; dx, the run, is yellow+SHIFT = 2.0 # how far f's axes move left to make room for f′'s readout+++def f(x: float) -> float:+ """A wave on a slope: rising, flat and falling stretches."""+ return float(np.sin(x - 4.8) + (x - 4.8) / 3)+++def quotient(x: float, dx: float) -> float:+ """The secant's slope: (f(x + dx) − f(x)) / dx."""+ return (f(x + dx) - f(x)) / dx+++def slope(x: float) -> float:+ """The tangent's slope, the derivative, by a central difference."""+ eps = 1e-6+ return (f(x + eps) - f(x - eps)) / (2 * eps)+++def sign_color(s: float) -> m.ManimColor:+ """Green for a rising slope, red for a falling one, white where it is flat."""+ return m.interpolate_color(+ m.WHITE, m.GREEN if s > 0 else m.RED, min(abs(s) / FLAT, 1.0)+ )+++def zeros(func: Callable[[float], float], lo: float, hi: float) -> list[float]:+ """Where `func` changes sign between lo and hi, by bisection on a fine grid."""+ xs = np.linspace(lo, hi, 400)+ ys = [func(float(x)) for x in xs]+ found = []+ for a, b, ya, yb in zip(xs[:-1], xs[1:], ys[:-1], ys[1:], strict=True):+ if ya * yb < 0:+ a, b = float(a), float(b)+ for _ in range(40):+ mid = (a + b) / 2+ if func(a) * func(mid) <= 0:+ b = mid+ else:+ a = mid+ found.append((a + b) / 2)+ return found+++def clip(+ p: np.ndarray, q: np.ndarray, low: np.ndarray, high: np.ndarray+) -> tuple[np.ndarray, np.ndarray]:+ """The part of the segment pq inside the box from `low` to `high` (Liang–Barsky)."""+ t0, t1 = 0.0, 1.0+ d = q - p+ for k in range(2):+ if abs(d[k]) < 1e-12:+ continue+ a, b = (low[k] - p[k]) / d[k], (high[k] - p[k]) / d[k]+ t0, t1 = max(t0, min(a, b)), min(t1, max(a, b))+ return p + t0 * d, p + max(t1, t0) * d+++def axes(y_range: list[float], y_length: float) -> m.Axes:+ return m.Axes(+ x_range=[0, X_MAX + 0.3, 1],+ y_range=y_range,+ x_length=9.4,+ y_length=y_length,+ tips=False,+ axis_config={"stroke_width": 3, "color": m.GREY_B},+ )+++def colored_quotient(tex: str) -> m.MathTex:+ """A formula with the rise f(x + dx) − f(x) in df's color and the run dx in yellow."""+ formula = m.MathTex(tex, font_size=60)+ for part in formula.get_parts_by_tex("dx", substring=False):+ part.set_color(m.YELLOW)+ formula.get_parts_by_tex("f(x+dx) - f(x)").set_color(DF_COLOR)+ return formula+++class DerivativeSlope(m.Scene):+ def construct(self) -> None:+ top = axes([-Y_MAX, Y_MAX, 1], 3.4).move_to(1.9 * m.UP)+ curve = top.plot(f, x_range=[X_MIN, X_MAX], color=m.BLUE, stroke_width=7)+ f_label = m.MathTex("f(x)", color=m.BLUE, font_size=52)+ f_label.next_to(curve.get_end(), m.RIGHT, buff=0.2)+ graph = m.VGroup(top, curve, f_label)++ x = m.ValueTracker(X0)+ log_dx = m.ValueTracker(float(np.log(DX0)))++ def dx() -> float:+ return float(np.exp(log_dx.get_value()))++ def point(t: float) -> np.ndarray:+ return top.c2p(t, f(t))++ def secant() -> m.Line:+ s = quotient(x.get_value(), dx())+ p, q = point(x.get_value()), point(x.get_value() + dx())+ direction = top.c2p(1, s) - top.c2p(0, 0)+ direction = direction / np.linalg.norm(direction)+ mid = (p + q) / 2+ half = np.linalg.norm(q - p) / 2 + 1.5+ start, end = clip(+ mid - half * direction,+ mid + half * direction,+ top.c2p(0, -Y_MAX),+ top.c2p(X_MAX, Y_MAX), # not past the curve's end, where its label is+ )+ return m.Line(start, end, color=sign_color(s), stroke_width=7)++ def legs() -> m.VGroup:+ x0, h = x.get_value(), dx()+ p, q = point(x0), point(x0 + h)+ corner = top.c2p(x0 + h, f(x0))+ run = m.Line(p, corner, color=m.YELLOW, stroke_width=5)+ rise = m.Line(corner, q, color=DF_COLOR, stroke_width=5)+ shown = float(np.clip((h - 0.3) / 0.5, 0, 1))+ run_label = m.MathTex("dx", color=m.YELLOW, font_size=44)+ run_label.next_to(run, m.DOWN, buff=0.12).set_opacity(shown)+ rise_label = m.MathTex("df", color=DF_COLOR, font_size=44)+ rise_label.next_to(rise, m.RIGHT, buff=0.12).set_opacity(shown)+ return m.VGroup(run, rise, run_label, rise_label)++ def far_dot() -> m.Dot:+ return m.Dot(point(x.get_value() + dx()), radius=0.08, color=m.WHITE)++ def near_dot() -> m.Dot:+ return m.Dot(point(x.get_value()), radius=0.09, color=m.WHITE)++ line = m.always_redraw(secant)+ triangle = m.always_redraw(legs)+ q_dot = m.always_redraw(far_dot)+ p_dot = m.always_redraw(near_dot)++ # the quotient, and its value: the secant's slope, then the tangent's+ quotient_tex = colored_quotient(+ r"{{ \frac{df}{dx} }} {{=}} \frac{ {{f(x+dx) - f(x)}} }{ {{dx}} } {{=}}"+ )+ ratio = quotient_tex[0] # its glyphs: d, f, d, x, the bar+ m.VGroup(*ratio[0:2]).set_color(DF_COLOR)+ m.VGroup(*ratio[2:4]).set_color(m.YELLOW)+ quotient_tex.move_to(1.9 * m.DOWN + 0.8 * m.LEFT)+ number = m.DecimalNumber(0, num_decimal_places=2, font_size=60)+ tangent_phase = [False]++ def show_value(mob: m.Mobject) -> None:+ x0 = x.get_value()+ s = slope(x0) if tangent_phase[0] else quotient(x0, dx())+ number.set_value(s)+ number.set_color(sign_color(s))++ show_value(number)+ number.next_to(quotient_tex, m.RIGHT, buff=0.25)+ number.add_updater(show_value)++ dx_label = m.MathTex("dx =", color=m.YELLOW, font_size=44)+ dx_label.move_to(3.3 * m.DOWN + 0.6 * m.LEFT)+ dx_number = m.DecimalNumber(+ DX0, num_decimal_places=3, font_size=44, color=m.YELLOW+ )+ dx_number.next_to(dx_label, m.RIGHT, buff=0.2)+ dx_number.add_updater(lambda d: d.set_value(dx()))+ dx_readout = m.VGroup(dx_label, dx_number)++ # 0–3 s: the curve; two points on it, the secant through them, the run dx and+ # the rise df+ self.add(top)+ self.play(m.Create(curve), m.FadeIn(f_label), run_time=1.6)+ self.play(+ m.FadeIn(p_dot),+ m.FadeIn(q_dot),+ m.Create(line),+ m.FadeIn(triangle),+ run_time=1.2,+ )+ self.play(+ m.Write(quotient_tex), m.FadeIn(number), m.FadeIn(dx_readout), run_time=1.5+ )+ self.wait(0.4)+ # 5–9 s: dx shrinks toward 0; the secant turns into the tangent+ self.play(log_dx.animate.set_value(float(np.log(DX1))), run_time=4)+ self.remove(triangle, q_dot)+ limit_tex = colored_quotient(+ r"{{f'(x)}} {{=}} \lim_{ {{dx}} \to 0}"+ r" \frac{ {{f(x+dx) - f(x)}} }{ {{dx}} } {{=}}"+ )+ limit_tex.move_to(quotient_tex).align_to(quotient_tex, m.RIGHT)+ self.play(+ m.TransformMatchingTex(quotient_tex, limit_tex),+ m.FadeOut(dx_readout),+ run_time=2,+ )+ tangent_phase[0] = True+ self.wait(0.4)++ # 11–16 s: the limit is f′(x); room for its own graph, below+ prime, equals = limit_tex[0], limit_tex[1]+ rest = m.VGroup(*limit_tex[2:])+ self.remove(limit_tex)+ self.add(prime, equals, rest)+ number.remove_updater(show_value) # held still while it moves+ self.play(+ m.FadeOut(rest),+ number.animate.next_to(equals, m.RIGHT, buff=0.25),+ run_time=1,+ )+ bottom = axes([-1.1, 1.6, 1], 3.0).move_to(np.array([-SHIFT, -2.2, 0]))+ readout = m.VGroup(prime, equals, number)+ self.play(+ graph.animate.shift(SHIFT * m.LEFT),+ readout.animate.scale(56 / 60).move_to(+ bottom.get_right() + 0.45 * m.RIGHT, aligned_edge=m.LEFT+ ),+ run_time=2,+ )+ number.add_updater(show_value)++ lo_hi = [0.0, 0.0] # the stretch of x traced so far++ def traced() -> m.VGroup:+ x0 = x.get_value()+ lo_hi[0], lo_hi[1] = min(lo_hi[0], x0), max(lo_hi[1], x0)+ lo, hi = lo_hi+ pieces = m.VGroup()+ if hi - lo < 1e-3:+ return pieces+ cuts = [lo, *zeros(slope, lo, hi), hi]+ for a, b in pairwise(cuts):+ if b - a < 1e-4:+ continue+ pieces.add(+ bottom.plot(+ slope,+ x_range=[a, b, (b - a) / max(2, int(40 * (b - a)))],+ color=m.GREEN if slope((a + b) / 2) > 0 else m.RED,+ stroke_width=7,+ )+ )+ return pieces++ def slope_dot() -> m.Dot:+ s = slope(x.get_value())+ return m.Dot(bottom.c2p(x.get_value(), s), radius=0.09, color=sign_color(s))++ def drop() -> m.DashedLine:+ s = slope(x.get_value())+ return m.DashedLine(+ point(x.get_value()),+ bottom.c2p(x.get_value(), s),+ color=m.GREY_B,+ stroke_width=2.5,+ dash_length=0.08,+ )++ self.play(m.Create(bottom), x.animate.set_value(X_MIN), run_time=1.8)+ dot = m.always_redraw(slope_dot)+ connector = m.always_redraw(drop)+ self.play(m.FadeIn(dot), m.Create(connector), run_time=0.5)+ lo_hi[0] = lo_hi[1] = x.get_value()+ self.add(m.always_redraw(traced))+ # 16–24 s: slide x along the curve; the tangent's slope, as a height, draws f′+ self.play(x.animate.set_value(X_MAX), run_time=7.5)+ hilltop = zeros(slope, X0, X_MAX)[0]+ self.play(x.animate.set_value(hilltop), run_time=2)+ self.wait(1.5)+++if __name__ == "__main__":+ DerivativeSlope().render("derivative.mp4")diff --git a/examples/euler_identity.py b/examples/euler_identity.pynew file mode 100644index 00000000..d5909000--- /dev/null+++ b/examples/euler_identity.py@@ -0,0 +1,195 @@+"""e^{iπ} = −1, as a walk.++The exponential is a sum: eˣ = 1 + x + x²/2! + x³/3! + ⋯. Put x = iπ and draw the terms as+arrows, tip to tail. Each term is the last one times iπ/n, and multiplying by i turns an arrow a+quarter turn, so the walk turns a quarter turn at every step; the arrows grow while π/n > 1,+then n! wins and they shrink, and the walk spirals in on a single point: −1. Put x = it instead:+as t changes the walk reshapes, and its end runs around the unit circle, at angle t from 1, so+e^{it} = cos t + i sin t. Halfway round, at t = π, it is −1: e^{iπ} + 1 = 0.+"""++import numpy as np++import manimgx as m++UNIT = 1.0 # scene units per unit of the complex plane+ZERO = np.array([-1.3, -0.45, 0.0]) # where 0 is on screen+TERMS = 20 # enough for |t| ≤ π: the next term is below 10⁻⁷+COLORS = m.color_gradient(+ [m.BLUE, m.TEAL, m.GREEN, m.YELLOW, m.GOLD, m.RED, m.MAROON, m.PURPLE], 10+)+COLUMN = 4.35 # the x of the formulas' column+WALL = 11.25+++def terms(x: complex, count: int = TERMS) -> np.ndarray:+ """The terms xⁿ/n! of the exponential series, n = 0 … count − 1: each the last times x/n."""+ out = np.empty(count, dtype=complex)+ out[0] = 1.0+ for n in range(1, count):+ out[n] = out[n - 1] * x / n+ return out+++def point(z: complex) -> np.ndarray:+ """Where the complex number z is on screen."""+ return ZERO + UNIT * np.array([z.real, z.imag, 0.0])+++def color(n: float) -> m.ManimColor:+ """The color of term n (between two terms, a blend of theirs)."""+ k = min(int(n), len(COLORS) - 1)+ following = COLORS[min(k + 1, len(COLORS) - 1)]+ return m.interpolate_color(COLORS[k], following, n - int(n))+++def term_arrow(start: complex, end: complex, n: float) -> m.Arrow:+ return m.Arrow(+ point(start),+ point(end),+ buff=0,+ stroke_width=8,+ tip_length=0.3,+ color=color(n),+ )+++def walk(x: complex) -> m.VGroup:+ """The terms of e^x as arrows tip to tail, leaving out those too short to see."""+ sums = np.concatenate([[0], np.cumsum(terms(x))])+ return m.VGroup(+ *(+ term_arrow(sums[n], sums[n + 1], n)+ for n in range(TERMS)+ if UNIT * abs(sums[n + 1] - sums[n]) > 0.02+ )+ )+++def next_term(arrow: m.Arrow, n: int, x: complex) -> m.UpdateFromAlphaFunc:+ """Turn a copy of term n − 1 into term n: its tail slides to the walk's end while it turns+ and stretches by x/n, continuously (by the powers (x/n)^α, α from 0 to 1)."""+ values = terms(x, n + 1)+ tail_from = complex(np.sum(values[: n - 1]))++ def update(mob: m.Mobject, alpha: float) -> None:+ tail = tail_from + alpha * values[n - 1]+ vector = values[n - 1] * (x / n) ** alpha+ mob.become(term_arrow(tail, tail + vector, n - 1 + alpha))++ return m.UpdateFromAlphaFunc(arrow, update)+++class EulerIdentity(m.Scene):+ def construct(self) -> None:+ plane = m.ComplexPlane(+ x_range=[-5, 2, 1],+ y_range=[-3.5, 3.5, 1],+ x_length=7 * UNIT,+ y_length=7 * UNIT,+ background_line_style={+ "stroke_color": m.BLUE_D,+ "stroke_width": 1.5,+ "stroke_opacity": 0.5,+ },+ )+ plane.shift(point(-1.5 + 0j) - plane.get_center())+ series = m.MathTex(r"e^{x} = \sum_{n=0}^{\infty} \frac{x^n}{n!}", font_size=56)+ series.move_to(np.array([COLUMN, 2.6, 0.0]))+ x_is = m.MathTex(r"{{x}} = {{i \pi}}", font_size=56)+ x_is.next_to(series, m.DOWN, buff=0.6)++ self.play(m.Create(plane, lag_ratio=0.1), m.Write(series), run_time=1.2)+ self.play(m.FadeIn(x_is), run_time=0.5)++ # the walk for x = iπ, term by term: each a quarter turn from the last+ x = 1j * np.pi+ values = terms(x)+ sums = np.concatenate([[0], np.cumsum(values)])+ names = [+ "1",+ r"i\pi",+ r"\frac{(i\pi)^2}{2!}",+ r"\frac{(i\pi)^3}{3!}",+ r"\frac{(i\pi)^4}{4!}",+ ]+ labels = m.VGroup()+ for n, name in enumerate(names):+ direction = values[n] / abs(values[n])+ outward = np.array([direction.imag, -direction.real, 0.0]) # its right side+ middle = point((sums[n] + sums[n + 1]) / 2)+ label = m.MathTex(name, font_size=44, color=COLORS[n])+ labels.add(label.next_to(middle, outward, buff=0.2))++ arrows = [term_arrow(0, 1, 0)]+ self.play(m.GrowArrow(arrows[0]), m.FadeIn(labels[0]), run_time=0.8)+ for n in range(1, 12):+ arrow = arrows[-1].copy()+ self.add(arrow)+ arrows.append(arrow)+ if n < len(names):+ self.play(next_term(arrow, n, x), m.FadeIn(labels[n]), run_time=1.0)+ else:+ self.play(next_term(arrow, n, x), run_time=0.45 if n < 8 else 0.25)+ rest = walk(x)[12:]+ self.add(rest)++ total = complex(sums[-1]) # the whole sum: −1, to the last digit drawn+ end = m.Dot(point(total), radius=0.09, color=m.WHITE)+ sign = "-" if total.real < 0 else "+"+ end_label = m.MathTex(+ "{{" + sign + "}}{{" + f"{abs(total.real):.0f}" + "}}", font_size=48+ )+ end_label.next_to(end, m.DL, buff=0.12)+ self.play(m.FadeIn(end, scale=0.5), m.Write(end_label), run_time=0.8)+ self.wait(0.6)++ # let the exponent vary: the walk for x = it, as t runs once round and back+ t = m.ValueTracker(np.pi)+ x_it = m.MathTex(r"{{x}} = {{i t}}", font_size=56).move_to(x_is)+ t_value = m.DecimalNumber(np.pi, num_decimal_places=2, font_size=56)+ t_row = m.VGroup(m.MathTex("t =", font_size=56), t_value)+ t_row.arrange(m.RIGHT, buff=0.2).next_to(x_it, m.DOWN, buff=0.45)+ t_value.add_updater(lambda d: d.set_value(t.get_value()))+ moving = m.always_redraw(lambda: walk(1j * t.get_value()))+ tip = m.always_redraw(+ lambda: m.Dot(point(np.exp(1j * t.get_value())), radius=0.09)+ )+ trace = m.TracedPath(tip.get_center, stroke_color=m.YELLOW, stroke_width=6)+ self.remove(*arrows, rest, end)+ self.add(trace, moving, tip)+ self.play(+ m.FadeOut(labels),+ m.FadeOut(end_label),+ m.TransformMatchingTex(x_is, x_it),+ m.FadeIn(t_row),+ run_time=1.0,+ )+ self.play(t.animate.set_value(-np.pi), run_time=5.5)+ circle_law = m.MathTex(r"e^{it} = \cos t + i \sin t", font_size=48)+ circle_law.next_to(t_row, m.DOWN, buff=0.75)+ self.play(+ t.animate(run_time=5.0).set_value(np.pi),+ m.Write(circle_law, run_time=1.5),+ )++ # halfway round+ minus_one = end_label.copy()+ self.play(m.FadeIn(minus_one), run_time=0.5)+ identity = m.MathTex(r"{{ e^{i\pi} }} {{=}} {{-}}{{1}}", font_size=80)+ identity.move_to(np.array([COLUMN, -2.75, 0.0]))+ self.play(+ m.FadeIn(identity[0]),+ m.FadeIn(identity[1]),+ m.TransformFromCopy(minus_one[0], identity[2]),+ m.TransformFromCopy(minus_one[1], identity[3]),+ run_time=1.3,+ )+ final = m.MathTex(r"{{ e^{i\pi} }} {{+}} {{1}} {{=}} {{0}}", font_size=80)+ final.move_to(identity)+ self.play(m.TransformMatchingTex(identity, final), run_time=1.6)+ self.wait(2.0)+++if __name__ == "__main__":+ EulerIdentity().render("euler_identity.mp4")diff --git a/examples/fourier_pi.py b/examples/fourier_pi.pynew file mode 100644index 00000000..99799b48--- /dev/null+++ b/examples/fourier_pi.py@@ -0,0 +1,187 @@+"""Circles on circles draw π.++Any closed curve is a sum of circular motions. Let z(t) be a point of the complex plane that+goes once around the curve as t runs from 0 to 1; then z(t) = Σ cₙ e^{2πint}. Each term is an+arrow of length |cₙ| that turns n times while the curve is traced once: put the arrows tip to+tail, and the last tip runs along the curve. Each cₙ is measured from the curve itself,+cₙ = ∫ z(t) e^{−2πint} dt, here from the outline of the letter π. With 101 arrows the drawing+can't be told from the letter (3Blue1Brown, "But what is a Fourier series?", 2019).+"""++import numpy as np++import manimgx as m++TERMS = 50 # the frequencies −TERMS … TERMS+PERIOD = 10.0 # seconds the arrows take to draw the curve once+SAMPLES = 4096 # points along the outline, evenly spaced+WALL = 5.0 # the README wall's 5 seconds start here+++def outline(glyph: m.Mobject) -> np.ndarray:+ """`SAMPLES` points evenly spaced along a closed outline, as complex numbers."""+ curves = glyph.points.reshape(-1, 4, 3)[:, :, :2]+ s = np.linspace(0, 1, 64, endpoint=False)[None, :, None]+ p0, p1, p2, p3 = (curves[:, k][:, None] for k in range(4))+ dense = (+ (1 - s) ** 3 * p0+ + 3 * (1 - s) ** 2 * s * p1+ + 3 * (1 - s) * s**2 * p2+ + s**3 * p3+ ).reshape(-1, 2)+ closed = np.vstack([dense, dense[:1]])+ run = np.concatenate(+ [[0], np.cumsum(np.linalg.norm(np.diff(closed, axis=0), axis=1))]+ )+ at = np.linspace(0, run[-1], SAMPLES, endpoint=False)+ return np.interp(at, run, closed[:, 0]) + 1j * np.interp(at, run, closed[:, 1])+++def coefficients(z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """The frequencies 0, 1, −1, 2, −2, … and their coefficients cₙ, by the discrete transform."""+ spectrum = np.fft.fft(z) / len(z)+ order = [0] + [n for k in range(1, TERMS + 1) for n in (k, -k)]+ frequencies = np.array(order)+ return frequencies, spectrum[frequencies % len(z)]+++def to_point(z: complex | np.ndarray) -> np.ndarray:+ z = np.asarray(z)+ return np.stack([z.real, z.imag, np.zeros_like(z.real)], axis=-1)+++class FourierPi(m.Scene):+ def construct(self) -> None:+ letter = m.MathTex(r"\pi").scale_to_fit_height(5.0).move_to(0.55 * m.UP)+ glyph = letter.family_members_with_points()[0]+ frequencies, c = coefficients(outline(glyph))+ clock = m.ValueTracker(0.0) # laps of the curve++ def tips(t: float) -> np.ndarray:+ """The chain's joints after t laps: its start, then each arrow's tip."""+ turns = c * np.exp(m.TAU * 1j * frequencies * t)+ return np.concatenate([[0], np.cumsum(turns)])++ # each arrow keeps its shape (|cₙ| doesn't change) and only turns and moves+ arrows = m.VGroup()+ circles = m.VGroup()+ bases: list[list[np.ndarray]] = []+ for coefficient in c[1:]:+ size = abs(coefficient)+ arrow = m.Arrow(+ m.ORIGIN,+ size * m.RIGHT,+ buff=0,+ stroke_width=2.5,+ tip_length=0.2,+ max_tip_length_to_length_ratio=0.25,+ max_stroke_width_to_length_ratio=12,+ color=m.GREY_A,+ )+ bases.append(+ [part.points.copy() for part in arrow.family_members_with_points()]+ )+ arrows.add(arrow)+ circles.add(+ m.Circle(+ radius=size, stroke_width=1.5, stroke_opacity=0.6, color=m.BLUE+ )+ )++ def place(chain: m.VGroup) -> None:+ joints = tips(clock.get_value())+ for k, (arrow, circle, shape) in enumerate(+ zip(arrows, circles, bases, strict=True)+ ):+ start, end = joints[k + 1], joints[k + 2] # joint 1 is the fixed c₀+ turn = np.angle(end - start)+ rotation = np.array(+ [+ [np.cos(turn), -np.sin(turn), 0],+ [np.sin(turn), np.cos(turn), 0],+ [0, 0, 1],+ ]+ )+ for part, base in zip(+ arrow.family_members_with_points(), shape, strict=True+ ):+ part.points = base @ rotation.T + to_point(start)+ circle.move_to(to_point(start))++ chain = m.VGroup(circles, arrows)+ chain.add_updater(place)+ place(chain)+ pen = m.Dot(radius=0.045, color=m.YELLOW)+ pen.add_updater(lambda dot: dot.move_to(to_point(tips(clock.get_value())[-1])))++ times = np.linspace(0, 1, 2400)+ curve = np.sum(+ c[None, :] * np.exp(m.TAU * 1j * np.outer(times, frequencies)), axis=1+ )+ full = m.VMobject(stroke_color=m.YELLOW, stroke_width=5).set_points_as_corners(+ to_point(curve)+ )+ drawn = full.copy()+ drawn.add_updater(+ lambda path: path.pointwise_become_partial(+ full, 0, min(clock.get_value(), 1)+ )+ )+ drawn.pointwise_become_partial(full, 0, 0)++ formula = m.MathTex(+ r"z(t) = \sum_{n=-50}^{50} c_n\, e^{2\pi i n t}", font_size=48+ ).to_edge(m.DOWN, buff=0.3)++ self.play(m.Write(letter), run_time=1.5)+ self.play(letter.animate.set_opacity(0.18), run_time=1)+ self.add(drawn)+ self.play(+ m.LaggedStart(*(m.GrowArrow(a) for a in arrows[:24]), lag_ratio=0.12),+ m.FadeIn(circles),+ m.FadeIn(arrows[24:]),+ run_time=2,+ )+ self.add(chain, pen)+ self.play(clock.animate.set_value(1.0), run_time=PERIOD, rate_func=m.linear)++ # a second lap, close up: the camera follows the pen+ clock.add_updater(lambda tracker, dt: tracker.increment_value(dt / PERIOD))+ close = m.ValueTracker(0.0)+ frame = self.camera.frame+ self.add(frame) # a mobject's updaters run while it is in the scene++ def follow(view: m.Mobject) -> None:+ zoom = 1 / (1 - 0.78 * close.get_value())+ view.scale_to_fit_height(8 / zoom).move_to(+ close.get_value() * pen.get_center()+ )+ # strokes are as wide on screen at every zoom+ drawn.set_stroke(width=5 / zoom)+ circles.set_stroke(width=1.5 / zoom)+ for arrow in arrows:+ arrow.set_stroke(width=2.5 / zoom, family=False)+ pen.scale_to_fit_width(0.09 / zoom)++ frame.add_updater(follow)+ self.play(close.animate.set_value(1.0), run_time=1.5)+ self.wait(4)+ self.play(close.animate.set_value(0.0), run_time=1.5)+ frame.clear_updaters()+ clock.clear_updaters()+ chain.clear_updaters()+ drawn.clear_updaters()+ pen.clear_updaters()+ self.play(+ m.FadeOut(chain),+ m.FadeOut(pen),+ letter.animate.set_opacity(0),+ drawn.animate.set_fill(m.YELLOW, opacity=1),+ m.Write(formula),+ run_time=2,+ )+ self.wait(2)+++if __name__ == "__main__":+ FourierPi().render("fourier_pi.mp4")diff --git a/examples/hilbert_curve.py b/examples/hilbert_curve.pynew file mode 100644index 00000000..92353b41--- /dev/null+++ b/examples/hilbert_curve.py@@ -0,0 +1,161 @@+"""A curve that fills a square: Hilbert's.++Split a square into a 2ⁿ × 2ⁿ grid and run a path through the centers of all its cells,+Hilbert's way: the path of order n + 1 is the path of order n with every point replaced by a+small copy of the first one, a U through the four quarters of its cell, turned so that the U's+join up. Each order doubles the length and halves the gaps, while every point of the path moves+less and less: the paths converge, to a curve that passes through every point of the square+(Hilbert, 1891). Its colors run along its length, so each part of the square keeps its color.+"""++import numpy as np++import manimgx as m++SIDE = 7.2 # the square's side, in scene units+CENTER = np.array([-1.5, 0.0, 0.0])+LAST_ORDER = 7+PIECES = 256 # the most pieces a path is drawn in, each in its own color+COLORS = [m.BLUE, m.TEAL, m.GREEN, m.YELLOW, m.GOLD, m.RED, m.MAROON, m.PURPLE]+WALL = 4.4+++def hilbert(order: int) -> np.ndarray:+ """The cells (x, y) of the 2^order × 2^order grid, in the order the path visits them."""+ size = 2**order+ t = np.arange(size * size)+ x, y = np.zeros_like(t), np.zeros_like(t)+ s = 1+ while s < size:+ rx = (t // 2) & 1+ ry = (t ^ rx) & 1+ swap = ry == 0+ flip = swap & (rx == 1)+ x, y = np.where(flip, s - 1 - x, x), np.where(flip, s - 1 - y, y)+ x, y = np.where(swap, y, x), np.where(swap, x, y)+ x, y = x + s * rx, y + s * ry+ t, s = t // 4, 2 * s+ return np.stack([x, y], 1)+++def vertices(order: int) -> np.ndarray:+ """The path of the given order: the centers of its cells, on screen."""+ cell = SIDE / 2**order+ corner = CENTER - SIDE / 2 * (m.RIGHT + m.UP)+ xy = (hilbert(order) + 0.5) * cell+ return corner + np.column_stack([xy, np.zeros(len(xy))])+++def pieces(count: int) -> list[np.ndarray]:+ """The vertices of each piece of a path through `count` vertices: its segments, or, for+ a long path, PIECES runs of them, each ending where the next begins."""+ if count <= PIECES:+ return [np.array([k, k + 1]) for k in range(count - 1)]+ run = count // PIECES+ return [np.arange(k * run, min((k + 1) * run + 1, count)) for k in range(PIECES)]+++def rainbow(s: float) -> m.ManimColor:+ """The color a fraction s of the way along the path."""+ x = s * (len(COLORS) - 1)+ k = min(int(x), len(COLORS) - 2)+ return m.interpolate_color(COLORS[k], COLORS[k + 1], x - k)+++def width(order: int) -> float:+ """The stroke for a path of this order: four tenths of its cell, at most 12."""+ return min(12.0, 40 * SIDE / 2**order)+++def drawn(+ points: np.ndarray, runs: list[np.ndarray], places: np.ndarray, order: int+) -> m.VGroup:+ """A path drawn piece by piece: piece k through points[runs[k]], colored by where along+ the path its vertices are (places: a fraction of the way, per point)."""+ group = m.VGroup()+ for run in runs:+ piece = m.VMobject(+ stroke_width=width(order), stroke_color=rainbow(places[run].mean())+ )+ piece.set_points_as_corners(points[run])+ piece.cap_style = m.CapStyleType.ROUND+ piece.joint_type = m.LineJointType.ROUND+ group.add(piece)+ return group+++def path_length(points: np.ndarray) -> float:+ """The length of the path through the points, in sides of the square."""+ return float(np.linalg.norm(np.diff(points, axis=0), axis=1).sum() / SIDE)+++class HilbertCurve(m.Scene):+ def construct(self) -> None:+ outline = m.Square(SIDE).move_to(CENTER)+ outline.set_stroke(m.GREY_C, width=2, opacity=0.6)++ first = vertices(1)+ path = drawn(first, pieces(4), np.arange(4) / 3, 1)++ order_label = m.Tex("order", font_size=48)+ order_value = m.Integer(1, font_size=72)+ length_label = m.Tex("length", font_size=48)+ length_value = m.DecimalNumber(+ path_length(first), num_decimal_places=2, font_size=72+ )+ column = m.VGroup(+ m.VGroup(order_label, order_value).arrange(m.RIGHT, buff=0.3),+ m.VGroup(length_label, length_value).arrange(m.RIGHT, buff=0.3),+ )+ column.arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.6).move_to(+ np.array([4.3, 0.0, 0.0])+ )+ side_note = m.Tex("(in sides of the square)", font_size=32, color=m.GREY_B)+ side_note.next_to(column, m.DOWN, aligned_edge=m.LEFT, buff=0.3)++ self.play(+ m.Create(outline),+ m.Create(path, lag_ratio=1.0),+ m.FadeIn(column),+ m.FadeIn(side_note),+ run_time=1.6,+ )+ self.wait(0.6)++ for order in range(1, LAST_ORDER):+ parents = vertices(order)+ children = vertices(order + 1)+ count = len(children)+ parent_of = np.arange(count) // 4+ runs = pieces(count)+ before = drawn(+ parents[parent_of], runs, parent_of / (len(parents) - 1), order+ )+ after = drawn(children, runs, np.arange(count) / (count - 1), order + 1)++ def measure(+ d: m.Mobject,+ alpha: float,+ start: np.ndarray = parents[parent_of],+ end: np.ndarray = children,+ ) -> None:+ assert isinstance(d, m.DecimalNumber)+ d.set_value(path_length((1 - alpha) * start + alpha * end))+ d.next_to(length_label, m.RIGHT, buff=0.3)++ self.remove(path)+ self.add(before)+ order_value.set_value(order + 1)+ self.play(+ m.Transform(before, after),+ m.UpdateFromAlphaFunc(length_value, measure),+ run_time=2.2,+ )+ self.remove(before)+ self.add(after)+ path = after+ self.wait(2.0)+++if __name__ == "__main__":+ HilbertCurve().render("hilbert_curve.mp4")diff --git a/examples/linear_maps.py b/examples/linear_maps.pynew file mode 100644index 00000000..e728d885--- /dev/null+++ b/examples/linear_maps.py@@ -0,0 +1,188 @@+"""A matrix is where the plane goes.++A 2 × 2 matrix's two columns say where the arrows î and ĵ land. Every point is so much î plus+so much ĵ, so they say where everything lands: grid lines stay straight, parallel and evenly+spaced. The square on î and ĵ becomes a parallelogram whose area is the determinant, the+factor by which every area grows. At 0 the plane flattens onto a line; below 0 it turns over+(3Blue1Brown, "Essence of linear algebra", 2016).+"""++from collections.abc import Callable++import numpy as np++import manimgx as m++WALL = 5.0 # the README wall's 5 seconds start here+EXTENT = 12 # the moving grid's lines run from −EXTENT to EXTENT+I_HAT, J_HAT, AREA = m.GREEN, m.RED, m.YELLOW+++def rotation(angle: float) -> np.ndarray:+ return np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])+++def straight(a: np.ndarray, b: np.ndarray) -> Callable[[float], np.ndarray]:+ """From matrix a to matrix b, each entry moving at a steady rate."""+ return lambda t: (1 - t) * a + t * b+++def turning(a: np.ndarray, angle: float) -> Callable[[float], np.ndarray]:+ """From matrix a, turning the plane by `angle` (a rotation stays a rotation throughout)."""+ return lambda t: rotation(t * angle) @ a+++IDENTITY = np.eye(2)+SHEAR = np.array([[1.0, 1.0], [0.0, 1.0]])+GENERAL = np.array([[1.5, -0.5], [0.5, 1.2]])+FLAT = np.array([[1.0, -2.0], [0.5, -1.0]]) # det 0+FLIPPED = np.array([[0.5, 1.0], [1.2, 0.2]]) # det < 0+++class LinearMaps(m.Scene):+ def construct(self) -> None:+ background = m.NumberPlane(+ x_range=[-8, 8],+ y_range=[-5, 5],+ background_line_style={+ "stroke_color": m.GREY,+ "stroke_width": 1,+ "stroke_opacity": 0.35,+ },+ axis_config={"stroke_opacity": 0.0},+ )++ lines = m.VGroup(+ *(+ m.Line(+ np.array([k, -EXTENT, 0.0]),+ np.array([k, EXTENT, 0.0]),+ stroke_color=m.BLUE_D,+ stroke_width=2 if k else 0,+ )+ for k in range(-EXTENT, EXTENT + 1)+ ),+ *(+ m.Line(+ np.array([-EXTENT, k, 0.0]),+ np.array([EXTENT, k, 0.0]),+ stroke_color=m.BLUE_D,+ stroke_width=2 if k else 0,+ )+ for k in range(-EXTENT, EXTENT + 1)+ ),+ )+ axes = m.VGroup(+ m.Line(+ np.array([0.0, -EXTENT, 0]),+ np.array([0.0, EXTENT, 0]),+ stroke_width=2.5,+ ),+ m.Line(+ np.array([-EXTENT, 0.0, 0]),+ np.array([EXTENT, 0.0, 0]),+ stroke_width=2.5,+ ),+ )+ square = m.VMobject(+ fill_color=AREA, fill_opacity=0.35, stroke_color=AREA, stroke_width=3+ )+ i_arrow = m.Arrow(m.ORIGIN, m.RIGHT, buff=0, color=I_HAT, stroke_width=7)+ j_arrow = m.Arrow(m.ORIGIN, m.UP, buff=0, color=J_HAT, stroke_width=7)+ i_label = m.MathTex(r"\hat{\imath}", color=I_HAT, font_size=56)+ j_label = m.MathTex(r"\hat{\jmath}", color=J_HAT, font_size=56)++ matrix = m.DecimalMatrix(+ [[-8.8, -8.8], [-8.8, -8.8]], # the widest entries, which size the brackets+ element_to_mobject_config={"num_decimal_places": 1},+ h_buff=1.6,+ ).scale(1.1)+ entries: list[m.DecimalNumber] = []+ for k, entry in enumerate(matrix.get_entries()):+ assert isinstance(entry, m.DecimalNumber)+ entry.set_color(I_HAT if k % 2 == 0 else J_HAT)+ entries.append(entry)+ det_label = m.MathTex(r"\det =", font_size=52)+ det_value = m.DecimalNumber(1.0, num_decimal_places=2, font_size=52, color=AREA)+ panel = m.VGroup(+ matrix, m.VGroup(det_label, det_value).arrange(m.RIGHT, buff=0.2)+ )+ panel.arrange(m.DOWN, buff=0.4, aligned_edge=m.LEFT).to_corner(m.UL, buff=0.4)+ det_place = det_value.get_left()+ slots = [entry.get_right() for entry in entries] # numbers align on their right++ grid = [(part, part.points.copy()) for part in (*lines, *axes)]++ def land(matrix_now: np.ndarray) -> None:+ lift = np.eye(3)+ lift[:2, :2] = matrix_now+ for part, points in grid:+ part.points = points @ lift.T++ def arrow_to(arrow: m.Arrow, end: np.ndarray, label: m.Mobject) -> None:+ tip = np.array([*end, 0.0])+ if np.linalg.norm(tip) < 1e-3:+ tip = np.array([1e-3, 0, 0])+ arrow.put_start_and_end_on(m.ORIGIN, tip)+ label.move_to(tip + 0.42 * tip / np.linalg.norm(tip) + 0.12 * m.UP)++ def show(matrix_now: np.ndarray) -> None:+ land(matrix_now)+ a, b = matrix_now[:, 0], matrix_now[:, 1]+ corners = [+ np.array([*p, 0.0]) for p in (np.zeros(2), a, a + b, b, np.zeros(2))+ ]+ square.set_points_as_corners(corners)+ arrow_to(i_arrow, a, i_label)+ arrow_to(j_arrow, b, j_label)+ for entry, value, slot in zip(+ entries, matrix_now.flatten(), slots, strict=True+ ):+ entry.set_value(value + 0.0) # no −0.0+ entry.move_to(slot, aligned_edge=m.RIGHT)+ det_value.set_value(np.linalg.det(matrix_now))+ det_value.move_to(det_place, aligned_edge=m.LEFT)++ def go(path: Callable[[float], np.ndarray], seconds: float = 2.2) -> None:+ self.play(+ m.UpdateFromAlphaFunc(+ m.VGroup(+ lines, axes, square, i_arrow, j_arrow, i_label, j_label, panel+ ),+ lambda _, alpha: show(path(alpha)),+ ),+ run_time=seconds,+ )++ show(IDENTITY)+ self.add(background)+ self.play(+ m.Create(lines, lag_ratio=0.02),+ m.Create(axes),+ run_time=1.5,+ )+ self.play(+ m.GrowArrow(i_arrow),+ m.GrowArrow(j_arrow),+ m.FadeIn(square),+ m.Write(i_label),+ m.Write(j_label),+ m.FadeIn(panel),+ run_time=1.2,+ )+ go(straight(IDENTITY, SHEAR))+ self.wait(0.5)+ go(turning(SHEAR, np.pi / 2))+ self.wait(0.5)+ go(straight(rotation(np.pi / 2) @ SHEAR, GENERAL))+ self.wait(0.5)+ go(straight(GENERAL, FLAT), 2.6)+ self.wait(0.8)+ go(straight(FLAT, FLIPPED), 2.4)+ self.wait(0.8)+ go(straight(FLIPPED, IDENTITY))+ self.wait(1.5)+++if __name__ == "__main__":+ LinearMaps().render("linear_maps.mp4")diff --git a/examples/prime_spirals.py b/examples/prime_spirals.pynew file mode 100644index 00000000..db12288b--- /dev/null+++ b/examples/prime_spirals.py@@ -0,0 +1,265 @@+"""Primes in polar coordinates: spirals, then rays.++Put every whole number n at distance n from the center and at angle n radians, and light up+the primes. Close in, the numbers wind round in six arms: 6 radians is just short of a full+turn, so n, n + 6, n + 12, … lie on a slowly turning arm, and the primes past 3 sit on only two+of the six (6k ± 1). Farther out, 44 radians is very nearly 7 turns, so the arms become 44+spirals, of which the primes use the 20 whose numbers share no factor with 44. Out past a+hundred thousand, 710 radians is 113 turns to within 6·10⁻⁵ radians, and the spirals+straighten into 710 rays; the primes fill the 280 that share no factor with 710, and do not+favor any of them (Dirichlet).+"""++import numpy as np++import manimgx as m++DISK = 3.85 # the radius of the view, in scene units+LAST = 1_000_000 # the largest number drawn+WALL = 15.3+++def sieve(n: int) -> np.ndarray:+ """is_prime[k] for k = 0 … n (Eratosthenes)."""+ is_prime = np.ones(n + 1, dtype=bool)+ is_prime[:2] = False+ for k in range(2, int(n**0.5) + 1):+ if is_prime[k]:+ is_prime[k * k :: k] = False+ return is_prime+++def polar(n: np.ndarray) -> np.ndarray:+ """The points (n cos n, n sin n), as rows."""+ return np.stack([n * np.cos(n), n * np.sin(n), np.zeros_like(n)], 1)+++def coprime_count(n: int) -> int:+ """How many residues mod n share no factor with n (Euler's φ)."""+ return int(np.sum(np.gcd(np.arange(n), n) == 1))+++def zoom_curve(keys: list[tuple[float, float]]) -> tuple[np.ndarray, np.ndarray]:+ """log10 of the view's radius against time, through the keys (time, radius): a monotone+ cubic (Fritsch–Carlson), so the zoom changes speed smoothly and never turns back."""+ t = np.array([k[0] for k in keys])+ y = np.log10([k[1] for k in keys])+ secant = np.diff(y) / np.diff(t)+ slope = np.zeros_like(y)+ inner = secant[:-1] * secant[1:] > 0+ slope[1:-1][inner] = 2 / (+ 1 / secant[:-1][inner] + 1 / secant[1:][inner]+ ) # harmonic mean+ times = np.linspace(t[0], t[-1], 2000)+ i = np.clip(np.searchsorted(t, times, side="right") - 1, 0, len(t) - 2)+ h = t[i + 1] - t[i]+ s = (times - t[i]) / h+ values = (+ (2 * s**3 - 3 * s**2 + 1) * y[i]+ + (s**3 - 2 * s**2 + s) * h * slope[i]+ + (-2 * s**3 + 3 * s**2) * y[i + 1]+ + (s**3 - s**2) * h * slope[i + 1]+ )+ return times, values+++ARM_COLORS = [m.BLUE, m.GREEN, m.YELLOW, m.GOLD, m.RED, m.PURPLE]+WHOLE_COLOR = m.GREY_B+PRIME_COLOR = m.TEAL+++class PrimeSpirals(m.Scene):+ def construct(self) -> None:+ is_prime = sieve(LAST)+ numbers = np.arange(1, LAST + 1, dtype=float)+ primes = numbers[is_prime[1:]]+ prime_points = polar(primes)+ wholes = numbers[:20_000]+ whole_points = polar(wholes)++ # the zoom: the radius of the view, in numbers, against the time on `clock`+ times, log_radius = zoom_curve(+ [+ (0.0, 16),+ (2.6, 16),+ (6.0, 75),+ (8.6, 125),+ (12.2, 2500),+ (14.2, 4200),+ (20.0, 380_000),+ (23.2, LAST),+ ]+ )+ clock = m.ValueTracker(0.0)++ def radius() -> float:+ return float(10 ** np.interp(clock.get_value(), times, log_radius))++ def dot_size() -> (+ float+ ): # dots shrink a little as they multiply, never with the zoom+ return float(+ np.interp(np.log10(radius()), [1.2, 2.2, 3.6, 6], [14, 8, 4.4, 2.0])+ )++ arm_mix = m.ValueTracker(0.0) # 0: wholes grey; 1: colored by n mod 6+ wholes_shown = m.ValueTracker(0.0)+ primes_shown = m.ValueTracker(0.0)+ grey = np.array(WHOLE_COLOR.to_rgba())+ arm_rgba = np.array([c.to_rgba() for c in ARM_COLORS])[wholes.astype(int) % 6]++ whole_cloud = m.PMobject()+ prime_cloud = m.PMobject()++ def place_wholes(cloud: m.PMobject) -> None:+ r = radius()+ count = int(np.searchsorted(wholes, r, side="right"))+ if wholes_shown.get_value() <= 0:+ count = 0 # gone for good+ mix = arm_mix.get_value()+ rgba = (1 - mix) * grey + mix * arm_rgba[:count]+ rgba[:, 3] = (0.5 + 0.3 * mix) * wholes_shown.get_value()+ cloud.points = whole_points[:count] * (DISK / r)+ cloud.paint = cloud.paint.but(fill=rgba, stroke_width=0.65 * dot_size())++ prime_rgba = np.tile(PRIME_COLOR.to_rgba(), (len(primes), 1))++ def place_primes(cloud: m.PMobject) -> None:+ r = radius()+ count = int(np.searchsorted(primes, r, side="right"))+ rgba = prime_rgba[:count].copy()+ rgba[:, 3] = primes_shown.get_value()+ cloud.points = prime_points[:count] * (DISK / r)+ cloud.paint = cloud.paint.but(fill=rgba, stroke_width=dot_size())++ # the six arms of the whole numbers: n ≡ k (mod 6), from the center out+ arm_reach = m.ValueTracker(+ 0.0+ ) # how far out they are drawn, as a part of the view+ arm_opacity = m.ValueTracker(0.0)+ arm_numbers = [+ np.concatenate([[0.0], np.arange(k, 400, 6.0)]) for k in range(6)+ ]+ arm_paths = [+ m.VMobject(stroke_color=ARM_COLORS[k], stroke_width=3) for k in range(6)+ ]+ arms = m.VGroup(*arm_paths)++ def place_arms(_: m.Mobject) -> None:+ r = radius()+ for arm, ns in zip(arm_paths, arm_numbers, strict=True):+ shown = ns[ns <= arm_reach.get_value() * r]+ if len(shown) < 2:+ shown = np.array([0.0, 1e-3])+ arm.set_points_smoothly(polar(shown) * (DISK / r))+ arm.set_stroke(opacity=0.8 * arm_opacity.get_value())++ arms.add_updater(place_arms)+ place_arms(arms)++ whole_cloud.add_updater(place_wholes)+ prime_cloud.add_updater(place_primes)+ place_wholes(whole_cloud)+ place_primes(prime_cloud)++ # the first primes, named+ names = m.VGroup()+ for p in primes[primes < 15]:+ name = m.MathTex(f"{int(p)}", font_size=40, color=PRIME_COLOR)+ names.add(name)++ def place_names(group: m.Mobject) -> None:+ r = radius()+ for name, p in zip(group.submobjects, primes, strict=False):+ at = polar(np.array([p]))[0] * (DISK / r)+ name.move_to(at + 0.32 * m.normalize(at + 1e-9))++ names.add_updater(place_names)+ place_names(names)+ rule = m.MathTex(r"(r, \theta) = (n, n)", font_size=48).to_corner(m.UL)++ # how far out the view reaches, to two digits+ bound_label = m.MathTex(r"n \le", font_size=48)+ bound_label.move_to(np.array([3.6, -3.45, 0.0]))+ bound = m.DecimalNumber(+ 16, num_decimal_places=0, group_with_commas=True, font_size=48+ )+ bound_row = m.VGroup(bound_label, bound)++ def show_bound(d: m.DecimalNumber) -> None:+ r = radius()+ rounded = round(r, -int(np.floor(np.log10(r))) + 1)+ if rounded != d.get_value():+ d.set_value(rounded)+ d.next_to(bound_label, m.RIGHT, buff=0.2)++ bound.add_updater(show_bound)++ def moment(turns_of: int, what: str) -> m.VGroup:+ """The label of a moment: why n wraps round nearly whole, and what follows."""+ turns = round(turns_of / (2 * np.pi))+ used = coprime_count(turns_of)+ times_two_pi = rf"{turns} \cdot 2\pi" if turns > 1 else r"2\pi"+ lines = m.VGroup(+ m.MathTex(rf"{turns_of} \approx " + times_two_pi, font_size=56),+ m.Tex(f"{turns_of} {what}", font_size=40),+ m.Tex(f"primes on {used}", font_size=40, color=PRIME_COLOR),+ )+ lines.arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.25)+ return lines.to_corner(m.UL)++ six = moment(6, "arms")+ forty_four = moment(44, "spirals")+ rays = moment(710, "rays")++ def advance(to: float, *animations: m.Animation) -> None:+ """Run the zoom's clock on to `to`, playing the animations meanwhile (each in its own+ time: the play lasts as long as the clock runs)."""+ ticking = clock.animate(run_time=to - clock.get_value(), rate_func=m.linear)+ self.play(ticking.set_value(to), *animations)++ self.add(whole_cloud, arms, prime_cloud)+ advance(+ 2.6,+ wholes_shown.animate(run_time=1.0).set_value(1.0),+ primes_shown.animate(run_time=1.0).set_value(1.0),+ m.LaggedStart(+ *(m.FadeIn(n, scale=0.5) for n in names), lag_ratio=0.3, run_time=2.0+ ),+ m.FadeIn(rule, run_time=1.0),+ m.FadeIn(bound_row, run_time=1.0),+ )+ advance(+ 6.0,+ m.FadeOut(names, run_time=1.5),+ arm_mix.animate(run_time=2.0).set_value(1.0),+ )+ names.clear_updaters()+ advance(+ 8.6,+ m.FadeIn(six, run_time=1.0),+ m.FadeOut(rule, run_time=1.0),+ arm_reach.animate(run_time=1.6).set_value(1.0),+ arm_opacity.animate(run_time=0.4).set_value(1.0),+ )+ advance(+ 12.2,+ m.FadeOut(six, run_time=1.0),+ arm_opacity.animate(run_time=1.5).set_value(0.0),+ arm_mix.animate(run_time=2.5).set_value(0.0),+ )+ arms.clear_updaters()+ self.remove(arms)+ advance(14.2, m.FadeIn(forty_four, run_time=1.0))+ advance(+ 20.0,+ m.FadeOut(forty_four, run_time=1.0),+ wholes_shown.animate(run_time=2.0).set_value(0.0),+ )+ advance(20.4)+ advance(23.2, m.FadeIn(rays, run_time=1.0))+ self.wait(1.0)+++if __name__ == "__main__":+ PrimeSpirals().render("prime_spirals.mp4")diff --git a/examples/pythagoras.py b/examples/pythagoras.pynew file mode 100644index 00000000..79a81e32--- /dev/null+++ b/examples/pythagoras.py@@ -0,0 +1,172 @@+"""a² + b² = c², by moving four triangles.++Put four copies of a right triangle, with legs a and b and hypotenuse c, inside a square of+side a + b, each in a corner and turned a quarter turn from the last: the space they leave is a+tilted square on the hypotenuse, of area c². Now slide three of them, without turning, until+the four pair up into two rectangles: the space left is a square of side a and a square of side+b. The big square and the four triangles never changed, so neither did the space they leave:+a² + b² = c².+"""++import numpy as np++import manimgx as m++A, B = 2.4, 3.6 # the legs, in scene units+S = A + B # the big square's side+CORNER = np.array([-5.75, -3.0, 0.0]) # the big square's lower left corner+CENTER = CORNER + np.array([S / 2, S / 2, 0.0])+A_COLOR, B_COLOR, C_COLOR = m.TEAL, m.GOLD, m.RED+TRIANGLE_FILL = m.BLUE_E+EDGE = 6 # the triangles' edges, in hundredths of a unit+OPACITY = 0.65 # the fill of the space left+WALL = 9.2+++def at(x: float, y: float) -> np.ndarray:+ """The point (x, y) of the big square, measured from its lower left corner."""+ return CORNER + np.array([x, y, 0.0])+++def triangle(right: np.ndarray, a_end: np.ndarray, b_end: np.ndarray) -> m.VGroup:+ """A right triangle with its right angle at `right` and its legs a and b ending at+ `a_end` and `b_end`: its body, its edges a, b and c, each in its color, and the mark+ of its right angle."""+ body = m.Polygon(right, a_end, b_end, stroke_width=0)+ body.set_fill(TRIANGLE_FILL, opacity=1.0)+ along_a, along_b = m.normalize(a_end - right), m.normalize(b_end - right)+ mark = m.VMobject(stroke_color=m.GREY_A, stroke_width=3)+ size = 0.3+ mark.set_points_as_corners(+ [+ right + size * along_a,+ right + size * (along_a + along_b),+ right + size * along_b,+ ]+ )+ return m.VGroup(+ body,+ m.Line(right, a_end, color=A_COLOR, stroke_width=EDGE),+ m.Line(right, b_end, color=B_COLOR, stroke_width=EDGE),+ m.Line(a_end, b_end, color=C_COLOR, stroke_width=EDGE),+ mark,+ )+++def body(triangle: m.VGroup) -> m.VMobject:+ """A triangle's body: the region it covers."""+ shape = triangle[0]+ assert isinstance(shape, m.VMobject)+ return shape+++def space_left(outline: m.VMobject, triangles: list[m.VGroup]) -> m.VMobject:+ """The part of the big square that the four triangles leave uncovered, as it is now."""+ covered = m.Union(*(body(t) for t in triangles))+ left = m.Difference(outline, covered, stroke_width=0)+ return left.set_fill(C_COLOR, opacity=OPACITY)+++def label(+ tex: str, color: m.ManimColor, x: float, y: float, size: int = 60+) -> m.MathTex:+ return m.MathTex(tex, font_size=size, color=color).move_to(at(x, y))+++class Pythagoras(m.Scene):+ def construct(self) -> None:+ outline = m.Polygon(at(0, 0), at(S, 0), at(S, S), at(0, S))+ outline.set_stroke(m.GREY_B, width=4)++ # one triangle in the lower right corner, then three copies, each turned a quarter+ # turn about the square's center from the last+ first = triangle(at(S, 0), at(S, A), at(A, 0))+ a_label = label("a", A_COLOR, S + 0.4, A / 2)+ b_label = label("b", B_COLOR, A + B / 2, -0.45)+ hypotenuse_mid = (at(S, A) + at(A, 0)) / 2+ c_label = m.MathTex("c", font_size=60, color=C_COLOR)+ c_label.move_to(hypotenuse_mid + 0.42 * m.normalize(CENTER - hypotenuse_mid))++ self.play(m.Create(outline), run_time=1.0)+ self.play(+ m.FadeIn(first[0]),+ *(m.Create(part) for part in first[1:]),+ run_time=1.2,+ )+ self.play(m.Write(a_label), m.Write(b_label), m.Write(c_label), run_time=0.8)+ triangles = [first]+ for _ in range(3):+ turned = triangles[-1].copy()+ self.play(m.Rotate(turned, m.PI / 2, about_point=CENTER), run_time=0.8)+ triangles.append(turned)+ _, upper_right, upper_left, lower_left = triangles++ # the other halves of the two labeled sides: each side is a + b+ self.play(+ m.FadeIn(label("a", A_COLOR, A / 2, -0.45)),+ m.FadeIn(label("b", B_COLOR, S + 0.4, A + B / 2)),+ run_time=0.6,+ )++ # the space left is the square on the hypotenuse+ tilted = m.Polygon(at(A, 0), at(S, A), at(B, S), at(0, B), stroke_width=0)+ tilted.set_fill(C_COLOR, opacity=OPACITY)+ c_squared = m.MathTex("c^2", font_size=96, color=C_COLOR).move_to(CENTER)+ self.add(tilted, *triangles) # under the triangles' edges+ self.play(+ m.FadeIn(tilted), m.FadeOut(c_label), m.Write(c_squared), run_time=1.2+ )++ equation = m.MathTex("{{a^2}} + {{b^2}} = {{c^2}}", font_size=96)+ equation.move_to(np.array([4.0, 0.0, 0.0]))+ eq_a, plus, eq_b, equals, eq_c = equation+ eq_a.set_color(A_COLOR)+ eq_b.set_color(B_COLOR)+ eq_c.set_color(C_COLOR)+ self.play(m.TransformFromCopy(c_squared[0], eq_c), run_time=1.5)+ self.wait(0.5)++ # three slides, none turning: the space left flows around each triangle as it moves+ left = m.always_redraw(lambda: space_left(outline, triangles))+ self.remove(tilted)+ self.add(left, *triangles)+ slides = [+ (upper_left, at(A, -B) - at(0, 0)), # across the tilted square, by c+ (upper_right, at(-B, 0) - at(0, 0)), # left along the top, by b+ (lower_left, at(0, A) - at(0, 0)), # up along the side, by a+ ]+ self.play(+ upper_left.animate(run_time=1.6).shift(slides[0][1]),+ m.FadeOut(c_squared, run_time=0.5),+ )+ for moving, by in slides[1:]:+ self.play(moving.animate.shift(by), run_time=1.6)++ # the space left is now two squares, on a and on b+ left.clear_updaters()+ a_square = m.Polygon(at(0, 0), at(A, 0), at(A, A), at(0, A), stroke_width=0)+ b_square = m.Polygon(at(A, A), at(S, A), at(S, S), at(A, S), stroke_width=0)+ for square in (a_square, b_square):+ square.set_fill(C_COLOR, opacity=OPACITY)+ self.remove(left)+ self.add(a_square, b_square, *triangles)+ a_squared = m.MathTex("a^2", font_size=80, color=A_COLOR).move_to(a_square)+ b_squared = m.MathTex("b^2", font_size=96, color=B_COLOR).move_to(b_square)+ self.play(+ a_square.animate.set_fill(A_COLOR, opacity=OPACITY),+ b_square.animate.set_fill(B_COLOR, opacity=OPACITY),+ m.Write(a_squared),+ m.Write(b_squared),+ run_time=1.2,+ )++ # the equation, from the areas' labels+ self.play(m.TransformFromCopy(a_squared[0], eq_a), m.FadeIn(plus), run_time=1.3)+ self.play(+ m.TransformFromCopy(b_squared[0], eq_b), m.FadeIn(equals), run_time=1.3+ )+ self.wait(2.0)+++if __name__ == "__main__":+ Pythagoras().render("pythagoras.mp4")diff --git a/examples/quadratic_formula.py b/examples/quadratic_formula.pynew file mode 100644index 00000000..29ad8d51--- /dev/null+++ b/examples/quadratic_formula.py@@ -0,0 +1,189 @@+"""The quadratic formula, by completing a square.++ax² + bx + c = 0 is solved by making its left side a perfect square. Divide by a and move the+constant across: x² + (b/a)x is then the area of a square of side x and a rectangle b/a by x.+Cut the rectangle in two and fold one half under the square, and the shape is a square of side+x + b/2a missing one small corner, (b/2a)². Add that corner to both sides; the left side is now+(x + b/2a)², and a square root and a subtraction later, x = (−b ± √(b² − 4ac))/2a. Each term+keeps its color as it moves: the algebra is the picture.+"""++import numpy as np++import manimgx as m++WALL = 9.6 # the README wall's 5 seconds start here+SIZE = 60 # the equations' font size+X, HALF = 2.4, 0.8 # the picture's x and b/2a, in screen units+SQUARE, STRIP, CORNER = m.BLUE, m.TEAL, m.YELLOW+COLORS = {"x2": SQUARE, "bx": STRIP, "sq": CORNER, "sq2": CORNER}++Terms = list[tuple[str, str]] # (key, LaTeX): a key names a term across the equations++E1: Terms = [("x2", "a x^2"), ("p1", "+"), ("bx", "b x"), ("p2", "+"), ("c", "c"),+ ("eq", "="), ("zero", "0")] # fmt: skip+E2: Terms = [("x2", "x^2"), ("p1", "+"), ("bx", r"\frac{b}{a} x"), ("p2", "+"),+ ("c", r"\frac{c}{a}"), ("eq", "="), ("zero", "0")] # fmt: skip+E3: Terms = [("x2", "x^2"), ("p1", "+"), ("bx", r"\frac{b}{a} x"), ("eq", "="),+ ("c", r"-\frac{c}{a}")] # fmt: skip+E4: Terms = [("x2", "x^2"), ("p1", "+"), ("bx", r"\frac{b}{a} x"), ("p3", "+"),+ ("sq", r"\left( \frac{b}{2a} \right)^2"), ("eq", "="),+ ("sq2", r"\left( \frac{b}{2a} \right)^2"), ("c", r"-\frac{c}{a}")] # fmt: skip+E5: Terms = [("lhs", r"\left( x + \frac{b}{2a} \right)^2"), ("eq", "="),+ ("rhs", r"\frac{b^2 - 4ac}{4a^2}")] # fmt: skip+E6: Terms = [("x", "x"), ("plus", "+"), ("half", r"\frac{b}{2a}"), ("eq", "="),+ ("root", r"\pm \frac{ \sqrt{b^2 - 4ac} }{2a}")] # fmt: skip+E7: Terms = [("x", "x"), ("eq", "="), ("sol", r"\frac{-b \pm \sqrt{b^2 - 4ac} }{2a}")]+++class Equation(m.MathTex):+ """An equation whose terms are named, so that a step can say which becomes which."""++ def __init__(self, terms: Terms, font_size: float = SIZE) -> None:+ super().__init__(+ " ".join("{{ " + tex + " }}" for _, tex in terms), font_size=font_size+ )+ assert len(self.submobjects) == len(terms)+ self.parts = {+ key: part for (key, _), part in zip(terms, self.submobjects, strict=True)+ }+ for key, color in COLORS.items():+ if key in self.parts:+ self.parts[key].set_color(color)+++def rectangle(+ left: float, top: float, width: float, height: float, color: str+) -> m.Rectangle:+ box = m.Rectangle(+ width=width, height=height, fill_color=color, fill_opacity=0.65,+ stroke_color=m.WHITE, stroke_width=2,+ ) # fmt: skip+ return box.move_to([left + width / 2, top - height / 2, 0])+++class QuadraticFormula(m.Scene):+ def step(+ self,+ before: Equation,+ after: Equation,+ come_from: dict[str, m.Mobject] | None = None,+ path_arc: float = 0,+ run_time: float = 1.6,+ ) -> None:+ """Turn `before` into `after`. Symbols that appear in both fly to their new places+ and the rest fade; or, given `come_from`, each term moves to the term of the same key,+ and a term it names is drawn out of a copy of that mobject."""+ if come_from is None:+ self.play(+ m.TransformMatchingShapes(before, after, path_arc=path_arc),+ run_time=run_time,+ )+ return+ self.remove(before)+ self.add(*before.submobjects)+ moves: list[m.Animation] = []+ for key, part in after.parts.items():+ if key in come_from:+ moves.append(m.FadeTransform(come_from[key].copy(), part))+ elif key in before.parts:+ moves.append(m.ReplacementTransform(before.parts[key], part))+ else:+ moves.append(m.FadeIn(part, shift=0.25 * m.DOWN))+ moves += [+ m.FadeOut(part)+ for key, part in before.parts.items()+ if key not in after.parts+ ]+ self.play(*moves, run_time=run_time)+ self.remove(*before.submobjects, *after.submobjects)+ self.add(after)++ def construct(self) -> None:+ center, top = 0.4 * m.UP, 2.65 * m.UP+ e1, e2, e3 = (Equation(e).move_to(center) for e in (E1, E2, E3))+ e4, e5 = (Equation(e).move_to(top) for e in (E4, E5))+ e6 = Equation(E6).move_to(top)+ e7 = Equation(E7, font_size=76).move_to(0.2 * m.UP)++ self.play(m.Write(e1), run_time=1.5)+ self.wait(0.6)+ self.step(e1, e2)+ self.wait(0.4)+ self.step(e2, e3, path_arc=-0.5 * np.pi)+ self.wait(0.3)++ # the picture: x² + (b/a)x as areas, built from the terms+ left, ceiling = -(X + HALF) / 2, 0.75+ square = rectangle(left, ceiling, X, X, SQUARE)+ strip = rectangle(left + X, ceiling, 2 * HALF, X, STRIP)+ self.play(e3.animate.move_to(top), run_time=0.8)+ self.play(+ m.TransformFromCopy(e3.parts["x2"], square),+ m.TransformFromCopy(e3.parts["bx"], strip),+ run_time=1.4,+ )+ side = m.MathTex("x", font_size=44)+ x_top = side.copy().next_to(square, m.UP, buff=0.15)+ x_left = side.copy().next_to(square, m.LEFT, buff=0.15)+ b_over_a = m.MathTex(r"\frac{b}{a}", font_size=40, color=STRIP).next_to(+ strip, m.UP, 0.15+ )+ self.play(+ *(m.FadeIn(label) for label in (x_top, x_left, b_over_a)), run_time=0.7+ )++ # cut the strip in two and fold one half under the square+ kept = rectangle(left + X, ceiling, HALF, X, STRIP)+ folded = rectangle(left + X + HALF, ceiling, HALF, X, STRIP)+ self.remove(strip)+ self.add(kept, folded)+ half_top = m.MathTex(r"\frac{b}{2a}", font_size=36, color=STRIP)+ half_left = half_top.copy()+ under = rectangle(left, ceiling - X, X, HALF, STRIP)+ half_top.next_to(kept, m.UP, 0.15)+ half_left.next_to(under, m.LEFT, 0.15)+ self.play(+ m.Transform(folded, under, path_arc=-np.pi / 2),+ m.FadeTransform(b_over_a, half_top),+ m.FadeTransform(b_over_a.copy(), half_left),+ run_time=1.6,+ )+ corner = rectangle(left + X, ceiling - X, HALF, HALF, CORNER)+ outline = m.DashedVMobject(corner.copy().set_fill(opacity=0), num_dashes=16)+ self.play(m.Create(outline), run_time=0.6)+ self.play(m.FadeIn(corner), m.FadeOut(outline), run_time=0.5)++ # add the corner to both sides+ self.step(e3, e4, come_from={"sq": corner, "sq2": corner}, run_time=1.8)+ self.wait(0.5)++ # the left side is a square+ whole = m.Square(side_length=X + HALF, stroke_color=m.WHITE, stroke_width=6)+ whole.move_to([left + (X + HALF) / 2, ceiling - (X + HALF) / 2, 0])+ brace = m.Brace(whole, m.RIGHT, buff=0.15)+ brace_label = m.MathTex(r"x + \frac{b}{2a}", font_size=44).next_to(+ brace, m.RIGHT, 0.15+ )+ self.step(e4, e5, run_time=2)+ self.play(+ m.Create(whole), m.GrowFromCenter(brace), m.Write(brace_label), run_time=1.2+ )+ self.wait(0.8)++ # a square root, and x alone+ picture = m.VGroup(+ square, kept, folded, corner, whole, brace, brace_label,+ x_top, x_left, half_top, half_left,+ ) # fmt: skip+ self.play(m.FadeOut(picture), run_time=0.8)+ self.step(e5, e6, run_time=1.8)+ self.wait(0.3)+ self.step(e6, e7, run_time=1.8)+ box = m.SurroundingRectangle(e7, color=m.YELLOW, buff=0.35, stroke_width=5)+ self.play(m.Create(box), run_time=1)+ self.wait(2)+++if __name__ == "__main__":+ QuadraticFormula().render("quadratic_formula.mp4")diff --git a/examples/riemann_sums.py b/examples/riemann_sums.pynew file mode 100644index 00000000..51ad8f93--- /dev/null+++ b/examples/riemann_sums.py@@ -0,0 +1,262 @@+"""The area under a curve is the limit of sums of thin rectangles.++Cut the stretch from a to b into strips of width Δx and stand a rectangle in each, as tall as+the curve at the strip's left edge: the rectangles' areas add up to Σ f(xᵢ)Δx, close to the area+under the curve but not equal to it. Halve Δx and every rectangle splits in two, the new right+half rising or sinking to meet the curve; the sum creeps toward the true area. In the limit+Δx → 0 the sum becomes the integral ∫ₐᵇ f(x) dx, and the integral is the area.+"""++import numpy as np++import manimgx as m++WALL = 3.4 # the rectangles split, again and again++A, B = 0.5, 4.5 # the region+LEVELS = 6 # halvings: Δx from 1 down to 1/64+COLORS = (m.BLUE, m.GREEN) # the rectangles' gradient, left to right+++def F(x: np.ndarray) -> np.ndarray:+ """A wave on a slope, at every x of an array."""+ return 1 + 0.6 * x + 0.9 * np.sin(1.6 * x)+++def f(x: float) -> float:+ return float(F(np.asarray(x)))+++def exact_area(a: float, b: float, n: int = 20000) -> float:+ """∫ₐᵇ f(x) dx by Simpson's rule on n (even) strips."""+ xs = np.linspace(a, b, n + 1)+ ys = np.array([f(x) for x in xs])+ h = (b - a) / n+ return float(h / 3 * (ys[0] + ys[-1] + 4 * ys[1:-1:2].sum() + 2 * ys[2:-1:2].sum()))+++def gap(width: float) -> float:+ """The gap between neighbouring rectangles `width` wide, in scene units: a sliver of+ page between wide ones, none between thin ones, which overlap a hair instead (two edges+ that merely touch would show a seam)."""+ return 0.06 * min(1.0, width / 0.5) ** 2 - 0.01 * (1 - min(1.0, width / 0.1))+++class RiemannSums(m.Scene):+ def construct(self) -> None:+ axes = m.Axes(+ x_range=[0, 5, 1],+ y_range=[0, 5, 1],+ x_length=10.5,+ y_length=5.2,+ tips=False,+ axis_config={"stroke_width": 3, "color": m.GREY_B},+ ).move_to(np.array([0.2, -0.75, 0]))+ curve = axes.plot(f, x_range=[0.05, 4.95], color=m.YELLOW, stroke_width=7)+ curve.set_z_index(1) # over the rectangles+ f_label = m.MathTex("f(x)", color=m.YELLOW, font_size=52)+ f_label.next_to(axes.c2p(4.95, f(4.95)), m.RIGHT, buff=0.2)+ ends = m.VGroup(+ *[+ m.MathTex(name, font_size=48).next_to(axes.c2p(x, 0), m.DOWN, buff=0.25)+ for name, x in (("a", A), ("b", B))+ ]+ )+ x_unit = axes.get_x_unit_size()+ origin = axes.c2p(0, 0)+ y_unit = axes.c2p(0, 1)[1] - origin[1]+ gradient = np.array([c.to_rgb() for c in m.color_gradient(list(COLORS), 101)])++ def color_at(x: np.ndarray) -> np.ndarray:+ """The gradient's color (RGB rows) at each x, from a's to b's."""+ k = np.clip(np.round(100 * (x - A) / (B - A)), 0, 100).astype(int)+ return gradient[k]++ # the rectangles of level L (Δx = 1/2^L) splitting into those of level L + 1, at+ # progress s: each into a left half that keeps its height and a right half that+ # moves to the curve at its own left edge+ level = m.ValueTracker(0.0) # L + s+ grown = m.ValueTracker(0.0) # how far the first rectangles have risen+ memo: dict[tuple[float, float], tuple[np.ndarray, ...]] = {}++ def pair(a: np.ndarray, b: np.ndarray) -> np.ndarray:+ """Interleave two arrays row by row: a[0], b[0], a[1], b[1], …"""+ return np.stack([a, b], axis=1).reshape(-1, *a.shape[1:])++ def strips() -> tuple[np.ndarray, ...]:+ """The rectangles shown, as arrays: left and right x, height, the gaps at+ their left and right, and their colors (RGB rows)."""+ key = (level.get_value(), grown.get_value())+ if key in memo:+ return memo[key]+ whole = min(int(key[0]), LEVELS)+ s = key[0] - whole+ dx = 1 / 2**whole+ outer = (1 - s) * gap(dx * x_unit) + s * gap(dx / 2 * x_unit)+ inner = (1 - s) * -0.01 + s * gap(dx / 2 * x_unit) # the split opens+ x = A + dx * np.arange(round((B - A) / dx))+ h = key[1] * F(x)+ n = len(x)+ if s == 0:+ shown = (+ x,+ x + dx,+ h,+ np.full(n, outer),+ np.full(n, outer),+ color_at(x + dx / 2),+ )+ else:+ mid = x + dx / 2+ parent = color_at(mid)+ shown = (+ pair(x, mid),+ pair(mid, x + dx),+ pair(h, h + s * (key[1] * F(mid) - h)),+ pair(np.full(n, outer), np.full(n, inner)),+ pair(np.full(n, inner), np.full(n, outer)),+ pair(+ parent + s * (color_at(x + dx / 4) - parent),+ parent + s * (color_at(x + 3 * dx / 4) - parent),+ ),+ )+ memo.clear()+ memo[key] = shown+ return shown++ def area_shown() -> float:+ left, right, h, *_ = strips()+ return float(((right - left) * h).sum())++ pieces: list[m.VMobject] = [] # the rectangles' shapes, reshaped every frame++ def rectangles(group: m.Mobject) -> None:+ """Reshape the rectangles in place (one VMobject each, made anew only when+ their number changes)."""+ left, right, h, gap_left, gap_right, colors = strips()+ if len(pieces) != len(left):+ pieces[:] = [m.VMobject(stroke_width=0, fill_opacity=1) for _ in left]+ group.submobjects = list(pieces)+ x0 = origin[0] + left * x_unit + gap_left / 2+ x1 = origin[0] + right * x_unit - gap_right / 2+ y0, y1 = origin[1], origin[1] + h * y_unit+ for k, rect in enumerate(pieces):+ rect.set_points_as_corners(+ [+ [x0[k], y0, 0],+ [x1[k], y0, 0],+ [x1[k], y1[k], 0],+ [x0[k], y1[k], 0],+ [x0[k], y0, 0],+ ]+ )+ rect.set_fill(m.ManimColor.from_rgb(colors[k]), 1)++ bars = m.VGroup()+ rectangles(bars)+ bars.add_updater(rectangles)++ # the readouts: Δx, the sum of the areas (live), and the true area it tends to+ dx_tex = m.MathTex(r"\Delta x =", font_size=52)+ dx_tex.move_to(np.array([-6.6, 3.3, 0]), aligned_edge=m.LEFT)++ def delta(dx: float) -> m.MathTex:+ """Δx's value, written out exactly: 1, 0.5, 0.25, …"""+ return m.MathTex(f"{dx:g}", font_size=52).next_to(dx_tex, m.RIGHT, buff=0.2)++ dx_value = delta(1)+ sum_tex = m.MathTex(+ r"{{ \sum_{i} }} {{f(}} {{x_i}} {{)}} \, {{\Delta x}} {{=}}", font_size=56+ )+ sum_tex.get_parts_by_tex("f(").set_color(m.YELLOW)+ sum_tex.get_parts_by_tex("x_i").set_color(m.YELLOW)+ sum_tex.get_parts_by_tex(")").set_color(m.YELLOW)+ sum_tex.move_to(np.array([-0.9, 3.2, 0]), aligned_edge=m.LEFT)+ truth = exact_area(A, B)+ # the number after the "=": the rectangles' total area, until it becomes the+ # integral's value, `settled` once Δx → 0 (−1 until then)+ settled = m.ValueTracker(-1.0)+ equals = [sum_tex[-1]]+ total = m.DecimalNumber(0, num_decimal_places=2, font_size=56)++ # its opacity: it fades in by this, not by an animation, which would hold its value+ written = m.ValueTracker(0.0)++ def show_total(mob: m.Mobject) -> None:+ value = settled.get_value()+ total.set_value(area_shown() if value < 0 else value)+ total.next_to(equals[0], m.RIGHT, buff=0.25)+ total.set_opacity(written.get_value())++ show_total(total)+ total.add_updater(show_total)+ self.add(total)+ target = m.MathTex(r"\to", font_size=56, color=m.GREY_B)+ target_value = m.DecimalNumber(+ truth, num_decimal_places=2, font_size=56, color=m.GREY_B+ )+ goal = m.VGroup(target, target_value).arrange(m.RIGHT, buff=0.25)+ widest = target_value.copy().move_to(total, aligned_edge=m.LEFT) # 5 characters+ goal.next_to(widest, m.RIGHT, buff=0.35)++ self.add(axes)+ self.play(m.Create(curve), m.FadeIn(f_label), m.FadeIn(ends), run_time=1.4)+ self.add(bars)+ self.play(+ grown.animate.set_value(1.0),+ m.FadeIn(dx_tex),+ m.FadeIn(dx_value),+ m.Write(sum_tex),+ written.animate.set_value(1.0),+ run_time=1.5,+ )+ self.play(m.FadeIn(goal, shift=0.2 * m.LEFT), run_time=0.5)+ # Δx halves, again and again: the sum creeps toward the area+ # Δx's new value comes in as the split begins+ early = m.squish_rate_func(m.smooth, 0.0, 0.35)+ for k in range(LEVELS):+ new_value = delta(1 / 2 ** (k + 1))+ self.play(+ level.animate.set_value(k + 1.0),+ m.FadeOut(dx_value, shift=0.3 * m.UP, rate_func=early),+ m.FadeIn(new_value, shift=0.3 * m.UP, rate_func=early),+ run_time=1.8 if k < 3 else 1.4,+ )+ dx_value = new_value+ self.wait(0.15)+ self.wait(0.4)++ # Δx → 0: the sum becomes the integral, and the integral is the area+ integral_tex = m.MathTex(+ r"{{ \int_a^b }} {{f(}} {{x}} {{)}} \, {{dx}} {{=}}", font_size=56+ )+ integral_tex.get_parts_by_tex("f(").set_color(m.YELLOW)+ integral_tex.get_parts_by_tex("x", substring=False).set_color(m.YELLOW)+ integral_tex.get_parts_by_tex(")").set_color(m.YELLOW)+ width = integral_tex.width + 0.25 + total.width # with its value, centered+ left = axes.get_center()[0] - width / 2+ integral_tex.move_to(np.array([left, 3.2, 0]), aligned_edge=m.LEFT)+ region = axes.get_area(axes.plot(f, x_range=[A, B, 0.01]), x_range=(A, B))+ region.set_stroke(width=0).set_fill(list(COLORS), opacity=1)+ region.set_sheen_direction(m.RIGHT)+ settled.set_value(area_shown())+ self.play(+ m.TransformMatchingTex(+ sum_tex,+ integral_tex,+ key_map={r"\sum_{i}": r"\int_a^b", "x_i": "x", r"\Delta x": "dx"},+ ),+ m.FadeOut(dx_tex),+ m.FadeOut(dx_value),+ m.FadeOut(goal),+ settled.animate.set_value(truth),+ m.FadeIn(region), # over the thin rectangles, which it then replaces+ run_time=2,+ )+ equals[0] = integral_tex[-1]+ self.remove(bars)+ self.wait(2)+++if __name__ == "__main__":+ RiemannSums().render("riemann_sums.mp4")diff --git a/examples/taylor_series.py b/examples/taylor_series.pynew file mode 100644index 00000000..660114d4--- /dev/null+++ b/examples/taylor_series.py@@ -0,0 +1,157 @@+"""Polynomials that turn into the sine.++Near 0, sin x looks like x. Subtract x³/3! and the cubic bends back down with the sine; add+x⁵/5! and it follows the next turn; every term fixes the error the one before it left. The+Taylor polynomial of degree 2n + 1 matches sin x and its first 2n + 1 derivatives at 0, and its+error is at most |x|^(2n+3)/(2n + 3)!: a factorial outruns any power, so each new term hugs the+wave over a wider stretch, and the whole infinite series is the sine everywhere.+"""++from math import factorial++import numpy as np++import manimgx as m++WALL = 9.4 # the polynomial chases the sine out to the edges++DEGREES = list(range(1, 41, 2)) # 1, 3, …, 39+# the terms written out one by one, to x¹⁹/19!; the rest rush in at the end+WRITTEN = 10+X_MAX = 11.0 # the axes run over |x| ≤ X_MAX+Y_MAX = 3.0 # and |y| ≤ Y_MAX; a polynomial is cut where it leaves them+COLORS = m.color_gradient([m.YELLOW, m.RED, m.PURPLE_A], WRITTEN)+XS = np.linspace(-X_MAX, X_MAX, 2201)+++def term(degree: int, x: np.ndarray) -> np.ndarray:+ """The series' term of this (odd) degree: ±x^degree / degree!."""+ sign = -1 if degree % 4 == 3 else 1+ return sign * x**degree / factorial(degree)+++def term_tex(degree: int) -> str:+ if degree == 1:+ return "x"+ sign = "-" if degree % 4 == 3 else "+"+ return sign + rf" \frac{{x^{{{degree}}}}}{{{degree}!}}"+++def color(k: int) -> m.ManimColor:+ """The color of the polynomial with k + 1 terms, and of its last term."""+ return COLORS[min(k, WRITTEN - 1)]+++def series_tex(count: int) -> m.MathTex:+ """sin x ≈ the first `count` terms; past seven, the middle ones go into ⋯."""+ shown = list(range(count))+ if count > 7:+ shown = [0, 1, 2, 3, -1, count - 1]+ parts = [r"\sin x", r"\approx"]+ parts += [r"+ \cdots" if k < 0 else term_tex(DEGREES[k]) for k in shown]+ tex = m.MathTex(*parts, font_size=50)+ tex[0].set_color(m.BLUE)+ for part, k in zip(tex[2:], shown, strict=True):+ if k >= 0:+ part.set_color(color(k))+ return tex.move_to(3.25 * m.UP)+++class TaylorSeries(m.Scene):+ def construct(self) -> None:+ axes = m.Axes(+ x_range=[-X_MAX, X_MAX, np.pi],+ y_range=[-Y_MAX, Y_MAX, 1],+ x_length=13.4,+ y_length=5.4,+ tips=False,+ axis_config={"stroke_width": 3, "color": m.GREY_B},+ ).move_to(0.7 * m.DOWN)+ sine = axes.plot(+ np.sin, x_range=[-X_MAX, X_MAX, 0.02], color=m.BLUE, stroke_width=6+ )++ # the polynomial: all the terms below `reach`, and the next one scaled by its fraction+ reach = m.ValueTracker(1.0)++ def polynomial() -> m.VMobject:+ done = int(reach.get_value())+ s = reach.get_value() - done+ ys = np.sum([term(d, XS) for d in DEGREES[:done]], axis=0)+ if s > 0 and done < len(DEGREES):+ ys = ys + s * term(DEGREES[done], XS)+ # keep the stretch around 0 inside the axes, cut where it leaves them+ inside = np.abs(ys) <= Y_MAX+ middle = len(XS) // 2+ left_out = np.nonzero(~inside[:middle])[0]+ right_out = np.nonzero(~inside[middle:])[0]+ lo = left_out[-1] + 1 if len(left_out) else 0+ hi = middle + right_out[0] if len(right_out) else len(XS)+ xs, ys_in = list(XS[lo:hi]), list(ys[lo:hi])+ if lo > 0: # the exact point where it leaves, on each side+ a, b = lo, lo - 1+ bound = np.sign(ys[b]) * Y_MAX+ t = (bound - ys[a]) / (ys[b] - ys[a])+ xs.insert(0, XS[a] + t * (XS[b] - XS[a]))+ ys_in.insert(0, bound)+ if hi < len(XS):+ a, b = hi - 1, hi+ bound = np.sign(ys[b]) * Y_MAX+ t = (bound - ys[a]) / (ys[b] - ys[a])+ xs.append(XS[a] + t * (XS[b] - XS[a]))+ ys_in.append(bound)+ shade = color(done - 1)+ if s > 0 and done < len(DEGREES):+ shade = m.interpolate_color(color(done - 1), color(done), s)+ # thinner once past the written terms, so the sine shows around it+ width = 7 - 3 * min(1.0, max(0.0, (reach.get_value() - WRITTEN) / 4))+ curve = m.VMobject(stroke_color=shade, stroke_width=width)+ curve.set_points_as_corners(axes.c2p(np.array(xs), np.array(ys_in)).T)+ return curve++ poly = m.always_redraw(polynomial)+ series = series_tex(1)++ self.add(axes)+ self.play(m.Create(sine), run_time=1.6)+ self.play(m.Create(poly), m.Write(series), run_time=1.2)+ self.remove(poly)+ poly = m.always_redraw(polynomial)+ self.add(poly)+ # each new term bends the polynomial along one more turn of the wave+ for count in range(2, WRITTEN + 1):+ new_series = series_tex(count)+ self.play(+ reach.animate.set_value(float(count)),+ m.TransformMatchingTex(series, new_series),+ run_time=1.6,+ )+ series = new_series+ self.wait(0.8)++ # all the terms: the series is the sine+ whole = m.MathTex(+ r"\sin x",+ "=",+ r"\sum_{n=0}^{\infty} \frac{(-1)^n\, x^{2n+1}}{(2n+1)!}",+ font_size=56,+ )+ whole[0].set_color(m.BLUE)+ whole.move_to(3.2 * m.UP)+ # every term at once: the polynomial lies on the sine all the way across+ self.play(reach.animate.set_value(float(len(DEGREES))), run_time=2.5)+ name, approx, terms = series[0], series[1], m.VGroup(*series[2:])+ self.remove(series)+ self.add(name, approx, terms)+ self.play(m.FadeOut(terms, shift=0.4 * m.UP), run_time=0.8)+ self.play(+ m.ReplacementTransform(approx, whole[1]),+ name.animate.move_to(whole[0]),+ m.FadeIn(whole[2], shift=0.4 * m.UP),+ run_time=1.4,+ )+ self.wait(2)+++if __name__ == "__main__":+ TaylorSeries().render("taylor_series.mp4")diff --git a/examples/times_tables.py b/examples/times_tables.pynew file mode 100644index 00000000..eb7ea5fc--- /dev/null+++ b/examples/times_tables.py@@ -0,0 +1,88 @@+"""Times tables on a circle.++Put 200 points around a circle, numbered 0 to 199, and join each point n to the point k·n,+counting around the circle (mod 200). For k = 2 the lines wrap a cardioid, the heart traced by+a point on a circle rolling around another of the same size; for k = 3, a nephroid, with two+lobes; for k, a curve with k − 1 lobes. Let k grow continuously and the figure turns, splits+and folds from one curve into the next.+"""++import numpy as np++import manimgx as m++WALL = 3.2 # the README wall's 5 seconds start here+POINTS = 200+RADIUS = 3.45+++def on_circle(angle: np.ndarray) -> np.ndarray:+ return RADIUS * np.stack(+ [np.cos(angle), np.sin(angle), np.zeros_like(angle)], axis=-1+ )+++class TimesTables(m.Scene):+ def construct(self) -> None:+ k = m.ValueTracker(2.0)+ n = np.arange(POINTS)+ start = np.pi + m.TAU * n / POINTS # point 0 on the left, as in a clock turned+ colors = m.color_gradient(+ [m.BLUE, m.TEAL, m.GREEN, m.YELLOW, m.RED, m.PURPLE, m.BLUE], POINTS+ )+ chords = m.VGroup(+ *(+ m.Line(m.LEFT, m.RIGHT, stroke_width=2, stroke_opacity=0.75, color=c)+ for c in colors+ )+ )++ def draw(group: m.VGroup) -> None:+ ends = on_circle(np.pi + m.TAU * k.get_value() * n / POINTS)+ begins = on_circle(start)+ for line, a, b in zip(group, begins, ends, strict=True):+ assert isinstance(line, m.Line)+ line.set_points_as_corners([a, b])++ chords.add_updater(draw)+ draw(chords)+ ring = m.Circle(radius=RADIUS, stroke_color=m.GREY_B, stroke_width=3)+ dots = m.VGroup(+ *(m.Dot(p, radius=0.022, color=m.GREY_A) for p in on_circle(start))+ )++ rule = m.MathTex(r"n \mapsto k \cdot n \pmod{200}", font_size=46)+ value = m.DecimalNumber(2.0, num_decimal_places=2, font_size=60, color=m.YELLOW)+ k_label = m.MathTex("k =", font_size=60)+ readout = m.VGroup(k_label, value).arrange(m.RIGHT, buff=0.2)+ panel = m.VGroup(rule, readout).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.35)+ panel.to_corner(m.UL, buff=0.5)+ value.add_updater(lambda d: d.set_value(k.get_value()))++ names = {2: "cardioid", 3: "nephroid", 4: "three lobes", 5: "four lobes"}+ name = m.Tex(names[2], font_size=48, color=m.GREY_A).next_to(+ panel, m.DOWN, aligned_edge=m.LEFT, buff=0.4+ )++ self.play(m.Create(ring), m.FadeIn(dots), run_time=1)+ self.play(m.Create(chords, lag_ratio=0.01), m.Write(panel), run_time=1.8)+ self.play(m.FadeIn(name), run_time=0.4)+ for target in (3, 4, 5):+ self.play(+ k.animate.set_value(target),+ m.FadeOut(name),+ run_time=2.4,+ )+ name = m.Tex(names[target], font_size=48, color=m.GREY_A).move_to(+ name, aligned_edge=m.LEFT+ )+ self.play(m.FadeIn(name), run_time=0.4)+ self.wait(0.6)+ self.play(m.FadeOut(name), run_time=0.3)+ # then on, without stopping: the figures between and beyond+ self.play(k.animate.set_value(34), run_time=12, rate_func=m.linear)+ self.wait(1)+++if __name__ == "__main__":+ TimesTables().render("times_tables.mp4")diff --git a/examples/unit_circle.py b/examples/unit_circle.pynew file mode 100644index 00000000..d23c641f--- /dev/null+++ b/examples/unit_circle.py@@ -0,0 +1,200 @@+"""Sine and cosine are a circle turning.++Turn a radius of the unit circle by an angle θ. Its tip is (cos θ, sin θ): cos θ is how far it+reaches across, sin θ how high it rises, the two legs of a right triangle whose hypotenuse is+the radius. Carry the height to the right as θ grows and it draws the sine wave; the reach+draws the cosine, the same wave a quarter turn ahead. And since the legs and the radius make a+right triangle, sin²θ + cos²θ = 1 at every angle.+"""++import numpy as np++import manimgx as m++WALL = 3.0 # the README wall's 5 seconds start here+CENTER = np.array([-4.55, 0.35, 0.0]) # the circle's+RADIUS = 1.45+ORIGIN = np.array([-2.35, 0.35, 0.0]) # where θ = 0 on the waves' axis+LENGTH = 9.0 # the waves' axis, one turn long+SINE, COSINE = m.YELLOW, m.GREEN+++def on_wave(theta: float, value: float) -> np.ndarray:+ return ORIGIN + np.array([LENGTH * theta / m.TAU, RADIUS * value, 0.0])+++class UnitCircle(m.Scene):+ def construct(self) -> None:+ theta = m.ValueTracker(0.0)+ circle = m.Circle(radius=RADIUS, stroke_color=m.GREY_B, stroke_width=4).move_to(+ CENTER+ )+ across = m.Line(+ CENTER + 1.25 * RADIUS * m.LEFT,+ CENTER + 1.25 * RADIUS * m.RIGHT,+ stroke_width=2,+ stroke_color=m.GREY_D,+ )+ upright = m.Line(+ CENTER + 1.25 * RADIUS * m.DOWN,+ CENTER + 1.25 * RADIUS * m.UP,+ stroke_width=2,+ stroke_color=m.GREY_D,+ )+ axis = m.Arrow(+ ORIGIN,+ ORIGIN + (LENGTH + 0.5) * m.RIGHT,+ buff=0,+ stroke_width=3,+ color=m.GREY_B,+ tip_length=0.2,+ )+ ticks = m.VGroup()+ for k, tex in enumerate(+ [r"\frac{\pi}{2}", r"\pi", r"\frac{3\pi}{2}", r"2\pi"], start=1+ ):+ at = ORIGIN + LENGTH * k / 4 * m.RIGHT+ ticks.add(+ m.Line(+ at + 0.1 * m.DOWN, at + 0.1 * m.UP, stroke_width=3, color=m.GREY_B+ )+ )+ ticks.add(+ m.MathTex(tex, font_size=34, color=m.GREY_A).next_to(+ at, m.DOWN, buff=0.22+ )+ )+ for value in (1, -1):+ at = ORIGIN + RADIUS * value * m.UP+ ticks.add(+ m.DashedLine(+ at,+ at + LENGTH * m.RIGHT,+ stroke_width=1.5,+ stroke_opacity=0.5,+ color=m.GREY_D,+ )+ )++ def tip() -> np.ndarray:+ a = theta.get_value()+ return CENTER + RADIUS * np.array([np.cos(a), np.sin(a), 0.0])++ def foot() -> np.ndarray:+ return np.array([tip()[0], CENTER[1], 0.0])++ radius = m.always_redraw(+ lambda: m.Line(CENTER, tip(), stroke_width=4, color=m.WHITE)+ )+ cos_leg = m.always_redraw(+ lambda: m.Line(CENTER, foot(), stroke_width=7, color=COSINE)+ )+ sin_leg = m.always_redraw(+ lambda: m.Line(foot(), tip(), stroke_width=7, color=SINE)+ )+ dot = m.always_redraw(lambda: m.Dot(tip(), radius=0.09, color=m.WHITE))++ def angle() -> float:+ """θ, from 0 to a whole turn, then on into the next turn from 0 again."""+ a = theta.get_value()+ return max(a if a <= m.TAU + 1e-9 else a - m.TAU, 1e-4)++ arc = m.always_redraw(+ lambda: m.Arc(+ radius=0.38,+ start_angle=0,+ angle=angle(),+ arc_center=CENTER,+ stroke_width=3,+ color=m.GREY_A,+ )+ )+ theta_label = m.always_redraw(+ lambda: m.MathTex(r"\theta", font_size=36).move_to(+ CENTER + 0.62 * np.array([np.cos(angle() / 2), np.sin(angle() / 2), 0])+ )+ )++ def wave(f: np.ufunc, color: str) -> m.Mobject:+ def draw() -> m.VMobject:+ a = max(theta.get_value(), 1e-3)+ return m.ParametricFunction(+ lambda s: on_wave(s, f(s)),+ t_range=[0, a, a / 120],+ stroke_width=6,+ color=color,+ )++ return m.always_redraw(draw)++ sine, cosine = wave(np.sin, SINE), wave(np.cos, COSINE)+ sine_head = m.always_redraw(+ lambda: m.Dot(+ on_wave(theta.get_value(), np.sin(theta.get_value())),+ radius=0.08,+ color=SINE,+ )+ )+ cosine_head = m.always_redraw(+ lambda: m.Dot(+ on_wave(theta.get_value(), np.cos(theta.get_value())),+ radius=0.08,+ color=COSINE,+ )+ )+ carry = m.always_redraw(+ lambda: m.DashedLine(+ tip(),+ on_wave(theta.get_value(), np.sin(theta.get_value())),+ stroke_width=2.5,+ color=SINE,+ dash_length=0.12,+ )+ )++ self.play(+ m.Create(circle),+ m.FadeIn(across, upright),+ m.GrowArrow(axis),+ m.FadeIn(ticks),+ run_time=1.5,+ )+ self.play(+ m.FadeIn(+ radius, cos_leg, sin_leg, dot, arc, theta_label, sine_head, cosine_head+ ),+ run_time=0.6,+ )+ self.add(sine, cosine, carry)+ self.play(theta.animate.set_value(m.TAU), run_time=10, rate_func=m.linear)++ names = m.VGroup( # by each wave's first peak+ m.MathTex(r"\sin\theta", font_size=48, color=SINE).next_to(+ on_wave(np.pi / 2, 1), m.UP, buff=0.25+ ),+ m.MathTex(r"\cos\theta", font_size=48, color=COSINE).next_to(+ on_wave(np.pi, -1), m.DOWN, buff=0.25+ ),+ )+ identity = m.MathTex(+ r"{{ \sin^2\theta }} + {{ \cos^2\theta }} = 1", font_size=56+ )+ identity.set_color_by_tex(r"\sin^2", SINE).set_color_by_tex(r"\cos^2", COSINE)+ identity.move_to(CENTER + 2.75 * m.DOWN)+ for traced in (sine, cosine):+ traced.clear_updaters() # the waves stay as one turn drew them+ self.play(+ m.FadeIn(names), m.FadeOut(carry, sine_head, cosine_head), run_time=0.8+ )+ self.play(theta.animate.set_value(m.TAU + 0.9), run_time=1.2)+ self.play(+ m.TransformFromCopy(sin_leg, identity[0]),+ m.TransformFromCopy(cos_leg, identity[2]),+ m.FadeIn(identity[1], identity[3]),+ run_time=1.6,+ )+ self.wait(2)+++if __name__ == "__main__":+ UnitCircle().render("unit_circle.mp4")diff --git a/tests/docs/test_classics.py b/tests/docs/test_classics.pynew file mode 100644index 00000000..9f7758e9--- /dev/null+++ b/tests/docs/test_classics.py@@ -0,0 +1,46 @@+"""The classic example films execute through the same loader the Gallery uses."""++from pathlib import Path++import pytest+from docs import examples++from manimgx.rendering.film import Frame++FILMS = (+ "circle_area",+ "colliding_blocks",+ "complex_maps",+ "derivative",+ "euler_identity",+ "fourier_pi",+ "galton_board",+ "hilbert_curve",+ "linear_maps",+ "lorenz_attractor",+ "prime_spirals",+ "pythagoras",+ "quadratic_formula",+ "riemann_sums",+ "surface_plots",+ "taylor_series",+ "times_tables",+ "unit_circle",+)+ROOT = Path(__file__).parents[2]++[email protected](pixel_width=160, pixel_height=90, frame_rate=2)[email protected]("name", FILMS)+def test_classic_film_renders_to_the_end(name: str) -> None:+ code = (ROOT / "examples" / f"{name}.py").read_text(encoding="utf-8")+ scene = examples.load(examples.Example(code, f"examples/{name}.py"))+ samples: set[bytes] = set()++ def keep(frame: Frame) -> None:+ pixels = frame.pixels() # draw every frame, including the final holds+ if len(samples) < 2:+ samples.add(pixels)++ scene().render(frames=keep)+ assert len(samples) == 2, f"{name} never changed its rendered image"