Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Type Annotations: Fixing errors showing up in static type checking tool mypy (#1241)

Arona24c26c878e8
diff --git a/manim/animation/animation.py b/manim/animation/animation.py
index cd85ab843..001f8ec25 100644
--- a/manim/animation/animation.py
+++ b/manim/animation/animation.py
@@ -4,13 +4,10 @@
__all__ = ["Animation", "Wait"]
-import typing
from copy import deepcopy
-from typing import Union
+from typing import TYPE_CHECKING, Callable, Iterable, Optional, Tuple, Union
-import numpy as np
-
-if typing.TYPE_CHECKING:
+if TYPE_CHECKING:
from manim.scene.scene import Scene
from .. import logger
@@ -26,7 +23,7 @@ DEFAULT_ANIMATION_LAG_RATIO: float = 0.0
class Animation:
def __init__(
self,
- mobject: Mobject,
+ mobject: Union[Mobject, None],
# If lag_ratio is 0, the animation is applied to all submobjects
# at the same time
# If 1, it is applied to each successively.
@@ -34,21 +31,21 @@ class Animation:
# with lagged start times
lag_ratio: float = DEFAULT_ANIMATION_LAG_RATIO,
run_time: float = DEFAULT_ANIMATION_RUN_TIME,
- rate_func: typing.Callable[[float, float], np.ndarray] = smooth,
+ rate_func: Callable[[float], float] = smooth,
name: str = None,
remover: bool = False, # remove a mobject from the screen?
suspend_mobject_updating: bool = True,
**kwargs,
) -> None:
self._typecheck_input(mobject)
- self.run_time = run_time
- self.rate_func = rate_func
- self.name = name
- self.remover = remover
- self.suspend_mobject_updating = suspend_mobject_updating
- self.lag_ratio = lag_ratio
- self.starting_mobject = None
- self.mobject = mobject
+ self.run_time: float = run_time
+ self.rate_func: Callable[[float], float] = rate_func
+ self.name: Optional[str] = name
+ self.remover: bool = remover
+ self.suspend_mobject_updating: bool = suspend_mobject_updating
+ self.lag_ratio: float = lag_ratio
+ self.starting_mobject: Mobject = Mobject()
+ self.mobject: Mobject = mobject if mobject is not None else Mobject()
if kwargs:
logger.debug("Animation received extra kwargs: %s", kwargs)
@@ -60,9 +57,9 @@ class Animation:
)
)
- def _typecheck_input(self, mobject: Mobject) -> None:
+ def _typecheck_input(self, mobject: Union[Mobject, None]) -> None:
if mobject is None:
- logger.debug("creating dummy animation")
+ logger.debug("Animation with empty mobject")
elif not isinstance(mobject, Mobject) and not isinstance(
mobject, OpenGLMobject
):
@@ -94,7 +91,7 @@ class Animation:
def finish(self) -> None:
self.interpolate(1)
- if self.suspend_mobject_updating:
+ if self.suspend_mobject_updating and self.mobject is not None:
self.mobject.resume_updating()
def clean_up_from_scene(self, scene: "Scene") -> None:
@@ -105,13 +102,13 @@ class Animation:
# Keep track of where the mobject starts
return self.mobject.copy()
- def get_all_mobjects(self) -> typing.Tuple[Mobject, typing.Union[Mobject, None]]:
+ def get_all_mobjects(self) -> Tuple[Mobject, Mobject]:
"""
Ordering must match the ordering of arguments to interpolate_submobject
"""
return self.mobject, self.starting_mobject
- def get_all_families_zipped(self) -> typing.Iterator[typing.Tuple]:
+ def get_all_families_zipped(self) -> Iterable[Tuple]:
return zip(
*[mob.family_members_with_points() for mob in self.get_all_mobjects()]
)
@@ -138,7 +135,7 @@ class Animation:
# Methods for interpolation, the mean of an Animation
def interpolate(self, alpha: float) -> None:
- alpha = np.clip(alpha, 0, 1)
+ alpha = min(max(alpha, 0), 1)
self.interpolate_mobject(self.rate_func(alpha))
def update(self, alpha: float) -> None:
@@ -159,12 +156,16 @@ class Animation:
self.interpolate_submobject(*mobs, sub_alpha)
def interpolate_submobject(
- self, submobject: Mobject, starting_submobject: Mobject, alpha: float
- ) -> None:
+ self,
+ submobject: Mobject,
+ starting_submobject: Mobject,
+ # target_copy: Mobject, #Todo: fix - signature of interpolate_submobject differes in Transform().
+ alpha: float,
+ ) -> "Animation":
# Typically implemented by subclass
pass
- def get_sub_alpha(self, alpha: float, index: int, num_submobjects: int):
+ def get_sub_alpha(self, alpha: float, index: int, num_submobjects: int) -> float:
# TODO, make this more understandable, and/or combine
# its functionality with AnimationGroup's method
# build_animations_with_timings
@@ -172,7 +173,7 @@ class Animation:
full_length = (num_submobjects - 1) * lag_ratio + 1
value = alpha * full_length
lower = index * lag_ratio
- return np.clip((value - lower), 0, 1)
+ return min(max((value - lower), 0), 1)
# Getters and setters
def set_run_time(self, run_time: float) -> "Animation":
@@ -183,12 +184,15 @@ class Animation:
return self.run_time
def set_rate_func(
- self, rate_func: typing.Callable[[float, float], np.ndarray]
+ self,
+ rate_func: Callable[[float], float],
) -> "Animation":
self.rate_func = rate_func
return self
- def get_rate_func(self) -> typing.Callable[[float, float], np.ndarray]:
+ def get_rate_func(
+ self,
+ ) -> Callable[[float], float]:
return self.rate_func
def set_name(self, name: str) -> "Animation":
@@ -198,9 +202,6 @@ class Animation:
def is_remover(self) -> bool:
return self.remover
- def is_dummy(self) -> bool:
- return self.mobject is None
-
def prepare_animation(
anim: Union["Animation", "mobject._AnimationBuilder"]
@@ -245,13 +246,14 @@ def prepare_animation(
class Wait(Animation):
def __init__(
- self, duration: float = 1, stop_condition=None, **kwargs
+ self, run_time: float = 1, stop_condition=None, **kwargs
): # what is stop_condition?
- self.duration = duration
- self.mobject = None
+ self.duration: float = run_time
self.stop_condition = stop_condition
- self.is_static_wait = False
- super().__init__(None, **kwargs)
+ self.is_static_wait: bool = False
+ super().__init__(None, run_time=run_time, **kwargs)
+ # quick fix to work in opengl setting:
+ self.mobject.shader_wrapper_list = []
def begin(self) -> None:
pass
diff --git a/manim/animation/composition.py b/manim/animation/composition.py
index 95563bd9c..6e207da8c 100644
--- a/manim/animation/composition.py
+++ b/manim/animation/composition.py
@@ -1,5 +1,7 @@
"""Tools for displaying multiple animations at once."""
-import typing
+
+
+from typing import TYPE_CHECKING, Callable, Optional, Union
import numpy as np
@@ -8,11 +10,10 @@ from ..animation.animation import Animation, prepare_animation
from ..mobject.mobject import Group, Mobject
from ..mobject.opengl_mobject import OpenGLGroup
from ..scene.scene import Scene
-from ..utils.bezier import interpolate
from ..utils.iterables import remove_list_redundancies
from ..utils.rate_functions import linear
-if typing.TYPE_CHECKING:
+if TYPE_CHECKING:
from ..mobject.types.opengl_vectorized_mobject import OpenGLVGroup
from ..mobject.types.vectorized_mobject import VGroup
@@ -26,9 +27,9 @@ class AnimationGroup(Animation):
def __init__(
self,
*animations: Animation,
- group: typing.Union[Group, "VGroup", OpenGLGroup, "OpenGLVGroup"] = None,
- run_time: float = None,
- rate_func: typing.Callable[[float], float] = linear,
+ group: Union[Group, "VGroup", OpenGLGroup, "OpenGLVGroup"] = None,
+ run_time: Optional[float] = None,
+ rate_func: Callable[[float], float] = linear,
lag_ratio: float = 0,
**kwargs
) -> None:
@@ -36,24 +37,18 @@ class AnimationGroup(Animation):
self.group = group
if self.group is None:
mobjects = remove_list_redundancies(
- [anim.mobject for anim in self.animations if not anim.is_dummy()]
+ [anim.mobject for anim in self.animations]
)
if config["renderer"] == "opengl":
self.group = OpenGLGroup(*mobjects)
else:
self.group = Group(*mobjects)
super().__init__(self.group, rate_func=rate_func, lag_ratio=lag_ratio, **kwargs)
- self.run_time = run_time
- self.init_run_time()
+ self.run_time: float = self.init_run_time(run_time)
def get_all_mobjects(self) -> Group:
return self.group
- def get_run_time(self) -> float:
- if super().get_run_time() is None:
- self.init_run_time()
- return super().get_run_time()
-
def begin(self) -> None:
for anim in self.animations:
anim.begin()
@@ -70,13 +65,13 @@ class AnimationGroup(Animation):
for anim in self.animations:
anim.update_mobjects(dt)
- def init_run_time(self) -> None:
+ def init_run_time(self, run_time) -> float:
self.build_animations_with_timings()
if self.anims_with_timings:
self.max_end_time = np.max([awt[2] for awt in self.anims_with_timings])
else:
self.max_end_time = 0
- self.run_time = self.max_end_time if self.run_time is None else self.run_time
+ return self.max_end_time if run_time is None else run_time
def build_animations_with_timings(self) -> None:
"""
@@ -84,14 +79,13 @@ class AnimationGroup(Animation):
(anim, start_time, end_time)
"""
self.anims_with_timings = []
- curr_time = 0
+ curr_time: float = 0
for anim in self.animations:
- start_time = curr_time
- end_time = start_time + anim.get_run_time()
+ start_time: float = curr_time
+ end_time: float = start_time + anim.get_run_time()
self.anims_with_timings.append((anim, start_time, end_time))
- # Start time of next animation is based on
- # the lag_ratio
- curr_time = interpolate(start_time, end_time, self.lag_ratio)
+ # Start time of next animation is based on the lag_ratio
+ curr_time = (1 - self.lag_ratio) * start_time + self.lag_ratio * end_time
def interpolate(self, alpha: float) -> None:
# Note, if the run_time of AnimationGroup has been
@@ -115,7 +109,6 @@ class Succession(AnimationGroup):
def begin(self) -> None:
assert len(self.animations) > 0
- self.init_run_time()
self.update_active_animation(0)
def finish(self) -> None:
@@ -129,9 +122,9 @@ class Succession(AnimationGroup):
def update_active_animation(self, index: int) -> None:
self.active_index = index
if index >= len(self.animations):
- self.active_animation = None
- self.active_start_time = None
- self.active_end_time = None
+ self.active_animation: Optional[Animation] = None
+ self.active_start_time: Optional[float] = None
+ self.active_end_time: Optional[float] = None
else:
self.active_animation = self.animations[index]
self.active_animation.begin()
@@ -139,14 +132,15 @@ class Succession(AnimationGroup):
self.active_end_time = self.anims_with_timings[index][2]
def next_animation(self) -> None:
- self.active_animation.finish()
+ if self.active_animation is not None:
+ self.active_animation.finish()
self.update_active_animation(self.active_index + 1)
def interpolate(self, alpha: float) -> None:
- current_time = interpolate(0, self.run_time, alpha)
+ current_time = alpha * self.run_time
while self.active_end_time is not None and current_time >= self.active_end_time:
self.next_animation()
- if self.active_animation:
+ if self.active_animation is not None and self.active_start_time is not None:
elapsed = current_time - self.active_start_time
active_run_time = self.active_animation.get_run_time()
subalpha = elapsed / active_run_time if active_run_time != 0.0 else 1.0
@@ -166,9 +160,9 @@ class LaggedStart(AnimationGroup):
class LaggedStartMap(LaggedStart):
def __init__(
self,
- AnimationClass: Animation,
+ AnimationClass: Callable[..., Animation],
mobject: Mobject,
- arg_creator: typing.Callable[[Mobject], str] = None,
+ arg_creator: Callable[[Mobject], str] = None,
run_time: float = 2,
**kwargs
) -> None:
diff --git a/manim/animation/creation.py b/manim/animation/creation.py
index 3066640ce..a0b241554 100644
--- a/manim/animation/creation.py
+++ b/manim/animation/creation.py
@@ -72,14 +72,14 @@ __all__ = [
import itertools as it
-import typing
+from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
from colour import Color
from .. import logger
-if typing.TYPE_CHECKING:
+if TYPE_CHECKING:
from manim.mobject.svg.text_mobject import Text
from ..animation.animation import Animation
@@ -105,7 +105,7 @@ class ShowPartial(Animation):
"""
- def __init__(self, mobject: typing.Union[VMobject, OpenGLVMobject], **kwargs):
+ def __init__(self, mobject: Union[Mobject, OpenGLVMobject, None], **kwargs):
if not isinstance(mobject, (VMobject, OpenGLVMobject)):
raise TypeError("This Animation only works on vectorized mobjects")
super().__init__(mobject, **kwargs)
@@ -150,13 +150,13 @@ class Create(ShowPartial):
def __init__(
self,
- mobject: typing.Union[VMobject, OpenGLVMobject],
+ mobject: Union[VMobject, OpenGLVMobject],
lag_ratio: float = 1.0,
**kwargs,
) -> None:
super().__init__(mobject, lag_ratio=lag_ratio, **kwargs)
- def _get_bounds(self, alpha: float) -> typing.Tuple[int, float]:
+ def _get_bounds(self, alpha: float) -> Tuple[int, float]:
return (0, alpha)
@@ -169,7 +169,7 @@ class ShowCreation(Create):
)
super().__init__(mobject, lag_ratio=lag_ratio, **kwargs)
- def _get_bounds(self, alpha: float) -> typing.Tuple[int, float]:
+ def _get_bounds(self, alpha: float) -> Tuple[int, float]:
return (0, alpha)
@@ -192,10 +192,8 @@ class Uncreate(Create):
def __init__(
self,
- mobject: typing.Union[VMobject, OpenGLVMobject],
- rate_func: typing.Callable[[float, float], np.ndarray] = lambda t: smooth(
- 1 - t
- ),
+ mobject: Union[VMobject, OpenGLVMobject],
+ rate_func: Callable[[float], float] = lambda t: smooth(1 - t),
remover: bool = True,
**kwargs,
) -> None:
@@ -216,13 +214,13 @@ class DrawBorderThenFill(Animation):
def __init__(
self,
- vmobject: typing.Union[VMobject, OpenGLVMobject],
+ vmobject: Union[VMobject, OpenGLVMobject],
run_time: float = 2,
- rate_func: typing.Callable[[float], np.ndarray] = double_smooth,
+ rate_func: Callable[[float], float] = double_smooth,
stroke_width: float = 2,
stroke_color: str = None,
- draw_border_animation_config: typing.Dict = {}, # what does this dict accept?
- fill_animation_config: typing.Dict = {},
+ draw_border_animation_config: Dict = {}, # what does this dict accept?
+ fill_animation_config: Dict = {},
**kwargs,
) -> None:
self._typecheck_input(vmobject)
@@ -231,11 +229,9 @@ class DrawBorderThenFill(Animation):
self.stroke_color = stroke_color
self.draw_border_animation_config = draw_border_animation_config
self.fill_animation_config = fill_animation_config
- self.outline = None
+ self.outline = self.get_outline()
- def _typecheck_input(
- self, vmobject: typing.Union[VMobject, OpenGLVMobject]
- ) -> None:
+ def _typecheck_input(self, vmobject: Union[VMobject, OpenGLVMobject]) -> None:
if not isinstance(vmobject, (VMobject, OpenGLVMobject)):
raise TypeError("DrawBorderThenFill only works for vectorized Mobjects")
@@ -250,21 +246,21 @@ class DrawBorderThenFill(Animation):
sm.set_stroke(color=self.get_stroke_color(sm), width=self.stroke_width)
return outline
- def get_stroke_color(
- self, vmobject: typing.Union[VMobject, OpenGLVMobject]
- ) -> Color:
+ def get_stroke_color(self, vmobject: Union[VMobject, OpenGLVMobject]) -> Color:
if self.stroke_color:
return self.stroke_color
elif vmobject.get_stroke_width() > 0:
return vmobject.get_stroke_color()
return vmobject.get_color()
- def get_all_mobjects(self) -> typing.List[typing.Union[Mobject, None]]:
+ def get_all_mobjects(self) -> List[Union[Mobject, None]]:
return [*super().get_all_mobjects(), self.outline]
def interpolate_submobject(
self, submobject: Mobject, starting_submobject: Mobject, outline, alpha: float
) -> None: # Fixme: not matching the parent class? What is outline doing here?
+ index: int
+ subalpha: int
index, subalpha = integer_interpolate(0, 2, alpha)
if index == 0:
submobject.pointwise_become_partial(outline, 0, subalpha)
@@ -287,34 +283,38 @@ class Write(DrawBorderThenFill):
def __init__(
self,
- vmobject: typing.Union[VMobject, OpenGLVMobject],
- run_time: float = None,
- lag_ratio: float = None,
- rate_func: typing.Callable[[float], np.ndarray] = linear,
+ vmobject: Union[VMobject, OpenGLVMobject],
+ rate_func: Callable[[float], float] = linear,
**kwargs,
) -> None:
- self.run_time = run_time
- self.lag_ratio = lag_ratio
- self._set_default_config_from_length(vmobject)
+ run_time: Optional[float] = kwargs.pop("run_time", None)
+ lag_ratio: Optional[float] = kwargs.pop("lag_ratio", None)
+ run_time, lag_ratio = self._set_default_config_from_length(
+ vmobject, run_time, lag_ratio
+ )
super().__init__(
vmobject,
- run_time=self.run_time,
- lag_ratio=self.lag_ratio,
rate_func=rate_func,
+ run_time=run_time,
+ lag_ratio=lag_ratio,
**kwargs,
)
def _set_default_config_from_length(
- self, vmobject: typing.Union[VMobject, OpenGLVMobject]
- ) -> None:
+ self,
+ vmobject: Union[VMobject, OpenGLVMobject],
+ run_time: Optional[float],
+ lag_ratio: Optional[float],
+ ) -> Tuple[float, float]:
length = len(vmobject.family_members_with_points())
- if self.run_time is None:
+ if run_time is None:
if length < 15:
- self.run_time = 1
+ run_time = 1
else:
- self.run_time = 2
- if self.lag_ratio is None:
- self.lag_ratio = min(4.0 / length, 0.2)
+ run_time = 2
+ if lag_ratio is None:
+ lag_ratio = min(4.0 / length, 0.2)
+ return run_time, lag_ratio
class Unwrite(Write):
@@ -349,18 +349,18 @@ class Unwrite(Write):
def __init__(
self,
vmobject: VMobject,
- run_time: float = None,
- lag_ratio: float = None,
- rate_func: typing.Callable[[float], np.ndarray] = linear,
+ rate_func: Callable[[float], float] = linear,
reverse: bool = False,
**kwargs,
) -> None:
self.vmobject = vmobject
- self.run_time = run_time
- self.lag_ratio = lag_ratio
self.reverse = reverse
- self._set_default_config_from_length(vmobject)
+ run_time: Optional[float] = kwargs.pop("run_time", None)
+ lag_ratio: Optional[float] = kwargs.pop("lag_ratio", None)
+ run_time, lag_ratio = self._set_default_config_from_length(
+ vmobject, run_time, lag_ratio
+ )
super().__init__(
vmobject,
run_time=run_time,
@@ -403,7 +403,7 @@ class ShowIncreasingSubsets(Animation):
self,
group: Mobject,
suspend_mobject_updating: bool = False,
- int_func: typing.Callable[[np.ndarray], np.ndarray] = np.floor,
+ int_func: Callable[[np.ndarray], np.ndarray] = np.floor,
**kwargs,
) -> None:
self.all_submobs = list(group.submobjects)
@@ -442,24 +442,23 @@ class AddTextLetterByLetter(ShowIncreasingSubsets):
self,
text: "Text",
suspend_mobject_updating: bool = False,
- int_func: typing.Callable[[np.ndarray], np.ndarray] = np.ceil,
- rate_func: typing.Callable[[float], float] = linear,
+ int_func: Callable[[np.ndarray], np.ndarray] = np.ceil,
+ rate_func: Callable[[float], float] = linear,
time_per_char: float = 0.1,
- run_time: typing.Optional[float] = None,
+ run_time: Optional[float] = None,
**kwargs,
) -> None:
# time_per_char must be above 0.06, or the animation won't finish
self.time_per_char = time_per_char
- self.run_time = run_time
- if self.run_time is None:
- self.run_time = np.max((0.06, self.time_per_char)) * len(text)
+ if run_time is None:
+ run_time = np.max((0.06, self.time_per_char)) * len(text)
super().__init__(
text,
suspend_mobject_updating=suspend_mobject_updating,
int_func=int_func,
rate_func=rate_func,
- run_time=self.run_time,
+ run_time=run_time,
**kwargs,
)
@@ -469,8 +468,8 @@ class ShowSubmobjectsOneByOne(ShowIncreasingSubsets):
def __init__(
self,
- group: typing.Iterable[Mobject],
- int_func: typing.Callable[[np.ndarray], np.ndarray] = np.ceil,
+ group: Iterable[Mobject],
+ int_func: Callable[[np.ndarray], np.ndarray] = np.ceil,
**kwargs,
) -> None:
new_group = Group(*group)
diff --git a/manim/animation/transform.py b/manim/animation/transform.py
index 9d694b5c1..35175f9d6 100644
--- a/manim/animation/transform.py
+++ b/manim/animation/transform.py
@@ -26,7 +26,17 @@ __all__ = [
import inspect
import types
-import typing
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ TypeVar,
+ Union,
+)
import numpy as np
@@ -38,26 +48,30 @@ from ..mobject.opengl_mobject import OpenGLMobject
from ..utils.paths import path_along_arc, straight_path
from ..utils.rate_functions import smooth, squish_rate_func
-if typing.TYPE_CHECKING:
+if TYPE_CHECKING:
from ..scene.scene import Scene
class Transform(Animation):
def __init__(
self,
- mobject: Mobject,
- target_mobject: typing.Optional[Mobject] = None,
- path_func: typing.Optional[typing.Callable] = None,
+ mobject: Optional[Mobject],
+ target_mobject: Optional[Mobject] = None,
+ path_func: Optional[Callable] = None,
path_arc: float = 0,
path_arc_axis: np.ndarray = OUT,
replace_mobject_with_target_in_scene: bool = False,
**kwargs,
) -> None:
- self.path_arc = path_arc
- self.path_func = path_func
- self.path_arc_axis = path_arc_axis
- self.replace_mobject_with_target_in_scene = replace_mobject_with_target_in_scene
- self.target_mobject = target_mobject
+ self.path_arc: float = path_arc
+ self.path_func: Optional[Callable] = path_func
+ self.path_arc_axis: np.ndarray = path_arc_axis
+ self.replace_mobject_with_target_in_scene: bool = (
+ replace_mobject_with_target_in_scene
+ )
+ self.target_mobject: Mobject = (
+ target_mobject if target_mobject is not None else Mobject()
+ )
super().__init__(mobject, **kwargs)
self._init_path_func()
@@ -77,7 +91,6 @@ class Transform(Animation):
# call so that the actual target_mobject stays
# preserved.
self.target_mobject = self.create_target()
- self.check_target_mobject_validity()
self.target_copy = self.target_mobject.copy()
# Note, this potentially changes the structure
# of both mobject and target_mobject
@@ -87,31 +100,18 @@ class Transform(Animation):
self.mobject.align_data(self.target_copy)
super().begin()
- def create_target(self) -> typing.Union[Mobject, None]:
+ def create_target(self) -> Mobject:
# Has no meaningful effect here, but may be useful
# in subclasses
return self.target_mobject
- def check_target_mobject_validity(self) -> None:
- if self.target_mobject is None:
- raise NotImplementedError(
- f"{self.__class__.__name__}.create_target not properly implemented"
- )
-
def clean_up_from_scene(self, scene: "Scene") -> None:
super().clean_up_from_scene(scene)
if self.replace_mobject_with_target_in_scene:
scene.remove(self.mobject)
scene.add(self.target_mobject)
- def update_config(self, **kwargs: typing.Dict[str, typing.Any]) -> None:
- Animation.update_config(self, **kwargs)
- if "path_arc" in kwargs:
- self.path_func = path_along_arc(
- kwargs["path_arc"], kwargs.get("path_arc_axis", OUT)
- )
-
- def get_all_mobjects(self) -> typing.List[Mobject]:
+ def get_all_mobjects(self) -> List[Mobject]:
return [
self.mobject,
self.starting_mobject,
@@ -119,17 +119,13 @@ class Transform(Animation):
self.target_copy,
]
- def get_all_families_zipped(self) -> typing.Iterable[tuple]: # more precise typing?
- return zip(
- *[
- mob.family_members_with_points()
- for mob in [
- self.mobject,
- self.starting_mobject,
- self.target_copy,
- ]
- ]
- )
+ def get_all_families_zipped(self) -> Iterable[tuple]: # more precise typing?
+ mobs = [
+ self.mobject,
+ self.starting_mobject,
+ self.target_copy,
+ ]
+ return zip(*[mob.family_members_with_points() for mob in mobs])
def interpolate_submobject(
self,
@@ -137,7 +133,7 @@ class Transform(Animation):
starting_submobject: Mobject,
target_copy: Mobject,
alpha: float,
- ) -> "Transform": # doesn't match the parent class?
+ ) -> "Transform":
submobject.interpolate(starting_submobject, target_copy, alpha, self.path_func)
return self
@@ -203,8 +199,8 @@ class _MethodAnimation(MoveToTarget):
class ApplyMethod(Transform):
def __init__(
- self, method: types.MethodType, *args, **kwargs
- ) -> None: # method typing? for args?
+ self, method: Callable, *args, **kwargs
+ ) -> None: # method typing (we want to specify Mobject method)? for args?
"""
Method is a method of Mobject, ``args`` are arguments for
that method. Key word arguments should be passed in
@@ -218,7 +214,7 @@ class ApplyMethod(Transform):
self.method_args = args
super().__init__(method.__self__, **kwargs)
- def check_validity_of_input(self, method: types.MethodType) -> None:
+ def check_validity_of_input(self, method: Callable) -> None:
if not inspect.ismethod(method):
raise ValueError(
"Whoops, looks like you accidentally invoked "
@@ -306,7 +302,8 @@ class ApplyFunction(Transform):
self.function = function
super().__init__(mobject, **kwargs)
- def create_target(self) -> typing.Any:
+ def create_target(self) -> Any:
+ assert isinstance(self.mobject, Mobject)
target = self.function(self.mobject.copy())
if not isinstance(target, Mobject):
raise TypeError(
@@ -375,7 +372,7 @@ class TransformAnimations(Transform):
self,
start_anim: Animation,
end_anim: Animation,
- rate_func: typing.Callable = squish_rate_func(smooth),
+ rate_func: Callable = squish_rate_func(smooth),
**kwargs,
) -> None:
self.start_anim = start_anim
@@ -386,14 +383,15 @@ class TransformAnimations(Transform):
self.run_time = max(start_anim.run_time, end_anim.run_time)
for anim in start_anim, end_anim:
anim.set_run_time(self.run_time)
-
if (
- start_anim.starting_mobject.get_num_points()
+ start_anim.starting_mobject is not None
+ and end_anim.starting_mobject is not None
+ and start_anim.starting_mobject.get_num_points()
!= end_anim.starting_mobject.get_num_points()
):
start_anim.starting_mobject.align_data(end_anim.starting_mobject)
for anim in start_anim, end_anim:
- if hasattr(anim, "target_mobject"):
+ if isinstance(anim, Transform) and anim.starting_mobject is not None:
anim.starting_mobject.align_data(anim.target_mobject)
super().__init__(
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 8bb9e5424..a2a766384 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -13,7 +13,7 @@ import types
import warnings
from functools import reduce
from pathlib import Path
-from typing import Callable, List, Optional, Union
+from typing import Callable, List, Optional, TypeVar, Union
import numpy as np
from colour import Color
@@ -42,6 +42,7 @@ from ..utils.space_ops import (
# TODO: Explain array_attrs
Updater = Union[Callable[["Mobject"], None], Callable[["Mobject", float], None]]
+T = TypeVar("T", bound="Mobject")
class Mobject(Container):
@@ -647,7 +648,7 @@ class Mobject(Container):
Path(config.get_dir("video_dir")).joinpath((name or str(self)) + ".png")
)
- def copy(self) -> "Mobject":
+ def copy(self: T) -> T:
"""Create and return an identical copy of the :class:`Mobject` including all :attr:`submobjects`.
Returns
@@ -2147,7 +2148,7 @@ class Mobject(Container):
return self.shuffle(*args, **kwargs)
# Alignment
- def align_data(self, mobject):
+ def align_data(self, mobject: "Mobject"):
self.null_point_align(mobject)
self.align_submobjects(mobject)
self.align_points(mobject)
diff --git a/manim/mobject/mobject_update_utils.py b/manim/mobject/mobject_update_utils.py
index 66c9ad5b0..90658b53a 100644
--- a/manim/mobject/mobject_update_utils.py
+++ b/manim/mobject/mobject_update_utils.py
@@ -83,7 +83,6 @@ def turn_animation_into_updater(animation, cycle=False, **kwargs):
the updater will be popped upon completion
"""
mobject = animation.mobject
- animation.update_config(**kwargs)
animation.suspend_mobject_updating = False
animation.begin()
animation.total_time = 0
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index 1e9c83d54..8dd73f37a 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -801,7 +801,7 @@ class Scene(Container):
self.renderer.play(self, *args, **kwargs)
def wait(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):
- self.play(Wait(duration=duration, stop_condition=stop_condition))
+ self.play(Wait(run_time=duration, stop_condition=stop_condition))
def wait_until(self, stop_condition, max_time=60):
"""
diff --git a/manim/utils/rate_functions.py b/manim/utils/rate_functions.py
index 272d6a452..f48eeb88d 100644
--- a/manim/utils/rate_functions.py
+++ b/manim/utils/rate_functions.py
@@ -74,44 +74,43 @@ from ..utils.bezier import bezier
from ..utils.simple_functions import sigmoid
-def linear(t: typing.Union[np.ndarray, float]) -> typing.Union[np.ndarray, float]:
+def linear(t: float) -> float:
return t
-def smooth(t: float, inflection: float = 10.0) -> np.ndarray:
+def smooth(t: float, inflection: float = 10.0) -> float:
error = sigmoid(-inflection / 2)
- return np.clip(
- (sigmoid(inflection * (t - 0.5)) - error) / (1 - 2 * error),
- 0,
+ return min(
+ max((sigmoid(inflection * (t - 0.5)) - error) / (1 - 2 * error), 0),
1,
)
-def rush_into(t: float, inflection: float = 10.0) -> np.ndarray:
+def rush_into(t: float, inflection: float = 10.0) -> float:
return 2 * smooth(t / 2.0, inflection)
-def rush_from(t: float, inflection: float = 10.0) -> np.ndarray:
+def rush_from(t: float, inflection: float = 10.0) -> float:
return 2 * smooth(t / 2.0 + 0.5, inflection) - 1
-def slow_into(t: np.ndarray) -> np.ndarray:
+def slow_into(t: float) -> float:
return np.sqrt(1 - (1 - t) * (1 - t))
-def double_smooth(t: float) -> np.ndarray:
+def double_smooth(t: float) -> float:
if t < 0.5:
return 0.5 * smooth(2 * t)
else:
return 0.5 * (1 + smooth(2 * t - 1))
-def there_and_back(t: float, inflection: float = 10.0) -> np.ndarray:
+def there_and_back(t: float, inflection: float = 10.0) -> float:
new_t = 2 * t if t < 0.5 else 2 * (1 - t)
return smooth(new_t, inflection)
-def there_and_back_with_pause(t: float, pause_ratio: float = 1.0 / 3) -> np.ndarray:
+def there_and_back_with_pause(t: float, pause_ratio: float = 1.0 / 3) -> float:
a = 1.0 / pause_ratio
if t < 0.5 - pause_ratio / 2:
return smooth(a * t)
@@ -121,29 +120,31 @@ def there_and_back_with_pause(t: float, pause_ratio: float = 1.0 / 3) -> np.ndar
return smooth(a - a * t)
-def running_start(t: float, pull_factor: float = -0.5) -> typing.Iterable:
+def running_start(
+ t: float, pull_factor: float = -0.5
+) -> typing.Iterable: # what is func return type?
return bezier([0, 0, pull_factor, pull_factor, 1, 1, 1])(t)
def not_quite_there(
- func: typing.Callable[[float, typing.Optional[float]], np.ndarray] = smooth,
+ func: typing.Callable[[float], float] = smooth,
proportion: float = 0.7,
-) -> typing.Callable[[float], np.ndarray]:
+) -> typing.Callable[[float], float]:
def result(t):
return proportion * func(t)
return result
-def wiggle(t: float, wiggles: float = 2) -> np.ndarray:
+def wiggle(t: float, wiggles: float = 2) -> float:
return there_and_back(t) * np.sin(wiggles * np.pi * t)
def squish_rate_func(
- func: typing.Callable[[float], typing.Any],
+ func: typing.Callable[[float], float],
a: float = 0.4,
b: float = 0.6,
-) -> typing.Callable[[float], typing.Any]: # what is func return type?
+) -> typing.Callable[[float], float]:
def result(t):
if a == b:
return a
@@ -168,21 +169,21 @@ def lingering(t: float) -> float:
return squish_rate_func(lambda t: t, 0, 0.8)(t)
-def exponential_decay(t: np.ndarray, half_life: float = 0.1) -> np.ndarray:
+def exponential_decay(t: float, half_life: float = 0.1) -> float:
# The half-life should be rather small to minimize
# the cut-off error at the end
return 1 - np.exp(-t / half_life)
-def ease_in_sine(t: np.ndarray) -> float:
+def ease_in_sine(t: float) -> float:
return 1 - np.cos((t * np.pi) / 2)
-def ease_out_sine(t: np.ndarray) -> float:
+def ease_out_sine(t: float) -> float:
return np.sin((t * np.pi) / 2)
-def ease_in_out_sine(t: np.ndarray) -> float:
+def ease_in_out_sine(t: float) -> float:
return -(np.cos(np.pi * t) - 1) / 2