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

Implement drawing caches

apoogdke7f2d451104f
diff --git a/src/manimgx/caches.py b/src/manimgx/caches.py
new file mode 100644
index 00000000..2d915002
--- /dev/null
+++ b/src/manimgx/caches.py
@@ -0,0 +1,76 @@
+"""What manimgx remembers: values it has worked out once, kept to be read again.
+
+Every such memory is a `Memo`: bounded (past its limit it forgets everything at once) and
+invisible (forgetting changes no result, only the time one takes). `clear` forgets them all,
+as the tests do to show that nothing depends on what is remembered.
+
+What an object holds is remembered the same way: a value assigned equal to the one it holds
+(`unchanged`) keeps the one held, and so all that was derived from it — an upload, normals, a
+frame's record."""
+
+from collections.abc import Callable, Hashable
+
+import numpy as np
+
+_FORGETTERS: list[Callable[[], None]] = []
+
+
+def unchanged(value: np.ndarray, held: object) -> bool:
+ """Is `value` the array `held`, bit for bit (so that keeping the one held changes nothing)?
+ An array of up to 1,024 items is compared whole; a bigger one at 16 items spread over it
+ first, so that one that changed is told at once."""
+ if value is held:
+ return True
+ if not (
+ isinstance(held, np.ndarray)
+ and value.shape == held.shape
+ and value.dtype == held.dtype
+ ):
+ return False
+ if value.size <= 1024:
+ return value.tobytes() == held.tobytes()
+ bits = f"u{value.itemsize}" # the items' bits, compared as unsigned integers
+ items, kept = value.reshape(-1).view(bits), held.reshape(-1).view(bits)
+ step = len(items) // 16
+ return bool(
+ np.array_equal(items[::step], kept[::step]) and np.array_equal(items, kept)
+ )
+
+
+class Memo[K: Hashable, V](dict[K, V]):
+ """A value for each key, worked out once: `memo.recall(key, make)`.
+
+ Args:
+ limit: How many values it keeps; past it, it forgets them all.
+ """
+
+ __slots__ = ("limit",)
+
+ def __init__(self, limit: int) -> None:
+ super().__init__()
+ self.limit = limit
+ _FORGETTERS.append(self.clear)
+
+ def recall(self, key: K, make: Callable[[], V]) -> V:
+ """The value for `key`: remembered, or made now by `make` and remembered."""
+ value = self.get(key)
+ return self.keep(key, make()) if value is None else value
+
+ def keep(self, key: K, value: V) -> V:
+ """Remember `value` for `key` (forgetting everything first, past the limit)."""
+ if len(self) >= self.limit:
+ self.clear()
+ self[key] = value
+ return value
+
+
+def forgets[F: Callable[..., object]](cached: F) -> F:
+ """Have `clear` forget a function's own cache too (a `functools.cache`)."""
+ _FORGETTERS.append(getattr(cached, "cache_clear")) # noqa: B009
+ return cached
+
+
+def clear() -> None:
+ """Forget everything remembered."""
+ for forget in _FORGETTERS:
+ forget()
diff --git a/tests/unit/test_caches.py b/tests/unit/test_caches.py
new file mode 100644
index 00000000..d1194b4c
--- /dev/null
+++ b/tests/unit/test_caches.py
@@ -0,0 +1,68 @@
+"""What an object holds, compared: an array assigned again is the one held when their bits are.
+
+- `unchanged(value, held)` is bit equality: true exactly when `held` is an array of the
+ value's shape and type with the value's bytes, however either is laid out in memory. So a
+ NaN is itself and -0.0 is not 0.0, the same bits read as another type are not the same
+ array, and nothing but an array is ever what is held. An array past 1,024 items is probed
+ at 16 items first, which changes no answer (an item between the probes counts too).
+"""
+
+from collections.abc import Callable
+
+import numpy as np
+from hypothesis import example, given
+from hypothesis import strategies as st
+from tests.strategies import arrays
+
+from manimgx.caches import unchanged
+
+# compared whole, whole, and probed first (400 × 3 is past 1,024 items)
+held_arrays = st.sampled_from([(7, 3), (40, 3), (400, 3)]).flatmap(arrays)
+
+
+def one_changed(held: np.ndarray, at: int, by: float) -> np.ndarray:
+ changed = held.copy()
+ changed.reshape(-1)[at % held.size] += by
+ return changed
+
+
+# each: (the value assigned, what is held), from a held array and an item and an amount
+VARIANTS: dict[str, Callable[[np.ndarray, int, float], tuple[np.ndarray, object]]] = {
+ "itself": lambda h, at, by: (h, h),
+ "a copy": lambda h, at, by: (h.copy(), h),
+ "Fortran order": lambda h, at, by: (np.asfortranarray(h), h),
+ "a transposed copy": lambda h, at, by: (h.T.copy().T, h),
+ "one item changed": lambda h, at, by: (one_changed(h, at, by), h),
+ "another shape": lambda h, at, by: (h.reshape(3, -1), h),
+ "one row fewer": lambda h, at, by: (h[:-1], h),
+ "another type": lambda h, at, by: (h.astype(np.float32), h),
+ "the same bits as integers": lambda h, at, by: (h.view(np.int64), h),
+ "-0.0 for 0.0": lambda h, at, by: (-np.zeros_like(h), np.zeros_like(h)),
+ "NaN for NaN": lambda h, at, by: (np.full_like(h, np.nan), np.full_like(h, np.nan)),
+ "a list held": lambda h, at, by: (h.copy(), h.tolist()),
+ "nothing held": lambda h, at, by: (h.copy(), None),
+}
+
+
+@given(
+ held=held_arrays,
+ how=st.sampled_from(sorted(VARIANTS)),
+ at=st.integers(0),
+ by=st.floats(0.5, 10.0),
+)
+@example(held=np.zeros(3000), how="-0.0 for 0.0", at=0, by=1.0)
+@example(held=np.zeros(3000), how="NaN for NaN", at=0, by=1.0)
+@example(
+ held=np.zeros((400, 3)), how="one item changed", at=1, by=1.0
+) # not one probed
+def test_unchanged_is_bit_equality(
+ held: np.ndarray, how: str, at: int, by: float
+) -> None:
+ value, kept = VARIANTS[how](held, at, by)
+ bits = (
+ isinstance(kept, np.ndarray)
+ and value.shape == kept.shape
+ and value.dtype == kept.dtype
+ and value.tobytes() == kept.tobytes()
+ )
+ assert unchanged(value, kept) == bits