The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add shared test fixtures and oracles
apoogdk78978ddb7723
diff --git a/tests/conftest.py b/tests/conftest.pynew file mode 100644index 00000000..7898d7a3--- /dev/null+++ b/tests/conftest.py@@ -0,0 +1,150 @@+"""What every test starts from: the scene clock at 0, the configuration as it ships (but for+what its `config` marks change: `pytestmark = pytest.mark.config(pixel_width=320,+pixel_height=180)` for a module, or one test's own mark over it), nothing remembered for a test+marked `cold` (`manimgx.caches.clear` before and after it), and the Hypothesis profiles;+and the timed benchmarks' options (`--bench REF`, `--bench-rounds`): the tests marked `timed`+(`tests/benchmarks/test_speed.py`) render each workload once in the suite, and with `--bench`+are timed against REF, alone.++Profiles: `default`; `thorough` (2,000 examples a property, for a hunt); `mutation` (for+mutmut: reproducible, and one failing example is enough). On CI (the CI variable), Hypothesis+loads its own `ci` profile: derandomized, no database, a reproduction blob on failure. Choose+one with `--hypothesis-profile NAME`.+"""++import dataclasses+import os+from collections.abc import Iterator++import pytest+from hypothesis import HealthCheck, Phase, settings++from manimgx import caches+from manimgx.animation import clock+from manimgx.config import config++settings.register_profile(+ "default", deadline=None+) # speed is the benchmarks' to measure+settings.register_profile("thorough", max_examples=2_000, deadline=None)+settings.register_profile(+ "mutation",+ derandomize=True,+ database=None,+ deadline=None,+ phases=[Phase.explicit, Phase.reuse, Phase.generate],+ report_multiple_bugs=False,+ suppress_health_check=[HealthCheck.differing_executors],+)+if "CI" not in os.environ:+ settings.load_profile("default")++_SHIPPED = dataclasses.asdict(config)+++def pytest_addoption(parser: pytest.Parser) -> None:+ group = parser.getgroup("manimgx benchmarks")+ group.addoption(+ "--bench",+ default=None,+ metavar="REF",+ help=(+ "time the benchmarks (tests/benchmarks/test_speed.py), alone: this checkout"+ " against REF's manimgx (a commit, branch or tag, or another checkout's"+ " directory), side by side"+ ),+ )+ group.addoption(+ "--bench-rounds",+ type=int,+ default=5,+ metavar="N",+ help="rounds per timed benchmark (default: 5)",+ )+++def pytest_configure(config: pytest.Config) -> None:+ config.addinivalue_line(+ "markers", "timed: a benchmark, timed with --bench (and then run alone)"+ )+ config.addinivalue_line(+ "markers",+ "config(**options): the configuration a test runs with, over the shipped one",+ )+ config.addinivalue_line(+ "markers",+ "cold: the test starts and ends with nothing remembered (caches.clear)",+ )+ if config.getoption("bench") is not None and getattr(+ config.option, "numprocesses", None+ ):+ raise pytest.UsageError("time the benchmarks alone: --bench runs with -n 0")+++def pytest_collection_modifyitems(+ config: pytest.Config, items: list[pytest.Item]+) -> None:+ """With --bench, the timed benchmarks run alone: nothing else runs beside what is timed."""+ if config.getoption("bench") is None:+ return+ kept, dropped = [], []+ for item in items:+ (kept if item.get_closest_marker("timed") else dropped).append(item)+ if dropped:+ config.hook.pytest_deselected(items=dropped)+ items[:] = kept++[email protected](autouse=True)+def fresh_world(request: pytest.FixtureRequest) -> Iterator[None]:+ """Each test starts at scene time 0 with the shipped configuration, changed as its `config`+ marks say (the nearest last: a test's over its class's over its module's); marked `cold`,+ or under mutmut (so that a mutant of remembered code runs), with nothing remembered."""+ clock.reset()+ cold = "MUTANT_UNDER_TEST" in os.environ or request.node.get_closest_marker("cold")+ if cold:+ caches.clear()+ for mark in reversed(list(request.node.iter_markers("config"))):+ for name, value in mark.kwargs.items():+ if not hasattr(config, name): # a field, or a property (frame_height)+ raise pytest.UsageError(f"the configuration has no {name!r}")+ setattr(config, name, value)+ yield+ for name, value in _SHIPPED.items():+ setattr(config, name, value)+ clock.reset()+ if cold:+ caches.clear()+++def two_fonts(+ monkeypatch: pytest.MonkeyPatch, tmp_path: os.PathLike[str]+) -> tuple[str, str]:+ """Two font search paths, `first` and `second`, whose fonts differ only in their size: the+ engine sets text as it does, and a glyph from `second` comes out half as wide and a+ quarter as tall. A capital's height tells the two apart (text is calibrated by it), and so+ do the widths calibration leaves. Layouts are cached in the test's own directory; mark the+ test `cold` so that nothing remembered from other fonts answers for these."""+ import numpy as np++ from manimgx.drawing import typesetting as tc++ first, second = os.path.join(tmp_path, "first"), os.path.join(tmp_path, "second")+ sizes = {first: (1.0, 1.0), second: (0.5, 0.25)}+ native = tc._engine.typeset++ def typeset(+ source: str, fonts: list[str], packages: str | None = None+ ) -> tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool]:+ raw, shapes, labels, system = native(source, fonts, packages)+ rows = np.frombuffer(raw).reshape(-1, tc.ROW).copy()+ wide, tall = next((sizes[path] for path in fonts if path in sizes), (1.0, 1.0))+ places = rows[:, tc.PLACEMENT] # (sx, ky, kx, sy, tx, ty): x's, then y's, apart+ places[:, ::2] *= wide+ places[:, 1::2] *= tall+ return rows.tobytes(), shapes, labels, system++ monkeypatch.setattr(tc, "_CACHE", tc.Path(tmp_path, "layouts"))+ monkeypatch.setattr(tc._engine, "typeset", typeset)+ return first, seconddiff --git a/tests/oracles.py b/tests/oracles.pynew file mode 100644index 00000000..7cd8ddbf--- /dev/null+++ b/tests/oracles.py@@ -0,0 +1,423 @@+"""Slow, plain reference implementations the tests compare manimgx with: each computes the same+quantity by another, obviously correct algorithm (de Casteljau's construction, numpy's root+finder, quadrature, triangle fans), so a test that agrees with one checks something.++And what an object holds, walked plainly: `reachable(root)` is everything an object reaches+(through attributes, containers, bound methods, closures, partials and an array's base), so+`reaches(root, targets)` says whether it keeps any of them, with no garbage collection to wait+on; `assert_replica(original, replica)` walks two object graphs side by side, to show that one+is an isomorphic copy of the other sharing no mutable part; `drawn_box(mob)` is the tight box+of what a mobject's family draws."""++import contextlib+import enum+import functools+import gc+import numbers+import pathlib+import sys+import types+import weakref+from collections.abc import Iterable+from itertools import pairwise+from typing import cast++import numpy as np+from numpy.polynomial import legendre+++def bezier_points(curves: np.ndarray, t: np.ndarray) -> np.ndarray:+ """Each cubic curve at each parameter, by de Casteljau's construction: (curves, len(t),+ dim)."""+ array = np.asarray(curves, dtype=float)+ p = array.reshape(-1, 1, 4, array.shape[-1])+ t = np.asarray(t, dtype=float)[None, :, None, None]+ while p.shape[2] > 1: # each round interpolates between neighbouring points+ p = (1 - t) * p[:, :, :-1] + t * p[:, :, 1:]+ return p[:, :, 0]+++def sample(curves: np.ndarray, per_curve: int = 200) -> np.ndarray:+ """Points along cubic curves, `per_curve` evenly spaced in each one's parameter."""+ points = bezier_points(curves, np.linspace(0, 1, per_curve))+ return points.reshape(-1, points.shape[-1])+++def curve_box(points: np.ndarray) -> np.ndarray:+ """(2, dim): the tight box of cubic curves, by numpy's roots of each coordinate's+ derivative."""+ array = np.asarray(points, dtype=float)+ curves = array.reshape(-1, 4, array.shape[-1])+ found = [curves[:, 0], curves[:, 3]]+ for c in curves:+ for d in range(c.shape[1]):+ p0, p1, p2, p3 = c[:, d]+ derivative = [+ 3 * (p3 - 3 * p2 + 3 * p1 - p0),+ 6 * (p2 - 2 * p1 + p0),+ 3 * (p1 - p0),+ ]+ if not any(derivative[:2]):+ continue+ for r in np.roots(derivative):+ if abs(r.imag) < 1e-12 and 0 <= r.real <= 1:+ found.append(bezier_points(c, np.array([r.real]))[0])+ everything = np.concatenate(found)+ return np.array([everything.min(axis=0), everything.max(axis=0)])+++_NODES, _WEIGHTS = legendre.leggauss(24)+++def arc_lengths(points: np.ndarray, pieces: int = 16) -> np.ndarray:+ """Each cubic curve's length: Gauss–Legendre quadrature of its speed, on `pieces` equal+ stretches of each stretch between the speed's minima (where a cusp makes the speed+ kink, a quadrature across it would lose digits)."""+ array = np.asarray(points, dtype=float)+ curves = array.reshape(-1, 4, array.shape[-1])+ lengths = []+ for curve in curves:+ d = 3 * np.diff(curve, axis=0) # B'(t) = a t² + b t + c+ a, b, c = d[0] - 2 * d[1] + d[2], 2 * (d[1] - d[0]), d[0]+ # d/dt |B'|² / 2 = (a t² + b t + c)·(2 a t + b): a cubic, zero at the speed's minima+ cubic = [2 * a @ a, 3 * a @ b, b @ b + 2 * a @ c, b @ c]+ cuts = sorted(+ r.real+ for r in (np.roots(cubic) if any(cubic) else [])+ if abs(r.imag) < 1e-12 and 0 < r.real < 1+ )+ edges = np.unique(np.concatenate([[0.0, 1.0], cuts]))+ total = 0.0+ for lo, hi in pairwise(edges):+ grid = np.linspace(lo, hi, pieces + 1)+ half = np.diff(grid) / 2+ t = ((grid[:-1] + half)[:, None] + np.outer(half, _NODES)).ravel()+ w = np.outer(half, _WEIGHTS).ravel()+ speed = np.linalg.norm(np.outer(t * t, a) + np.outer(t, b) + c, axis=1)+ total += float(speed @ w)+ lengths.append(total)+ return np.array(lengths)+++def look(mob: object) -> list[tuple[object, ...]]:+ """What a mobject shows, member by member: its kind, points, paint, z-index and how many+ submobjects it has; two mobjects that look the same draw the same frames."""+ from manimgx.mobject import Mobject++ assert isinstance(mob, Mobject)+ seen = []+ for member in mob.get_family():+ p = member.paint+ seen.append(+ (+ type(member).__name__,+ member.points.tobytes(),+ *(+ np.asarray(getattr(p, name)).tobytes()+ for name in ("fill", "stroke", "background")+ ),+ p.stroke_width,+ p.background_width,+ p.sheen_factor,+ np.asarray(p.sheen_direction).tobytes(),+ member.z_index,+ len(member.submobjects),+ )+ )+ return seen+++def polygon_area(xy: np.ndarray) -> float:+ """A polygon's signed area, positive counterclockwise, by triangles fanned from its+ first vertex."""+ array = np.asarray(xy, dtype=float)+ d = array[:, :2] - array[0, :2]+ return float(np.sum(d[1:-1, 0] * d[2:, 1] - d[2:, 0] * d[1:-1, 1]) / 2)+++def area_weighted_normals(points: np.ndarray, triangles: np.ndarray) -> np.ndarray:+ """Each vertex's normal: the sum of (b − a) × (c − a) over the triangles it is a corner of,+ added corner by corner (every triangle's first corner, then every second, then every+ third)."""+ out = np.zeros(points.shape)+ a, b, c = (points[triangles[:, k]] for k in range(3))+ faces = np.cross(b - a, c - a)+ for k in range(3):+ np.add.at(out, triangles[:, k], faces)+ return out+++def drawn_box(mob: object) -> np.ndarray | None:+ """(2, dim): the tight box of what a mobject's family draws — a path's curves (by+ `curve_box`), any other kind's points — or None if it draws nothing."""+ from manimgx.mobject import Mobject++ assert isinstance(mob, Mobject)+ boxes = []+ for leaf in mob.family_members_with_points():+ points = leaf.points+ whole = len(points) - len(points) % 4 if leaf._curves else 0 # a path's curves+ if whole:+ boxes.append(curve_box(points[:whole]))+ if len(points) > whole: # points of their own: a lone anchor, a cloud, a mesh+ rest = points[whole:]+ boxes.append(np.array([rest.min(axis=0), rest.max(axis=0)]))+ if not boxes:+ return None+ stacked = np.array(boxes)+ return np.array([stacked[:, 0].min(axis=0), stacked[:, 1].max(axis=0)])+++# ── what an object holds ─────────────────────────────────────────────────────────────+_SKIP = (type, types.ModuleType, types.CodeType, types.BuiltinFunctionType, weakref.ref)+_ATOMS = (int, float, complex, bool, str, bytes, type(None), range, slice)+++def _referents(obj: object) -> Iterable[object]:+ """What an object refers to: a function's closure and defaults (not its globals), a+ bound method's object and function, an array's base, an object's attributes."""+ if isinstance(obj, _SKIP):+ return ()+ if isinstance(obj, types.FunctionType):+ out: list[object] = []+ for cell in obj.__closure__ or ():+ with contextlib.suppress(ValueError): # (an empty cell)+ out.append(cell.cell_contents)+ out.extend(obj.__defaults__ or ())+ out.extend((obj.__kwdefaults__ or {}).values())+ return out+ if isinstance(obj, types.MethodType):+ return (obj.__self__, obj.__func__)+ if isinstance(obj, np.ndarray):+ return () if obj.base is None else (obj.base,)+ if hasattr(obj, "__dict__") and not isinstance(obj, dict):+ return (*vars(obj).values(), *gc.get_referents(obj))+ return gc.get_referents(obj)+++def reachable(root: object) -> dict[int, object]:+ """Everything `root` reaches, by id (itself included); classes, modules and functions'+ globals are not followed."""+ seen: dict[int, object] = {}+ stack = [root]+ while stack:+ obj = stack.pop()+ if id(obj) in seen or isinstance(obj, _ATOMS):+ continue+ seen[id(obj)] = obj+ stack.extend(_referents(obj))+ return seen+++def mutable_parts(root: object) -> dict[int, object]:+ """What `root` holds that can change in place — mobjects, lists, dicts, sets, writable+ arrays, objects — reached without passing through a value (a paint, a geometry, a+ function, one of manimgx's module-level objects), by id."""+ seen: dict[int, object] = {}+ stack = [root]+ while stack:+ obj = stack.pop()+ if id(obj) in seen or isinstance(obj, _ATOMS):+ continue+ if obj is not root and (_is_value(obj) or module_global(obj)):+ continue+ seen[id(obj)] = obj+ stack.extend(_referents(obj))+ return seen+++def reaches(root: object, targets: Iterable[object]) -> list[object]:+ """The targets `root` reaches: empty if it keeps none of them."""+ ids = {id(t) for t in targets}+ return [obj for key, obj in reachable(root).items() if key in ids]+++def _module_globals() -> set[int]:+ """manimgx's module-level objects (ORIGIN, a default LinearBase…): a mobject may take one as+ a default and hold it, and a copy may hold it or a copy of it."""+ out: set[int] = set()+ for name, module in list(sys.modules.items()):+ if name.startswith("manimgx") and module is not None:+ for value in vars(module).values():+ if not isinstance(value, (types.ModuleType, type, types.FunctionType)):+ out.add(id(value))+ return out+++_GLOBALS: set[int] = set()+++def module_global(obj: object) -> bool:+ """Is `obj` one of manimgx's module-level objects (a constant, a default)?"""+ if not _GLOBALS:+ _GLOBALS.update(_module_globals())+ return id(obj) in _GLOBALS and not isinstance(obj, _ATOMS)+++def _values() -> tuple[type, ...]:+ from manimgx.drawing.geometry import Blend+ from manimgx.drawing.paint import ManimColor, Paint++ return (+ Paint,+ Blend,+ ManimColor,+ types.FunctionType,+ functools.partial,+ np.ufunc,+ np.generic,+ frozenset,+ enum.Enum,+ pathlib.PurePath,+ numbers.Number,+ )+++def _is_value(obj: object) -> bool:+ """Shared freely by a mobject and its replica: a value never changed in place."""+ if isinstance(obj, (*_ATOMS, *_SKIP, *_values())):+ return True+ if type(obj).__module__ in (+ "typing",+ "types",+ ): # (`__orig_class__`: a generic alias)+ return True+ if module_global(obj):+ return True+ if isinstance(obj, np.ndarray):+ return not obj.flags.writeable+ if isinstance(obj, tuple):+ return all(_is_value(v) for v in obj)+ return False+++_PAINTED = ("fill", "stroke", "background", "stroke_width", "background_width")+++def _same_value(x: object, y: object) -> bool:+ from manimgx.drawing.geometry import Blend+ from manimgx.drawing.paint import Paint++ if x is y:+ return True+ if isinstance(x, np.ndarray) and isinstance(y, np.ndarray):+ return x.shape == y.shape and np.array_equal(x, y, equal_nan=True)+ if isinstance(x, types.FunctionType) and isinstance(y, types.FunctionType):+ return x.__code__ is y.__code__+ if isinstance(x, Blend) and isinstance(y, Blend):+ return np.array_equal(x.points(), y.points())+ if isinstance(x, Paint) and isinstance(y, Paint):+ return all(np.array_equal(getattr(x, n), getattr(y, n)) for n in _PAINTED)+ if isinstance(x, tuple) and isinstance(y, tuple):+ return len(x) == len(y) and all(map(_same_value, x, y))+ if module_global(x):+ return type(x) is type(y) and (+ not hasattr(x, "__dict__")+ or (+ vars(x).keys() == vars(y).keys()+ and all(_same_value(vars(x)[k], vars(y)[k]) for k in vars(x))+ )+ )+ try:+ return bool(x == y)+ except Exception: # (an array's truth, a value with no equality)+ return False+++def _same_key(a: object, b: object) -> bool:+ """Dictionary keys are identities (a graph's vertex, a VDict's key): never copied."""+ if isinstance(a, tuple) and isinstance(b, tuple):+ return len(a) == len(b) and all(map(_same_key, a, b))+ return a is b or (_is_value(a) and _same_value(a, b))+++def _pairs(x: object, y: object, path: str) -> list[tuple[object, object, str]]:+ """The parts of x and y to walk next, checking that the two hold parts alike."""++ assert type(x) is type(y), f"{path}: {type(x).__name__} became {type(y).__name__}"+ if isinstance(x, (list, tuple)):+ ys = cast("list[object] | tuple[object, ...]", y)+ assert len(x) == len(ys), f"{path}: {len(x)} items became {len(ys)}"+ return [(a, b, f"{path}[{i}]") for i, (a, b) in enumerate(zip(x, ys))]+ if isinstance(x, dict):+ yd = cast("dict[object, object]", y)+ assert len(x) == len(yd), f"{path}: {len(x)} keys became {len(yd)}"+ out = []+ for (ka, va), (kb, vb) in zip(x.items(), yd.items()):+ # a key is an identity (a vertex, a VDict's key) the replica borrows, or a part+ # copied with the rest (an updater keying its clock stamp, a key made with it)+ if isinstance(ka, types.MethodType) or not _same_key(ka, kb):+ out.append((ka, kb, f"{path}.key"))+ out.append((va, vb, f"{path}[{ka!r}]"))+ return out+ if isinstance(x, set):+ assert x == y, f"{path}: the sets differ"+ return []+ if isinstance(x, types.MethodType):+ ym = cast("types.MethodType", y)+ assert x.__func__ is ym.__func__, f"{path}: another method"+ return [(x.__self__, ym.__self__, f"{path}.__self__")]+ if hasattr(x, "__dict__"):+ shared = cast("frozenset[str]", getattr(type(x), "shared", frozenset()))+ dx, dy = vars(x), vars(y)+ assert dx.keys() == dy.keys(), f"{path}: the attributes {dx.keys() ^ dy.keys()}"+ out = []+ for name in dx:+ if name in shared: # declared shared: a value, never changed in place+ assert dx[name] is dy[name] or _same_value(dx[name], dy[name]), (+ f"{path}.{name}: a shared attribute differs"+ )+ assert name == "style" or dx[name] is None or _is_value(dx[name]), (+ f"{path}.{name}: a mutable {type(dx[name]).__name__} is declared shared"+ )+ else:+ out.append((dx[name], dy[name], f"{path}.{name}"))+ return out+ return []+++def assert_replica(original: object, replica: object) -> None:+ """The replica is an isomorphic copy of the original that shares no mutable part.++ Walking the two object graphs side by side, each part of the replica answers to one part+ of the original: of the same type, with the same plain values; two references to one+ mobject or object in the original are two references to one in the replica (containers+ are rebuilt per reference, as `mobject.copied` rebuilds them); and nothing mutable — a+ mobject, list, dict, set, writable array or object — is in both. Values are shared freely:+ numbers, strings, read-only arrays, paints, geometries, colors, functions, and manimgx's+ module-level objects."""+ pairs: dict[int, object] = {}+ mine: dict[int, object] = {}+ rebuilt: list[object] = []+ stack: list[tuple[object, object, str]] = [(original, replica, "root")]+ while stack:+ x, y, path = stack.pop()+ if id(x) in pairs:+ assert pairs[id(x)] is y, f"{path}: an alias became two parts"+ continue+ if module_global(+ x+ ): # a module's default (ORIGIN, a LinearBase): kept or copied+ assert y is x or _same_value(x, y), f"{path}: {x!r} became {y!r}"+ continue+ if isinstance(x, np.ndarray) and x.flags.writeable: # (each reference copied)+ assert isinstance(y, np.ndarray), f"{path}: an array became {y!r}"+ assert np.array_equal(x, y, equal_nan=True), f"{path}: the values differ"+ assert not np.shares_memory(x, y), f"{path}: a writable array is shared"+ continue+ if _is_value(x):+ assert _is_value(y), f"{path}: {x!r} became {y!r}"+ assert _same_value(x, y), f"{path}: {x!r} became {y!r}"+ continue+ assert x is not y, f"{path}: a mutable {type(x).__name__} is shared"+ mine[id(x)] = x+ if isinstance(x, (list, tuple, dict, set)):+ rebuilt.append(y)+ else:+ pairs[id(x)] = y+ stack.extend(_pairs(x, y, path))+ images = [pairs[k] for k in mine if k in pairs]+ assert len({id(y) for y in images}) == len(images), "two parts became one"+ assert not {id(y) for y in [*images, *rebuilt]} & set(mine), (+ "the replica holds parts of the original"+ )diff --git a/tests/scenes.py b/tests/scenes.pynew file mode 100644index 00000000..18297f36--- /dev/null+++ b/tests/scenes.py@@ -0,0 +1,452 @@+"""Scenes made of functions, and stories to tell: the kit for what scenes show.++`scene(construct)` is a scene whose `construct` is a function (`scene_3d`, a 3D scene's);+`frames(scene)` draws a scene and keeps every frame it shows; `instants(construct, probe)`+keeps what `probe` sees of a scene at every instant it computes.++A scene with no video and no pixel sink counts its frames without drawing them, so a story+costs milliseconds. `record(story, fps, fast)` tells a story and keeps what each frame shows of+the stage (the mobjects the story puts on it), leaf by leaf, on the path the scene takes: a play+computed ahead of time ("fast", as the film receives it) or frame by frame (`fast=False`).+`stories()` draws random stories: a stage of shapes, then plays of animation trees, as data+Hypothesis can shrink.+"""++from collections.abc import Callable+from dataclasses import dataclass, field+from fractions import Fraction+from typing import TYPE_CHECKING, NamedTuple++import numpy as np+from hypothesis import strategies as st++import manimgx as m+from manimgx.animation import easing as rf+from manimgx.config import config+from manimgx.drawing.geometry import bezier_remap+from manimgx.drawing.paint import Paint+from manimgx.rendering.film import Frame+from manimgx.scene import _tracks++if TYPE_CHECKING:+ from manimgx.animation.transform import Transform+ from manimgx.drawing.geometry import Path+ from manimgx.scene import Act+++def scene(construct: Callable[[m.Scene], None]) -> m.Scene:+ """A scene whose `construct` is `construct`."""++ class Told(m.Scene):+ def construct(self) -> None:+ construct(self)++ return Told()+++def scene_3d(construct: Callable[[m.ThreeDScene], None]) -> m.ThreeDScene:+ """A 3D scene whose `construct` is `construct`."""++ class Told(m.ThreeDScene):+ def construct(self) -> None:+ construct(self)++ return Told()+++def frames(scene: m.Scene) -> list[np.ndarray]:+ """Every frame `scene` shows, drawn at the configured size: (height, width, 4) rows of+ red, green, blue and opacity, 0 to 255; a frame shown n times, n times."""+ shape = (config.pixel_height, config.pixel_width, 4)+ shown: list[np.ndarray] = []++ def keep(frame: Frame) -> None:+ pixels = np.frombuffer(frame.pixels(), np.uint8).reshape(shape)+ shown.extend([pixels] * frame.repeat)++ scene.render(None, frames=keep)+ return shown+++def instants[T](+ construct: Callable[[m.Scene], None], probe: Callable[[m.Scene], T]+) -> dict[Fraction, T]:+ """What `probe` sees of the scene at every instant it computes (frames, plays' ends, the+ closing frame), every frame computed (none ahead): the world at each instant, once what+ opens at it has begun."""+ seen: dict[Fraction, T] = {}++ class Probed(m.Scene):+ def construct(self) -> None:+ construct(self)++ def _instant(+ self,+ t: Fraction,+ act: "Act | None" = None,+ stepping: bool = True,+ framing: bool = True,+ ) -> None:+ super()._instant(t, act, stepping, framing)+ seen[t] = probe(self)++ def _pure_tweens(self, anim: m.Animation, alpha: list[float]) -> None:+ return None++ Probed().render()+ return seen+++class Look(NamedTuple):+ """What a leaf shows: its points (compared by `same_look`), and its paint, rounded."""++ points: np.ndarray+ brushes: tuple[bytes, ...] # fill, stroke, background, and the trim window+ widths: tuple[float, float]+ dash: tuple[float, ...] | None+++type Shot = tuple[Look, ...]+"""What a frame shows: the looks of the leaves it draws, in drawing order."""+++def look(leaf: m.Mobject) -> Look:+ p = leaf.paint+ return Look(+ np.array(leaf.points),+ tuple(+ np.round(getattr(p, name), 9).tobytes()+ for name in ("fill", "stroke", "background", "trim")+ ),+ (round(float(p.stroke_width), 9), round(float(p.background_width), 9)),+ None if p.dash is None else tuple(round(x, 9) for x in p.dash),+ )+++def same_look(a: Look, b: Look) -> bool:+ """Do two looks draw the same? The same paint, and the same curves: a path cut into more+ curves (as aligning it for a transform cuts it) is the same path."""+ if (a.brushes, a.widths, a.dash) != (b.brushes, b.widths, b.dash):+ return False+ pa, pb = (+ (a.points, b.points) if len(a.points) <= len(b.points) else (b.points, a.points)+ )+ if len(pa) != len(pb) and len(pa) % 4 == 0 and len(pa) and len(pb) % 4 == 0:+ pa = bezier_remap(pa.reshape(-1, 4, 3), len(pb) // 4).reshape(-1, 3)+ return pa.shape == pb.shape and np.allclose(pa, pb, rtol=0, atol=1e-9)+++def assert_same_shots(x: Shot, y: Shot, where: str) -> None:+ assert len(x) == len(y), f"{where}: {len(x)} leaves drawn, not {len(y)}"+ for i, (p, q) in enumerate(zip(x, y, strict=True)):+ assert same_look(p, q), f"{where}: leaf {i} differs"+++def assert_same_frames(a: dict[int, Shot], b: dict[int, Shot]) -> None:+ """Two recordings show the same frames: the same leaves drawn in the same order, alike."""+ assert sorted(a) == sorted(b)+ for k in a:+ assert_same_shots(a[k], b[k], f"frame {k}")+++def outcome(+ story: Callable[["Recorder"], None], fps: int = 10, fast: bool = True+) -> "Recorder | type":+ """What telling a story comes to: its recording, or the kind of error it raises (a story+ may ask the impossible, as two replacements of one mobject in one play)."""+ try:+ return record(story, fps, fast)+ except ValueError as error:+ return type(error)+++def _frames_alike(a: "Recorder", b: "Recorder") -> None:+ assert_same_frames(a.frames, b.frames)+++def assert_same_outcome(+ a: "Recorder | type",+ b: "Recorder | type",+ alike: "Callable[[Recorder, Recorder], None]" = _frames_alike,+) -> None:+ """Two outcomes alike: recordings alike (by default, the same frames), or the same error."""+ if isinstance(a, Recorder) and isinstance(b, Recorder):+ alike(a, b)+ else:+ assert a == b+++def assert_same_instants(a: "Recorder", b: "Recorder") -> None:+ """Two recordings at different frame rates show the same world at every instant both+ have a frame at: the world at an instant does not depend on the frame rate."""+ common = sorted(+ {Fraction(k, a.fps) for k in a.frames} & {Fraction(k, b.fps) for k in b.frames}+ )+ assert common+ for t in common:+ assert_same_shots(+ a.frames[int(t * a.fps)], b.frames[int(t * b.fps)], f"at {t} s"+ )+++def seen(looks: list[Look | None], paints: list[Paint]) -> Shot:+ """What a frame shows: the looks of the leaves drawn, in drawing order, but those no one+ can see (every brush transparent, to the 9 decimals looks are compared to: an invisible+ part alignment added, a rounding past its fading in)."""+ return tuple(+ x+ for x, p in zip(looks, paints, strict=True)+ if x is not None+ and max(p.fill[:, 3].max(), p.stroke[:, 3].max(), p.background[:, 3].max())+ > 1e-9+ )+++class Recorder(m.Scene):+ """Tells `story(self)`; `frames[k]` is what frame k shows: the looks of the leaves it+ draws, in drawing order (see `seen`), however their families are structured."""++ def __init__(+ self, story: Callable[["Recorder"], None], fast: bool, fps: int+ ) -> None:+ super().__init__()+ self.story, self.fast, self.fps = story, fast, fps+ self.stage: list[m.Mobject] = []+ self.frames: dict[int, Shot] = {}++ def construct(self) -> None:+ self.story(self)++ def shot(+ self, looks: dict[int, Look | None], paints: dict[int, Paint] | None = None+ ) -> Shot:+ drawn, paints = self.display_list(), paints or {}+ return seen(+ [looks[id(leaf)] if id(leaf) in looks else look(leaf) for leaf in drawn],+ [paints.get(id(leaf), leaf.paint) for leaf in drawn],+ )++ def _emit(self, repeat: int = 1) -> None:+ shot = self.shot({})+ for k in range(self.frame, self.frame + max(repeat, 0)):+ self.frames[k] = shot+ super()._emit(repeat)++ def _pure_tweens(+ self, anim: m.Animation, alpha: list[float]+ ) -> "tuple[list[tuple[Transform, Path]], set[int]] | None":+ return super()._pure_tweens(anim, alpha) if self.fast else None++ def _advance_tweens(+ self,+ anim: m.Animation,+ tweens: "list[tuple[Transform, Path]]",+ alpha: list[float],+ introduced: set[int],+ ) -> None:+ # each frame of a play computed ahead, as the film receives it: a leaf between its+ # keyframes at its t, as it was before its part began (-1), or absent (-2)+ tracks = {+ id(leaf): (keys, path, index, t)+ for leaf, keys, path, index, t in _tracks(+ anim, tweens, np.array(alpha), introduced+ )+ }+ for f in range(len(alpha)):+ looks: dict[int, Look | None] = {}+ paints: dict[int, Paint] = {}+ for leaf in self.display_list():+ track = tracks.get(id(leaf))+ if track is None:+ continue+ keys, path, index, t = track+ if index[f] == -1:+ continue+ if index[f] == -2:+ looks[id(leaf)] = None+ continue+ saved = leaf._geometry, leaf.paint+ leaf.interpolate(keys[index[f]], keys[index[f] + 1], float(t[f]), path)+ looks[id(leaf)], paints[id(leaf)] = look(leaf), leaf.paint+ leaf._geometry, leaf.paint = saved+ self.frames[self.frame + f] = self.shot(looks, paints)+ super()._advance_tweens(anim, tweens, alpha, introduced)+++def record(+ story: Callable[[Recorder], None], fps: int = 10, fast: bool = True+) -> Recorder:+ """Tell a story at `fps` on the scene's path (or frame by frame) and keep its frames."""+ saved = config.frame_rate+ config.frame_rate = fps+ try:+ scene = Recorder(story, fast, fps)+ scene.render()+ finally:+ config.frame_rate = saved+ return scene+++# ── stories ─────────────────────────────────────────────────────────────────────────────+SHAPES: dict[str, Callable[[], m.Mobject]] = {+ "square": lambda: m.Square(1.2, color=m.BLUE, fill_opacity=0.5),+ "circle": lambda: m.Circle(0.7, color=m.RED),+ "triangle": lambda: m.Triangle(color=m.GREEN, fill_opacity=1),+ "dots": lambda: m.VGroup(*(m.Dot(i * m.RIGHT * 0.5) for i in range(3))),+ "line": lambda: m.Line(m.LEFT, m.RIGHT, color=m.YELLOW),+}+MONOTONE = [+ "linear",+ "smooth",+ "rush_into",+ "double_smooth",+ "ease_out_cubic",+ "slow_into",+ "lingering",+]+ANY_RATE = [+ *MONOTONE,+ "there_and_back",+ "wiggle",+ "ease_out_back",+ "running_start",+ "ease_in_elastic",+]+COLORS = [m.RED, m.YELLOW, m.TEAL]+++@dataclass+class Leaf:+ kind: str+ mob: int+ shape: str = "circle"+ v: tuple[float, float] = (1.0, 0.0)+ angle: float = 1.0+ rate: str | None = None+ run_time: float | None = None+ lag: float | None = None++ def build(self, stage: list[m.Mobject]) -> m.Animation:+ mob, v = stage[self.mob % len(stage)], np.array([*self.v, 0.0])+ kw: dict = {} # the options drawn+ if self.rate is not None:+ kw["rate_func"] = getattr(rf, self.rate)+ if self.run_time is not None:+ kw["run_time"] = self.run_time+ if self.lag is not None:+ kw["lag_ratio"] = self.lag+ return {+ "transform": lambda: m.Transform(mob, SHAPES[self.shape]().shift(v), **kw),+ "replace": lambda: m.ReplacementTransform(+ mob, SHAPES[self.shape]().shift(v), **kw+ ),+ "shift": lambda: mob.animate(**kw).shift(v),+ "turn": lambda: mob.animate(**kw).rotate(self.angle),+ "recolor": lambda: mob.animate(**kw).set_color(COLORS[int(self.angle) % 3]),+ "rotate": lambda: m.Rotate(mob, self.angle, **kw),+ "fade_in": lambda: m.FadeIn(mob, shift=v, **kw),+ "fade_out": lambda: m.FadeOut(mob, shift=v, **kw),+ "create": lambda: m.Create(mob, **kw),+ "write": lambda: m.Write(mob, **kw),+ "grow": lambda: m.GrowFromCenter(mob, **kw),+ "indicate": lambda: m.Indicate(mob, **kw),+ "reveal": lambda: m.ShowIncreasingSubsets(mob, **kw),+ "wait": lambda: m.Wait(self.run_time or 0.5),+ }[self.kind]()+++@dataclass+class Node:+ kind: str # "group" | "succession" | "lagged"+ parts: list["Leaf | Node"]+ lag: float | None = None+ rate: str | None = None++ def build(self, stage: list[m.Mobject]) -> m.Animation:+ kw: dict = {}+ if self.lag is not None:+ kw["lag_ratio"] = self.lag+ if self.rate is not None:+ kw["rate_func"] = getattr(rf, self.rate)+ group = {+ "group": m.AnimationGroup,+ "succession": m.Succession,+ "lagged": m.LaggedStart,+ }+ return group[self.kind](*(p.build(stage) for p in self.parts), **kw)+++@dataclass+class Story:+ stage: list[str]+ added: list[bool]+ plays: list[list[Leaf | Node]] = field(default_factory=list)++ def __call__(self, scene: Recorder) -> None:+ scene.stage = self.tell(scene)++ def tell(self, scene: m.Scene) -> list[m.Mobject]:+ """Tell the story on `scene`; its stage."""+ stage = [+ SHAPES[s]().shift([i - 2.0, 0.5 * (i % 2), 0])+ for i, s in enumerate(self.stage)+ ]+ scene.add(*(mob for mob, added in zip(stage, self.added, strict=True) if added))+ for play in self.plays:+ scene.play(*(tree.build(stage) for tree in play))+ return stage+++KINDS = ["transform", "replace", "shift", "turn", "recolor", "rotate", "fade_in", "fade_out",+ "create", "write", "grow", "indicate", "reveal", "wait"] # fmt: skip+++def leaves(+ stage: int, rates: list[str] = MONOTONE, kinds: list[str] = KINDS+) -> st.SearchStrategy[Leaf]:+ """An animation of one of `stage` mobjects, of a kind, with options drawn."""+ return st.builds(+ Leaf,+ kind=st.sampled_from(kinds),+ mob=st.integers(0, stage - 1),+ shape=st.sampled_from(sorted(SHAPES)),+ v=st.tuples(*[st.sampled_from([0.0, 0.5, 1.0, 1.5])] * 2),+ angle=st.sampled_from([0.5, 1.0, np.pi / 2, np.pi, -1.0]),+ rate=st.none() | st.sampled_from(rates),+ run_time=st.none() | st.sampled_from([0.3, 0.5, 1.0, 1.3]),+ lag=st.none() | st.sampled_from([0.0, 0.1, 0.25, 0.5, 1.0]),+ )+++def trees(+ stage: int, rates: list[str], kinds: list[str]+) -> st.SearchStrategy[Leaf | Node]:+ """An animation tree: leaves under groups, successions and lagged starts."""+ return st.recursive(+ leaves(stage, rates, kinds),+ lambda parts: st.builds(+ Node,+ kind=st.sampled_from(["group", "succession", "lagged"]),+ parts=st.lists(parts, min_size=1, max_size=3),+ lag=st.none() | st.sampled_from([0.0, 0.25, 0.5, 1.0]),+ rate=st.none() | st.sampled_from(MONOTONE),+ ),+ max_leaves=5,+ )+++def stories(+ draw: st.DrawFn, rates: list[str] = MONOTONE, kinds: list[str] = KINDS+) -> Story:+ """A stage of 1 to 4 shapes, some added, and 1 to 3 plays of animation trees."""+ stage = draw(st.lists(st.sampled_from(sorted(SHAPES)), min_size=1, max_size=4))+ added = draw(st.lists(st.booleans(), min_size=len(stage), max_size=len(stage)))+ plays = draw(+ st.lists(+ st.lists(trees(len(stage), rates, kinds), min_size=1, max_size=3),+ min_size=1,+ max_size=3,+ )+ )+ return Story(stage, added, plays)diff --git a/tests/strategies.py b/tests/strategies.pynew file mode 100644index 00000000..0b0bca2e--- /dev/null+++ b/tests/strategies.py@@ -0,0 +1,530 @@+"""Hypothesis strategies for manimgx's values: numbers at a scene's scale, points and vectors,+Bézier curves and paths, colors and paints, rate functions, mobjects and animations.++Every strategy draws valid input only: finite numbers within a scene's reach (no NaN, infinity or+subnormal, which no scene draws), curves as their four control points, colors as manimgx reads+them. What a test checks for invalid input it writes out by hand."""++from collections.abc import Callable+from pathlib import Path+from typing import NamedTuple++import numpy as np+import svgelements+from hypothesis import strategies as st+from hypothesis.extra import numpy as hnp++import manimgx as m+from manimgx.animation import easing+from manimgx.drawing.paint import Paint++REACH = 100.0+"""How far from the origin a scene reaches, in scene units: twelve frames' widths."""+++def reals(bound: float = REACH) -> st.SearchStrategy[float]:+ """Finite floats in [-bound, bound], 0 for any a scene cannot tell from 0 (below 1e-9)."""+ return st.floats(-bound, bound, allow_nan=False).map(+ lambda x: x if abs(x) >= 1e-9 else 0.0+ )+++def arrays(+ shape: int | tuple[int, ...], bound: float = REACH+) -> st.SearchStrategy[np.ndarray]:+ """Float arrays of a shape, each entry in [-bound, bound]."""+ return hnp.arrays(np.float64, shape, elements=reals(bound))+++def points(bound: float = REACH) -> st.SearchStrategy[np.ndarray]:+ """A point: (3,)."""+ return arrays(3, bound)+++def vectors(+ min_norm: float = 1e-3, bound: float = 10.0+) -> st.SearchStrategy[np.ndarray]:+ """A vector no shorter than `min_norm`: a direction with a length."""+ return arrays(3, bound).filter(lambda v: np.linalg.norm(v) >= min_norm)+++def angles(bound: float = 4 * np.pi) -> st.SearchStrategy[float]:+ """An angle, in radians, up to two turns either way."""+ return reals(bound)+++def curves(+ draw: st.DrawFn, min_curves: int = 1, max_curves: int = 6, bound: float = 20.0+) -> np.ndarray:+ """The control points of a continuous path of cubic curves: (4n, 3), each curve starting+ where the one before it ends."""+ n = draw(st.integers(min_curves, max_curves))+ anchors = draw(arrays((n + 1, 3), bound))+ handles = draw(arrays((n, 2, 3), bound))+ out = np.empty((4 * n, 3))+ out[0::4], out[1::4], out[2::4], out[3::4] = (+ anchors[:-1],+ handles[:, 0],+ handles[:, 1],+ anchors[1:],+ )+ return out+++def paths(draw: st.DrawFn, min_curves: int = 1, max_curves: int = 6) -> m.VMobject:+ """A VMobject of one subpath of cubic curves."""+ path = m.VMobject()+ path.points = draw(curves(min_curves, max_curves))+ return path+++rgbs = hnp.arrays(np.float64, 3, elements=st.floats(0, 1))+rgbas = hnp.arrays(np.float64, 4, elements=st.floats(0, 1))+colors = rgbas.map(lambda x: m.ManimColor(tuple(float(c) for c in x)))+++def brushes(max_rows: int = 3) -> st.SearchStrategy[np.ndarray]:+ """A brush: rows of red, green, blue and opacity (gradient stops)."""+ return hnp.arrays(+ np.float64,+ st.tuples(st.integers(1, max_rows), st.just(4)),+ elements=st.floats(0, 1),+ )+++paints = st.builds(+ lambda fill, stroke, width: Paint().but(+ fill=fill, stroke=stroke, stroke_width=width+ ),+ brushes(),+ brushes(),+ st.floats(0, 16),+)++RATE_FUNCTIONS: list[Callable[[float], float]] = [+ f+ for name in easing.__all__+ if name+ not in {+ "RateFunction",+ "unit_interval",+ "zero",+ "squish_rate_func",+ "not_quite_there",+ }+ and callable(f := getattr(easing, name))+]+rate_funcs = st.sampled_from(RATE_FUNCTIONS)+++# every public mobject class, made through its public constructor with small, valid arguments;+# `tests/test_tests.py` holds the registry to every class `manimgx` exports, so the laws every+# mobject keeps run over each (ArrowTip is abstract: its subclasses stand for it)+def _svg() -> m.SVGMobject:+ return m.SVGMobject(+ Path(__file__).parent / "integration/cases/svg_mobject_example/shapes.svg"+ )+++def _image() -> m.ImageMobject:+ pixels = np.zeros((4, 4, 4), np.uint8)+ pixels[..., 0], pixels[..., 3] = np.arange(16).reshape(4, 4) * 16, 255+ return m.ImageMobject(pixels)+++_square = lambda: m.Square() # noqa: E731+_lines = lambda: (m.Line(m.ORIGIN, m.RIGHT), m.Line(m.ORIGIN, m.UP)) # noqa: E731+MOBJECTS: dict[str, Callable[[], m.Mobject]] = {+ "AmbientLight": lambda: m.AmbientLight(),+ "Angle": lambda: m.Angle(*_lines()),+ "AnimatedBoundary": lambda: m.AnimatedBoundary(_square()),+ "AnnotationDot": lambda: m.AnnotationDot(),+ "AnnularSector": lambda: m.AnnularSector(),+ "Annulus": lambda: m.Annulus(),+ "Arc": lambda: m.Arc(0.5, 2),+ "ArcBetweenPoints": lambda: m.ArcBetweenPoints(m.LEFT, m.RIGHT),+ "ArcBrace": lambda: m.ArcBrace(),+ "ArcPolygon": lambda: m.ArcPolygon(),+ "ArcPolygonFromArcs": lambda: m.ArcPolygonFromArcs(),+ "Arrow": lambda: m.Arrow(m.LEFT, m.RIGHT),+ "Arrow3D": lambda: m.Arrow3D(),+ "ArrowCircleFilledTip": lambda: m.ArrowCircleFilledTip(),+ "ArrowCircleTip": lambda: m.ArrowCircleTip(),+ "ArrowSquareFilledTip": lambda: m.ArrowSquareFilledTip(),+ "ArrowSquareTip": lambda: m.ArrowSquareTip(),+ "ArrowTriangleFilledTip": lambda: m.ArrowTriangleFilledTip(),+ "ArrowTriangleTip": lambda: m.ArrowTriangleTip(),+ "ArrowVectorField": lambda: m.ArrowVectorField(+ lambda p: np.array([-p[1], p[0], 0]), x_range=[-2, 2, 1], y_range=[-2, 2, 1]+ ),+ "Axes": lambda: m.Axes(),+ "BackgroundRectangle": lambda: m.BackgroundRectangle(_square()),+ "BarChart": lambda: m.BarChart([1, -2, 3]),+ "Brace": lambda: m.Brace(_square()),+ "BraceBetweenPoints": lambda: m.BraceBetweenPoints(m.LEFT, m.RIGHT),+ "BraceLabel": lambda: m.BraceLabel(_square(), "x"),+ "BraceText": lambda: m.BraceText(_square(), "side"),+ "BulletedList": lambda: m.BulletedList("one", "two"),+ "Circle": lambda: m.Circle(),+ "Code": lambda: m.Code(code_string="x = 1", language="python"),+ "ComplexPlane": lambda: m.ComplexPlane(),+ "ComplexValueTracker": lambda: m.ComplexValueTracker(1 + 2j),+ "Cone": lambda: m.Cone(),+ "ConvexHull": lambda: m.ConvexHull(*m.regular_vertices(6)[0]),+ "ConvexHull3D": lambda: m.ConvexHull3D(+ *np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]], float)+ ),+ "Cross": lambda: m.Cross(),+ "Cube": lambda: m.Cube(),+ "CubicBezier": lambda: m.CubicBezier(m.LEFT, m.UP, m.UR, m.RIGHT),+ "CurvedArrow": lambda: m.CurvedArrow(m.LEFT, m.RIGHT),+ "CurvedDoubleArrow": lambda: m.CurvedDoubleArrow(m.LEFT, m.RIGHT),+ "CurvesAsSubmobjects": lambda: m.CurvesAsSubmobjects(m.Circle()),+ "Cutout": lambda: m.Cutout(m.Square(3), m.Circle(0.5)),+ "Cylinder": lambda: m.Cylinder(),+ "DashedLine": lambda: m.DashedLine(m.LEFT, m.RIGHT),+ "DashedVMobject": lambda: m.DashedVMobject(m.Circle()),+ "DecimalMatrix": lambda: m.DecimalMatrix([[1.5, 2.25], [3.0, 4.5]]),+ "DecimalNumber": lambda: m.DecimalNumber(3.14),+ "DecimalTable": lambda: m.DecimalTable([[1.5, 2.25]]),+ "DiGraph": lambda: m.DiGraph([1, 2, 3], [(1, 2), (2, 3)], layout="circular"),+ "Difference": lambda: m.Difference(m.Square(2), m.Circle(0.5)),+ "Dodecahedron": lambda: m.Dodecahedron(),+ "Dot": lambda: m.Dot(),+ "Dot3D": lambda: m.Dot3D(),+ "DoubleArrow": lambda: m.DoubleArrow(m.LEFT, m.RIGHT),+ "Elbow": lambda: m.Elbow(),+ "Ellipse": lambda: m.Ellipse(),+ "EnvironmentLight": lambda: m.EnvironmentLight(),+ "Exclusion": lambda: m.Exclusion(m.Square(2), m.Circle(1).shift(m.RIGHT)),+ "FullScreenRectangle": lambda: m.FullScreenRectangle(),+ "FunctionGraph": lambda: m.FunctionGraph(np.sin, x_range=[-3, 3]),+ "Graph": lambda: m.Graph([1, 2, 3], [(1, 2), (2, 3)], layout="circular"),+ "Group": lambda: m.Group(m.Square(), m.Dot()),+ "Icosahedron": lambda: m.Icosahedron(),+ "ImageMobject": _image,+ "ImageMobjectFromCamera": lambda: m.ImageMobjectFromCamera(m.Camera()),+ "ImplicitFunction": lambda: m.ImplicitFunction(+ lambda x, y: x * x + y * y - 1, x_range=[-2, 2], y_range=[-2, 2]+ ),+ "Integer": lambda: m.Integer(7),+ "IntegerMatrix": lambda: m.IntegerMatrix([[1, 2], [3, 4]]),+ "IntegerTable": lambda: m.IntegerTable([[1, 2]]),+ "Intersection": lambda: m.Intersection(m.Square(2), m.Circle(1.2)),+ "Label": lambda: m.Label("x"),+ "LabeledArrow": lambda: m.LabeledArrow("a", start=m.LEFT, end=m.RIGHT),+ "LabeledDot": lambda: m.LabeledDot("1"),+ "LabeledLine": lambda: m.LabeledLine("l", start=m.LEFT, end=m.RIGHT),+ "LabeledPolygram": lambda: m.LabeledPolygram(+ [[0, 0, 0], [2, 0, 0], [1, 2, 0]], label="t"+ ),+ "Light": lambda: m.Light(m.UR),+ "Line": lambda: m.Line(m.LEFT, m.RIGHT),+ "Line3D": lambda: m.Line3D(),+ "ManimBanner": lambda: m.ManimBanner(),+ "MathTable": lambda: m.MathTable([["x", "y"]]),+ "MathTex": lambda: m.MathTex(r"e^{i\pi} + 1 = 0"),+ "MathTexPart": lambda: m.MathTex("a", "b")[0],+ "MathTypst": lambda: m.MathTypst("x^2"),+ "Matrix": lambda: m.Matrix([[1, 2], [3, 4]]),+ "MeshMobject": lambda: m.MeshMobject(),+ "Mobject": lambda: m.Mobject(),+ "Mobject1D": lambda: m.Mobject1D(),+ "MobjectMatrix": lambda: m.MobjectMatrix([[m.Dot(), m.Square(0.3)]]),+ "MobjectTable": lambda: m.MobjectTable([[m.Dot(), m.Square(0.3)]]),+ "NumberLine": lambda: m.NumberLine(),+ "NumberPlane": lambda: m.NumberPlane(),+ "Octahedron": lambda: m.Octahedron(),+ "PGroup": lambda: m.PGroup(m.PointCloudDot()),+ "PMobject": lambda: m.PMobject(),+ "Paragraph": lambda: m.Paragraph("a", "b"),+ "ParametricFunction": lambda: m.ParametricFunction(+ lambda t: np.array([np.cos(t), np.sin(2 * t), 0]), t_range=(0, 6)+ ),+ "Point": lambda: m.Point(),+ "PointCloudDot": lambda: m.PointCloudDot(),+ "PointLight": lambda: m.PointLight(),+ "PolarPlane": lambda: m.PolarPlane(),+ "Polygon": lambda: m.Polygon(m.LEFT, m.UP, m.RIGHT),+ "Polygram": lambda: m.Polygram([m.LEFT, m.UP, m.RIGHT]),+ "Polyhedron": lambda: m.Polyhedron(+ [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]],+ [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]],+ ),+ "Prism": lambda: m.Prism(),+ "Rectangle": lambda: m.Rectangle(width=3, height=1),+ "RegularPolygon": lambda: m.RegularPolygon(7),+ "RegularPolygram": lambda: m.RegularPolygram(7),+ "RightAngle": lambda: m.RightAngle(*_lines()),+ "RoundedRectangle": lambda: m.RoundedRectangle(),+ "SVGMobject": _svg,+ "SampleSpace": lambda: m.SampleSpace(),+ "ScreenRectangle": lambda: m.ScreenRectangle(),+ "Sector": lambda: m.Sector(),+ "SingleStringMathTex": lambda: m.SingleStringMathTex("x^2"),+ "Sphere": lambda: m.Sphere(),+ "SpotLight": lambda: m.SpotLight(),+ "Square": lambda: m.Square(1.5),+ "Star": lambda: m.Star(),+ "StealthTip": lambda: m.StealthTip(),+ "StreamLines": lambda: m.StreamLines(+ lambda p: np.array([1.0, 0.5, 0]), x_range=[-2, 2, 1], y_range=[-2, 2, 1]+ ),+ "SunLight": lambda: m.SunLight(),+ "Surface": lambda: m.Surface(lambda u, v: np.array([u, v, u * v]), resolution=8),+ "SurroundingRectangle": lambda: m.SurroundingRectangle(m.Circle()),+ "Table": lambda: m.Table([["a", "b"]]),+ "TangentLine": lambda: m.TangentLine(m.Circle(), 0.3),+ "Tetrahedron": lambda: m.Tetrahedron(),+ "Tex": lambda: m.Tex("hello"),+ "Text": lambda: m.Text("manimgx"),+ "ThreeDAxes": lambda: m.ThreeDAxes(),+ "ThreeDVMobject": lambda: m.ThreeDVMobject(),+ "TipableVMobject": lambda: m.TipableVMobject(),+ "Title": lambda: m.Title("Title"),+ "Torus": lambda: m.Torus(),+ "TracedPath": lambda: m.TracedPath(lambda: m.ORIGIN),+ "Triangle": lambda: m.Triangle(),+ "Typst": lambda: m.Typst("*bold* text"),+ "Underline": lambda: m.Underline(m.Text("word")),+ "Union": lambda: m.Union(m.Square(2), m.Circle(1).shift(m.RIGHT)),+ "UnitInterval": lambda: m.UnitInterval(),+ "VDict": lambda: m.VDict([("s", m.Square())]),+ "VGroup": lambda: m.VGroup(m.Square(), m.Circle().shift(m.RIGHT)),+ "VMobject": lambda: m.VMobject().set_points_as_corners([m.LEFT, m.UP, m.RIGHT]),+ "VMobjectFromSVGPath": lambda: m.VMobjectFromSVGPath(+ svgelements.Path("M 0 0 L 10 10 L 20 0 Z")+ ),+ "ValueTracker": lambda: m.ValueTracker(2.5),+ "Variable": lambda: m.Variable(1.5, "x"),+ "Vector": lambda: m.Vector(m.UP),+ "VectorField": lambda: m.VectorField(+ lambda p: p, x_range=[-1, 1, 1], y_range=[-1, 1, 1]+ ),+ "VectorizedPoint": lambda: m.VectorizedPoint(m.UR),+}+mobjects = st.sampled_from(sorted(MOBJECTS)).map(lambda name: MOBJECTS[name]())+drawn = mobjects.filter(lambda mob: mob.boundary_box() is not None)+"""Mobjects that draw something: they have a box to lay out and measure."""+++# ── animations ─────────────────────────────────────────────────────────────────────────+MONOTONE: list[Callable[[float], float]] = [+ easing.linear, easing.smooth, easing.smoothstep, easing.smootherstep,+ easing.rush_into, easing.rush_from, easing.slow_into, easing.double_smooth,+ easing.lingering, easing.exponential_decay,+ *(getattr(easing, f"ease_{way}_{kind}") for way in ("in", "out", "in_out")+ for kind in ("sine", "quad", "cubic", "quart", "quint", "expo", "circ")),+] # fmt: skip+"""The rate functions that never go back: progress only grows with time."""++type World = list[m.Mobject]+++class Played(NamedTuple):+ """An animation as the registry makes it: the mobjects it is given (`world`, made afresh+ each call), and the animation made of them (`make`)."""++ world: Callable[[], World]+ make: Callable[[World], m.Animation]+++def _shape() -> World:+ return [m.Square(1.2, color=m.BLUE, fill_opacity=0.5)]+++def _shapes() -> World:+ return [*_shape(), m.Circle(0.7, color=m.RED).shift(1.5 * m.RIGHT)]+++def _group() -> World:+ return [m.VGroup(*_shapes())]+++def _groups() -> World:+ return [m.VGroup(*_shapes()), m.VGroup(*_shapes()[::-1]).shift(m.DOWN)]+++def _word() -> World:+ return [m.Text("ab")]+++def _typed() -> World:+ return [m.Text("ab"), m.Rectangle(width=0.1, height=0.5)]+++def _saved() -> World:+ (square,) = _shape()+ square.save_state().shift(m.RIGHT).set_color(m.YELLOW)+ return [square]+++def _targeted() -> World:+ (square,) = _shape()+ square.generate_target().shift(m.RIGHT).set_color(m.YELLOW)+ return [square]+++def _nothing() -> World:+ return []+++def _as[T: m.Mobject](mob: m.Mobject, kind: type[T]) -> T:+ """A world's mobject, as the kind its entry made."""+ assert isinstance(mob, kind)+ return mob+++class _TypeNameMatching(m.TransformMatchingAbstractBase):+ """A matching by the parts' class names (the corpus's own subclass)."""++ @staticmethod+ def get_mobject_parts(mobject: m.Mobject) -> list[m.Mobject]:+ return list(mobject.submobjects) or [mobject]++ @staticmethod+ def get_mobject_key(mobject: m.Mobject) -> str:+ return type(mobject).__name__+++_SILENCE = np.zeros(4800, np.float32) # a tenth of a second at 48 kHz++# every public animation class, made through its public constructor with small, valid arguments+# of mobjects the entry makes afresh; `tests/test_tests.py` holds the registry to every class+# `manimgx` exports, so the laws every animation keeps run over each+ANIMATIONS: dict[str, Played] = {+ "Add": Played(_shape, lambda w: m.Add(w[0])),+ "AddTextLetterByLetter": Played(_word, lambda w: m.AddTextLetterByLetter(w[0])),+ "AddTextWordByWord": Played(+ lambda: [m.Text("a b")], lambda w: m.AddTextWordByWord(w[0])+ ),+ "Animate": Played(_shape, lambda w: w[0].animate.shift(m.RIGHT).rotate(1.0)),+ "Animation": Played(_shape, lambda w: m.Animation(w[0])),+ "AnimationGroup": Played(+ _shapes,+ lambda w: m.AnimationGroup(m.FadeIn(w[0]), m.Rotate(w[1], 1.0), lag_ratio=0.3),+ ),+ "ApplyComplexFunction": Played(+ _shape, lambda w: m.ApplyComplexFunction(lambda z: z * (1 + 0.5j), w[0])+ ),+ "ApplyFunction": Played(+ _shape, lambda w: m.ApplyFunction(lambda mob: mob.shift(m.RIGHT), w[0])+ ),+ "ApplyMatrix": Played(_shape, lambda w: m.ApplyMatrix([[1, 1], [0, 1]], w[0])),+ "ApplyMethod": Played(_shape, lambda w: m.ApplyMethod(w[0].shift, m.RIGHT)),+ "ApplyPointwiseFunction": Played(+ _shape, lambda w: m.ApplyPointwiseFunction(lambda p: 1.5 * p, w[0])+ ),+ "ApplyWave": Played(_shape, lambda w: m.ApplyWave(w[0])),+ "Blink": Played(_shape, lambda w: m.Blink(w[0])),+ "Broadcast": Played(lambda: [m.Circle()], lambda w: m.Broadcast(w[0])),+ "ChangeDecimalToValue": Played(+ lambda: [m.DecimalNumber(1.0)],+ lambda w: m.ChangeDecimalToValue(_as(w[0], m.DecimalNumber), 3.0),+ ),+ "ChangeSpeed": Played(+ _shape, lambda w: m.ChangeSpeed(m.Rotate(w[0], 1.0), {0.5: 2})+ ),+ "ChangingDecimal": Played(+ lambda: [m.DecimalNumber(1.0)],+ lambda w: m.ChangingDecimal(_as(w[0], m.DecimalNumber), lambda a: 1 + 2 * a),+ ),+ "Circumscribe": Played(_shape, lambda w: m.Circumscribe(w[0])),+ "ClockwiseTransform": Played(_shapes, lambda w: m.ClockwiseTransform(w[0], w[1])),+ "ComplexHomotopy": Played(+ _shape, lambda w: m.ComplexHomotopy(lambda z, t: z * (1 + t), w[0])+ ),+ "CounterclockwiseTransform": Played(+ _shapes, lambda w: m.CounterclockwiseTransform(w[0], w[1])+ ),+ "Create": Played(_shape, lambda w: m.Create(w[0])),+ "CyclicReplace": Played(_shapes, lambda w: m.CyclicReplace(w[0], w[1])),+ "DrawBorderThenFill": Played(_shape, lambda w: m.DrawBorderThenFill(w[0])),+ "FadeIn": Played(_shape, lambda w: m.FadeIn(w[0], shift=m.UP)),+ "FadeOut": Played(_shape, lambda w: m.FadeOut(w[0], scale=0.5)),+ "FadeToColor": Played(_shape, lambda w: m.FadeToColor(w[0], m.YELLOW)),+ "FadeTransform": Played(_shapes, lambda w: m.FadeTransform(w[0], w[1])),+ "FadeTransformPieces": Played(_groups, lambda w: m.FadeTransformPieces(w[0], w[1])),+ "Flash": Played(_nothing, lambda w: m.Flash(m.ORIGIN)),+ "FocusOn": Played(_nothing, lambda w: m.FocusOn(m.ORIGIN)),+ "GrowArrow": Played(+ lambda: [m.Arrow(m.LEFT, m.RIGHT)], lambda w: m.GrowArrow(w[0])+ ),+ "GrowFromCenter": Played(_shape, lambda w: m.GrowFromCenter(w[0])),+ "GrowFromEdge": Played(_shape, lambda w: m.GrowFromEdge(w[0], m.UP)),+ "GrowFromPoint": Played(_shape, lambda w: m.GrowFromPoint(w[0], m.LEFT)),+ "Homotopy": Played(+ _shape, lambda w: m.Homotopy(lambda x, y, z, t: (x + t, y, z), w[0])+ ),+ "Indicate": Played(_shape, lambda w: m.Indicate(w[0])),+ "LaggedStart": Played(+ _shapes,+ lambda w: m.LaggedStart(m.FadeIn(w[0]), m.Rotate(w[1], 1.0), lag_ratio=0.5),+ ),+ "LaggedStartMap": Played(_group, lambda w: m.LaggedStartMap(m.FadeIn, w[0])),+ "MaintainPositionRelativeTo": Played(+ _shapes, lambda w: m.MaintainPositionRelativeTo(w[0], w[1])+ ),+ "MoveAlongPath": Played(+ lambda: [m.Dot(), m.Line(m.LEFT, m.RIGHT)],+ lambda w: m.MoveAlongPath(w[0], _as(w[1], m.VMobject)),+ ),+ "MoveToTarget": Played(_targeted, lambda w: m.MoveToTarget(w[0])),+ "PhaseFlow": Played(+ _shape, lambda w: m.PhaseFlow(lambda p: np.array([-p[1], p[0], 0.0]), w[0])+ ),+ "RemoveTextLetterByLetter": Played(+ _word, lambda w: m.RemoveTextLetterByLetter(w[0])+ ),+ "ReplacementTransform": Played(+ _shapes, lambda w: m.ReplacementTransform(w[0], w[1])+ ),+ "Restore": Played(_saved, lambda w: m.Restore(w[0])),+ "Rotate": Played(_shape, lambda w: m.Rotate(w[0], 1.0)),+ "Rotating": Played(_shape, lambda w: m.Rotating(w[0])),+ "ScaleInPlace": Played(_shape, lambda w: m.ScaleInPlace(w[0], 2.0)),+ "ShowIncreasingSubsets": Played(_group, lambda w: m.ShowIncreasingSubsets(w[0])),+ "ShowPassingFlash": Played(_shape, lambda w: m.ShowPassingFlash(w[0])),+ "ShowPassingFlashWithThinningStrokeWidth": Played(+ _shape, lambda w: m.ShowPassingFlashWithThinningStrokeWidth(w[0])+ ),+ "ShowSubmobjectsOneByOne": Played(+ _group, lambda w: m.ShowSubmobjectsOneByOne(w[0])+ ),+ "ShrinkToCenter": Played(_shape, lambda w: m.ShrinkToCenter(w[0])),+ "Sound": Played(_nothing, lambda w: m.Sound(_SILENCE, rate=48000)),+ "Speech": Played(_nothing, lambda w: m.Speech(_SILENCE, text="a", rate=48000)),+ "SpinInFromNothing": Played(_shape, lambda w: m.SpinInFromNothing(w[0])),+ "SpiralIn": Played(_group, lambda w: m.SpiralIn(w[0])),+ "Succession": Played(+ _shapes, lambda w: m.Succession(m.FadeIn(w[0]), m.Rotate(w[1], 1.0))+ ),+ "Swap": Played(_shapes, lambda w: m.Swap(w[0], w[1])),+ "Transform": Played(_shapes, lambda w: m.Transform(w[0], w[1])),+ "TransformFromCopy": Played(_shapes, lambda w: m.TransformFromCopy(w[0], w[1])),+ "TransformMatchingAbstractBase": Played(+ _groups, lambda w: _TypeNameMatching(w[0], w[1], fade_transform_mismatches=True)+ ),+ "TransformMatchingShapes": Played(+ _groups, lambda w: m.TransformMatchingShapes(w[0], w[1])+ ),+ "TransformMatchingTex": Played(+ lambda: [m.MathTex("a", "b"), m.MathTex("b", "a")],+ lambda w: m.TransformMatchingTex(w[0], w[1]),+ ),+ "TypeWithCursor": Played(_typed, lambda w: m.TypeWithCursor(w[0], w[1])),+ "Uncreate": Played(_shape, lambda w: m.Uncreate(w[0])),+ "UntypeWithCursor": Played(_typed, lambda w: m.UntypeWithCursor(w[0], w[1])),+ "Unwrite": Played(_shape, lambda w: m.Unwrite(w[0])),+ "UpdateFromAlphaFunc": Played(+ _shape, lambda w: m.UpdateFromAlphaFunc(w[0], lambda mob, a: mob.set_x(a))+ ),+ "UpdateFromFunc": Played(+ _shape, lambda w: m.UpdateFromFunc(w[0], lambda mob: mob.set_y(1.0))+ ),+ "Wait": Played(_nothing, lambda w: m.Wait()),+ "Wiggle": Played(_group, lambda w: m.Wiggle(w[0])),+ "Write": Played(_word, lambda w: m.Write(w[0])),+}diff --git a/tests/test_tests.py b/tests/test_tests.pynew file mode 100644index 00000000..89f4dbe6--- /dev/null+++ b/tests/test_tests.py@@ -0,0 +1,81 @@+"""The unit tests mirror the package: `tests/unit/<path>/test_<module>.py` tests+`src/manimgx/<path>/<module>.py`, so a module's tests are where its path says,+and each test module opens with the properties it checks. The registries the laws run over+hold every public class: `MOBJECTS` every mobject, `ANIMATIONS` every animation."""++import ast+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+SOURCE = ROOT / "src" / "manimgx"+UNIT = ROOT / "tests" / "unit"+++def test_every_unit_test_module_tests_a_source_module() -> None:+ strays = [+ str(test.relative_to(UNIT))+ for test in UNIT.rglob("test_*.py")+ if not (+ SOURCE / test.parent.relative_to(UNIT) / test.name.removeprefix("test_")+ ).exists()+ ]+ assert not strays, (+ f"unit test modules without a source module of that path: {strays}"+ )+++def test_every_python_file_under_unit_is_a_test_module() -> None:+ others = [+ str(p.relative_to(UNIT))+ for p in UNIT.rglob("*.py")+ if not p.name.startswith("test_")+ ]+ assert not others, (+ f"shared test code goes in tests/strategies.py or tests/oracles.py: {others}"+ )+++def test_every_public_mobject_class_is_in_the_registry() -> None:+ import inspect++ from tests.strategies import MOBJECTS++ import manimgx+ from manimgx.mobject import Mobject++ public = {+ name+ for name, value in vars(manimgx).items()+ if inspect.isclass(value) and issubclass(value, Mobject)+ }+ abstract = {"ArrowTip"} # its subclasses stand for it+ missing = sorted(public - abstract - set(MOBJECTS))+ assert not missing, f"public mobject classes the laws do not reach: {missing}"+++def test_every_public_animation_class_is_in_the_registry() -> None:+ import inspect++ from tests.strategies import ANIMATIONS++ import manimgx+ from manimgx.animation.timeline import Animation++ public = {+ name+ for name, value in vars(manimgx).items()+ if inspect.isclass(value) and issubclass(value, Animation)+ }+ missing = sorted(public - set(ANIMATIONS))+ assert not missing, f"public animation classes the laws do not reach: {missing}"+++def test_every_unit_test_module_states_its_properties() -> None:+ silent = [+ str(test.relative_to(UNIT))+ for test in UNIT.rglob("test_*.py")+ if not ast.get_docstring(ast.parse(test.read_text(encoding="utf-8")))+ ]+ assert not silent, (+ f"test modules without a docstring stating what they check: {silent}"+ )