Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Perf: Improve speed and robustness of `Mobject` and `OpenGLMobject` add/remove operations (#4957)

nikolajmunk5bf0c6dc7bb6
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 5d52899c7..0084cb738 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -15,6 +15,7 @@ import sys
import types
import warnings
from collections.abc import Callable, Iterable, Iterator, MutableSet, Sequence
+from contextlib import suppress
from functools import partialmethod, reduce
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
@@ -36,8 +37,12 @@ from ..utils.color import (
interpolate_color,
)
from ..utils.exceptions import MultiAnimationOverrideException
-from ..utils.iterables import list_update, remove_list_redundancies
+from ..utils.iterables import (
+ list_difference_update,
+ remove_list_redundancies,
+)
from ..utils.paths import straight_path
+from ..utils.simple_functions import clip
from ..utils.space_ops import angle_between_vectors, normalize, rotation_matrix
if TYPE_CHECKING:
@@ -474,10 +479,88 @@ class Mobject:
"""
return self
+ def _insert_submobjects(self, index: int, mobjects: Sequence[Mobject]) -> Self:
+ """Common backing implementation for :meth:`add`, :meth:`add_to_back`, and
+ :meth:`insert`.
+
+ Inserts ``mobjects`` into :attr:`submobjects` such that they end up starting
+ at ``index`` (following the semantics of :meth:`list.insert`). Mobjects that
+ are already present are moved to the new position instead of being duplicated.
+ """
+ # TODO: The logic of adding/inserting submobjects is inconsistent with that of
+ # OpenGLMobjects. Mobjects *do* move already-present submobjects if they are
+ # reinserted, and input is deduplicated by keeping the *last* (rightmost)
+ # occurrence of an element, while OpenGLMobjects *don't* move already-present
+ # submobjects and they deduplicate input by keeping the *first* occurrence.
+ # This behavior should be made consistent when technically possible.
+
+ self._assert_valid_submobjects(mobjects)
+
+ if not mobjects:
+ return self
+
+ unique_mobjects = remove_list_redundancies(mobjects)
+ if len(mobjects) != len(unique_mobjects):
+ logger.warning(
+ "Attempted adding some Mobject as a child more than once, "
+ "this is not possible. Repetitions are ignored.",
+ )
+
+ if not self.submobjects:
+ self.submobjects = unique_mobjects
+ return self
+
+ n = len(self.submobjects)
+
+ # Normalize the index to be in the range [0, n] following the semantics of list.insert
+ norm_index = clip(index if index >= 0 else n + index, 0, n)
+
+ # Shortcut for the common case of adding a single mobject
+ if len(unique_mobjects) == 1:
+ mobject = unique_mobjects[0]
+ # If the mobject is already present at or next to the provided index, we
+ # don't need to do anything
+ if any(
+ self.submobjects[j] is mobject
+ for j in (norm_index - 1, norm_index)
+ if 0 <= j < n
+ ):
+ return self
+
+ try:
+ old_index = self.submobjects.index(mobject)
+ except ValueError: # mobject isn't already present
+ self.submobjects.insert(norm_index, mobject)
+ return self
+
+ # Compensate for list shifting after popping
+ new_index = norm_index if norm_index < old_index else norm_index - 1
+ self.submobjects.pop(old_index)
+ self.submobjects.insert(new_index, mobject)
+ return self
+
+ if norm_index >= len(self.submobjects):
+ # Skip one list difference since we're just extending the list
+ self.submobjects = [
+ *list_difference_update(self.submobjects, unique_mobjects),
+ *unique_mobjects,
+ ]
+ else:
+ head = list_difference_update(
+ it.islice(self.submobjects, norm_index), unique_mobjects
+ )
+ tail = list_difference_update(
+ it.islice(self.submobjects, norm_index, None), unique_mobjects
+ )
+
+ self.submobjects = [*head, *unique_mobjects, *tail]
+ return self
+
def add(self, *mobjects: Mobject) -> Self:
"""Add mobjects as submobjects.
- The mobjects are added to :attr:`submobjects`.
+ The mobjects are added to :attr:`submobjects`. If a mobject to be added is
+ already a submobject of ``self``, it will be moved to its new position.
Subclasses of mobject may implement ``+`` and ``+=`` dunder methods.
@@ -498,18 +581,21 @@ class Mobject:
:class:`TypeError`
When trying to add an object that is not an instance of :class:`Mobject`.
-
Notes
-----
A mobject cannot contain itself, and it cannot contain a submobject
- more than once. If the parent mobject is displayed, the newly-added
+ more than once. The ``mobjects`` list will be deduplicated before its contents
+ are added; the last (rightmost) occurrence of a duplicate mobject will be the
+ one that is kept.
+ If the parent mobject is displayed, the newly-added
submobjects will also be displayed (i.e. they are automatically added
to the parent Scene).
See Also
--------
- :meth:`remove`
:meth:`add_to_back`
+ :meth:`insert`
+ :meth:`remove`
Examples
--------
@@ -551,24 +637,23 @@ class Mobject:
[child]
"""
- self._assert_valid_submobjects(mobjects)
- unique_mobjects = remove_list_redundancies(mobjects)
- if len(mobjects) != len(unique_mobjects):
- logger.warning(
- "Attempted adding some Mobject as a child more than once, "
- "this is not possible. Repetitions are ignored.",
- )
+ return self._insert_submobjects(len(self.submobjects), mobjects)
- self.submobjects = list_update(self.submobjects, unique_mobjects)
- return self
+ # TODO: Since the addition of the private _insert_submobjects method, it has been
+ # possible to insert multiple mobjects into the submobjects list at once. In the
+ # future, the signature of `insert` should be changed to:
+ # def insert(
+ # self, index: int, *mobjects: Mobject
+ # ) -> Self:
+ # This can either be done as part of a larger breaking change or as a gradual
+ # change with a period of supporting both argument names and appropriate deprecation
+ # warnings for use of the singular "mobject" keyword.
def insert(self, index: int, mobject: Mobject) -> Self:
- """Inserts a mobject at a specific position into self.submobjects
+ """Inserts a mobject at a specific position into the submobjects list.
- Effectively just calls ``self.submobjects.insert(index, mobject)``,
- where ``self.submobjects`` is a list.
-
- Highly adapted from ``Mobject.add``.
+ If ``mobject`` is already a submobject of ``self``, it will be moved to the new
+ position.
Parameters
----------
@@ -576,10 +661,41 @@ class Mobject:
The index at which
mobject
The mobject to be inserted.
+
+
+ .. note::
+ ``mobject`` will be inserted at position ``index``, but there is no
+ guarantee that this will be its final position in :attr:`submobjects`, since
+ the list will shift if ``mobject`` was already present at a lower index than
+ ``index``.
+
+ Returns
+ -------
+ :class:`Mobject`
+ ``self``
+
+ Raises
+ ------
+ :class:`ValueError`
+ When a mobject tries to add itself.
+ :class:`TypeError`
+ When trying to add an object that is not an instance of :class:`Mobject`.
+
+ Notes
+ -----
+ A mobject cannot contain itself, and it cannot contain a submobject
+ more than once.
+ If the parent mobject is displayed, the newly-added
+ submobject will also be displayed (i.e. it is automatically added
+ to the parent Scene).
+
+ See Also
+ --------
+ :meth:`add`
+ :meth:`add_to_back`
+ :meth:`remove`
"""
- self._assert_valid_submobjects([mobject])
- self.submobjects.insert(index, mobject)
- return self
+ return self._insert_submobjects(index, (mobject,))
def __add__(self, mobject: Mobject) -> Self:
raise NotImplementedError
@@ -590,7 +706,7 @@ class Mobject:
def add_to_back(self, *mobjects: Mobject) -> Self:
"""Add all passed mobjects to the back of the submobjects.
- If :attr:`submobjects` already contains the given mobjects, they just get moved
+ If :attr:`submobjects` already contains any of the given mobjects, they just get moved
to the back instead.
Parameters
@@ -621,24 +737,24 @@ class Mobject:
Notes
-----
A mobject cannot contain itself, and it cannot contain a submobject
- more than once. If the parent mobject is displayed, the newly-added
+ more than once. The ``mobjects`` list will be deduplicated before its contents
+ are added; the last (rightmost) occurrence of a duplicate mobject will be the
+ one that is kept.
+ If the parent mobject is displayed, the newly-added
submobjects will also be displayed (i.e. they are automatically added
to the parent Scene).
See Also
--------
- :meth:`remove`
:meth:`add`
+ :meth:`insert`
+ :meth:`remove`
"""
- self._assert_valid_submobjects(mobjects)
- self.remove(*mobjects)
- # dict.fromkeys() removes duplicates while maintaining order
- self.submobjects = list(dict.fromkeys(mobjects)) + self.submobjects
- return self
+ return self._insert_submobjects(0, mobjects)
def remove(self, *mobjects: Mobject) -> Self:
- """Remove :attr:`submobjects`.
+ """Remove submobjects.
The mobjects are removed from :attr:`submobjects`, if they exist.
@@ -659,9 +775,14 @@ class Mobject:
:meth:`add`
"""
- for mobject in mobjects:
- if mobject in self.submobjects:
- self.submobjects.remove(mobject)
+ if not self.submobjects:
+ return self
+
+ if len(mobjects) == 1:
+ with suppress(ValueError):
+ self.submobjects.remove(mobjects[0])
+ return self
+ self.submobjects = list_difference_update(self.submobjects, mobjects)
return self
def __sub__(self, other: Mobject) -> Self:
@@ -1122,8 +1243,7 @@ class Mobject:
:meth:`get_updaters`
"""
- while update_function in self.updaters:
- self.updaters.remove(update_function)
+ self.updaters = list_difference_update(self.updaters, [update_function])
return self
def clear_updaters(self, recursive: bool = True) -> Self:
@@ -2410,7 +2530,7 @@ class Mobject:
return Group(
*(
template.copy().pointwise_become_partial(self, a1, a2)
- for a1, a2 in zip(alphas[:-1], alphas[1:], strict=True)
+ for a1, a2 in it.pairwise(alphas)
)
)
@@ -2629,7 +2749,7 @@ class Mobject:
x = VGroup(s1, s2, s3, s4).set_x(0).arrange(buff=1.0)
self.add(x)
"""
- for m1, m2 in zip(self.submobjects[:-1], self.submobjects[1:], strict=True):
+ for m1, m2 in it.pairwise(self.submobjects):
m2.next_to(m1, direction, buff, **kwargs)
if center:
self.center()
diff --git a/manim/mobject/opengl/opengl_mobject.py b/manim/mobject/opengl/opengl_mobject.py
index a99b6aff2..b8e33da41 100644
--- a/manim/mobject/opengl/opengl_mobject.py
+++ b/manim/mobject/opengl/opengl_mobject.py
@@ -8,6 +8,7 @@ import sys
import types
import warnings
from collections.abc import Callable, Iterable, Iterator, Sequence
+from contextlib import suppress
from functools import partialmethod, wraps
from math import ceil
from typing import (
@@ -54,7 +55,7 @@ from manim.utils.config_ops import _Data, _Uniforms
# from ..utils.iterables import batch_by_property
from manim.utils.iterables import (
batch_by_property,
- list_update,
+ list_difference_update,
listify,
make_even,
resize_array,
@@ -823,10 +824,90 @@ class OpenGLMobject:
def family_members_with_points(self) -> Sequence[OpenGLMobject]:
return [m for m in self.get_family() if m.has_points()]
+ def _update_new_children(self, mobjects: Iterable[OpenGLMobject]) -> Self:
+ for mob in mobjects:
+ if self not in mob.parents:
+ mob.parents.append(self)
+ self.assemble_family()
+ return self
+
+ def _insert_submobjects(
+ self,
+ index: int,
+ mobjects: Sequence[OpenGLMobject],
+ update_parent: bool,
+ ) -> Self:
+ """Common backing implementation for :meth:`add`, :meth:`add_to_back`, and
+ :meth:`insert`.
+
+ Inserts ``mobjects`` into :attr:`submobjects` such that they end up starting
+ at ``index`` (following the semantics of :meth:`list.insert`). Mobjects which
+ are already present in :attr:`submobjects` will be ignored and therefore keep
+ their current position.
+ """
+ # TODO: The logic of adding/inserting submobjects is inconsistent with that of
+ # Mobjects. OpenGLMobjects *do not* move already-present submobjects if they are
+ # reinserted, and input is deduplicated by keeping the *first* (leftmost)
+ # occurrence of an element, while Mobjects *do* move already-present submobjects
+ # and they deduplicate input by keeping the *last* occurrence.
+ # This behavior should be made consistent when technically possible.
+
+ if update_parent:
+ assert len(mobjects) == 1, "Can't set multiple parents."
+ mobjects[0].parent = self
+
+ self._assert_valid_submobjects(mobjects)
+
+ unique_mobjects = dict.fromkeys(mobjects)
+ if len(mobjects) != len(unique_mobjects):
+ logger.warning(
+ "Attempted adding some Mobject as a child more than once, "
+ "this is not possible. Repetitions are ignored.",
+ )
+
+ if not self._submobjects:
+ self._submobjects = list(unique_mobjects)
+ self._update_new_children(self._submobjects)
+ return self
+
+ # Shortcut for the common case of adding a single mobject
+ if len(unique_mobjects) == 1:
+ mob = unique_mobjects.popitem()[0]
+ if mob not in self._submobjects:
+ if index >= len(self._submobjects):
+ self._submobjects.append(mob)
+ else:
+ self._submobjects.insert(index, mob)
+ self._update_new_children([mob])
+ return self
+
+ # Remove already-present submobjects from input
+ for mob in self._submobjects:
+ if not unique_mobjects:
+ break
+ if mob in unique_mobjects:
+ unique_mobjects.pop(mob)
+
+ if not unique_mobjects: # No new mobjects to add
+ return self
+
+ if index >= len(self._submobjects):
+ # If we can just extend with the new mobjects, that is much faster than
+ # concatenating.
+ self._submobjects.extend(unique_mobjects)
+ else:
+ head = it.islice(self._submobjects, index)
+ tail = it.islice(self._submobjects, index, None)
+ # Skip the setter of self.submobjects
+ self._submobjects = [*head, *unique_mobjects, *tail]
+ self._update_new_children(unique_mobjects)
+ return self
+
def add(self, *mobjects: OpenGLMobject, update_parent: bool = False) -> Self:
"""Add mobjects as submobjects.
- The mobjects are added to :attr:`submobjects`.
+ The mobjects are added to :attr:`submobjects`. Any mobject in ``mobjects`` which
+ is already present in :attr:`submobjects` will keep its current position.
Subclasses of mobject may implement ``+`` and ``+=`` dunder methods.
@@ -851,14 +932,15 @@ class OpenGLMobject:
Notes
-----
A mobject cannot contain itself, and it cannot contain a submobject
- more than once. If the parent mobject is displayed, the newly-added
- submobjects will also be displayed (i.e. they are automatically added
- to the parent Scene).
+ more than once. The ``mobjects`` list will be deduplicated before its contents
+ are added; the first (leftmost) occurrence of a duplicate mobject will be the
+ one that is kept.
See Also
--------
- :meth:`remove`
:meth:`add_to_back`
+ :meth:`insert`
+ :meth:`remove`
Examples
--------
@@ -889,34 +971,24 @@ class OpenGLMobject:
ValueError: Cannot add OpenGLMobject as a submobject of itself (at index 0).
"""
- if update_parent:
- assert len(mobjects) == 1, "Can't set multiple parents."
- mobjects[0].parent = self
-
- self._assert_valid_submobjects(mobjects)
-
- if any(mobjects.count(elem) > 1 for elem in mobjects):
- logger.warning(
- "Attempted adding some Mobject as a child more than once, "
- "this is not possible. Repetitions are ignored.",
- )
- for mobject in mobjects:
- if mobject not in self.submobjects:
- self.submobjects.append(mobject)
- if self not in mobject.parents:
- mobject.parents.append(self)
- self.assemble_family()
- return self
+ return self._insert_submobjects(len(self.submobjects), mobjects, update_parent)
+
+ # TODO: Since the addition of the private _insert_submobjects method, it has been
+ # possible to insert multiple mobjects into the submobjects list at once. In the
+ # future, the signature of `insert` should be changed to:
+ # def insert(
+ # self, index: int, *mobjects: OpenGLMobject, update_parent: bool = False
+ # ) -> Self:
+ # This can either be done as part of a larger breaking change or as a gradual
+ # change with a period of supporting both argument names and appropriate deprecation
+ # warnings for use of the singular "mobject" keyword.
+ # The same should be done for Mobject.insert.
def insert(
self, index: int, mobject: OpenGLMobject, update_parent: bool = False
) -> Self:
- """Inserts a mobject at a specific position into self.submobjects
-
- Effectively just calls ``self.submobjects.insert(index, mobject)``,
- where ``self.submobjects`` is a list.
-
- Highly adapted from ``OpenGLMobject.add``.
+ """Inserts a mobject at a specific position into ``self.submobjects``. If the
+ mobject is already a submobject of ``self``, its position does not change.
Parameters
----------
@@ -927,19 +999,7 @@ class OpenGLMobject:
update_parent
Whether or not to set ``mobject.parent`` to ``self``.
"""
- if update_parent:
- mobject.parent = self
-
- self._assert_valid_submobjects([mobject])
-
- if mobject not in self.submobjects:
- self.submobjects.insert(index, mobject)
-
- if self not in mobject.parents:
- mobject.parents.append(self)
-
- self.assemble_family()
- return self
+ return self._insert_submobjects(index, [mobject], update_parent)
def remove(self, *mobjects: OpenGLMobject, update_parent: bool = False) -> Self:
"""Remove :attr:`submobjects`.
@@ -967,20 +1027,29 @@ class OpenGLMobject:
assert len(mobjects) == 1, "Can't remove multiple parents."
mobjects[0].parent = None
- for mobject in mobjects:
- if mobject in self.submobjects:
- self.submobjects.remove(mobject)
- if self in mobject.parents:
- mobject.parents.remove(self)
- self.assemble_family()
+ if not self.submobjects:
+ return self
+
+ n = len(self.submobjects)
+ if len(mobjects) == 1:
+ with suppress(ValueError):
+ self.submobjects.remove(mobjects[0])
+ else:
+ self._submobjects = list_difference_update(self._submobjects, mobjects)
+
+ if len(self.submobjects) != n:
+ for mobject in mobjects:
+ with suppress(ValueError):
+ mobject.parents.remove(self)
+
+ self.assemble_family()
return self
def add_to_back(self, *mobjects: OpenGLMobject) -> Self:
- # NOTE: is the note true OpenGLMobjects?
"""Add all passed mobjects to the back of the submobjects.
- If :attr:`submobjects` already contains the given mobjects, they just get moved
- to the back instead.
+ Any mobject in ``mobject`` which is already present in :attr:`submobjects`
+ is not moved.
Parameters
----------
@@ -995,7 +1064,7 @@ class OpenGLMobject:
.. note::
- Technically, this is done by adding (or moving) the mobjects to
+ Technically, this is done by adding the mobjects to
the head of :attr:`submobjects`. The head of this list is rendered
first, which places the corresponding mobjects behind the
subsequent list members.
@@ -1010,26 +1079,46 @@ class OpenGLMobject:
Notes
-----
A mobject cannot contain itself, and it cannot contain a submobject
- more than once. If the parent mobject is displayed, the newly-added
- submobjects will also be displayed (i.e. they are automatically added
- to the parent Scene).
+ more than once. The ``mobjects`` list will be deduplicated before its contents
+ are added; the first (leftmost) occurrence of a duplicate mobject will be the
+ one that is kept.
See Also
--------
- :meth:`remove`
:meth:`add`
+ :meth:`insert`
+ :meth:`remove`
"""
- self._assert_valid_submobjects(mobjects)
- self.submobjects = list_update(mobjects, self.submobjects)
- return self
+ return self._insert_submobjects(0, mobjects, update_parent=False)
def replace_submobject(self, index: int, new_submob: OpenGLMobject) -> Self:
+ """Replaces the submobject at the given index with a new submobject.
+ If ``self.submobjects`` already contains the new submobject, it is also removed
+ from its previous position.
+
+ Parameters
+ ----------
+ index
+ The index of the submobject to replace.
+ new_submob
+ The new submobject to insert at the given index.
+ """
self._assert_valid_submobjects([new_submob])
old_submob = self.submobjects[index]
- if self in old_submob.parents:
- old_submob.parents.remove(self)
+ if old_submob == new_submob:
+ return self
+
+ existing_index = None
+ with suppress(ValueError):
+ existing_index = self.submobjects.index(new_submob)
self.submobjects[index] = new_submob
+ if existing_index is not None:
+ self.submobjects.pop(existing_index)
+
+ with suppress(ValueError):
+ old_submob.parents.remove(self)
+ self._update_new_children([new_submob])
self.assemble_family()
return self
@@ -1058,7 +1147,7 @@ class OpenGLMobject:
x = OpenGLVGroup(s1, s2, s3, s4).set_x(0).arrange(buff=1.0)
self.add(x)
"""
- for m1, m2 in zip(self.submobjects[:-1], self.submobjects[1:], strict=True):
+ for m1, m2 in it.pairwise(self.submobjects):
m2.next_to(m1, direction, **kwargs)
if center:
self.center()
@@ -1573,10 +1662,12 @@ class OpenGLMobject:
return self
def remove_updater(self, update_function: _Updater) -> Self:
- for updater_list in [self.time_based_updaters, self.non_time_updaters]:
- updater_list = cast("list[_Updater]", updater_list)
- while update_function in updater_list:
- updater_list.remove(update_function)
+ self.time_based_updaters = list_difference_update(
+ self.time_based_updaters, [update_function]
+ )
+ self.non_time_updaters = list_difference_update(
+ self.non_time_updaters, [update_function]
+ )
self.refresh_has_updater_status()
return self
@@ -2489,7 +2580,7 @@ class OpenGLMobject:
return OpenGLGroup(
*(
template.copy().pointwise_become_partial(self, a1, a2)
- for a1, a2 in zip(alphas[:-1], alphas[1:], strict=True)
+ for a1, a2 in it.pairwise(alphas)
)
)
diff --git a/manim/mobject/opengl/opengl_vectorized_mobject.py b/manim/mobject/opengl/opengl_vectorized_mobject.py
index ea1c289d3..cc1756d19 100644
--- a/manim/mobject/opengl/opengl_vectorized_mobject.py
+++ b/manim/mobject/opengl/opengl_vectorized_mobject.py
@@ -588,7 +588,7 @@ class OpenGLVMobject(OpenGLMobject):
new_points.extend(
[
partial_bezier_points(tup, a1, a2)
- for a1, a2 in zip(alphas[:-1], alphas[1:], strict=True)
+ for a1, a2 in it.pairwise(alphas)
],
)
else:
@@ -776,9 +776,7 @@ class OpenGLVMobject(OpenGLMobject):
# )
split_indices = [0, *split_indices, len(points)]
return [
- points[i1:i2]
- for i1, i2 in zip(split_indices[:-1], split_indices[1:], strict=True)
- if (i2 - i1) >= nppc
+ points[i1:i2] for i1, i2 in it.pairwise(split_indices) if (i2 - i1) >= nppc
]
def get_subpaths(self):
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index 8d0526853..a7bb5ac4f 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -1372,9 +1372,7 @@ class VMobject(Mobject):
filtered = filter(filter_func, range(nppcc, len(points), nppcc))
split_indices = [0] + list(filtered) + [len(points)]
return (
- points[i1:i2]
- for i1, i2 in zip(split_indices[:-1], split_indices[1:], strict=True)
- if (i2 - i1) >= nppcc
+ points[i1:i2] for i1, i2 in it.pairwise(split_indices) if (i2 - i1) >= nppcc
)
def get_subpaths_from_points(self, points: CubicBezierPath) -> list[CubicSpline]:
diff --git a/manim/utils/iterables.py b/manim/utils/iterables.py
index cdd41e59d..66708353a 100644
--- a/manim/utils/iterables.py
+++ b/manim/utils/iterables.py
@@ -28,7 +28,7 @@ from collections.abc import (
Reversible,
Sequence,
)
-from typing import TYPE_CHECKING, TypeVar, overload
+from typing import TYPE_CHECKING, TypeVar, cast, overload
import numpy as np
@@ -133,7 +133,7 @@ def concatenate_lists(*list_of_lists: Iterable[T]) -> list[T]:
return [item for lst in list_of_lists for item in lst]
-def list_difference_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]:
+def list_difference_update(l1: Iterable[T], l2: Iterable[U]) -> list[T]:
"""Returns a list containing all the elements of l1 not in l2.
Examples
@@ -147,7 +147,7 @@ def list_difference_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]:
return [e for e in l1 if e not in l2]
-def list_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]:
+def list_update(l1: Iterable[T], l2: Iterable[U]) -> list[T | U]:
"""Used instead of ``set.update()`` to maintain order,
making sure duplicates are removed from l1, not l2.
Removes overlap of l1 and l2 and then concatenates l2 unchanged.
@@ -160,7 +160,7 @@ def list_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]:
[1, 3, 2, 4, 4]
"""
l2 = list(l2)
- return list_difference_update(l1, l2) + l2
+ return list_difference_update(l1, l2) + cast(list[T | U], l2)
@overload
diff --git a/tests/module/mobject/mobject/test_mobject.py b/tests/module/mobject/mobject/test_mobject.py
index 051cd30c4..b4f3e371b 100644
--- a/tests/module/mobject/mobject/test_mobject.py
+++ b/tests/module/mobject/mobject/test_mobject.py
@@ -26,11 +26,13 @@ def test_mobject_add():
"""Call this function with a Container instance to test its add() method."""
# check that obj.submobjects is updated correctly
obj = Mobject()
- assert len(obj.submobjects) == 0
- obj.add(Mobject())
- assert len(obj.submobjects) == 1
- obj.add(*(Mobject() for _ in range(10)))
- assert len(obj.submobjects) == 11
+ assert obj.submobjects == []
+ child = Mobject()
+ obj.add(child)
+ assert obj.submobjects == [child]
+ new_mobjects = [Mobject() for _ in range(10)]
+ obj.add(*new_mobjects)
+ assert obj.submobjects == [child] + new_mobjects
# check that adding a mobject twice does not actually add it twice
repeated = Mobject()
@@ -39,10 +41,20 @@ def test_mobject_add():
obj.add(repeated)
assert len(obj.submobjects) == 12
+ # check that adding already existing mobjects moves them to the end of the list
+ obj.add(*reversed(new_mobjects))
+ assert obj.submobjects == [child, repeated] + list(reversed(new_mobjects))
+
# check that Mobject.add() returns the Mobject (for chained calls)
assert obj.add(Mobject()) is obj
assert len(obj.submobjects) == 13
+ obj = Mobject()
+ # check that inserting duplicate mobjects keeps the last occurrence
+ m1, m2 = Mobject(), Mobject()
+ obj.add(m1, m2, m1)
+ assert obj.submobjects == [m2, m1]
+
obj = Mobject()
# a Mobject cannot contain itself
@@ -78,6 +90,86 @@ def test_mobject_remove():
assert obj.remove(Mobject()) is obj
+def test_mobject_insert():
+ obj = Mobject()
+ m1, m2, m3, m4 = [Mobject(name=f"m{i}") for i in range(1, 5)]
+ # Insert into empty list
+ obj.insert(0, m1)
+ assert obj.submobjects == [m1]
+
+ # Inserting shifts existing mobjects to the right
+ obj.insert(0, m2)
+ assert obj.submobjects == [m2, m1]
+
+ # Inserting with negative index inserts counting from the end like a list
+ obj.insert(-1, m3)
+ assert obj.submobjects == [m2, m3, m1]
+
+ # Inserting with index greater than length appends
+ obj.insert(10, m4)
+ assert obj.submobjects == [m2, m3, m1, m4]
+
+ # Inserting an existing submobject moves it to the new position
+ obj.insert(4, m1)
+ assert obj.submobjects == [m2, m3, m4, m1]
+
+ # Inserting an existing submobject at or immediately next to its current position
+ # does not change the order
+ obj.insert(3, m1)
+ assert obj.submobjects == [m2, m3, m4, m1]
+ obj.insert(3, m4)
+ assert obj.submobjects == [m2, m3, m4, m1]
+
+ # can only insert Mobjects
+ with pytest.raises(TypeError) as add_str_info:
+ obj.insert(1, "foo")
+ assert str(add_str_info.value) == (
+ "Only values of type Mobject can be added as submobjects of Mobject, "
+ "but the value foo (at index 0) is of type str."
+ )
+
+
+def test_mobject_add_to_back():
+ obj = Mobject()
+ m1, m2, m3, m4 = [Mobject(name=f"m{i}") for i in range(1, 5)]
+
+ # Adding to empty list is the same as adding normally
+ obj.add_to_back(m1)
+ assert obj.submobjects == [m1]
+
+ # Adding a new submobject adds it to the back
+ obj.add_to_back(m2)
+ assert obj.submobjects == [m2, m1]
+
+ # Adding existing submobjects that are already at the back does not change the order
+ obj.add_to_back(m1)
+ assert obj.submobjects == [m1, m2]
+ obj.add_to_back(m1, m2)
+ assert obj.submobjects == [m1, m2]
+
+ # Adding an existing submobject moves it to the back
+ obj.add_to_back(m2)
+ assert obj.submobjects == [m2, m1]
+
+ # In case of duplicates, the last occurrence of a submobject is kept
+ obj.add_to_back(m3, m1, m3)
+ assert obj.submobjects == [m1, m3, m2]
+
+ # The order of the non-prepended submobjects is preserved
+ obj.remove(*obj.submobjects)
+ obj.add(m1, m2, m3, m4)
+ obj.add_to_back(m2, m4)
+ assert obj.submobjects == [m2, m4, m1, m3]
+
+ # can only add Mobjects
+ with pytest.raises(TypeError) as add_str_info:
+ obj.add_to_back("foo")
+ assert str(add_str_info.value) == (
+ "Only values of type Mobject can be added as submobjects of Mobject, "
+ "but the value foo (at index 0) is of type str."
+ )
+
+
def test_mobject_dimensions_single_mobject():
# A Mobject with no points and no submobjects has no dimensions
empty = Mobject()
diff --git a/tests/opengl/test_family_opengl.py b/tests/opengl/test_family_opengl.py
index f16d0e475..3ed9ba353 100644
--- a/tests/opengl/test_family_opengl.py
+++ b/tests/opengl/test_family_opengl.py
@@ -91,3 +91,169 @@ def test_shift_family(using_opengl_renderer):
for m in family:
np.testing.assert_allclose(positions_before[m] + RIGHT, positions_after[m])
+
+
+def test_opengl_mobject_family_updated_on_change(using_opengl_renderer):
+ """Test that the family of an OpenGLMobject is updated correctly when submobjects
+ are added or removed, and that the family is not updated if no changes are made.
+ """
+ # This is based on the assumption that obj.family is replaced with a new list when submobjects
+ # are added or removed. If this implementation detail changes, this test may need to be updated.
+ obj = OpenGLMobject()
+ family = obj.get_family()
+ assert family == [obj]
+ submobs = [OpenGLMobject() for _ in range(10)]
+
+ # Add new submobjects; family should be updated.
+ obj.add(*submobs)
+ assert family is not obj.get_family()
+ family = obj.get_family()
+ assert len(family) == 11
+ for submob in submobs:
+ assert submob in family
+
+ # Remove a submobject; family should be updated.
+ obj.remove(submobs[0])
+ family = obj.get_family()
+ assert len(family) == 10
+ assert submobs[0] not in family
+
+ # Remove a submobject that is not in the family; family should not be updated.
+ obj.remove(OpenGLMobject())
+ assert family is obj.get_family()
+
+ # Add a submobject that is already in the family; family should not be updated.
+ obj.add(submobs[1])
+ assert family is obj.get_family()
+
+ # Add a mix of new and existing submobjects; family should be updated.
+ obj.add(OpenGLMobject(), submobs[2])
+ assert family is not obj.get_family()
+ family = obj.get_family()
+ assert len(family) == 11
+
+ # Remove a mix of existing and non-existing submobjects; family should be updated.
+ obj.remove(submobs[3], OpenGLMobject())
+ assert family is not obj.get_family()
+
+
+def test_opengl_mobject_add_updates_parents(using_opengl_renderer):
+ """Test that the parents of an OpenGLMobject are updated correctly when they are added to
+ another OpenGLMobject.
+ """
+ parent = OpenGLMobject(name="parent")
+ child, child2, child3 = [OpenGLMobject(name=f"child_{i}") for i in range(3)]
+
+ # Initially, the child has no parent.
+ assert child.parents == []
+
+ # Add the child to the parent; the child's parent should be updated.
+ parent.add(child)
+ assert child.parents == [parent]
+
+ # Add the child to another parent; the child's parent should be updated.
+ new_parent = OpenGLMobject()
+ new_parent.add(child)
+ for p in parent, new_parent:
+ assert p in child.parents
+
+ # Add a child multiple times to the same parent; the child's parent should not
+ # be duplicated.
+ parent.remove(*parent.submobjects)
+ parent.add(child2)
+ parent.add(child2)
+ assert child2.parents == [parent]
+
+
+def test_opengl_mobject_remove_updates_parents(using_opengl_renderer):
+ """Test that the parents of an OpenGLMobject are updated correctly when they are removed from
+ another OpenGLMobject.
+ """
+ parent = OpenGLMobject(name="parent")
+ child, child2, child3 = [OpenGLMobject(name=f"child_{i}") for i in range(3)]
+
+ parent.add(child)
+
+ # Remove the child from the parent; the child's parent should be updated.
+ parent.remove(child)
+ assert child.parents == []
+
+ # Remove a child with multiple parents
+ new_parent = OpenGLMobject()
+ parent.add(child)
+ new_parent.add(child)
+ parent.remove(child)
+ assert child.parents == [new_parent]
+ assert parent not in child.parents
+
+ # Remove a child that is not in the parent; the child's parent should not be updated.
+ parent.remove(child2)
+ assert child2.parents == []
+
+ # Remove the child from the new parent; the child's parent should be updated.
+ new_parent.remove(child)
+ assert new_parent not in child.parents
+
+ # Remove a mix of existing and non-existing children; the existing child's parent should be
+ # updated correctly.
+ parent.add(child)
+ assert child.parents == [parent]
+ parent.remove(child2, child, child3)
+ for c in [child, child2, child3]:
+ assert parent not in c.parents
+
+
+def test_opengl_mobject_replace_submobject_updates_parents(using_opengl_renderer):
+ """Test that replace_submobject() updates the parents of both the removed
+ and inserted submobjects correctly.
+ """
+ parent = OpenGLMobject()
+ old_submob = OpenGLMobject()
+ new_submob = OpenGLMobject()
+ parent.add(old_submob)
+
+ parent.replace_submobject(0, new_submob)
+
+ assert parent not in old_submob.parents
+ assert new_submob.parents == [parent]
+
+ # Inserting the same mobject again should not affect the parent list
+ parent.add(OpenGLMobject())
+ parent.replace_submobject(1, new_submob)
+ assert new_submob.parents == [parent]
+
+
+def test_opengl_mobject_insert_updates_parents(using_opengl_renderer):
+ """Test that insert() updates the parents of the inserted submobjects correctly."""
+ parent = OpenGLMobject()
+ submob1 = OpenGLMobject()
+ submob2 = OpenGLMobject()
+
+ parent.insert(0, submob1)
+ assert submob1.parents == [parent]
+
+ parent.insert(1, submob2)
+ assert submob1.parents == [parent]
+ assert submob2.parents == [parent]
+
+ # Inserting an existing submobject should not affect the parent list
+ parent.insert(0, submob1)
+ assert submob1.parents == [parent]
+
+
+def test_opengl_mobject_add_to_back_updates_parents(using_opengl_renderer):
+ """Test that add_to_back() updates the parents of the added submobjects correctly."""
+ parent = OpenGLMobject()
+ submob1 = OpenGLMobject()
+ submob2 = OpenGLMobject()
+
+ parent.add_to_back(submob1)
+ assert submob1.parents == [parent]
+
+ parent.add_to_back(submob2)
+ assert submob1.parents == [parent]
+ assert submob2.parents == [parent]
+
+ # Adding an existing submobject should not affect the parent list
+ parent.add_to_back(submob1)
+ assert submob1.parents == [parent]
diff --git a/tests/opengl/test_opengl_mobject.py b/tests/opengl/test_opengl_mobject.py
index 947448f4c..9a8c1d9e2 100644
--- a/tests/opengl/test_opengl_mobject.py
+++ b/tests/opengl/test_opengl_mobject.py
@@ -13,11 +13,13 @@ def test_opengl_mobject_add(using_opengl_renderer):
"""Call this function with a Container instance to test its add() method."""
# check that obj.submobjects is updated correctly
obj = OpenGLMobject()
- assert len(obj.submobjects) == 0
- obj.add(OpenGLMobject())
- assert len(obj.submobjects) == 1
- obj.add(*(OpenGLMobject() for _ in range(10)))
- assert len(obj.submobjects) == 11
+ assert obj.submobjects == []
+ child = OpenGLMobject()
+ obj.add(child)
+ assert obj.submobjects == [child]
+ new_mobjects = [OpenGLMobject() for _ in range(10)]
+ obj.add(*new_mobjects)
+ assert obj.submobjects == [child] + new_mobjects
# check that adding a OpenGLMobject twice does not actually add it twice
repeated = OpenGLMobject()
@@ -26,10 +28,20 @@ def test_opengl_mobject_add(using_opengl_renderer):
obj.add(repeated)
assert len(obj.submobjects) == 12
+ # check that adding already existing mobjects doesn't affect order
+ obj.add(*reversed(new_mobjects))
+ assert obj.submobjects == [child] + new_mobjects + [repeated]
+
# check that OpenGLMobject.add() returns the OpenGLMobject (for chained calls)
assert obj.add(OpenGLMobject()) is obj
assert len(obj.submobjects) == 13
+ obj = OpenGLMobject()
+ # check that inserting duplicate mobjects keeps the first occurrence
+ m1, m2 = OpenGLMobject(), OpenGLMobject()
+ obj.add(m1, m2, m1)
+ assert obj.submobjects == [m1, m2]
+
obj = OpenGLMobject()
# an OpenGLMobject cannot contain itself
@@ -50,6 +62,76 @@ def test_opengl_mobject_add(using_opengl_renderer):
assert len(obj.submobjects) == 0
+def test_opengl_mobject_insert(using_opengl_renderer):
+ obj = OpenGLMobject()
+ m1, m2, m3, m4 = [OpenGLMobject(name=f"m{i}") for i in range(1, 5)]
+ # Insert into empty list
+ obj.insert(0, m1)
+ assert obj.submobjects == [m1]
+
+ # Inserting shifts existing submobjects to the right
+ obj.insert(0, m2)
+ assert obj.submobjects == [m2, m1]
+
+ # Inserting with negative index inserts counting from the end like a list
+ obj.insert(-1, m3)
+ assert obj.submobjects == [m2, m3, m1]
+
+ # Inserting with index greater than length appends
+ obj.insert(10, m4)
+ assert obj.submobjects == [m2, m3, m1, m4]
+
+ # Inserting an existing submobject does nothing
+ for i in range(len(obj.submobjects) + 1):
+ obj.insert(i, m3)
+ assert obj.submobjects == [m2, m3, m1, m4]
+
+ # obj cannot insert itself
+ with pytest.raises(ValueError) as insert_self_info:
+ obj.insert(0, obj)
+ assert str(insert_self_info.value) == (
+ "Cannot add OpenGLMobject as a submobject of itself (at index 0)."
+ )
+
+ # can only add Mobjects
+ with pytest.raises(TypeError) as insert_str_info:
+ obj.insert(0, "foo")
+ assert str(insert_str_info.value) == (
+ "Only values of type OpenGLMobject can be added as submobjects of "
+ "OpenGLMobject, but the value foo (at index 0) is of type str."
+ )
+
+
+def test_opengl_mobject_add_to_back(using_opengl_renderer):
+ obj = OpenGLMobject()
+ m1, m2, m3, m4 = [OpenGLMobject(name=f"m{i}") for i in range(1, 5)]
+
+ # Adding to empty list is the same as adding normally
+ obj.add_to_back(m1)
+ assert obj.submobjects == [m1]
+
+ # Adding a new submobject adds it to the back
+ obj.add_to_back(m2)
+ assert obj.submobjects == [m2, m1]
+
+ # In case of duplicate input, the first occurrence of a submobject is kept
+ obj.add_to_back(m3, m4, m3)
+ assert obj.submobjects == [m3, m4, m2, m1]
+
+ # Adding an existing submobject does nothing
+ for mob in obj.submobjects:
+ obj.add_to_back(mob)
+ assert obj.submobjects == [m3, m4, m2, m1]
+
+ # can only add Mobjects
+ with pytest.raises(TypeError) as add_str_info:
+ obj.add_to_back("foo")
+ assert str(add_str_info.value) == (
+ "Only values of type OpenGLMobject can be added as submobjects of "
+ "OpenGLMobject, but the value foo (at index 0) is of type str."
+ )
+
+
def test_opengl_mobject_remove(using_opengl_renderer):
"""Test OpenGLMobject.remove()."""
obj = OpenGLMobject()
@@ -106,3 +188,31 @@ def test_opengl_rotate_about_vertex_view(using_opengl_renderer):
# The first vertex should remain in the same position (within numerical precision)
rotated_vertices = triangle.get_vertices()
np.testing.assert_allclose(rotated_vertices[0], first_vertex, atol=1e-6)
+
+
+def test_replace_submobject(using_opengl_renderer):
+ """Test that replace_submobject() puts the new submobject in the correct
+ place and removes the old one.
+ """
+ parent = OpenGLMobject()
+ old_submobs = [OpenGLMobject() for _ in range(3)]
+ parent.add(*old_submobs)
+ new_submob = OpenGLMobject()
+
+ parent.replace_submobject(1, new_submob)
+
+ assert parent.submobjects == [old_submobs[0], new_submob, old_submobs[2]]
+ assert old_submobs[1] not in parent.submobjects
+
+
+def test_replace_submobject_with_existing_submobject(using_opengl_renderer):
+ """Test that replacing with a submobject that is already present moves it
+ to the new index instead of duplicating it.
+ """
+ parent = OpenGLMobject()
+ submobs = [OpenGLMobject() for _ in range(3)]
+ parent.add(*submobs)
+
+ parent.replace_submobject(0, submobs[2])
+
+ assert parent.submobjects == [submobs[2], submobs[1]]