A community-maintained Python framework for creating mathematical animations.
type animation.py and compostion.py
Syrus Dark619449734221
diff --git a/manim/animation/animation.py b/manim/animation/animation.pyindex 005dcc494..9e59642be 100644--- a/manim/animation/animation.py+++ b/manim/animation/animation.py@@ -4,37 +4,37 @@__all__ = ["Animation", "Wait"]+import typingfrom copy import deepcopyimport numpy as np+from manim.scene.scene import Scenefrom .. import loggerfrom ..mobject.mobject import Mobject-from ..utils.rate_functions import smooth--DEFAULT_ANIMATION_RUN_TIME = 1.0-DEFAULT_ANIMATION_LAG_RATIO = 0+DEFAULT_ANIMATION_RUN_TIME: float = 1.0+DEFAULT_ANIMATION_LAG_RATIO: int = 0class Animation:def __init__(self,- mobject,+ mobject: Mobject,# If lag_ratio is 0, the animation is applied to all submobjects# at the same time# If 1, it is applied to each successively.# If 0 < lag_ratio < 1, its applied to each# with lagged start times- lag_ratio=DEFAULT_ANIMATION_LAG_RATIO,- run_time=DEFAULT_ANIMATION_RUN_TIME,- rate_func=smooth,- name=None,- remover=False, # remove a mobject from the screen?- suspend_mobject_updating=True,+ lag_ratio: float = DEFAULT_ANIMATION_LAG_RATIO,+ run_time: int = DEFAULT_ANIMATION_RUN_TIME,+ rate_func: typing.Callable[[float, float], np.ndarray] = 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_timeself.rate_func = rate_func@@ -49,21 +49,22 @@ class Animation:if hasattr(self, "CONFIG"):logger.error(- "CONFIG has been removed from ManimCommunity. Please use keyword arguments instead."+ ("CONFIG has been removed from ManimCommunity.",+ "Please use keyword arguments instead."))- def _typecheck_input(self, mobject):+ def _typecheck_input(self, mobject: Mobject) -> None:if mobject is None:logger.warning("creating dummy animation")elif not isinstance(mobject, Mobject):raise TypeError("Animation only works on Mobjects")- def __str__(self):+ def __str__(self) -> str:if self.name:return self.namereturn self.__class__.__name__ + str(self.mobject)- def begin(self):+ def begin(self) -> None:# This is called right as an animation is being# played. As much initialization as possible,# especially any mobject copying, should live in@@ -79,31 +80,31 @@ class Animation:self.mobject.suspend_updating()self.interpolate(0)- def finish(self):+ def finish(self) -> None:self.interpolate(1)if self.suspend_mobject_updating:self.mobject.resume_updating()- def clean_up_from_scene(self, scene):+ def clean_up_from_scene(self, scene: Scene) -> None:if self.is_remover():scene.remove(self.mobject)- def create_starting_mobject(self):+ def create_starting_mobject(self) -> Mobject:# Keep track of where the mobject startsreturn self.mobject.copy()- def get_all_mobjects(self):+ def get_all_mobjects(self) -> typing.Tuple[Mobject, typing.Union[Mobject, None]]:"""Ordering must match the ording of arguments to interpolate_submobject"""return self.mobject, self.starting_mobject- def get_all_families_zipped(self):+ def get_all_families_zipped(self) -> typing.Iterator[typing.Tuple]:return zip(*[mob.family_members_with_points() for mob in self.get_all_mobjects()])- def update_mobjects(self, dt):+ def update_mobjects(self, dt: int) -> None:"""Updates things like starting_mobject, and (forTransforms) target_mobject. Note, since typically@@ -114,25 +115,25 @@ class Animation:for mob in self.get_all_mobjects_to_update():mob.update(dt)- def get_all_mobjects_to_update(self):+ def get_all_mobjects_to_update(self) -> list:# The surrounding scene typically handles# updating of self.mobject. Besides, in# most cases its updating is suspended anywayreturn list(filter(lambda m: m is not self.mobject, self.get_all_mobjects()))- def copy(self):+ def copy(self) -> "Animation":return deepcopy(self)- def update_config(self, **kwargs):+ def update_config(self, **kwargs: typing.Dict[str, typing.Any]) -> "Animation":self.__dict__.update(kwargs)return self# Methods for interpolation, the mean of an Animation- def interpolate(self, alpha):+ def interpolate(self, alpha: float) -> None:alpha = np.clip(alpha, 0, 1)self.interpolate_mobject(self.rate_func(alpha))- def update(self, alpha):+ def update(self, alpha: float) -> None:"""This method shouldn't exist, but it's here tokeep many old scenes from breaking@@ -143,17 +144,19 @@ class Animation:)self.interpolate(alpha)- def interpolate_mobject(self, alpha):+ def interpolate_mobject(self, alpha: float) -> None:families = list(self.get_all_families_zipped())for i, mobs in enumerate(families):sub_alpha = self.get_sub_alpha(alpha, i, len(families))self.interpolate_submobject(*mobs, sub_alpha)- def interpolate_submobject(self, submobject, starting_sumobject, alpha):+ def interpolate_submobject(+ self, submobject: Mobject, starting_sumobject: Mobject, alpha: float+ ) -> None:# Typically implemented by subclasspass- def get_sub_alpha(self, alpha, index, num_submobjects):+ def get_sub_alpha(self, alpha: float, index: int, num_submobjects: int):# TODO, make this more understanable, and/or combine# its functionality with AnimationGroup's method# build_animations_with_timings@@ -164,46 +167,50 @@ class Animation:return np.clip((value - lower), 0, 1)# Getters and setters- def set_run_time(self, run_time):+ def set_run_time(self, run_time: float) -> "Animation":self.run_time = run_timereturn self- def get_run_time(self):+ def get_run_time(self) -> float:return self.run_time- def set_rate_func(self, rate_func):+ def set_rate_func(+ self, rate_func: typing.Callable[[float, float], np.ndarray]+ ) -> "Animation":self.rate_func = rate_funcreturn self- def get_rate_func(self):+ def get_rate_func(self) -> typing.Callable[[float, float], np.ndarray]:return self.rate_func- def set_name(self, name):+ def set_name(self, name: str) -> "Animation":self.name = namereturn self- def is_remover(self):+ def is_remover(self) -> bool:return self.removerclass Wait(Animation):- def __init__(self, duration=1, stop_condition=None, **kwargs):+ def __init__(+ self, duration: float = 1, stop_condition=None, **kwargs+ ): # what is stop_condition?self.duration = durationself.mobject = Noneself.stop_condition = stop_conditionsuper().__init__(None, **kwargs)- def begin(self):+ def begin(self) -> None:pass- def finish(self):+ def finish(self) -> None:pass- def clean_up_from_scene(self, scene):+ def clean_up_from_scene(self, scene: Scene) -> None:pass- def update_mobjects(self, dt):+ def update_mobjects(self, dt: int) -> None:pass- def interpolate(self, alpha):+ def interpolate(self, alpha: float) -> None:passdiff --git a/manim/animation/composition.py b/manim/animation/composition.pyindex 5cccf6e27..0d72f1940 100644--- a/manim/animation/composition.py+++ b/manim/animation/composition.py@@ -1,8 +1,11 @@"""Tools for displaying multiple animations at once."""+import typing+import numpy as npfrom ..animation.animation import Animation-from ..mobject.mobject import Group+from ..mobject.mobject import Group, Mobject+from ..scene.scene import Scenefrom ..utils.bezier import interpolatefrom ..utils.iterables import remove_list_redundanciesfrom ..utils.rate_functions import linear@@ -10,19 +13,19 @@ from ..utils.rate_functions import linear__all__ = ["AnimationGroup", "Succession", "LaggedStart", "LaggedStartMap"]-DEFAULT_LAGGED_START_LAG_RATIO = 0.05+DEFAULT_LAGGED_START_LAG_RATIO: float = 0.05class AnimationGroup(Animation):def __init__(self,- *animations,- group=None,+ *animations: Animation,+ group: Group = None,run_time=None,- rate_func=linear,- lag_ratio=0,+ rate_func: typing.Callable[[float], float] = linear,+ lag_ratio: float = 0,**kwargs- ):+ ) -> None:self.animations = animationsself.group = groupif self.group is None:@@ -33,31 +36,31 @@ class AnimationGroup(Animation):self.run_time = run_timeself.init_run_time()- def get_all_mobjects(self):+ def get_all_mobjects(self) -> Group:return self.group- def get_run_time(self):+ 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):+ def begin(self) -> None:for anim in self.animations:anim.begin()- def finish(self):+ def finish(self) -> None:for anim in self.animations:anim.finish()- def clean_up_from_scene(self, scene):+ def clean_up_from_scene(self, scene: Scene) -> None:for anim in self.animations:anim.clean_up_from_scene(scene)- def update_mobjects(self, dt):+ def update_mobjects(self, dt: int) -> None:for anim in self.animations:anim.update_mobjects(dt)- def init_run_time(self):+ def init_run_time(self) -> None: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])@@ -65,7 +68,7 @@ class AnimationGroup(Animation):self.max_end_time = 0self.run_time = self.max_end_time if self.run_time is None else self.run_time- def build_animations_with_timings(self):+ def build_animations_with_timings(self) -> None:"""Creates a list of triplets of the form(anim, start_time, end_time)@@ -80,7 +83,7 @@ class AnimationGroup(Animation):# the lag_ratiocurr_time = interpolate(start_time, end_time, self.lag_ratio)- def interpolate(self, alpha):+ def interpolate(self, alpha: float) -> None:# Note, if the run_time of AnimationGroup has been# set to something other than its default, these# times might not correspond to actual times,@@ -97,23 +100,23 @@ class AnimationGroup(Animation):class Succession(AnimationGroup):- def __init__(self, *animations, lag_ratio=1, **kwargs):+ def __init__(self, *animations: Animation, lag_ratio: float = 1, **kwargs) -> None:super().__init__(*animations, lag_ratio=lag_ratio, **kwargs)- def begin(self):+ def begin(self) -> None:assert len(self.animations) > 0self.init_run_time()self.update_active_animation(0)- def finish(self):+ def finish(self) -> None:while self.active_animation is not None:self.next_animation()- def update_mobjects(self, dt):+ def update_mobjects(self, dt: int) -> None:if self.active_animation:self.active_animation.update_mobjects(dt)- def update_active_animation(self, index):+ def update_active_animation(self, index: int) -> None:self.active_index = indexif index >= len(self.animations):self.active_animation = None@@ -125,11 +128,11 @@ class Succession(AnimationGroup):self.active_start_time = self.anims_with_timings[index][1]self.active_end_time = self.anims_with_timings[index][2]- def next_animation(self):+ def next_animation(self) -> None:self.active_animation.finish()self.update_active_animation(self.active_index + 1)- def interpolate(self, alpha):+ def interpolate(self, alpha: float) -> None:current_time = interpolate(0, self.run_time, alpha)while self.active_end_time is not None and current_time >= self.active_end_time:self.next_animation()@@ -141,12 +144,24 @@ class Succession(AnimationGroup):class LaggedStart(AnimationGroup):- def __init__(self, *animations, lag_ratio=DEFAULT_LAGGED_START_LAG_RATIO, **kwargs):+ def __init__(+ self,+ *animations: Animation,+ lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO,+ **kwargs+ ):super().__init__(*animations, lag_ratio=lag_ratio, **kwargs)class LaggedStartMap(LaggedStart):- def __init__(self, AnimationClass, mobject, arg_creator=None, run_time=2, **kwargs):+ def __init__(+ self,+ AnimationClass: Animation,+ mobject: Mobject,+ arg_creator: typing.Callable[[Mobject], str] = None,+ run_time: float = 2,+ **kwargs+ ) -> None:args_list = []for submob in mobject:if arg_creator: