A community-maintained Python framework for creating mathematical animations.
Improve Animation docs (#1521)
Anton Ballmaier86af56ffe91f
diff --git a/manim/animation/animation.py b/manim/animation/animation.pyindex 3b683762d..b34578269 100644--- a/manim/animation/animation.py+++ b/manim/animation/animation.py@@ -5,7 +5,17 @@ __all__ = ["Animation", "Wait", "override_animation"]from copy import deepcopy-from typing import TYPE_CHECKING, Callable, Iterable, Optional, Tuple, Type, Union+from typing import (+ TYPE_CHECKING,+ Callable,+ Iterable,+ List,+ Optional,+ Sequence,+ Tuple,+ Type,+ Union,+)if TYPE_CHECKING:from manim.scene.scene import Scene@@ -22,6 +32,68 @@ DEFAULT_ANIMATION_LAG_RATIO: float = 0.0class Animation:+ """An animation.++ Animations have a fixed time span.++ Parameters+ ----------+ mobject+ The mobject to be animated. This is not required for all types of animations.+ lag_ratio+ Defines the delay after which the animation is applied to submobjects. This lag+ is relative to the duration of the animation.++ This does not influence the total+ runtime of the animation. Instead the runtime of individual animations is+ adjusted so that the complete animation has the defined run time.++ run_time+ The duration of the animation in seconds.+ rate_func+ The function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`) .++ For example ``rate_func(0.5)`` is the proportion of the animation that is done+ after half of the animations run time.+ name+ The name of the animation. This gets displayed while rendering the animation.+ Defaults to <class-name>(<Mobject-name>).+ remover+ Whether the given mobject should be removed from the scene after this animation.+ suspend_mobject_updating+ Whether updaters of the mobject should be suspended during the animation.+++ Examples+ --------++ .. manim:: LagRatios++ class LagRatios(Scene):+ def construct(self):+ ratios = [0, 0.1, 0.5, 1, 2] # demonstrated lag_ratios++ # Create dot groups+ group = VGroup(*[Dot() for _ in range(4)]).arrange_submobjects()+ groups = VGroup(*[group.copy() for _ in ratios]).arrange_submobjects(buff=1)+ self.add(groups)++ # Label groups+ self.add(Text("lag_ratio = ").scale(0.7).next_to(groups, UP, buff=1.5))+ for group, ratio in zip(groups, ratios):+ self.add(Text(str(ratio)).scale(0.7).next_to(group, UP))++ #Animate groups with different lag_ratios+ self.play(AnimationGroup(*[+ group.animate(lag_ratio=ratio, run_time=1.5).shift(DOWN * 2)+ for group, ratio in zip(groups, ratios)+ ]))++ # lag_ratio also works recursively on nested submobjects:+ self.play(groups.animate(run_time=1, lag_ratio=0.1).shift(UP * 2))++ """+def __new__(cls,mobject: Optional[Mobject] = None,@@ -46,11 +118,6 @@ class Animation:def __init__(self,mobject: Optional[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 timeslag_ratio: float = DEFAULT_ANIMATION_LAG_RATIO,run_time: float = DEFAULT_ANIMATION_RUN_TIME,rate_func: Callable[[float], float] = smooth,@@ -96,10 +163,13 @@ class Animation:return str(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- # this method+ """Begin the animation.++ This method is called right as an animation is being played. As much+ initialization as possible, especially any mobject copying, should live in this+ method.++ """self.starting_mobject = self.create_starting_mobject()if self.suspend_mobject_updating:# All calls to self.mobject's internal updaters@@ -112,11 +182,29 @@ class Animation:self.interpolate(0)def finish(self) -> None:+ # TODO: begin and finish should require a scene as parameter.+ # That way Animation.clean_up_from_screen and Scene.add_mobjects_from_animations+ # could be removed as they fulfill basically the same purpose.+ """Finish the animation.++ This method gets called when the animation is over.++ """self.interpolate(1)if self.suspend_mobject_updating and self.mobject is not None:self.mobject.resume_updating()def clean_up_from_scene(self, scene: "Scene") -> None:+ """Clean up the :class:`~.Scene` after finishing the animation.++ This includes to :meth:`~.Scene.remove` the Animation's+ :class:`~.Mobject` if the animation is a remover.++ Parameters+ ----------+ scene+ The scene the animation should be cleaned up from.+ """if self.is_remover():scene.remove(self.mobject)@@ -124,9 +212,15 @@ class Animation:# Keep track of where the mobject startsreturn self.mobject.copy()- def get_all_mobjects(self) -> Tuple[Mobject, Mobject]:- """+ def get_all_mobjects(self) -> Sequence[Mobject]:+ """Get all mobjects involved in the animation.+Ordering must match the ordering of arguments to interpolate_submobject++ Returns+ -------+ Sequence[Mobject]+ The sequence of mobjects."""return self.mobject, self.starting_mobject@@ -146,17 +240,43 @@ class Animation:for mob in self.get_all_mobjects_to_update():mob.update(dt)- def get_all_mobjects_to_update(self) -> list:+ def get_all_mobjects_to_update(self) -> List[Mobject]:+ """Get all mobjects to be updated during the animation.++ Returns+ -------+ List[Mobject]+ The list of mobjects to be updated during the animation.+ """# 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) -> "Animation":+ """Create a copy of the animation.++ Returns+ -------+ Animation+ A copy of ``self``+ """return deepcopy(self)# Methods for interpolation, the mean of an Animation++ # TODO: stop using alpha as parameter name in different meanings.def interpolate(self, alpha: float) -> None:+ """Set the animation progress.++ This method gets called for every frame during an animation.++ Parameters+ ----------+ alpha+ The relative time to set the aniamtion to, 0 meaning the start, 1 meaning+ the end.+ """alpha = min(max(alpha, 0), 1)self.interpolate_mobject(self.rate_func(alpha))@@ -181,6 +301,22 @@ class Animation:passdef get_sub_alpha(self, alpha: float, index: int, num_submobjects: int) -> float:+ """Get the animation progress of any submobjects subanimation.++ Parameters+ ----------+ alpha+ The overall animation progress+ index+ The index of the subanimation.+ num_submobjects+ The total count of subanimations.++ Returns+ -------+ float+ The progress of the subanimation.+ """# TODO, make this more understandable, and/or combine# its functionality with AnimationGroup's method# build_animations_with_timings@@ -192,29 +328,92 @@ class Animation:# Getters and settersdef set_run_time(self, run_time: float) -> "Animation":+ """Set the run time of the animation.++ Parameters+ ----------+ run_time+ The new time the animation should take in seconds.++ .. note::++ The run_time of an animation should not be changed while it is already+ running.++ Returns+ -------+ Animation+ ``self``+ """self.run_time = run_timereturn selfdef get_run_time(self) -> float:+ """Get the run time of the animation.++ Returns+ -------+ float+ The time the animation takes in seconds.+ """return self.run_timedef set_rate_func(self,rate_func: Callable[[float], float],) -> "Animation":+ """Set the rate function of the animation.++ Parameters+ ----------+ run_time+ The new time the animation should take in seconds.+++ Returns+ -------+ Animation+ ``self``+ """self.rate_func = rate_funcreturn selfdef get_rate_func(self,) -> Callable[[float], float]:+ """Get the rate function of the animation.++ Returns+ -------+ Callable[[float], float]+ The rate fucntion of the animation.+ """return self.rate_funcdef set_name(self, name: str) -> "Animation":+ """Set the name of the animation.++ Parameters+ ----------+ name+ The new name of the animation.++ Returns+ -------+ Animation+ ``self``+ """self.name = namereturn selfdef is_remover(self) -> bool:+ """Test if a the animation is a remover.++ Returns+ -------+ bool+ ``True`` if the animation is a remover, ``False`` otherwise.+ """return self.removerdiff --git a/manim/animation/composition.py b/manim/animation/composition.pyindex 6e207da8c..d39f3b634 100644--- a/manim/animation/composition.py+++ b/manim/animation/composition.py@@ -1,7 +1,7 @@"""Tools for displaying multiple animations at once."""-from typing import TYPE_CHECKING, Callable, Optional, Union+from typing import TYPE_CHECKING, Callable, Optional, Sequence, Unionimport numpy as np@@ -46,8 +46,8 @@ class AnimationGroup(Animation):super().__init__(self.group, rate_func=rate_func, lag_ratio=lag_ratio, **kwargs)self.run_time: float = self.init_run_time(run_time)- def get_all_mobjects(self) -> Group:- return self.group+ def get_all_mobjects(self) -> Sequence[Mobject]:+ return list(self.group)def begin(self) -> None:for anim in self.animations:diff --git a/manim/animation/creation.py b/manim/animation/creation.pyindex d758caa48..55d26f873 100644--- a/manim/animation/creation.py+++ b/manim/animation/creation.py@@ -71,7 +71,17 @@ __all__ = [import itertools as it-from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple, Union+from typing import (+ TYPE_CHECKING,+ Callable,+ Dict,+ Iterable,+ List,+ Optional,+ Sequence,+ Tuple,+ Union,+)import numpy as npfrom colour import Color@@ -238,7 +248,7 @@ class DrawBorderThenFill(Animation):return vmobject.get_stroke_color()return vmobject.get_color()- def get_all_mobjects(self) -> List[Union[Mobject, None]]:+ def get_all_mobjects(self) -> Sequence[Mobject]:return [*super().get_all_mobjects(), self.outline]def interpolate_submobject(diff --git a/manim/animation/transform.py b/manim/animation/transform.pyindex 7a2194e5a..6fb9680b8 100644--- a/manim/animation/transform.py+++ b/manim/animation/transform.py@@ -26,7 +26,7 @@ __all__ = [import inspectimport types-from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional+from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Sequenceimport numpy as np@@ -116,7 +116,7 @@ class Transform(Animation):scene.remove(self.mobject)scene.add(self.target_mobject)- def get_all_mobjects(self) -> List[Mobject]:+ def get_all_mobjects(self) -> Sequence[Mobject]:return [self.mobject,self.starting_mobject,@@ -489,7 +489,7 @@ class FadeTransform(Transform):source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match)source.set_opacity(0)- def get_all_mobjects(self):+ def get_all_mobjects(self) -> Sequence[Mobject]:return [self.mobject,self.starting_mobject,