Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

perf: Mobject's Sequence methods no longer copy self.submobjects on every call (#4915)

nikolajmunk2c2fba998e8f
diff --git a/manim/mobject/graphing/probability.py b/manim/mobject/graphing/probability.py
index 3da8a839c..31c8d9058 100644
--- a/manim/mobject/graphing/probability.py
+++ b/manim/mobject/graphing/probability.py
@@ -6,7 +6,7 @@ __all__ = ["SampleSpace", "BarChart"]
from collections.abc import Iterable, MutableSequence, Sequence
-from typing import Any
+from typing import Any, cast
import numpy as np
@@ -207,12 +207,12 @@ class SampleSpace(Rectangle):
if hasattr(parts, subattr):
self.add(getattr(parts, subattr))
- def __getitem__(self, index: int) -> VMobject:
+ def __getitem__(self, index: Any) -> VMobject:
if hasattr(self, "horizontal_parts"):
return self.horizontal_parts[index]
elif hasattr(self, "vertical_parts"):
return self.vertical_parts[index]
- return self.split()[index]
+ return cast(VMobject, super().__getitem__(index))
class BarChart(Axes):
diff --git a/manim/mobject/matrix.py b/manim/mobject/matrix.py
index 73fc7b4e5..016b67338 100644
--- a/manim/mobject/matrix.py
+++ b/manim/mobject/matrix.py
@@ -627,7 +627,7 @@ def get_det_text(
parens = MathTex("(", ")")
parens.scale(initial_scale_factor)
parens.stretch_to_fit_height(matrix.height)
- l_paren, r_paren = parens.split()
+ l_paren, r_paren = parens
l_paren.next_to(matrix, LEFT, buff=0.1)
r_paren.next_to(matrix, RIGHT, buff=0.1)
det = Tex("det")
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 615d6b90e..589711bc6 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -2489,19 +2489,34 @@ class Mobject:
# Family matters
- def __getitem__(self, value: Any) -> Mobject | Group:
- self_list = self.split()
+ def __getitem__(self, value: Any) -> Mobject:
if isinstance(value, slice):
GroupClass = self.get_group_class()
- return GroupClass(*self_list.__getitem__(value))
- rv: Mobject | Group = self_list.__getitem__(value)
- return rv
+
+ if self.has_no_points():
+ return GroupClass(*self.submobjects[value])
+
+ r = range(*value.indices(len(self)))
+ if not r: # If slice is empty
+ return GroupClass()
+ if 0 not in r:
+ # If self is not included in the slice, we can gain a small speed boost
+ # by indexing directly into the submobjects list.
+ stop = r.stop - 1 if (r.step > 0 or r.stop > 0) else None
+ return GroupClass(*self.submobjects[r.start - 1 : stop : r.step])
+
+ return GroupClass(*[self.submobjects[i - 1] if i != 0 else self for i in r])
+
+ index: int = range(len(self))[value] # Normalize the index
+ if self.has_no_points():
+ return self.submobjects[index]
+ return self if index == 0 else self.submobjects[index - 1]
def __iter__(self) -> Iterator[Mobject]:
- return iter(self.split())
+ return it.chain([self] if self.has_points() else [], self.submobjects)
def __len__(self) -> int:
- return len(self.split())
+ return len(self.submobjects) + (1 if self.has_points() else 0)
def get_group_class(self) -> type[Group]:
return Group
diff --git a/manim/mobject/text/tex_mobject.py b/manim/mobject/text/tex_mobject.py
index e4e4865cd..6784cfad0 100644
--- a/manim/mobject/text/tex_mobject.py
+++ b/manim/mobject/text/tex_mobject.py
@@ -588,10 +588,12 @@ class MathTex(SingleStringMathTex):
return self
def index_of_part(self, part: VMobject) -> int:
- split_self = self.split()
- if part not in split_self:
+ index, *_ = next(
+ ((i, mob) for i, mob in enumerate(self) if mob == part), [None]
+ )
+ if index is None:
raise ValueError("Trying to get index of part not in MathTex")
- return split_self.index(part)
+ return index
def sort_alphabetically(self) -> None:
self.submobjects.sort(key=lambda m: m.get_tex_string())
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index 768091ea6..b523028ff 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -13,8 +13,8 @@ __all__ = [
import itertools as it
import sys
-from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
-from typing import TYPE_CHECKING, Any, Literal
+from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping, Sequence
+from typing import TYPE_CHECKING, Any, Literal, cast
import numpy as np
from PIL.Image import Image
@@ -47,7 +47,6 @@ from manim.utils.iterables import (
from manim.utils.space_ops import rotate_vector, shoelace_direction
if TYPE_CHECKING:
- from collections.abc import Iterator
from typing import Self
import numpy.typing as npt
@@ -175,7 +174,7 @@ class VMobject(Mobject):
return self._assert_valid_submobjects_internal(submobjects, VMobject)
def __iter__(self) -> Iterator[VMobject]:
- return iter(self.split())
+ return cast(Iterator[VMobject], super().__iter__())
# OpenGL compatibility
@property
@@ -2330,9 +2329,7 @@ class VGroup(VMobject, metaclass=ConvertToOpenGL):
self.submobjects[key] = value
def __getitem__(self, key: int | slice) -> VMobject:
- if isinstance(key, slice):
- return VGroup(self.submobjects[key])
- return self.submobjects[key]
+ return cast(VMobject, super().__getitem__(key))
class VDict(VMobject, metaclass=ConvertToOpenGL):
diff --git a/tests/module/mobject/mobject/test_mobject.py b/tests/module/mobject/mobject/test_mobject.py
index a7eaee644..051cd30c4 100644
--- a/tests/module/mobject/mobject/test_mobject.py
+++ b/tests/module/mobject/mobject/test_mobject.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from itertools import product
+
import numpy as np
import pytest
@@ -258,3 +260,152 @@ def test_apply_matrix_about_vertex_view():
# The first vertex should remain in the same position (within numerical precision)
transformed_vertices = triangle.get_vertices()
np.testing.assert_allclose(transformed_vertices[0], first_vertex, atol=1e-6)
+
+
+# Tests for methods which provide Mobject's sequence interface
+
+
+def build_mobject(n=10, has_points=False, mob_cls=Mobject):
+ """Construct a mobject (with/without points) with n submobjects, and return it along with its
+ split() result.
+ """
+ mob = mob_cls()
+ mob.add(*[mob_cls() for _ in range(n)])
+ if has_points:
+ mob.points = np.zeros((3, 3))
+ return mob, mob.split()
+
+
[email protected]("has_points", [True, False])
+def test_getitem_single_index(has_points):
+ """Test that indexing a mobject behaves the same as indexing Mobject.split()."""
+ n = 10
+ mob, mob_list = build_mobject(n, has_points=has_points)
+ length = (n + 1) if has_points else n
+ for i in range(-length, length):
+ assert mob[i] == mob_list[i]
+
+ # Check that indexing outside valid range raises IndexError
+ with pytest.raises(IndexError):
+ mob[length]
+ with pytest.raises(IndexError):
+ mob[-length - 1]
+
+
[email protected]("has_points", [True, False])
+def test_getitem_single_index_no_submobjects(has_points):
+ """Test that indexing into a mobject with no submobjects behaves correctly."""
+ mob, _ = build_mobject(0, has_points=has_points)
+ if has_points:
+ assert mob[0] == mob
+ else:
+ with pytest.raises(IndexError):
+ mob[0]
+ with pytest.raises(IndexError):
+ mob[1]
+
+
[email protected]("has_points", [True, False])
+def test_getitem_slice(has_points):
+ """Test that slicing a mobject behaves the same as slicing Mobject.split()."""
+ n = 10
+ mob, mob_list = build_mobject(n, has_points=has_points)
+ length = (n + 1) if has_points else n
+ for start, stop, step in product(range(-length, length), repeat=3):
+ assert mob[start:stop].submobjects == mob_list[start:stop]
+ if step == 0:
+ with pytest.raises(ValueError):
+ mob[start:stop:step]
+ else:
+ assert mob[start:stop:step].submobjects == mob_list[start:stop:step]
+
+ # Check that slicing with too high stop value is possible
+ too_high_index = length * 2
+ assert mob[1:too_high_index].submobjects == mob[1:].submobjects
+ assert mob[1:too_high_index].submobjects == mob_list[1:too_high_index]
+
+ # Check that slicing with too low start value works
+ too_low_index = -(length * 2)
+ assert mob[too_low_index:1].submobjects == mob[:1].submobjects
+ assert mob[too_low_index:1].submobjects == mob_list[too_low_index:1]
+
+
[email protected]("has_points", [True, False])
[email protected]("mob_cls", [Mobject, VMobject])
+def test_getitem_slice_group_type(has_points, mob_cls):
+ """Test that the group created from slicing a mobject has the appropriate type
+ for the type of the mobject.
+ """
+ n = 10
+ mob, _ = build_mobject(n, has_points=has_points, mob_cls=mob_cls)
+ group_cls = mob.get_group_class()
+ length = (n + 1) if has_points else n
+ for start, stop, step in product(range(-length, length), repeat=3):
+ if not step:
+ continue
+ assert type(mob[start:stop:step]) is group_cls
+
+
[email protected]("has_points", [True, False])
+def test_getitem_slice_no_submobjects(has_points):
+ """Test that slicing a mobject with no submobjects behaves correctly."""
+ mob, _ = build_mobject(0, has_points=has_points)
+ expected = [] if not has_points else [mob]
+ assert mob[:].submobjects == expected
+ assert mob[::].submobjects == expected
+ assert mob[:1].submobjects == expected
+ assert mob[::2].submobjects == expected
+
+
[email protected]("has_points", [True, False])
+def test_getitem_index_types(has_points):
+ """Test that __getitem__ accepts anything implementing __index__ and rejects
+ floats, like the list type does.
+ """
+ n = 10
+ mob, mob_list = build_mobject(n, has_points=has_points)
+
+ class Ix:
+ def __index__(self):
+ return 1
+
+ assert mob[0] == mob_list[0]
+ assert mob[True] == mob_list[1]
+ assert mob[np.int64(2)] == mob_list[2] # e.g. mob[np.argmin(...)]
+ assert mob[Ix()] == mob_list[1]
+ with pytest.raises(TypeError):
+ mob[1.5]
+
+ if not has_points:
+ # Indexing into an empty mobject with an invalid type should throw
+ # a TypeError instead of IndexError
+ with pytest.raises(TypeError):
+ mob[1.5]
+
+
[email protected]("has_points", [True, False])
[email protected]("n", [0, 10])
+def test_iter_mobject_unpacking(has_points, n):
+ """Test that unpacking a Mobject behaves correctly."""
+ mob, mob_list = build_mobject(n, has_points=has_points)
+ assert list(mob) == mob_list
+ assert [*mob] == mob_list
+
+
[email protected]("has_points", [True, False])
[email protected]("n", [0, 10])
+def test_iter_mobject_iteration(has_points, n):
+ """Test that iterating over a Mobject behaves the same as iterating over Mobject.split()."""
+ mob, mob_list = build_mobject(n, has_points=has_points)
+ mob_iterator = iter(mob)
+ mob_list_iterator = iter(mob_list)
+ for a, b in zip(mob_iterator, mob_list_iterator, strict=True):
+ assert a == b
+
+
[email protected]("has_points", [True, False])
[email protected]("n", [0, 10])
+def test_len_mobject(has_points, n):
+ """Test that len(mob) behaves the same as len(mob.split())."""
+ mob, mob_list = build_mobject(n, has_points=has_points)
+ assert len(mob) == len(mob_list)