Skip to content

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

Python

Add render benchmarks

apoogdkddceb8a71610
diff --git a/tests/benchmarks/__init__.py b/tests/benchmarks/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/benchmarks/conftest.py b/tests/benchmarks/conftest.py
new file mode 100644
index 00000000..cfb216cf
--- /dev/null
+++ b/tests/benchmarks/conftest.py
@@ -0,0 +1,70 @@
+"""The trees the timed benchmarks compare and their rounds, from `--bench` and `--bench-rounds`
+(declared in `tests/conftest.py`), and the table a timed run ends with: on the terminal, and in
+the job's summary on GitHub Actions."""
+
+import os
+
+import pytest
+from tests.benchmarks.harness import Row, Tree, checkout, here
+
+LABELS = pytest.StashKey[tuple[str, str]]()
+HEADER = ("workload", "base", "head", "change", "rounds", "wall", "memory", "work")
+
+
[email protected](scope="session")
+def trees(pytestconfig: pytest.Config) -> tuple[Tree, Tree] | None:
+ """(the tree compared with, this checkout) with `--bench REF`, None without: the suite.
+ A commit's tree is made in pytest's cache, and kept."""
+ ref = pytestconfig.getoption("bench")
+ if ref is None:
+ return None
+ base = checkout(str(ref), pytestconfig.cache.mkdir("manimgx-trees"))
+ head = here()
+ pytestconfig.stash[LABELS] = (base.label, head.label)
+ return base, head
+
+
[email protected](scope="session")
+def rounds(pytestconfig: pytest.Config) -> int:
+ value = pytestconfig.getoption("bench_rounds")
+ assert isinstance(value, int)
+ return value
+
+
+def pytest_terminal_summary(
+ terminalreporter: pytest.TerminalReporter, config: pytest.Config
+) -> None:
+ rows = sorted(
+ (
+ value
+ for reports in terminalreporter.stats.values()
+ for report in reports
+ if getattr(report, "when", None) == "call"
+ for name, value in getattr(report, "user_properties", ())
+ if name == "timed" and isinstance(value, Row)
+ ),
+ key=lambda row: row.order,
+ )
+ if not rows:
+ return
+ base, head = config.stash.get(LABELS, ("REF", "this checkout"))
+ rounds = config.getoption("bench_rounds")
+ title = f"{head} against {base}: {rows[0].unit}, the median of {rounds} rounds"
+ table = [HEADER, *(row.cells for row in rows)]
+ widths = [max(len(row[k]) for row in table) for k in range(len(HEADER))]
+ terminalreporter.section(f"benchmarks: {title}")
+ for row in table:
+ cells = [
+ cell.ljust(width) if k in (0, len(row) - 1) else cell.rjust(width)
+ for k, (cell, width) in enumerate(zip(row, widths, strict=True))
+ ]
+ terminalreporter.write_line(" ".join(cells).rstrip())
+ summary = os.environ.get("GITHUB_STEP_SUMMARY")
+ if summary:
+ with open(summary, "a", encoding="utf-8") as out:
+ out.write(f"### Benchmarks: {title}\n\n")
+ for k, row in enumerate(table):
+ out.write("| " + " | ".join(row) + " |\n")
+ if k == 0:
+ out.write("|" + "---|" * len(HEADER) + "\n")
+ out.write("\n")
diff --git a/tests/benchmarks/harness.py b/tests/benchmarks/harness.py
new file mode 100644
index 00000000..c30df713
--- /dev/null
+++ b/tests/benchmarks/harness.py
@@ -0,0 +1,335 @@
+"""Two manimgx trees, timed side by side on one machine.
+
+A `Tree` is a manimgx package on disk: its `src/`, its engine built in it. `here()` is this
+checkout's; `checkout(ref, trees)` makes one of a commit under `trees` (its sources from git; its
+engine this checkout's when the commit's engine sources are this checkout's, else built), or
+takes another checkout's. A `Workload` is a scene file, rendered as a user renders it:
+`manimgx render`, in a fresh process with a tree first on its path. `run` measures one render,
+from launch to exit; `compare` runs a workload with two trees in turns, a round running both in
+a random order.
+
+Time is compared, never pinned: the two trees run on the same machine at the same time, so what
+the machine does to one it does to the other, and a round's ratio is what is kept.
+"""
+
+import ctypes
+import importlib.machinery
+import json
+import os
+import random
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import tomllib
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import IO
+
+from tests.benchmarks.work import Work
+
+ROOT = Path(__file__).resolve().parents[2]
+KEEP = 4
+"""How many commits' trees are kept (the least recently used go first)."""
+LAYOUTS = (
+ ("src", ("src", "fonts", "LICENSE-THIRD-PARTY", "LICENSE-LAVAPIPE")),
+ ("python/manimgx/src", ("python",)),
+)
+"""Where a commit keeps manimgx's package (`src/`), and what the package is built from
+beside its engine's sources and the project's files: the package at the repository's root, as
+now, or in python/, as before."""
+ENGINE = ("rust",)
+"""What the engine is built from: its crates, their manifest and lockfile."""
+
+
+@dataclass(frozen=True, slots=True)
+class Tree:
+ """A manimgx to time: `src` holds the package, its engine built; `label` names it."""
+
+ src: Path
+ label: str
+
+
+@dataclass(frozen=True, slots=True)
+class Workload:
+ """A scene file, rendered to a video by `manimgx render` with these options."""
+
+ scene: Path
+ options: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class Cost:
+ """What a render cost, from launch to exit: CPU seconds (every thread's), wall seconds,
+ peak memory (MB), and the instructions it retired, where the system counts them for a
+ process (macOS; elsewhere None)."""
+
+ cpu: float
+ wall: float
+ memory: float
+ instructions: int | None
+
+ @property
+ def measure(self) -> float:
+ """What a comparison judges: the instructions where they are counted, which do not
+ change with the cores that ran the process or with what else the machine does (its CPU
+ seconds, on a loaded Mac, move by tens of percent); else the CPU seconds."""
+ return self.cpu if self.instructions is None else self.instructions
+
+
+@dataclass(frozen=True, slots=True)
+class Row:
+ """A timed workload's line in the table a timed run ends with (`conftest.py`), in the
+ workloads' `order`; `unit` names what was judged."""
+
+ order: int
+ unit: str
+ cells: tuple[str, ...]
+
+
+class Incomparable(Exception):
+ """The tree compared with cannot render the workload: it uses what came after it."""
+
+
+def _git(*args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=ROOT, capture_output=True, text=True, check=True
+ ).stdout.strip()
+
+
+def _engine(src: Path) -> Path | None:
+ """The engine's binary in a tree's package, if built."""
+ for suffix in importlib.machinery.EXTENSION_SUFFIXES:
+ path = src / "manimgx" / f"_engine{suffix}"
+ if path.exists():
+ return path
+ return None
+
+
+def here() -> Tree:
+ """This checkout, as it is on disk."""
+ src = ROOT / LAYOUTS[0][0]
+ return Tree(src, f"this checkout ({_git('rev-parse', '--short', 'HEAD')})")
+
+
+def checkout(ref: str, trees: Path) -> Tree:
+ """The tree of `ref`: a directory holding a manimgx checkout, or a commit (a branch, tag
+ or hash), made once under `trees/<hash>/`."""
+ path = Path(ref)
+ for src, _ in LAYOUTS:
+ if (path / src / "manimgx").is_dir():
+ return _verified(Tree(path.resolve() / src, str(path)))
+ try:
+ sha = _git("rev-parse", "--verify", f"{ref}^{{commit}}")
+ except subprocess.CalledProcessError:
+ msg = f"{ref} is neither a commit of this repository nor a manimgx checkout"
+ raise ValueError(msg) from None
+ src, sources = _layout(sha)
+ home = trees / sha
+ tree = Tree(home / src, f"{ref} ({sha[:8]})")
+ if _engine(tree.src) is None:
+ shutil.rmtree(home, ignore_errors=True)
+ _extract(sha, home, sources)
+ _build(sha, home, sources)
+ if _engine(tree.src) is None:
+ msg = f"building {sha[:8]} made no engine"
+ raise RuntimeError(msg)
+ home.touch() # recently used
+ for old in sorted(trees.iterdir(), key=lambda p: p.stat().st_mtime)[:-KEEP]:
+ shutil.rmtree(old, ignore_errors=True)
+ return _verified(tree)
+
+
+def _layout(sha: str) -> tuple[str, tuple[str, ...]]:
+ """Commit `sha`'s layout, one of `LAYOUTS`."""
+ for layout in LAYOUTS:
+ found = subprocess.run(
+ ["git", "cat-file", "-e", f"{sha}:{layout[0]}/manimgx"],
+ cwd=ROOT,
+ stderr=subprocess.DEVNULL,
+ )
+ if found.returncode == 0:
+ return layout
+ msg = f"{sha[:8]} holds no manimgx package"
+ raise ValueError(msg)
+
+
+def _extract(sha: str, home: Path, sources: tuple[str, ...]) -> None:
+ """Write commit `sha`'s package, engine sources and project files into `home`."""
+ home.mkdir(parents=True)
+ paths = [*sources, *ENGINE, "pyproject.toml", "uv.lock", "README.md", "LICENSE"]
+ archive = subprocess.run(
+ ["git", "archive", "--format=tar", sha, *paths],
+ cwd=ROOT,
+ capture_output=True,
+ check=True,
+ ).stdout
+ with tempfile.TemporaryFile() as buffer:
+ buffer.write(archive)
+ buffer.seek(0)
+ with tarfile.open(fileobj=buffer) as tar:
+ tar.extractall(home, filter="data")
+
+
+def _build(sha: str, home: Path, sources: tuple[str, ...]) -> None:
+ """Give the tree in `home` its engine: this checkout's, if `sha` has the same engine
+ sources, or else one built from its own (reusing this checkout's compiled
+ dependencies)."""
+ ours = _engine(ROOT / LAYOUTS[0][0])
+ same = subprocess.run(["git", "diff", "--quiet", sha, "--", *ENGINE], cwd=ROOT)
+ if sources == LAYOUTS[0][1] and same.returncode == 0 and ours is not None:
+ shutil.copy2(ours, home / LAYOUTS[0][0] / "manimgx" / ours.name)
+ return
+ # a workspace's root is no project: its package is built as a member of it
+ project = tomllib.loads((home / "pyproject.toml").read_text(encoding="utf-8"))
+ package = [] if "project" in project else ["--package", "manimgx"]
+ env = dict(os.environ, CARGO_TARGET_DIR=str(ROOT / "rust" / "target"))
+ subprocess.run(
+ ["uv", "sync", "--frozen", "--no-default-groups", "--project", str(home)]
+ + package,
+ env=env,
+ check=True,
+ )
+
+
+def _environment(tree: Tree, tmp: str, *path: Path) -> dict[str, str]:
+ """A run's environment: `tree` first on the path; an empty temporary directory, so no run
+ finds another's Typst layouts; a fixed hash seed; and one thread for lavapipe (the software
+ GPU of Linux runners), so its time is one thread's work."""
+ return dict(
+ os.environ,
+ PYTHONPATH=os.pathsep.join(str(p) for p in (tree.src, *path)),
+ PYTHONHASHSEED="0",
+ TMPDIR=tmp,
+ TEMP=tmp,
+ TMP=tmp,
+ LP_NUM_THREADS="1",
+ )
+
+
+def _verified(tree: Tree) -> Tree:
+ """`tree`, once a process given its environment has been seen to import its manimgx."""
+ with tempfile.TemporaryDirectory(prefix="manimgx-benchmark-") as tmp:
+ where = subprocess.run(
+ [sys.executable, "-c", "import manimgx; print(manimgx.__file__)"],
+ env=_environment(tree, tmp, ROOT),
+ capture_output=True,
+ encoding="utf-8",
+ check=True,
+ ).stdout.strip()
+ if not Path(where).resolve().is_relative_to(tree.src.resolve()):
+ msg = f"{tree.label}'s runs would import {where}, not its manimgx"
+ raise RuntimeError(msg)
+ return tree
+
+
+def _launch(
+ tree: Tree, workload: Workload, tmp: str, stderr: int | IO[str], *module: str
+) -> subprocess.Popen[str]:
+ """Start `python -m manimgx render` on `workload` with `tree` (or, with `module`, that
+ module's command line on the same arguments), writing its video into `tmp`."""
+ video = str(Path(tmp) / "video.mp4")
+ return subprocess.Popen(
+ [sys.executable, "-m", *(module or ("manimgx",)), "render", str(workload.scene)]
+ + ["--output", video, *workload.options],
+ cwd=workload.scene.parent, # a scene reads its files next to it
+ env=_environment(tree, tmp, ROOT),
+ stdout=subprocess.DEVNULL,
+ stderr=stderr,
+ encoding="utf-8",
+ errors="replace",
+ )
+
+
+def _failed(tree: Tree, workload: Workload, stderr: str, status: int) -> RuntimeError:
+ last = (stderr.strip().splitlines() or [f"exit status {status}"])[-1]
+ return RuntimeError(f"{tree.label} fails {workload.scene.name}: {last}")
+
+
+def render(tree: Tree, workload: Workload, *options: str) -> None:
+ """Render `workload` once with `tree`, `options` after its own (the last one given of an
+ option counts); raise if it fails."""
+ with tempfile.TemporaryDirectory(prefix="manimgx-benchmark-") as tmp:
+ told = replace(workload, options=workload.options + options)
+ child = _launch(tree, told, tmp, subprocess.PIPE)
+ _, stderr = child.communicate()
+ if child.returncode:
+ raise _failed(tree, workload, stderr, child.returncode)
+
+
+def _instructions(pid: int) -> int | None:
+ """The instructions process `pid` retired, read once it has exited and before it is reaped
+ (macOS counts them for each process; elsewhere None)."""
+ os.waitid(os.P_PID, pid, os.WEXITED | os.WNOWAIT)
+ if sys.platform != "darwin":
+ return None
+ # proc_pid_rusage's rusage_info_v4 (sys/resource.h): a 16-byte uuid, then 35 counters,
+ # ri_instructions the 30th
+ usage = (ctypes.c_uint64 * 37)()
+ if ctypes.CDLL(None).proc_pid_rusage(pid, 4, usage):
+ return None
+ return usage[2 + 29]
+
+
+def run(tree: Tree, workload: Workload) -> Cost:
+ """Render `workload` with `tree` and measure the render, from launch to exit."""
+ if not hasattr(os, "wait4"):
+ msg = "the benchmarks are timed on Linux and macOS"
+ raise OSError(msg)
+ with (
+ tempfile.TemporaryDirectory(prefix="manimgx-benchmark-") as tmp,
+ open(
+ Path(tmp) / "stderr.txt", "w+", encoding="utf-8", errors="replace"
+ ) as stderr,
+ ):
+ start = time.perf_counter()
+ child = _launch(tree, workload, tmp, stderr)
+ instructions = _instructions(child.pid)
+ wall = time.perf_counter() - start
+ _, status, usage = os.wait4(child.pid, 0)
+ child.returncode = os.waitstatus_to_exitcode(status)
+ stderr.seek(0)
+ if child.returncode:
+ raise _failed(tree, workload, stderr.read(), child.returncode)
+ peak = usage.ru_maxrss / (2**20 if sys.platform == "darwin" else 2**10) # B, KiB
+ return Cost(usage.ru_utime + usage.ru_stime, wall, peak, instructions)
+
+
+def work(tree: Tree, workload: Workload) -> Work:
+ """The work `tree` does rendering `workload`, counted in one run (`tests.benchmarks.work`;
+ counting slows it down)."""
+ with tempfile.TemporaryDirectory(prefix="manimgx-benchmark-") as tmp:
+ out = Path(tmp) / "work.json"
+ child = _launch(
+ tree, workload, tmp, subprocess.PIPE, "tests.benchmarks.work", str(out)
+ )
+ _, stderr = child.communicate()
+ if child.returncode:
+ raise _failed(tree, workload, stderr, child.returncode)
+ return Work(**json.loads(out.read_text(encoding="utf-8")))
+
+
+def compare(
+ workload: Workload, base: Tree, head: Tree, count: int, warm: bool = True
+) -> list[tuple[Cost, Cost]]:
+ """(base, head) costs of each of `count` rounds. Both trees run in each round, in a random
+ order; with `warm`, after a round that is not kept (each tree's files read once, its
+ bytecode written). A base that cannot render the workload is `Incomparable`."""
+ order = random.Random(f"{workload.scene} {warm}")
+ samples: list[tuple[Cost, Cost]] = []
+ for kept in [False] * warm + [True] * count:
+ pair = [base, head]
+ order.shuffle(pair)
+ costs: dict[int, Cost] = {}
+ for tree in pair:
+ try:
+ costs[id(tree)] = run(tree, workload)
+ except RuntimeError as error:
+ if tree is base:
+ raise Incomparable(str(error)) from None
+ raise
+ if kept:
+ samples.append((costs[id(base)], costs[id(head)]))
+ return samples
diff --git a/tests/benchmarks/scenes/explainer.py b/tests/benchmarks/scenes/explainer.py
new file mode 100644
index 00000000..3bbbc90a
--- /dev/null
+++ b/tests/benchmarks/scenes/explainer.py
@@ -0,0 +1,33 @@
+"""A classic explainer: a curve drawn on axes, its area and its integral, then a tangent
+line sliding along it."""
+
+import numpy as np
+
+import manimgx as m
+
+
+class Explainer(m.Scene):
+ def construct(self) -> None:
+ axes = m.Axes(x_range=[0, 2 * np.pi, np.pi / 2], y_range=[-1.5, 1.5, 1])
+ sine = axes.plot(np.sin, color=m.BLUE, stroke_width=6)
+ dot = m.Dot(axes.i2gp(0, sine), radius=0.12, color=m.YELLOW)
+ area = axes.get_area(sine, x_range=(0, np.pi), color=m.BLUE, opacity=0.4)
+ label = m.MathTex(r"y = \sin x", font_size=72).to_corner(m.UR)
+ integral = m.MathTex(r"\int_0^\pi \sin x \, dx = 2", font_size=72).to_corner(
+ m.UR
+ )
+ self.play(m.Create(axes), m.Write(label))
+ self.play(m.Create(sine), m.MoveAlongPath(dot, sine), run_time=2.5)
+ self.play(m.FadeIn(area), m.TransformMatchingTex(label, integral))
+ along = m.ValueTracker(0)
+ tangent = m.always_redraw(
+ lambda: m.TangentLine(
+ sine, alpha=along.get_value(), length=3, color=m.YELLOW
+ )
+ )
+ dot.add_updater(
+ lambda d: d.move_to(sine.point_from_proportion(along.get_value()))
+ )
+ self.add(tangent, dot)
+ self.play(along.animate.set_value(1), run_time=4)
+ self.wait()
diff --git a/tests/benchmarks/scenes/morph.py b/tests/benchmarks/scenes/morph.py
new file mode 100644
index 00000000..b77b3930
--- /dev/null
+++ b/tests/benchmarks/scenes/morph.py
@@ -0,0 +1,33 @@
+"""A rippling surface, rebuilt every frame, with the camera circling it."""
+
+import numpy as np
+
+import manimgx as m
+
+
+class Morph(m.ThreeDScene):
+ def construct(self) -> None:
+ axes = m.ThreeDAxes(
+ x_range=[-3, 3, 1],
+ y_range=[-3, 3, 1],
+ z_range=[-2, 2, 1],
+ x_length=7,
+ y_length=7,
+ z_length=4,
+ )
+ phase = m.ValueTracker(0)
+ surface = m.always_redraw(
+ lambda: m.Surface(
+ lambda u, v: axes.c2p(
+ u, v, 0.8 * np.sin(2 * np.hypot(u, v) - phase.get_value())
+ ),
+ u_range=[-3, 3],
+ v_range=[-3, 3],
+ resolution=(48, 48),
+ checkerboard_colors=[m.BLUE_D, m.BLUE_E],
+ )
+ )
+ self.set_camera_orientation(phi=65 * m.DEGREES, theta=-45 * m.DEGREES)
+ self.add(axes, surface)
+ self.begin_ambient_camera_rotation(rate=0.3)
+ self.play(phase.animate.set_value(4 * np.pi), run_time=10, rate_func=m.linear)
diff --git a/tests/benchmarks/scenes/orbit.py b/tests/benchmarks/scenes/orbit.py
new file mode 100644
index 00000000..d1457cb9
--- /dev/null
+++ b/tests/benchmarks/scenes/orbit.py
@@ -0,0 +1,46 @@
+"""A surface plot on 3D axes, a curve drawn across it with a ball riding its tip, and the
+camera circling the whole time: every frame is new."""
+
+import numpy as np
+
+import manimgx as m
+
+
+class Orbit(m.ThreeDScene):
+ def construct(self) -> None:
+ axes = m.ThreeDAxes(
+ x_range=[-3, 3, 1],
+ y_range=[-3, 3, 1],
+ z_range=[-2, 2, 1],
+ x_length=7,
+ y_length=7,
+ z_length=4,
+ )
+ surface = m.Surface(
+ lambda u, v: axes.c2p(u, v, np.sin(u) * np.cos(v)),
+ u_range=[-3, 3],
+ v_range=[-3, 3],
+ resolution=(48, 48),
+ checkerboard_colors=[m.BLUE_D, m.BLUE_E],
+ )
+ curve = m.ParametricFunction(
+ lambda t: axes.c2p(
+ 2.4 * np.cos(t),
+ 2.4 * np.sin(t),
+ np.sin(2.4 * np.cos(t)) * np.cos(2.4 * np.sin(t)) + 0.08,
+ ),
+ t_range=[0, 2 * np.pi],
+ color=m.YELLOW,
+ stroke_width=6,
+ )
+ ball = m.Dot3D(curve.get_start(), radius=0.12, color=m.YELLOW)
+ self.set_camera_orientation(phi=65 * m.DEGREES, theta=-45 * m.DEGREES)
+ self.add(axes, surface, ball)
+ self.begin_ambient_camera_rotation(rate=0.3)
+ self.play(
+ m.Create(curve),
+ m.MoveAlongPath(ball, curve),
+ run_time=6,
+ rate_func=m.linear,
+ )
+ self.wait(4)
diff --git a/tests/benchmarks/test_laws.py b/tests/benchmarks/test_laws.py
new file mode 100644
index 00000000..4a58eb0b
--- /dev/null
+++ b/tests/benchmarks/test_laws.py
@@ -0,0 +1,647 @@
+"""What things cost grows as they do: no count of work grows faster than what is made.
+
+Each law compares two runs in one process: no number is pinned, and every machine checks it
+the same, since work (counted by `tests.benchmarks.work`) is the same everywhere. Each run
+starts from nothing remembered and is run once before it is counted, so it pays for its own
+work only: not for its first run's (imports, layouts, prototypes), nor for what another run
+left in manimgx's memories or flushed from them.
+
+- **Growth.** Made twice as big, a thing costs at most twice the work (a surface of twice the
+ resolution, four times): a path built curve by curve, a group of shapes played, a text
+ written, a paragraph or a line of code set, a graph redrawn every frame over wider axes, a
+ surface raised and turned, a path traced for longer, a film held for longer, a table laid
+ out (a row or a column of it too), a plane of more lines, a member removed from deeper in a
+ tree, a family listed or emptied however many paths reach its members, shapes matched to
+ shapes, an instant of a mobject with more updaters. Some cost Python nothing more as they
+ grow (their arrays do the growing): a regular polygon's vertices, curves refined into as many
+ or three times as many, a cloud's line, a line graph, rounded corners, a polygram, a sphere,
+ cone, cylinder or torus at a finer resolution; a function graph calls Python no more often
+ sampled more finely; and a point on a busier number line, or dashing equal curves again,
+ costs nothing more at all. A pole searched for three times as finely costs at most three
+ times the work (it refines the cells near the best, never the whole area: nine times). The
+ largest size always runs, where growth shows most; Hypothesis draws others and `target`
+ climbs toward the worst ratio.
+- **Sharing.** Copies of any mobject, moved, turned and scaled, upload what one does: a shape
+ is uploaded once, and its copies and moves are placements of it.
+- **Stillness.** A scene that holds any mobject still (one with no updater) costs as much for
+ half a minute as for a second: its held frames are one frame, shown longer.
+- **History.** A story told four times costs twice what two tellings do: nothing a scene keeps
+ makes its later frames dearer.
+- **Restating.** Assigning any mobject the points, colors and triangles it holds computes,
+ hashes and uploads nothing, once or every frame: all that was made of them stands.
+- **Remembering.** A construction manimgx remembers (an SVG, a text, a formula), made again,
+ computes nothing again.
+"""
+
+import math
+from collections.abc import Callable, Mapping
+from dataclasses import fields
+
+import numpy as np
+import pytest
+from hypothesis import assume, example, given, reject, settings, target
+from hypothesis import strategies as st
+from tests.benchmarks.work import Work, count
+from tests.scenes import SHAPES, Story, scene, stories
+from tests.strategies import MOBJECTS, angles
+
+import manimgx as m
+from manimgx import caches
+from manimgx.animation import clock
+from manimgx.config import config
+from manimgx.drawing.geometry import bezier_remap
+
+SLACK = 0.1
+"""A law's allowance over proportion, for what a thing's fixed costs and manimgx's memories
+leave uneven between two runs (a paint remembers the paints made from it, and `caches.clear`
+does not forget those)."""
+COUNTS = tuple(f.name for f in fields(Work))
+PYTHON = {"calls": 0, "loops": 0}
+"""The power of a law whose Python work does not grow at all: no loop runs once an element."""
+
+type Run = Callable[[], object]
+
+
+def render(construct: Callable[[m.Scene], None]) -> Run:
+ """A run that tells `construct` as a scene at 10 fps, its frames counted, not drawn."""
+
+ def run() -> None:
+ clock.reset()
+ config.frame_rate = 10
+ scene(construct).render()
+
+ return run
+
+
+def growth(small: Work, large: Work) -> dict[str, float]:
+ """Each count's growth: the larger run's over the smaller's (a count both leave at 0 did
+ not grow)."""
+ out = {}
+ for f in fields(Work):
+ a, b = getattr(small, f.name), getattr(large, f.name)
+ out[f.name] = b / a if a else (1.0 if b == 0 else math.inf)
+ return out
+
+
+def measured(make: Callable[[], Run]) -> Work:
+ """The work of the run `make` sets up (the setting up uncounted), from nothing
+ remembered (`caches.clear`) and once before it is counted: a run pays only for its own
+ work, never for what another left in, or flushed from, manimgx's memories."""
+ caches.clear()
+ make()() # what a first run pays once: imports, layouts, prototypes
+ return count(make())[1]
+
+
+def law(
+ build: Callable[[int], Run],
+ sizes: tuple[int, int],
+ power: int | Mapping[str, int] = 1,
+) -> Callable[..., None]:
+ """The growth law for the run `build(n)` sets up, at sizes in `sizes`: its work grows as
+ the size to `power`, every count's, or each count's named (`PYTHON`)."""
+ powers = power if isinstance(power, Mapping) else dict.fromkeys(COUNTS, power)
+ bounds = {k: 2**p * (1 + SLACK) for k, p in powers.items()}
+
+ def test(n: int) -> None:
+ small = measured(lambda: build(n))
+ large = measured(lambda: build(2 * n))
+ assert small.calls, "no work of manimgx's was counted: the law proves nothing"
+ grown = growth(small, large)
+ worst = max(bounds, key=lambda k: grown[k] / bounds[k])
+ target(min(grown[worst], 1e6) / bounds[worst], label="growth over the bound")
+ assert grown[worst] <= bounds[worst], (
+ f"at size {2 * n}, {grown[worst]:.2f}x the {worst} of size {n} (at most "
+ f"{bounds[worst]:.2f}x): {small} → {large}"
+ )
+
+ # a name of its own, before Hypothesis wraps it: its database and its derandomized
+ # draws are keyed by the function's name and source
+ test.__name__ = test.__qualname__ = f"test_{getattr(build, '__name__', 'law')}"
+ test.__doc__ = build.__doc__
+ return settings(max_examples=10)(
+ given(st.integers(*sizes))(example(sizes[1])(test))
+ )
+
+
+def path(n: int) -> Run:
+ """A path of `n` segments, built curve by curve, then drawn."""
+ corners = [[k / n, math.sin(7 * k / n), 0.0] for k in range(n + 1)]
+
+ def construct(scene: m.Scene) -> None:
+ built = m.VMobject().start_new_path(corners[0])
+ for corner in corners[1:]:
+ built.add_line_to(corner)
+ scene.play(m.Create(built))
+
+ return render(construct)
+
+
+def group(n: int) -> Run:
+ """`n` of each shape, faded in one after another, then moved, recolored and turned
+ together, in plays that last as long whatever `n` is."""
+
+ def construct(scene: m.Scene) -> None:
+ shapes = m.VGroup(*(SHAPES[s]() for s in sorted(SHAPES) * n)).arrange_in_grid()
+ scene.play(m.LaggedStart(*(m.FadeIn(s) for s in shapes), run_time=2))
+ scene.play(shapes.animate.shift(m.UP).set_color(m.RED))
+ scene.play(m.Transform(shapes, shapes.copy().rotate(1.0)))
+
+ return render(construct)
+
+
+def text(n: int) -> Run:
+ """A text of `n` words, written."""
+ words = " ".join(["manimgx"] * n)
+
+ def construct(scene: m.Scene) -> None:
+ scene.play(m.Write(m.Text(words, font_size=12).scale_to_fit_width(12)))
+
+ return render(construct)
+
+
+def plot(n: int) -> Run:
+ """Axes `n` units wide, and a graph over them redrawn every frame (up to 12 units, whose
+ graph's anchors stay under `bezier._SMOOTHING_UP_TO`: past it, smoothing solves in a loop
+ instead of applying a cached map, another algorithm)."""
+
+ def construct(scene: m.Scene) -> None:
+ axes = m.Axes(x_range=[0, n, 1], y_range=[-1, 1, 0.5])
+ k = m.ValueTracker(1.0)
+ graph = m.always_redraw(
+ lambda: axes.plot(lambda x: math.sin(k.get_value() * x))
+ )
+ scene.add(axes, graph)
+ scene.play(k.animate.set_value(2.0))
+
+ return render(construct)
+
+
+def surface(n: int) -> Run:
+ """A surface of resolution `n` by `n`, raised by an updater and turned."""
+
+ def construct(scene: m.Scene) -> None:
+ s = m.Surface(
+ lambda u, v: np.array([u, v, math.sin(u) * math.cos(v)]),
+ u_range=[-2, 2],
+ v_range=[-2, 2],
+ resolution=(n, n),
+ )
+ k = m.ValueTracker(0.0)
+ s.add_updater(lambda mob: mob.set_z(k.get_value()))
+ scene.add(s)
+ scene.play(k.animate.set_value(1.0), m.Rotate(s, 1.0))
+
+ return render(construct)
+
+
+def trace(n: int) -> Run:
+ """A dot going round for `n` seconds, its path traced."""
+
+ def construct(scene: m.Scene) -> None:
+ dot = m.Dot().shift(m.RIGHT)
+ scene.add(dot, m.TracedPath(dot.get_center))
+ scene.play(m.Rotate(dot, n * math.tau, about_point=m.ORIGIN, run_time=n))
+
+ return render(construct)
+
+
+def held(n: int) -> Run:
+ """A film `n` seconds long of a turning square and a digit counting tenths."""
+
+ def construct(scene: m.Scene) -> None:
+ square = m.Square()
+ square.add_updater(lambda mob, dt: mob.rotate(dt))
+ digit = m.Integer(0).add_updater(
+ lambda i: i.set_value(int(10 * clock.now) % 10)
+ )
+ scene.add(square, digit)
+ scene.wait(n)
+
+ return render(construct)
+
+
+def table(n: int) -> Run:
+ """A table of n by n entries, laid out with lines between its cells."""
+ return lambda: m.MobjectTable([[m.Square(0.2) for _ in range(n)] for _ in range(n)])
+
+
+def polygon(n: int) -> Run:
+ """The vertices of a regular polygon of `n` sides."""
+ return lambda: m.regular_vertices(n)
+
+
+def refine(n: int, factor: int = 1) -> Run:
+ """`n` equal curves refined into `factor` times as many."""
+ curves = np.tile(m.Line().points[None], (n, 1, 1))
+ return lambda: bezier_remap(curves, factor * n)
+
+
+def refine_threefold(n: int) -> Run:
+ """`n` equal curves refined into three times as many."""
+ return refine(n, 3)
+
+
+def dash(n: int) -> Run:
+ """A path of `n` equal lines dashed again: its curves were measured when it was first."""
+ path = m.VMobject().set_points(np.tile(m.Line().points, (n, 1)))
+ m.DashedVMobject(path)
+ return lambda: m.DashedVMobject(path)
+
+
+def removal(n: int) -> Run:
+ """A member removed from `n` levels down a tree in a scene."""
+ leaf = m.Mobject()
+ tree = leaf
+ for _ in range(n):
+ tree = m.Group(m.Mobject(), tree, m.Mobject())
+ world = m.Scene().add(tree)
+ return lambda: world.remove(leaf)
+
+
+def diamond(n: int) -> m.Mobject:
+ """`n` levels of a diamond: each level's two groups hold the one below, so the paths to
+ its bottom double a level, its members only add three."""
+ root = m.Mobject()
+ for _ in range(n):
+ left, right, parent = (m.Group() for _ in range(3))
+ left.submobjects = [root]
+ right.submobjects = [root]
+ parent.submobjects = [left, right]
+ root = parent
+ return root
+
+
+def family(n: int) -> Run:
+ """The family of a diamond `n` levels deep, listed."""
+ root = diamond(n)
+
+ def run() -> None:
+ assert len(root.get_family()) == 3 * n + 1
+
+ return run
+
+
+def emptying(n: int) -> Run:
+ """A scene of a diamond `n` levels deep, emptied by removing its bottom."""
+ root = diamond(n)
+ leaf = root.get_family()[-1]
+ world = m.Scene()
+ world.mobjects = [root]
+
+ def run() -> None:
+ world.remove(leaf)
+ assert world.mobjects == []
+
+ return run
+
+
+def matching(n: int) -> Run:
+ """`n` squares and `n` circles matched by shape onto the same, moved."""
+
+ def construct(scene: m.Scene) -> None:
+ shapes = m.VGroup(
+ *(m.Square() for _ in range(n)), *(m.Circle() for _ in range(n))
+ ).arrange()
+ scene.play(m.TransformMatchingShapes(shapes, shapes.copy().shift(m.UP)))
+
+ return render(construct)
+
+
+def updating(n: int) -> Run:
+ """A dot with `n` updaters, waiting a second: each instant walks its list once."""
+
+ def construct(scene: m.Scene) -> None:
+ dot = m.Dot()
+ for _ in range(n):
+ dot.add_updater(lambda mob, dt: None)
+ scene.add(dot)
+ scene.wait(1)
+
+ return render(construct)
+
+
+U = [[0, 0, 0], [2, 0, 0], [2, 2, 0], [1.5, 2, 0], [1.5, 0.5, 0],
+ [0.5, 0.5, 0], [0.5, 2, 0], [0, 2, 0], [0, 0, 0]] # fmt: skip
+
+
+def rectangle_pole(n: int) -> Run:
+ """A 32-by-2 rectangle's pole, to a precision of 1/n: its first cells hold it."""
+ rectangle = [[0, 0, 0], [32, 0, 0], [32, 2, 0], [0, 2, 0], [0, 0, 0]]
+ return lambda: m.polylabel([rectangle], precision=1 / n)
+
+
+def line_cloud(n: int) -> Run:
+ """A point cloud's line, `n` points to the unit: its points an array's, its Python
+ work the same however many."""
+ cloud = m.Mobject1D(density=n)
+ return lambda: cloud.add_line(m.ORIGIN, m.RIGHT)
+
+
+def ring_cloud(n: int) -> Run:
+ """A cloud dot of density `n`: n rings, n² points; its Python work grows with the rings."""
+ return lambda: m.PointCloudDot(radius=1, density=n)
+
+
+def code(n: int) -> Run:
+ """Code of one line `n` characters wide."""
+ return lambda: m.Code(code_string="H" * n, add_line_numbers=False)
+
+
+def row_table(n: int) -> Run:
+ """A table of one row of `n` dots, its lines inside and out."""
+ return lambda: m.MobjectTable(
+ [[m.Dot() for _ in range(n)]], include_outer_lines=True
+ )
+
+
+def column_table(n: int) -> Run:
+ """A table of one column of `n` dots, its lines inside and out."""
+ return lambda: m.MobjectTable(
+ [[m.Dot()] for _ in range(n)], include_outer_lines=True
+ )
+
+
+def annotated(n: int) -> Run:
+ """A number line's point for a number, the line carrying `n` members of no concern to
+ it."""
+ line = m.NumberLine(include_ticks=False, include_tip=True)
+ line.add(*(m.Mobject() for _ in range(n)))
+ return lambda: line.n2p(0.37)
+
+
+def graphed(n: int) -> Run:
+ """The graph of a function that takes arrays, sampled at `n` points: the function
+ (manimgx's, so its calls count) called on them at once (the smoothing of the samples
+ loops over them)."""
+ return lambda: m.FunctionGraph(
+ lambda t: m.interpolate(0.0, 2.0, t), x_range=(0, 1, 1 / n)
+ )
+
+
+def plotted(n: int) -> Run:
+ """A line graph of `n` vertices, on axes."""
+ axes = m.Axes()
+ xs = np.linspace(-1, 1, n)
+ return lambda: axes.plot_line_graph(xs, xs, add_vertex_dots=False)
+
+
+def plotted_in_space(n: int) -> Run:
+ """A line graph of `n` vertices, on spatial axes."""
+ axes = m.ThreeDAxes()
+ xs = np.linspace(-1, 1, n)
+ return lambda: axes.plot_line_graph(xs, xs, add_vertex_dots=False)
+
+
+def plane(n: int) -> Run:
+ """A number plane `2n` units wide."""
+ return lambda: m.NumberPlane(x_range=(-n, n), y_range=(-1, 1))
+
+
+def polar(n: int) -> Run:
+ """A polar plane of `n` circles."""
+ return lambda: m.PolarPlane(radius_max=n, azimuth_step=4)
+
+
+def rounded(n: int) -> Run:
+ """A square's corners rounded, each arc drawn through `n` anchors."""
+ return lambda: m.Square(2).round_corners(0.25, components_per_rounded_corner=n)
+
+
+def polygram(n: int) -> Run:
+ """A polygram of `n` vertices given as an array."""
+ vertices = np.arange(n * 3, dtype=float).reshape(n, 3)
+ return lambda: m.Polygram(vertices)
+
+
+def sphere(n: int) -> Run:
+ """A sphere at resolution `n`: its grid sampled at once."""
+ return lambda: m.Sphere(resolution=n)
+
+
+def cone(n: int) -> Run:
+ """A cone at resolution `n`: its grid sampled at once."""
+ return lambda: m.Cone(resolution=n)
+
+
+def cylinder(n: int) -> Run:
+ """A cylinder at resolution `n`: its grid sampled at once."""
+ return lambda: m.Cylinder(resolution=n)
+
+
+def torus(n: int) -> Run:
+ """A torus at resolution `n`: its grid sampled at once."""
+ return lambda: m.Torus(resolution=n)
+
+
+def paragraph(n: int) -> Run:
+ """A paragraph of two lines `n` characters long."""
+ return lambda: m.Paragraph("H" * n, "H" * n)
+
+
+test_a_path_grows_as_its_curves = law(path, (2, 200))
+test_a_group_grows_as_its_members = law(group, (2, 16))
+test_a_text_grows_as_its_words = law(text, (2, 24))
+test_a_redrawn_graph_grows_as_its_axes = law(plot, (2, 12))
+test_a_surface_grows_as_its_resolution_squared = law(surface, (4, 16), power=2)
+test_a_traced_path_grows_as_its_time = law(trace, (1, 4))
+test_a_film_grows_as_its_time = law(held, (1, 6))
+test_a_table_grows_as_its_cells = law(table, (2, 12), power=2)
+test_a_polygons_vertices_cost_python_nothing_more = law(polygon, (8, 256), PYTHON)
+test_refining_curves_costs_python_nothing_more = law(refine, (8, 256), PYTHON)
+test_refining_threefold_costs_python_nothing_more = law(
+ refine_threefold, (8, 256), PYTHON
+)
+test_dashing_equal_curves_again_costs_nothing_more = law(dash, (8, 64), power=0)
+test_a_removal_grows_as_its_depth = law(removal, (4, 100))
+test_a_family_grows_as_its_members = law(family, (4, 8))
+test_emptying_a_family_grows_as_its_members = law(emptying, (4, 8))
+test_a_matching_grows_as_its_parts = law(matching, (2, 32))
+test_an_instant_grows_as_its_updaters = law(updating, (2, 64))
+test_a_rectangles_pole_costs_nothing_more_finer = law(
+ rectangle_pole, (20, 100), power=0
+)
+test_a_line_cloud_costs_python_nothing_more = law(line_cloud, (32, 1024), PYTHON)
+test_a_cloud_dots_python_grows_as_its_rings = law(
+ ring_cloud, (8, 64), {"calls": 1, "loops": 1}
+)
+test_code_grows_as_its_width = law(code, (4, 64))
+test_a_row_table_grows_as_its_cells = law(row_table, (8, 64))
+test_a_column_table_grows_as_its_cells = law(column_table, (8, 64))
+test_a_lines_point_costs_nothing_more_on_a_busier_line = law(annotated, (16, 256), 0)
+test_a_function_graph_calls_python_no_more_finely = law(
+ graphed, (64, 1024), {"calls": 0}
+)
+test_a_line_graph_costs_python_nothing_more = law(plotted, (64, 512), PYTHON)
+test_a_spatial_line_graph_costs_python_nothing_more = law(
+ plotted_in_space, (64, 512), PYTHON
+)
+test_a_plane_grows_as_its_lines = law(plane, (8, 64))
+test_a_polar_plane_grows_as_its_circles = law(polar, (8, 64))
+test_rounding_costs_python_nothing_more = law(rounded, (2, 64), PYTHON)
+test_a_polygram_costs_python_nothing_more = law(polygram, (8, 256), PYTHON)
+test_a_sphere_costs_python_nothing_more = law(sphere, (8, 32), PYTHON)
+test_a_cone_costs_python_nothing_more = law(cone, (8, 32), PYTHON)
+test_a_cylinder_costs_python_nothing_more = law(cylinder, (8, 32), PYTHON)
+test_a_torus_costs_python_nothing_more = law(torus, (8, 32), PYTHON)
+test_a_paragraph_grows_as_its_glyphs = law(paragraph, (8, 256))
+
+
+def test_geometry_counts_distinguish_materialization_from_cached_reads() -> None:
+ points = np.arange(21.0).reshape(7, 3)
+
+ def read() -> None:
+ mob = m.Mobject()
+ mob.points = points
+ np.testing.assert_array_equal(mob.points, points)
+ np.testing.assert_array_equal(mob.points, points)
+ assert mob._geometry.terms[0][1].key
+
+ _, work = count(read)
+ assert work.points == len(points)
+ assert work.hashed == points.nbytes + len(str(points.shape).encode())
+
+
+def test_a_finer_pole_search_does_not_scan_the_area() -> None:
+ # its cost steps up a level at a time, so it is one pair of precisions, not a growth law
+ coarse = measured(lambda: lambda: m.polylabel([U], precision=0.03))
+ fine = measured(lambda: lambda: m.polylabel([U], precision=0.01))
+ grown = growth(coarse, fine)
+ assert max(grown.values()) <= 3 * (1 + SLACK), grown
+
+
+@settings(max_examples=25)
+@given(
+ name=st.sampled_from(sorted(MOBJECTS)),
+ copies=st.integers(2, 4),
+ turn=angles(),
+ scale=st.floats(0.25, 4),
+ shift=st.tuples(st.floats(-3, 3), st.floats(-3, 3)),
+)
+def test_copies_upload_what_one_does(
+ name: str, copies: int, turn: float, scale: float, shift: tuple[float, float]
+) -> None:
+ def show(k: int) -> Run:
+ def construct(scene: m.Scene) -> None:
+ group = m.Group(*(MOBJECTS[name]() for _ in range(k))).arrange(m.RIGHT)
+ scene.add(group)
+ scene.play(group.animate.shift([*shift, 0]).rotate(turn).scale(scale))
+ scene.play(*(m.Rotate(part, turn) for part in group))
+
+ return render(construct)
+
+ one, many = measured(lambda: show(1)), measured(lambda: show(copies))
+ assert many.uploaded == one.uploaded
+
+
+@settings(max_examples=25)
+@given(name=st.sampled_from(sorted(MOBJECTS)), seconds=st.integers(2, 30))
+def test_holding_still_costs_the_same_however_long(name: str, seconds: int) -> None:
+ # a mobject with an updater does not hold still: its updater runs every frame
+ assume(not any(member.updaters for member in MOBJECTS[name]().get_family()))
+
+ def hold(duration: float) -> Run:
+ def construct(scene: m.Scene) -> None:
+ scene.add(MOBJECTS[name]())
+ scene.wait(duration)
+
+ return render(construct)
+
+ short, long = measured(lambda: hold(1)), measured(lambda: hold(seconds))
+ grown = growth(short, long)
+ worst = max(grown, key=lambda k: grown[k])
+ assert grown[worst] <= 1 + SLACK, (
+ f"held {seconds} s, {grown[worst]:.2f}x the {worst} of 1 s: {short} → {long}"
+ )
+
+
+def restate(mob: m.Mobject) -> None:
+ """Assign each member what it holds: equal arrays, new objects."""
+ for member in mob.family_members_with_points():
+ member.points = member.points.copy()
+ member.fill_rgbas = member.fill_rgbas.copy()
+ if isinstance(member, m.MeshMobject):
+ member.triangles = member.triangles.copy()
+ if member.uvs is not None:
+ member.uvs = member.uvs.copy()
+
+
[email protected]("name", sorted(MOBJECTS))
+def test_restating_what_a_mobject_holds_costs_nothing(name: str) -> None:
+ """Assigning any mobject the points, colors and triangles it holds (equal arrays, new
+ objects) computes, hashes and uploads nothing: all that was made of them stands."""
+ mob = MOBJECTS[name]().rotate(0.3) # (moved: its points are a placement of a shape)
+ read = [member.points for member in mob.family_members_with_points()]
+ assert all(points is not None for points in read) # (read, as a frame reads them)
+ _, work = count(lambda: restate(mob))
+ assert (work.points, work.hashed, work.uploaded) == (0, 0, 0), work
+
+
[email protected]("name", ["Square", "Text", "Sphere", "Surface", "Polygram"])
+def test_restating_each_frame_costs_nothing_more(name: str) -> None:
+ """A scene whose updater assigns each member what it holds, every frame, computes,
+ hashes and uploads no more over 4 s than over 1 s (its Python work grows: the updater
+ runs)."""
+
+ def hold(seconds: int) -> Run:
+ def construct(scene: m.Scene) -> None:
+ mob = MOBJECTS[name]().rotate(0.3)
+ mob.add_updater(restate)
+ scene.add(mob)
+ scene.wait(seconds)
+
+ return render(construct)
+
+ grown = growth(measured(lambda: hold(1)), measured(lambda: hold(4)))
+ assert max(grown["points"], grown["hashed"], grown["uploaded"]) <= 1.1, grown
+
+
+REMEMBERED = {
+ "an SVG": MOBJECTS["SVGMobject"],
+ "a text": lambda: m.Text("one", font="Noto Sans"),
+ "another text in its font": lambda: m.Text("two", font="Noto Sans"),
+ "a formula": lambda: m.MathTex("H"),
+ "a Tex": lambda: m.Tex("H"),
+ "a list": lambda: m.BulletedList("H"),
+ "a title": lambda: m.Title("H"),
+}
+
+
[email protected]("name", sorted(REMEMBERED))
+def test_a_remembered_construction_computes_nothing_again(name: str) -> None:
+ """Made again, a construction it remembers is copied: no point computed, nothing hashed
+ or uploaded (the file is read and typeset once)."""
+ make = REMEMBERED[name]
+ caches.clear()
+ m.Text("zero", font="Noto Sans") # (its font's capital measured)
+ make()
+ _, work = count(make)
+ assert (work.points, work.hashed, work.uploaded) == (0, 0, 0), work
+
+
+def told(story: Story, times: int) -> Run:
+ """`story` told `times` times over, each telling on a fresh stage from a whole second (so
+ every telling's frames fall at the same instants of it)."""
+
+ def construct(scene: m.Scene) -> None:
+ for _ in range(times):
+ story.tell(scene)
+ scene.clear()
+ scene.wait(math.ceil(float(scene.clock) + 1e-9) - float(scene.clock))
+
+ return render(construct)
+
+
+@settings(max_examples=30)
+@given(stories())
+def test_a_story_costs_the_same_each_time_it_is_told(story: Story) -> None:
+ try:
+ told(story, 1)()
+ except ValueError: # a story may ask the impossible (see tests.scenes.outcome)
+ reject()
+ two, four = measured(lambda: told(story, 2)), measured(lambda: told(story, 4))
+ grown = growth(two, four)
+ worst = max(grown, key=lambda k: grown[k])
+ target(min(grown[worst], 1e6), label="four tellings over two")
+ assert grown[worst] <= 2 * (1 + SLACK), (
+ f"four tellings did {grown[worst]:.2f}x the {worst} of two: {two} → {four}"
+ )
diff --git a/tests/benchmarks/test_speed.py b/tests/benchmarks/test_speed.py
new file mode 100644
index 00000000..7428be27
--- /dev/null
+++ b/tests/benchmarks/test_speed.py
@@ -0,0 +1,178 @@
+"""manimgx is not slower than the manimgx it is compared with, on any workload.
+
+A workload is a scene rendered as a user renders it, `manimgx render`, in a process of its own
+from launch to exit: the README's three scenes as the README times them, and six example films,
+small. In the suite, each is rendered once, tiny: it still renders.
+
+`just bench REF` renders each workload with this checkout and with REF's manimgx, in turns, round
+after round on one machine, and compares what the runs cost: the instructions they retired where
+the system counts them (macOS), which stay put however busy the machine is, else their CPU
+seconds. A round's two runs make a ratio. A workload has become slower when the median ratio is
+more than 5% above 1 and the rounds agree: its 95% confidence bound (exact, and free of any
+assumption about the noise) is above 1, which five rounds give only if every one is slower. A
+workload that looks slower is timed as many rounds again, and judged on them all. Wall time and
+peak memory are shown beside it, and the work each tree did (`tests.benchmarks.work`), counted
+exactly, says what changed.
+"""
+
+import math
+from dataclasses import dataclass, fields
+from pathlib import Path
+from statistics import median
+
+import pytest
+from tests.benchmarks.harness import (
+ ROOT,
+ Cost,
+ Incomparable,
+ Row,
+ Tree,
+ Workload,
+ compare,
+ here,
+ render,
+ work,
+)
+from tests.benchmarks.work import Work
+
+pytestmark = pytest.mark.timed
+
+SCENES = Path(__file__).resolve().parent / "scenes"
+EXAMPLES = ROOT / "examples"
+SMALL = ("--resolution", "480x270", "--fps", "10")
+TINY = ("--resolution", "64x36", "--fps", "5")
+"""How the suite renders a workload once, to see that it still renders."""
+
+WORKLOADS: dict[str, Workload] = {
+ # the README's scenes, as it times them: 1920 x 1080 at 60 fps, to MP4
+ "orbit": Workload(SCENES / "orbit.py"),
+ "morph": Workload(SCENES / "morph.py"),
+ "explainer": Workload(SCENES / "explainer.py"),
+ # example films, small: their code and the feed, most of what a film costs
+ **{
+ name: Workload(EXAMPLES / f"{name}.py", SMALL)
+ for name in (
+ "clifford_torus", # surfaces: meshes, their normals, uploads
+ "heavy_top", # a simulation carrying meshes
+ "kuramoto_fireflies", # see-through points, sorted and blended
+ "lagrange_points", # a big surface raised by its points every frame
+ "neural_untangle", # paths traced curve by curve, thousands of small shapes
+ "taylor_poles", # axes, graphs and text
+ )
+ },
+}
+
+TOLERANCE = 0.05
+"""How much slower a workload may become before it counts as slower: above what noise moves a
+median (identical trees: instructions within 1.3% on a busy Mac, CPU time within 2.3% on a
+quiet one), below the smallest regression manimgx has had (6%)."""
+
+
+def bounds(ratios: tuple[float, ...]) -> tuple[float, float]:
+ """The 95% confidence bounds of the ratios' median, below and above: the k-th smallest
+ and largest ratio, for the largest k with P(Binomial(n, 1/2) < k) ≤ 5% (a sign test:
+ exact for any noise); none (0 and ∞) for fewer than five rounds."""
+ n, k = len(ratios), 0
+ while sum(math.comb(n, i) for i in range(k + 1)) <= 0.05 * 2**n:
+ k += 1
+ ordered = sorted(ratios)
+ return (ordered[k - 1], ordered[n - k]) if k else (0.0, math.inf)
+
+
+@dataclass(frozen=True, slots=True)
+class Change:
+ """The head's cost against the base's: each round's ratio of what is judged, and the
+ medians of what each tree cost."""
+
+ ratios: tuple[float, ...]
+ base: Cost
+ head: Cost
+
+ @staticmethod
+ def of(samples: list[tuple[Cost, Cost]]) -> "Change":
+ def middle(costs: list[Cost]) -> Cost:
+ counted = [c.instructions for c in costs if c.instructions is not None]
+ return Cost(
+ median(c.cpu for c in costs),
+ median(c.wall for c in costs),
+ median(c.memory for c in costs),
+ round(median(counted)) if counted else None,
+ )
+
+ return Change(
+ tuple(h.measure / b.measure for b, h in samples),
+ middle([b for b, _ in samples]),
+ middle([h for _, h in samples]),
+ )
+
+ @property
+ def ratio(self) -> float:
+ return median(self.ratios)
+
+ @property
+ def slower(self) -> bool:
+ return self.ratio > 1 + TOLERANCE and bounds(self.ratios)[0] > 1
+
+
+def work_change(base: Work, head: Work) -> str:
+ """The counts that differ, the most changed first: "points ×7330, calls +18%"."""
+ changes = []
+ for f in fields(Work):
+ was, now = getattr(base, f.name), getattr(head, f.name)
+ if was == now:
+ continue
+ factor = now / was if was else math.inf
+ if 0.5 < factor < 2:
+ shown = f"{factor - 1:+.2%}"
+ else:
+ shown = f"×{factor:.0f}" if factor >= 100 else f"×{factor:.3g}"
+ change = abs(math.log(factor)) if 0 < factor < math.inf else math.inf
+ changes.append((change, f"{f.name} {shown}"))
+ return ", ".join(text for _, text in sorted(changes, reverse=True))
+
+
[email protected]("name", list(WORKLOADS))
+def test_speed(
+ name: str,
+ trees: tuple[Tree, Tree] | None,
+ rounds: int,
+ request: pytest.FixtureRequest,
+) -> None:
+ workload = WORKLOADS[name]
+ if trees is None: # the suite, not a benchmark: the workload still renders
+ render(here(), workload, *TINY)
+ return
+ base, head = trees
+ try:
+ samples = compare(workload, base, head, rounds)
+ change = Change.of(samples)
+ if change.slower: # confirmed, or not, by as many rounds again
+ change = Change.of(samples + compare(workload, base, head, rounds, False))
+ worked = work_change(work(base, workload), work(head, workload))
+ except Incomparable as reason:
+ pytest.skip(str(reason))
+ counted = change.base.instructions is not None
+ low, high = min(change.ratios) - 1, max(change.ratios) - 1
+
+ def shown(cost: Cost) -> str:
+ return f"{cost.measure / 1e9:.2f}G" if counted else f"{cost.measure:.3f}"
+
+ cells = (
+ name,
+ shown(change.base),
+ shown(change.head),
+ f"{change.ratio - 1:+.1%}",
+ f"{low:+.1%} … {high:+.1%}",
+ f"{change.head.wall / change.base.wall - 1:+.1%}",
+ f"{change.head.memory / change.base.memory - 1:+.1%}",
+ worked,
+ )
+ unit = "instructions" if counted else "CPU seconds"
+ request.node.user_properties.append(
+ ("timed", Row(list(WORKLOADS).index(name), unit, cells))
+ )
+ assert not change.slower, (
+ f"{name} takes {change.ratio - 1:+.1%} {unit} against {base.label} (the rounds"
+ f" {low:+.1%} to {high:+.1%} of {len(change.ratios)})"
+ + (f"; its work: {worked}" if worked else "")
+ )
diff --git a/tests/benchmarks/work.py b/tests/benchmarks/work.py
new file mode 100644
index 00000000..28609737
--- /dev/null
+++ b/tests/benchmarks/work.py
@@ -0,0 +1,230 @@
+"""What a run asks of manimgx, counted: work, which is the same on every machine, where time is
+not.
+
+`count(fn)` runs `fn` and counts, in manimgx's own code:
+
+- `calls`, the Python functions run, and `loops`, the loops' iterations (a jump back), with
+ `sys.monitoring`: the interpreter's work;
+- `points`, the points computed from a geometry's pieces (`Blend.points`): the numpy work a
+ path or mesh costs to read;
+- `hashed`, the bytes hashed (`digest`) to name shapes and uploads;
+- `uploaded`, the bytes handed to the engine to keep: shapes, meshes, rows, textures.
+
+Counts are exact and the same on every system; `loops` also depends on the bytecode, so on
+the Python version. Counting slows a run down by about half.
+
+ python -m tests.benchmarks.work OUT.json ARGS…
+
+runs the command line `manimgx ARGS…` in this process, counting, and writes its work to OUT.json
+(what the timed benchmarks show beside a change).
+"""
+
+import importlib
+import json
+import runpy
+import sys
+from collections.abc import Callable, Iterator
+from contextlib import ExitStack, contextmanager
+from dataclasses import asdict, dataclass, fields
+from pathlib import Path
+from types import CodeType
+from typing import TYPE_CHECKING
+
+import manimgx
+
+# The compiler remains beside Film in either compared package layout.
+feed = importlib.import_module(manimgx.Film.__module__.removesuffix(".film") + ".feed")
+if TYPE_CHECKING:
+ from manimgx.drawing.geometry import Blend
+else:
+ Blend = feed.Blend
+
+_PACKAGE = Path(manimgx.__file__).parent
+_ROOTS = (str(_PACKAGE), str(_PACKAGE.resolve()))
+"""Where manimgx's code is, as its code objects name it: the path it was imported from, and
+that path resolved (they differ under a link, /tmp's on macOS)."""
+_UPLOADS = (
+ "add_path",
+ "grow_path",
+ "add_points",
+ "add_mesh",
+ "add_rows",
+ "add_texture",
+)
+
+
+@dataclass(frozen=True, slots=True)
+class Work:
+ """Counts of what a run did (see the module's docstring)."""
+
+ calls: int = 0
+ loops: int = 0
+ points: int = 0
+ hashed: int = 0
+ uploaded: int = 0
+
+ def __add__(self, other: "Work") -> "Work":
+ return Work(
+ *(getattr(self, f.name) + getattr(other, f.name) for f in fields(self))
+ )
+
+ def as_dict(self) -> dict[str, int]:
+ return asdict(self)
+
+
+class _Tally:
+ def __init__(self) -> None:
+ self.calls = self.loops = self.points = self.hashed = self.uploaded = 0
+
+ def work(self) -> Work:
+ return Work(self.calls, self.loops, self.points, self.hashed, self.uploaded)
+
+
+def count[T](fn: Callable[[], T], strict: bool = True) -> tuple[T, Work]:
+ """Run `fn`; its result and the work it did. With `strict`, a function counted that
+ this manimgx lacks (renamed, say) is an error; else it counts nothing (an older manimgx,
+ compared with this one)."""
+ with counting(strict) as tally:
+ result = fn()
+ return result, tally.work()
+
+
+@contextmanager
+def counting(strict: bool = True) -> Iterator[_Tally]:
+ """Count the work done inside the block (read `.work()` after it)."""
+ tally = _Tally()
+ with ExitStack() as stack:
+ _count_python(tally, stack)
+ _count_geometry(tally, stack, strict)
+ _count_uploads(tally, stack, strict)
+ yield tally
+
+
+def _count_python(tally: _Tally, stack: ExitStack) -> None:
+ monitoring = sys.monitoring
+ events = monitoring.events
+ tool = next(
+ t for t in (2, 3, 4) if monitoring.get_tool(t) is None
+ ) # a profiler's id
+ monitoring.use_tool_id(tool, "manimgx benchmarks")
+ disable = monitoring.DISABLE
+
+ def started(code: CodeType, _offset: int) -> object:
+ if not code.co_filename.startswith(_ROOTS):
+ return disable # never asked again for this code
+ tally.calls += 1
+ return None
+
+ def jumped(code: CodeType, source: int, destination: int) -> object:
+ if not code.co_filename.startswith(_ROOTS):
+ return disable
+ if destination <= source: # back to a loop's head
+ tally.loops += 1
+ return None
+
+ monitoring.register_callback(tool, events.PY_START, started)
+ monitoring.register_callback(tool, events.JUMP, jumped)
+ monitoring.set_events(tool, events.PY_START | events.JUMP)
+
+ def stop() -> None:
+ monitoring.set_events(tool, 0)
+ monitoring.register_callback(tool, events.PY_START, None)
+ monitoring.register_callback(tool, events.JUMP, None)
+ monitoring.free_tool_id(tool)
+ monitoring.restart_events() # what was disabled for this tool runs again
+
+ stack.callback(stop)
+
+
+def _counted(owner: object, name: str, strict: bool) -> object | None:
+ found = getattr(owner, name, None)
+ if found is None and strict:
+ msg = f"{owner!r} has no {name} to count: tests/benchmarks/work.py must follow"
+ raise AttributeError(msg)
+ return found
+
+
+def _count_geometry(tally: _Tally, stack: ExitStack, strict: bool) -> None:
+ points = _counted(Blend, "points", strict)
+ if callable(points):
+
+ def counted_points(self: Blend) -> object:
+ if getattr(self, "_points", None) is None: # computed now
+ tally.points += self.n
+ return points(self)
+
+ stack.enter_context(_patched(Blend, "points", counted_points))
+ geometry = sys.modules[
+ Blend.__module__
+ ] # the compared tree's owner, wherever it lives
+ for owner in (geometry, feed): # what names shapes, and what names uploads
+ digest = _counted(owner, "digest", strict)
+ if callable(digest):
+ stack.enter_context(_patched(owner, "digest", _hashing(tally, digest)))
+
+
+def _hashing(tally: _Tally, digest: Callable[..., object]) -> Callable[..., object]:
+ def counted_digest(*parts: bytes) -> object:
+ tally.hashed += sum(len(p) for p in parts)
+ return digest(*parts)
+
+ return counted_digest
+
+
+def _count_uploads(tally: _Tally, stack: ExitStack, strict: bool) -> None:
+ player = _counted(feed, "Player", strict)
+ if not callable(player):
+ return
+
+ class Counted:
+ """Stands for the engine's Player, counting the bytes each upload hands it."""
+
+ def __init__(self, *args: object, **kwargs: object) -> None:
+ self._player = player(*args, **kwargs)
+
+ def __getattr__(self, name: str) -> object:
+ attribute = getattr(self._player, name)
+ if name not in _UPLOADS or not callable(attribute):
+ return attribute
+
+ def upload(*args: object, **kwargs: object) -> object:
+ given = (*args, *kwargs.values())
+ tally.uploaded += sum(_size(a) for a in given)
+ return attribute(*args, **kwargs)
+
+ return upload
+
+ stack.enter_context(_patched(feed, "Player", Counted))
+
+
+def _size(value: object) -> int:
+ if isinstance(value, bytes | bytearray | memoryview):
+ return len(value)
+ nbytes = getattr(value, "nbytes", None)
+ return nbytes if isinstance(nbytes, int) else 0
+
+
+@contextmanager
+def _patched(owner: object, name: str, value: object) -> Iterator[None]:
+ saved = getattr(owner, name)
+ setattr(owner, name, value)
+ try:
+ yield
+ finally:
+ setattr(owner, name, saved)
+
+
+def main() -> None:
+ out, *args = sys.argv[1:]
+ sys.argv = ["manimgx", *args]
+ with counting(strict=False) as tally: # the manimgx compared with may lack a count
+ try:
+ runpy.run_module("manimgx", run_name="__main__", alter_sys=True)
+ except SystemExit as done:
+ if done.code:
+ raise
+ Path(out).write_text(json.dumps(tally.work().as_dict()), encoding="utf-8")
+
+
+if __name__ == "__main__":
+ main()