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

Compare complete frame streams across hold boundaries

Sina Atalay4fb331793586
diff --git a/tests/integration/corpus/compare.py b/tests/integration/corpus/compare.py
index 089a0aa5..446df4df 100644
--- a/tests/integration/corpus/compare.py
+++ b/tests/integration/corpus/compare.py
@@ -25,13 +25,15 @@ The verdict this feeds only sorts cases for review: CE has bugs of its own, "sam
"""
from collections.abc import Generator
+from contextlib import closing
from dataclasses import dataclass
from fractions import Fraction
+from itertools import zip_longest
from pathlib import Path
import numpy as np
from tests.integration.corpus.case import METRICS, Comparison, Frames
-from tests.integration.corpus.frames import Pixels, decode
+from tests.integration.corpus.frames import Pixels, decode, frame_hash
WINDOW = 7
@@ -85,20 +87,35 @@ def compare(
ce_hashes, mx_hashes = ce.hashes(), manimgx.hashes()
known: dict[tuple[str, str], tuple[float, ...]] = {} # held frames repeat pairs
rows: list[tuple[int, int, tuple[float, ...]]] = []
- ce_frames = _Cursor(decode(ce_video, size))
- mx_frames = _Cursor(decode(manimgx_video, size))
+ ce_frames = _Cursor(_recorded(ce_video, size, ce))
+ mx_frames = _Cursor(_recorded(manimgx_video, size, manimgx))
try:
for i, k in pairs: # both indices only grow: each video is read once
+ # Decode and authenticate held frames too before reusing their measurement.
+ left, right = ce_frames.at(i), mx_frames.at(k)
key = (ce_hashes[i], mx_hashes[k])
if key not in known:
- known[key] = measure(ce_frames.at(i), mx_frames.at(k))
+ known[key] = measure(left, right)
rows.append((i, k, known[key]))
+ ce_frames.finish()
+ mx_frames.finish()
finally:
ce_frames.close()
mx_frames.close()
return Comparison(pairs=tuple(rows), unpaired=tuple(unpaired))
+def _recorded(path: Path, size: tuple[int, int], facts: Frames) -> Generator[Pixels]:
+ """A complete movie whose decoded content still matches the recorded frame identities."""
+ with closing(decode(path, size)) as images:
+ for index, (pixels, identity) in enumerate(zip_longest(images, facts.hashes())):
+ if pixels is None or identity is None:
+ raise ValueError(f"{path}: frame count differs from its record")
+ if frame_hash(pixels.tobytes()) != identity:
+ raise ValueError(f"{path}: frame {index} differs from its record")
+ yield pixels
+
+
@dataclass(frozen=True, slots=True)
class Slot:
"""A step of the timeline: a scene time, and the frame each engine has on screen then
@@ -149,5 +166,10 @@ class _Cursor:
assert self._frame is not None
return self._frame
+ def finish(self) -> None:
+ # Unpaired frames still belong to the facts we are about to publish.
+ for _ in self._frames:
+ pass
+
def close(self) -> None:
self._frames.close()
diff --git a/tests/integration/corpus/frames.py b/tests/integration/corpus/frames.py
index 8725effd..fde347b5 100644
--- a/tests/integration/corpus/frames.py
+++ b/tests/integration/corpus/frames.py
@@ -35,11 +35,18 @@ def rgb(pixels: bytes | np.ndarray, size: tuple[int, int]) -> bytes:
class Recorder:
"""Frames as an engine draws them: their hashes, as runs, and, given a path, a video."""
- def __init__(self, size: tuple[int, int], fps: int, video: Path | None) -> None:
+ def __init__(
+ self,
+ size: tuple[int, int],
+ fps: int,
+ video: Path | None,
+ *,
+ compact: bool = True,
+ ) -> None:
self.size = size
self.runs: list[list[str | int]] = []
self.count = 0
- self._video = None if video is None else _Video(video, size, fps)
+ self._video = None if video is None else _Video(video, size, fps, compact)
def add(self, frame: bytes, repeat: int = 1) -> None:
"""One drawn frame (RGB bytes), shown `repeat` times."""
@@ -61,13 +68,15 @@ class Recorder:
class _Video:
- """Lossless video: x264 in RGB (libx264rgb) at QP 0, its slowest preset, one thread."""
+ """Lossless RGB video, compressed for archiving or for immediate comparison."""
- def __init__(self, path: Path, size: tuple[int, int], fps: int) -> None:
+ def __init__(
+ self, path: Path, size: tuple[int, int], fps: int, compact: bool
+ ) -> None:
self.size, self.rate, self.shown = size, Fraction(1, fps), 0
self.container = av.open(str(path), "w", options={"fflags": "+bitexact"})
options = {
- "preset": "veryslow",
+ "preset": "veryslow" if compact else "ultrafast",
"qp": "0",
"threads": "1",
"flags": "+bitexact",
diff --git a/tests/integration/test_corpus_comparison.py b/tests/integration/test_corpus_comparison.py
new file mode 100644
index 00000000..d787cc3f
--- /dev/null
+++ b/tests/integration/test_corpus_comparison.py
@@ -0,0 +1,83 @@
+"""Review comparisons authenticate whole movies, including held and unpaired frames."""
+
+from dataclasses import replace
+from fractions import Fraction
+from pathlib import Path
+
+import pytest
+from tests.integration.corpus import case as corpus
+from tests.integration.corpus import compare, references
+from tests.integration.corpus.frames import Recorder
+
+RED = (255, 0, 0)
+BLUE = (0, 0, 255)
+
+
+def case(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> corpus.Case:
+ monkeypatch.setattr(corpus, "CASES", tmp_path)
+ monkeypatch.setattr(corpus, "SIZE", (8, 8))
+ monkeypatch.setattr(references, "SIZE", (8, 8))
+ example = corpus.Case("comparison")
+ example.dir.mkdir()
+ example.scene.write_text("import manimgx\n", encoding="utf-8")
+ red = movie(example, "manimgx", [RED, RED])
+ movie(example, "ce", [RED, RED])
+ example.write_facts(
+ corpus.Facts(example.source_hash(), (8, 8), 10, red, red, "test", None)
+ )
+ return example
+
+
+def movie(
+ case: corpus.Case, engine: corpus.Engine, colors: list[tuple[int, int, int]]
+) -> corpus.Frames:
+ recorder = Recorder((8, 8), 10, case.video(engine), compact=False)
+ for color in colors:
+ recorder.add(bytes(color) * 64)
+ return corpus.Frames(
+ recorder.close(), Fraction(len(colors), 10), ((Fraction(0), len(colors)),)
+ )
+
+
[email protected]("engine", ["ce", "manimgx"])
[email protected]("colors", [[RED, BLUE], [RED], [RED, RED, RED]])
+def test_recompare_rejects_replaced_or_incomplete_movies_without_writing_facts(
+ case: corpus.Case, engine: corpus.Engine, colors: list[tuple[int, int, int]]
+) -> None:
+ before = case.facts_path.read_bytes()
+ movie(case, engine, colors)
+ with pytest.raises(ValueError, match="differs from its record"):
+ references.recompare(case)
+ assert case.facts_path.read_bytes() == before
+
+
+def test_unpaired_movie_tail_is_still_authenticated(case: corpus.Case) -> None:
+ facts = case.facts()
+ assert facts is not None
+ shorter = movie(case, "manimgx", [RED])
+ case.write_facts(replace(facts, manimgx=shorter))
+ before = case.facts_path.read_bytes()
+ movie(case, "ce", [RED, BLUE])
+ with pytest.raises(ValueError, match="frame 1 differs"):
+ references.recompare(case)
+ assert case.facts_path.read_bytes() == before
+
+
+def test_validated_holds_still_share_one_measurement(
+ case: corpus.Case, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ measure = compare.measure
+ measured = 0
+
+ def count(a: compare.Pixels, b: compare.Pixels) -> tuple[float, ...]:
+ nonlocal measured
+ measured += 1
+ return measure(a, b)
+
+ monkeypatch.setattr(compare, "measure", count)
+ assert references.recompare(case) == "compared"
+ facts = case.facts()
+ assert facts is not None
+ assert facts.verdict(corpus.Settings("max", 0)) == "working"
+ assert measured == 1
diff --git a/tests/integration/test_frame_comparison.py b/tests/integration/test_frame_comparison.py
new file mode 100644
index 00000000..71c6cdec
--- /dev/null
+++ b/tests/integration/test_frame_comparison.py
@@ -0,0 +1,104 @@
+"""A visual oracle compares complete films, regardless of how holds are grouped."""
+
+from itertools import groupby
+
+import pytest
+from hypothesis import given
+from hypothesis import strategies as st
+from tests.integration.corpus.frozen import Comparison, Difference
+
+
+class Film:
+ size = (1, 1)
+ fps = 10.0
+
+ def __init__(self, pixels: list[int], *, grouped: bool = True) -> None:
+ self.pixels = pixels
+ self.frames = len(pixels)
+ self.timeline: list[tuple[int, int]] = []
+ self.drawn: list[int] = []
+ first = 0
+ for _, group in groupby(pixels):
+ repeat = len(list(group))
+ self.timeline.extend(
+ [(first, repeat)]
+ if grouped
+ else [(first + offset, 1) for offset in range(repeat)]
+ )
+ first += repeat
+
+ def render(self, frame: int) -> bytes:
+ self.drawn.append(frame)
+ return bytes((self.pixels[frame], 0, 0, 255))
+
+
+@given(
+ pairs=st.lists(st.tuples(st.integers(0, 3), st.integers(0, 3)), max_size=50),
+ grouped=st.booleans(),
+)
+def test_every_frame_is_compared_across_independent_hold_boundaries(
+ pairs: list[tuple[int, int]], grouped: bool
+) -> None:
+ expected = Film([old for old, _ in pairs], grouped=grouped)
+ actual = Film([new for _, new in pairs], grouped=not grouped)
+ differences: list[Difference] = []
+ comparison = Comparison(
+ expected, lambda difference, _old, _new: differences.append(difference)
+ )
+ for index, repeat in actual.timeline:
+ comparison.add(index, repeat, bytes((actual.pixels[index], 0, 0)))
+ comparison.finish(actual.frames)
+ assert comparison.changed_frames == sum(old != new for old, new in pairs)
+ expanded = {
+ frame: (difference.changed_pixels, difference.max_channel_difference)
+ for difference in differences
+ for frame in range(difference.first, difference.first + difference.repeat)
+ }
+ assert expanded == {
+ index: (1, abs(old - new))
+ for index, (old, new) in enumerate(pairs)
+ if old != new
+ }
+ assert expected.drawn == [index for index, _ in expected.timeline]
+
+
+ ("index", "repeat"), [(1, 1), (-1, 1), (0, 0), (0, -1), (0, 3)]
+)
+def test_gaps_overlaps_and_nonpositive_or_excess_holds_fail(
+ index: int, repeat: int
+) -> None:
+ comparison = Comparison(Film([0, 0]), lambda *_: None)
+ with pytest.raises(ValueError, match=r"timeline|more frames"):
+ comparison.add(index, repeat, bytes(3))
+
+
+def test_a_repeated_callback_cannot_hide_a_missing_frame() -> None:
+ comparison = Comparison(Film([0, 0]), lambda *_: None)
+ comparison.add(0, 1, bytes(3))
+ with pytest.raises(ValueError, match="timeline"):
+ comparison.add(0, 1, bytes(3))
+
+
[email protected]("reported", [0, 1, 2, 3])
+def test_incomplete_callbacks_fail_even_when_film_count_matches(reported: int) -> None:
+ comparison = Comparison(Film([0, 0]), lambda *_: None)
+ comparison.add(0, 1, bytes(3))
+ with pytest.raises(ValueError, match="frame coverage"):
+ comparison.finish(reported)
+
+
[email protected]("timeline", [[(1, 2)], [(0, 0)], [(0, 1), (0, 1)], [(0, 1)]])
+def test_a_malformed_reference_timeline_is_rejected(
+ timeline: list[tuple[int, int]],
+) -> None:
+ reference = Film([0, 0])
+ reference.timeline = timeline
+ with pytest.raises(ValueError, match="reference timeline"):
+ Comparison(reference, lambda *_: None)
+
+
+def test_pixel_dimensions_are_checked_before_comparing() -> None:
+ comparison = Comparison(Film([0]), lambda *_: None)
+ with pytest.raises(ValueError, match="image size"):
+ comparison.add(0, 1, bytes(4))