The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Give animation clocks, transforms and matched parts explicit ownership
Sina Atalay5756ca3acfa9
diff --git a/src/manimgx/animation/clock.py b/src/manimgx/animation/clock.pyindex 99bb1d92..7b81115c 100644--- a/src/manimgx/animation/clock.py+++ b/src/manimgx/animation/clock.py@@ -10,6 +10,50 @@ every frame rate. `speed` runs off scene time, warped by ChangeSpeed."""from collections.abc import Callablefrom fractions import Fractionfrom itertools import pairwise+from math import inf, nextafter, ulp+++def _rounding_cell(value: float) -> tuple[Fraction, Fraction, bool]:+ """The binary64 rounding interval, and whether its ties belong to this value."""+ magnitude = abs(value)+ exact = Fraction(magnitude)+ low = (exact + Fraction(nextafter(magnitude, -inf))) / 2+ high = exact + Fraction(ulp(magnitude)) / 2+ closed = float(low) == magnitude+ return (-high, -low, closed) if value < 0 else (low, high, closed)+++def rational(value: float | Fraction) -> Fraction:+ """Recover the simplest rational that rounds to an authored float.++ A duration such as 5/6 keeps its frame boundary, while distinct floats stay distinct+ and a positive duration never becomes zero. Integers and explicit fractions are exact.+ """+ exact = Fraction(value)+ if not isinstance(value, float) or exact.denominator == 1:+ return exact+ low, high, _ = _rounding_cell(abs(value))+ # Both midpoints have larger denominators than exact itself, so excluding ties+ # cannot exclude the simplest candidate and avoids either neighbor's tie rule.+ # The continued fractions of the rounding interval share these integer parts.+ # The first integer strictly inside it gives the smallest possible denominator.+ a, b, c, d = low.numerator, low.denominator, high.numerator, high.denominator+ before, denominator = 1, 0+ while True:+ whole = a // b+ if (whole + 1) * d < c:+ denominator = (whole + 1) * denominator + before+ return Fraction(round(exact * denominator), denominator)+ before, denominator = denominator, whole * denominator + before+ a, b, c, d = d, c - whole * d, b, a - whole * b+++def frame_at(time: float | Fraction, rate: Fraction, *, after: bool = False) -> int:+ """First frame at this observed instant or later (strictly later with `after`)."""+ low, high, closed = _rounding_cell(float(time))+ at = (high if after else low) * rate+ return int(at // 1 + 1 if closed == after else -(-at // 1))+now = Fraction(0)"""The instant being computed — or, between plays, the end of the last one (where the scene'sdiff --git a/src/manimgx/animation/easing.py b/src/manimgx/animation/easing.pyindex 4d960296..9b6de433 100644--- a/src/manimgx/animation/easing.py+++ b/src/manimgx/animation/easing.py@@ -154,7 +154,7 @@ def smootherstep(t: float) -> float:@unit_intervaldef rush_into(t: float, inflection: float = 10.0) -> float:"""The first half of [smooth][manimgx.smooth], stretched over the whole time:- starts at rest and ends at full speed.+ starts slowly and ends at its greatest speed.Args:t: The time, from 0 to 1.@@ -169,7 +169,7 @@ def rush_into(t: float, inflection: float = 10.0) -> float:@unit_intervaldef rush_from(t: float, inflection: float = 10.0) -> float:"""The second half of [smooth][manimgx.smooth], stretched over the whole time:- starts at full speed and comes to rest.+ starts at its greatest speed and slows toward the end.Args:t: The time, from 0 to 1.@@ -183,7 +183,7 @@ def rush_from(t: float, inflection: float = 10.0) -> float:@unit_intervaldef slow_into(t: float) -> float:- """√(1 − (1 − t)²), a quarter circle: starts at once at full speed and slows to a+ """√(1 − (1 − t)²), a quarter circle: starts sharply and slows to astop."""return float(np.sqrt(1 - (1 - t) * (1 - t)))@@ -191,7 +191,7 @@ def slow_into(t: float) -> float:@unit_intervaldef double_smooth(t: float) -> float:"""Two [smooth][manimgx.smooth] moves, each half the way in half the time: comes to- rest at the middle."""+ its slowest speed at the middle."""return 0.5 * smooth(2 * t) if t < 0.5 else 0.5 * (1 + smooth(2 * t - 1))@@ -316,7 +316,7 @@ def exponential_decay(t: float, half_life: float = 0.1) -> float:"""1 − e^(−t / `half_life`), scaled to end at 1: shoots off, then closes in on theend, ever slower.- It is about 1 − 1/e ≈ 0.63 at `half_life`.+ With the default time constant, it reaches about 1 − 1/e ≈ 0.63 at t = 0.1.Args:t: The time, from 0 to 1.@@ -328,7 +328,7 @@ def exponential_decay(t: float, half_life: float = 0.1) -> float:return float(np.expm1(-t / half_life) / np.expm1(-1 / half_life))-# ── the ease family, verbatim from CE ──+# ── the ease family ──@unit_intervaldef ease_in_sine(t: float) -> float:"""1 − cos(πt/2): starts slow and speeds up."""@@ -452,13 +452,13 @@ def ease_in_out_expo(t: float) -> float:@unit_intervaldef ease_in_circ(t: float) -> float:- """1 − √(1 − t²), a quarter circle: starts at rest and ends at full speed."""+ """1 − √(1 − t²), a quarter circle: starts at rest and speeds up sharply."""return 1 - math.sqrt(1 - pow(t, 2))@unit_intervaldef ease_out_circ(t: float) -> float:- """√(1 − (t − 1)²), a quarter circle: starts at full speed and comes to rest."""+ """√(1 − (t − 1)²), a quarter circle: starts sharply and comes to rest."""return math.sqrt(1 - pow(t - 1, 2))diff --git a/src/manimgx/animation/matching.py b/src/manimgx/animation/matching.pyindex be7749e8..7ca4829f 100644--- a/src/manimgx/animation/matching.py+++ b/src/manimgx/animation/matching.py@@ -60,6 +60,7 @@ class TransformMatchingAbstractBase(AnimationGroup):than fade.key_map: Pairs of keys to match although they differ: the parts of `mobject`with the first key cross-fade into the target's parts with the second.+ These matches take precedence over equal keys.**kwargs: [Transform options][manimgx.animation.transform.TransformOptions] foreach of the animations it plays."""@@ -67,17 +68,22 @@ class TransformMatchingAbstractBase(AnimationGroup):# the parts are matched in their own order, so the result is the same in every run# (CE matched through salted hashes, in set order)- def __init__(+ def __init__[Key: Hashable](self,mobject: Mobject,target_mobject: Mobject,transform_mismatches: bool = False,fade_transform_mismatches: bool = False,- key_map: Mapping[Hashable, Hashable] | None = None,+ key_map: Mapping[Key, Hashable] | None = None,**kwargs: Unpack[TransformOptions],):source_map = self.get_shape_map(mobject)target_map = self.get_shape_map(target_mobject)+ key_mapped_source, key_mapped_target = Group(), Group()+ for key1, key2 in (key_map or {}).items():+ if key1 in source_map and key2 in target_map:+ key_mapped_source.add(source_map.pop(key1))+ key_mapped_target.add(target_map.pop(key2))matched = [key for key in source_map if key in target_map]anims: list[AnimationGroup | Transform] = [Transform(@@ -86,11 +92,6 @@ class TransformMatchingAbstractBase(AnimationGroup):**kwargs,)]- key_mapped_source, key_mapped_target = Group(), Group()- for key1, key2 in (key_map or {}).items():- if key1 in source_map and key2 in target_map:- key_mapped_source.add(source_map.pop(key1))- key_mapped_target.add(target_map.pop(key2))if len(key_mapped_source) > 0:anims.append(FadeTransformPieces(key_mapped_source, key_mapped_target, **kwargs)@@ -189,6 +190,7 @@ class TransformMatchingShapes(TransformMatchingAbstractBase):than fade.key_map: Pairs of keys to match although they differ: the parts of `mobject`with the first key cross-fade into the target's parts with the second.+ These matches take precedence over equal keys.**kwargs: [Transform options][manimgx.animation.transform.TransformOptions] foreach of the animations it plays.@@ -244,6 +246,7 @@ class TransformMatchingTex(TransformMatchingAbstractBase):than fade.key_map: Pairs of strings to match although they differ: the parts of `mobject`written the first way cross-fade into the target's parts written the second.+ These matches take precedence over equal keys.**kwargs: [Transform options][manimgx.animation.transform.TransformOptions] foreach of the animations it plays.diff --git a/src/manimgx/animation/motion.py b/src/manimgx/animation/motion.pyindex c393bd70..8b293899 100644--- a/src/manimgx/animation/motion.py+++ b/src/manimgx/animation/motion.py@@ -2249,7 +2249,7 @@ class Wiggle(Animation):)-class ChangingDecimal(Animation["DecimalNumber"]):+class ChangingDecimal[V: (float, complex) = float](Animation["DecimalNumber[V]"]):"""Change the value a number shows with the animation's progress.At every frame, the number shows `number_update_func` of the progress, from 0 to 1,@@ -2278,8 +2278,8 @@ class ChangingDecimal(Animation["DecimalNumber"]):def __init__(self,- decimal_mob: DecimalNumber,- number_update_func: Callable[[float], float],+ decimal_mob: DecimalNumber[V],+ number_update_func: Callable[[float], V],**kwargs: Unpack[AnimationOptions],) -> None:self.number_update_func = number_update_func@@ -2289,7 +2289,7 @@ class ChangingDecimal(Animation["DecimalNumber"]):self.mobject.set_value(self.number_update_func(self.rate_func(alpha)))-class ChangeDecimalToValue(ChangingDecimal):+class ChangeDecimalToValue[V: (float, complex) = float](ChangingDecimal[V]):"""Count a number to a value.It goes from the value it has when the animation is made to `target_number`, eased@@ -2314,8 +2314,8 @@ class ChangeDecimalToValue(ChangingDecimal):def __init__(self,- decimal_mob: DecimalNumber,- target_number: float,+ decimal_mob: DecimalNumber[V],+ target_number: V,**kwargs: Unpack[AnimationOptions],) -> None:start = decimal_mob.numberdiff --git a/src/manimgx/animation/timeline.py b/src/manimgx/animation/timeline.pyindex 36770add..813df6e9 100644--- a/src/manimgx/animation/timeline.py+++ b/src/manimgx/animation/timeline.py@@ -15,13 +15,13 @@ from typing import (Literal,NamedTuple,Self,- TypedDict,TypeIs,Unpack,)from warnings import deprecatedimport numpy as np+from typing_extensions import TypedDictfrom manimgx.animation import clockfrom manimgx.animation.easing import linear, smooth@@ -58,9 +58,8 @@ __all__ = []-class Untimed(TypedDict, total=False):- """Every animation option but `run_time`, which [`Wait`][manimgx.Wait] takes by- position."""+class _Untimed(TypedDict, total=False):+ """Untimed's keys, open, for the keywords that add to them."""lag_ratio: float"""How the parts of the mobject are staggered: each begins this fraction of its run@@ -88,16 +87,25 @@ class Untimed(TypedDict, total=False):does so (default True)."""-class AnimationOptions(Untimed, total=False):+class Untimed(_Untimed, total=False, closed=True):+ """Every animation option but `run_time`, which [`Wait`][manimgx.Wait] takes by+ position."""+++class _AnimationOptions(_Untimed, total=False):+ """AnimationOptions's keys, open, for the keywords that add to them."""++ run_time: float+ """How long the animation plays, in seconds (default 1)."""+++class AnimationOptions(_AnimationOptions, total=False, closed=True):"""The options every animation takes, by keyword.Each animation class sets its own defaults for them: [`Create`][manimgx.Create], forinstance, draws the parts of a mobject one after another (`lag_ratio=1`)."""- run_time: float- """How long the animation plays, in seconds (default 1)."""-_CASCADES: Memo[type, AnimationOptions] = Memo(1 << 12)@@ -274,6 +282,11 @@ class Animation[M: Mobject = Mobject]:)self._run_time = value+ @property+ def _duration(self) -> Fraction:+ """The scene's duration; compositions retain their computed rational exactly."""+ return clock.rational(self.run_time)+@deprecated("Manim CE's machinery: manimgx calls it itself (a custom animation overrides interpolate_mobject)",category=None,@@ -1074,31 +1087,31 @@ class AnimationGroup(Animation):self.done: set[int] = set()self._fresh: set[int] = set() # the parts begun at the instant being computed# a run time given; None: the layout's own, where its last part ends- self._given: float | None = (animation_defaults(type(self)) | kwargs).get(- "run_time"- )- self._layout: tuple[tuple[object, ...], float, list[Placed]] = ((), 0.0, [])+ self._given: float | Fraction | None = (+ animation_defaults(type(self)) | kwargs+ ).get("run_time")+ self._layout: tuple[tuple[object, ...], Fraction, list[Placed]] = ((), _0, [])self._playing = False # between `begin` and `finish`: its layout fixedself._placed: tuple[tuple[object, ...], list[Placed]] = ((), [])- def _laid_out(self) -> tuple[float, list[Placed]]:+ def _laid_out(self) -> tuple[Fraction, list[Placed]]:"""(where the last part ends, each part's window in the group's own time), from thelag and the parts' run times as they are now (a play's options set them after thegroup is made), fixed while it plays."""if self._playing:return self._layout[1], self._layout[2]- key = (self.lag_ratio, *(anim.run_time for anim in self.animations))+ lengths = tuple(anim._duration for anim in self.animations)+ key = (self.lag_ratio, *lengths)if key != self._layout[0]:spans, start = [], _0- lag = Fraction(self.lag_ratio).limit_denominator(10**6)- for anim in self.animations:- length = Fraction(anim.run_time).limit_denominator(10**6)+ lag = clock.rational(self.lag_ratio)+ for length in lengths:spans.append((start, start + length))start += length * lagtotal = max((end for _, end in spans), default=_0)windows = [(a / total, b / total) if total else (_0, _0) for a, b in spans]placed = [(float(a), float(b), b < 1, a, b) for a, b in windows]- self._layout = (key, float(total), placed)+ self._layout = (key, total, placed)return self._layout[1], self._layout[2]def _in(self, start: Fraction, end: Fraction) -> list[Placed]:@@ -1129,7 +1142,7 @@ class AnimationGroup(Animation):@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)def max_end_time(self) -> float:"""Where the last part ends, in seconds: the group's own run time."""- return self._laid_out()[0]+ return float(self._laid_out()[0])@property@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)@@ -1142,7 +1155,7 @@ class AnimationGroup(Animation):def run_time(self) -> float:"""How long the group plays, in seconds: the run time it was given, else where itslast part ends."""- return self.max_end_time if self._given is None else self._given+ return self.max_end_time if self._given is None else float(self._given)@run_time.setterdef run_time(self, value: float) -> None:@@ -1153,6 +1166,14 @@ class AnimationGroup(Animation):)self._given = value+ @property+ def _duration(self) -> Fraction:+ if type(self).run_time is not AnimationGroup.run_time:+ return clock.rational(self.run_time)+ return (+ self._laid_out()[0] if self._given is None else clock.rational(self._given)+ )+def _setup_scene(self, scene: Scene) -> None:self.scene = scene # each part is set up when it begins@@ -1482,14 +1503,21 @@ class ChangeSpeed(AnimationGroup):self.affects_speed_updaters = affects_speed_updaters# each stretch: (from, to, speed at from, speed at to, where it starts in real time)self._stretches: list[tuple[float, float, float, float, float]] = []- self._total = 0.0 # real time, per second of the wrapped animation+ total = _0 # real time, per second of the wrapped animationfor (a, v), (b, w) in pairwise(speeds.items()):- self._stretches.append((a, b, v, w, self._total))- self._total += 2 / (v + w) * (b - a)+ self._stretches.append((a, b, v, w, float(total)))+ total += (+ 2+ * (clock.rational(b) - clock.rational(a))+ / (clock.rational(v) + clock.rational(w))+ )+ self._total = float(total)self._before = kwargs.pop("rate_func", linear)kwargs["rate_func"] = self._rate- kwargs["run_time"] = self._total * self.anim.run_time+ duration = total * self.anim._duration+ kwargs["run_time"] = float(duration)super().__init__(self.anim, **kwargs)+ self._given = durationdef _rate(self, t: float) -> float:"""Its rate function: the wrapped animation's progress at the rate function given@@ -1514,8 +1542,7 @@ class ChangeSpeed(AnimationGroup):return 1.0# at a node, the later stretch (CE's piecewise lets the last condition win)for a, b, v, w, start in reversed(self._stretches):- end = start + 2 / (v + w) * (b - a)- if start / self._total <= t <= end / self._total:+ if start / self._total <= t:x = (self._total * t - start) / (b - a)d = ((w**2 - v**2) * (x * x) / 4 + v * x) * (b - a)return min(max(d + a, a), b) # never past its stretch's endsdiff --git a/src/manimgx/animation/transform.py b/src/manimgx/animation/transform.pyindex 65ef93f0..3c9fd9ae 100644--- a/src/manimgx/animation/transform.py+++ b/src/manimgx/animation/transform.py@@ -18,6 +18,7 @@ from manimgx.animation.timeline import (Animation,AnimationOptions,Key,+ _AnimationOptions,_updating,keyframe_at,)@@ -63,6 +64,7 @@ if TYPE_CHECKING:from manimgx.mobjects.grid import Matrix, Tablefrom manimgx.mobjects.images import ImageMobject, ImageMobjectFromCamerafrom manimgx.mobjects.plotting import (+ Axes,BarChart,ComplexPlane,NumberLine,@@ -78,8 +80,14 @@ if TYPE_CHECKING:Polygram,TipableVMobject,)- from manimgx.mobjects.text import BulletedList, MathTex- from manimgx.mobjects.three_d import Cone, Cylinder, Line3D, Polyhedron, Surface+ from manimgx.mobjects.text import BulletedList, MathTex, Typst+ from manimgx.mobjects.three_d import (+ Cylinder,+ Line3D,+ Polyhedron,+ Surface,+ _DirectedSurface,+ )from manimgx.mobjects.vector_field import StreamLines, VectorFieldclass _Of[T](Protocol):@@ -95,6 +103,8 @@ if TYPE_CHECKING:**P2 = ...,S3: Mobject = Never,**P3 = ...,+ S4: Mobject = Never,+ **P4 = ...,]:"""A mobject method as a proxy records it: for mobjects of kind S (the method's ownclass), the method's parameters P, returning the proxy — per kind, first match.@@ -108,6 +118,8 @@ if TYPE_CHECKING:def __get__[R](self, proxy: R, owner: type[_Of[S2]]) -> Callable[P2, R]: ...@overloaddef __get__[R](self, proxy: R, owner: type[_Of[S3]]) -> Callable[P3, R]: ...+ @overload+ def __get__[R](self, proxy: R, owner: type[_Of[S4]]) -> Callable[P4, R]: ...def __get__(self, proxy: object, owner: type) -> object:raise NotImplementedError # typing only@@ -128,6 +140,24 @@ if TYPE_CHECKING:m1: Callable[PA, A], m2: Callable[PB, B], m3: Callable[PC, C], /) -> _Method[A, PA, B, PB, C, PC]: ...+ @overload+ def recorded[+ A: Mobject,+ **PA,+ B: Mobject,+ **PB,+ C: Mobject,+ **PC,+ D: Mobject,+ **PD,+ ](+ m1: Callable[PA, A],+ m2: Callable[PB, B],+ m3: Callable[PC, C],+ m4: Callable[PD, D],+ /,+ ) -> _Method[A, PA, B, PB, C, PC, D, PD]: ...+def recorded(*methods: object) -> object:"""A method a proxy records, from each kind's bound method (its kind is what it returns)."""raise NotImplementedError # typing only@@ -136,7 +166,7 @@ if TYPE_CHECKING:__all__ = ["Animate", "Transform"]-class TransformOptions(AnimationOptions, total=False):+class TransformOptions(_AnimationOptions, total=False, closed=True):"""The options a transform takes, by keyword: the animation options and its path."""path_func: PathFunc | None@@ -635,7 +665,7 @@ class _Methods:) -> Self: ...save_state = recorded(_on(Mobject).save_state)- scale = recorded(_on(Arrow).scale, _on(Mobject).scale)+ scale = recorded(_on(Arrow).scale, _on(Typst).scale, _on(Mobject).scale)scale_to_fit_height = recorded(_on(Mobject).scale_to_fit_height)scale_to_fit_width = recorded(_on(Mobject).scale_to_fit_width)set = recorded(_on(Mobject).set)@@ -646,6 +676,7 @@ class _Methods:)set_coord = recorded(_on(Mobject).set_coord)set_fill = recorded(_on(Mobject).set_fill)+ set_material = recorded(_on(Mobject).set_material)set_opacity = recorded(_on(ImageMobject).set_opacity, _on(Mobject).set_opacity)set_points = recorded(_on(Mobject).set_points)set_sheen = recorded(_on(Mobject).set_sheen)@@ -681,18 +712,23 @@ class _Methods:# VMobjectadd_cubic_bezier_curve = recorded(_on(VMobject).add_cubic_bezier_curve)add_cubic_bezier_curve_to = recorded(_on(VMobject).add_cubic_bezier_curve_to)+ add_cubic_bezier_curves = recorded(_on(VMobject).add_cubic_bezier_curves)add_line_to = recorded(_on(VMobject).add_line_to)add_points_as_corners = recorded(_on(VMobject).add_points_as_corners)add_quadratic_bezier_curve_to = recorded(_on(VMobject).add_quadratic_bezier_curve_to)add_smooth_curve_to = recorded(_on(VMobject).add_smooth_curve_to)+ add_subpath = recorded(_on(VMobject).add_subpath)append_points = recorded(_on(VMobject).append_points)+ append_vectorized_mobject = recorded(_on(VMobject).append_vectorized_mobject)change_anchor_mode = recorded(_on(VMobject).change_anchor_mode)clear_points = recorded(_on(VMobject).clear_points)+ close_path = recorded(_on(VMobject).close_path)force_direction = recorded(_on(VMobject).force_direction)get_subcurve = recorded(_on(VMobject).get_subcurve)insert_n_curves = recorded(_on(VMobject).insert_n_curves)+ make_jagged = recorded(_on(VMobject).make_jagged)make_smooth = recorded(_on(VMobject).make_smooth)reverse_direction = recorded(_on(VMobject).reverse_direction)scale_handle_to_anchor_distances = recorded(@@ -705,9 +741,12 @@ class _Methods:set_shade_in_3d = recorded(_on(VMobject).set_shade_in_3d)start_new_path = recorded(_on(VMobject).start_new_path)# the kinds' own+ add_background_to_entries = recorded(_on(Table).add_background_to_entries)add_bases = recorded(_on(Cylinder).add_bases)add_coordinates = recorded(- _on(PolarPlane).add_coordinates, _on(ComplexPlane).add_coordinates+ _on(PolarPlane).add_coordinates,+ _on(ComplexPlane).add_coordinates,+ _on(Axes).add_coordinates,)add_display_frame = recorded(_on(ImageMobjectFromCamera).add_display_frame)add_highlighted_cell = recorded(_on(Table).add_highlighted_cell)@@ -731,6 +770,8 @@ class _Methods:increment_value = recorded(_on(ValueTracker[complex]).increment_value,_on(ValueTracker).increment_value,+ _on(DecimalNumber).increment_value,+ _on(DecimalNumber[complex]).increment_value,)match_colors = recorded(_on(PMobject).match_colors)move_arc_center_to = recorded(_on(Arc).move_arc_center_to)@@ -755,7 +796,7 @@ class _Methods:set_column_colors = recorded(_on(Matrix).set_column_colors, _on(Table).set_column_colors)- set_direction = recorded(_on(Cone).set_direction, _on(Cylinder).set_direction)+ set_direction = recorded(_on(_DirectedSurface).set_direction)set_fill_by_checkerboard = recorded(_on(Surface).set_fill_by_checkerboard)set_fill_by_value = recorded(_on(Surface).set_fill_by_value)set_length = recorded(_on(Line).set_length)@@ -769,6 +810,7 @@ class _Methods:_on(ComplexValueTracker).set_value,_on(ValueTracker).set_value,_on(DecimalNumber).set_value,+ _on(DecimalNumber[complex]).set_value,)start_animation = recorded(_on(StreamLines).start_animation)start_submobject_movement = recorded(_on(VectorField).start_submobject_movement)@@ -832,10 +874,24 @@ class Animate[M: Mobject](Transform[M], _Methods):self._chosen: PathFunc | None = self._path_funcself.keys = (None, self._replay)- def __call__(self, **anim_args: Unpack[TransformOptions]) -> Self:- """Set the animation's options, before any method is recorded.+ def __call__(+ self,+ function: Callable[[M], object] | None = None,+ /,+ **anim_args: Unpack[TransformOptions],+ ) -> Self:+ """Set the animation's options, before any method is recorded; and record a+ function of the mobject, as a method's call is recorded.++ A function can make any change, with methods of your own class too, and a type+ checker checks it against the mobject's class: `box.animate(lambda b: b.grow(2))`.+ (`box.animate.grow(2)` works as well, but through `animate` a type checker knows+ only manimgx's methods.)Args:+ function: A function that changes the mobject: tried at once on a copy, so a+ wrong call fails where it is written, and carried out as recorded methods+ are. None for none.**anim_args: [Transform options][manimgx.animation.transform.TransformOptions].Returns:@@ -860,9 +916,29 @@ class Animate[M: Mobject](Transform[M], _Methods):else self._path_func)self.keys = (None, self._replay)+ if function is not None:+ if self._override is not None:+ raise NotImplementedError(+ "Method chaining is currently not supported for overridden animations"+ )+ self._record(function, (), {})+ self._chaining = Truereturn self- def __getattr__(self, name: str) -> Callable[..., Animation]:+ def _record(+ self,+ function: Callable[..., object],+ args: tuple[object, ...],+ kwargs: dict[str, object],+ ) -> None:+ """Record a call of `function` on the mobject, tried at once on the target: a+ wrong call fails where it is written."""+ function(self._target, *args, **kwargs)+ own = {id(m) for mob in (self.mobject, self._target) for m in mob.get_family()}+ self.methods.append(_Call(function, args, kwargs, own))++ def _recorder(self, name: str) -> Callable[..., Animation]:+ """The mobject's method `name`, which records its calls."""if name.startswith("_") or "_target" not in self.__dict__:raise AttributeError(name)method = getattr(self._target, name)@@ -881,16 +957,17 @@ class Animate[M: Mobject](Transform[M], _Methods):)self._override = animationreturn animation- method(*args, **kwargs) # tried on the target: a wrong call fails here- own = {- id(m) for mob in (self.mobject, self._target) for m in mob.get_family()- }- self.methods.append(_Call(method.__func__, args, kwargs, own))+ self._record(method.__func__, args, kwargs)return selfself._chaining = Truereturn record+ if (+ not TYPE_CHECKING+ ): # a type checker knows the methods by the table, and no others+ __getattr__ = _recorder+def _replay(self, target: Mobject) -> Mobject:"""The recorded calls, carried out on (a copy of) the object as it is when the animationbegins, on their arguments as written."""@@ -975,7 +1052,8 @@ class Always[M: Mobject](_Methods):"""The mobject whose method calls become updaters."""return self._mobject- def __getattr__(self, name: str) -> Callable[..., Self]:+ def _updater(self, name: str) -> Callable[..., Self]:+ """The mobject's method `name`, whose calls become its updaters."""if name.startswith("_"):raise AttributeError(name)@@ -986,3 +1064,8 @@ class Always[M: Mobject](_Methods):return selfreturn add_updater++ if (+ not TYPE_CHECKING+ ): # a type checker knows the methods by the table, and no others+ __getattr__ = _updaterdiff --git a/tests/unit/animation/test_clock.py b/tests/unit/animation/test_clock.pyindex 0698ff6f..4f7d9c1e 100644--- a/tests/unit/animation/test_clock.py+++ b/tests/unit/animation/test_clock.py@@ -6,12 +6,68 @@one begun last rules while it lasts."""+import math+from fractions import Fraction+import pytest-from hypothesis import given+from hypothesis import example, givenfrom hypothesis import strategies as stfrom manimgx.animation import easing as rf-from manimgx.animation.clock import Clock+from manimgx.animation.clock import Clock, frame_at, rational+++@given(value=st.floats(allow_nan=False, allow_infinity=False))+@example(value=math.ulp(0.0))+@example(value=-math.ulp(0.0))+@example(value=float.fromhex("0x1.fffffffffffffp+1023"))+@example(value=1.0000004191481406)+def test_rational_time_preserves_the_supplied_float(value: float) -> None:+ exact = rational(value)+ assert float(exact) == value+ assert rational(-value) == -exact+ if exact.denominator > 1:+ # Independent nearest-rational oracle: a smaller denominator cannot round-trip.+ nearer = Fraction(value).limit_denominator(exact.denominator - 1)+ assert float(nearer) != value+++@given(numerator=st.integers(-10000, 10000), denominator=st.integers(1, 10000))+def test_small_rational_times_keep_their_exact_boundaries(+ numerator: int, denominator: int+) -> None:+ value = Fraction(numerator, denominator)+ assert rational(float(value)) == value+ assert rational(value) == value+++@given(exponent=st.integers(-1074, 52))+def test_adjacent_times_at_a_binary_exponent_boundary_stay_ordered(+ exponent: int,+) -> None:+ value = math.ldexp(1.0, exponent)+ before, after = math.nextafter(value, -math.inf), math.nextafter(value, math.inf)+ assert rational(before) < rational(value) < rational(after)+++@given(+ time=st.fractions(min_value=-1000, max_value=1000),+ rate=st.fractions(min_value=1, max_value=1000),+ after=st.booleans(),+)+@example(time=Fraction(1), rate=Fraction(2**54), after=False)+@example(time=Fraction(1) + Fraction(1, 2**53), rate=Fraction(2**54), after=True)+@example(time=Fraction(1) + Fraction(3, 2**53), rate=Fraction(2**54), after=False)+def test_sampling_chooses_the_first_representable_instant_not_before_the_event(+ time: Fraction, rate: Fraction, after: bool+) -> None:+ frame = frame_at(time, rate, after=after)+ before, here = float((frame - 1) / rate), float(frame / rate)+ if after:+ assert before <= float(time) < here+ else:+ assert before < float(time) <= here+# monotone maps of [0, 1] onto itself, of bounded slope (at most 10)PROGRESSES = [rf.linear, rf.smooth, rf.rush_into, rf.rush_from, rf.ease_out_quad, rf.double_smooth,diff --git a/tests/unit/animation/test_easing.py b/tests/unit/animation/test_easing.pyindex 747a9083..2be53573 100644--- a/tests/unit/animation/test_easing.py+++ b/tests/unit/animation/test_easing.py@@ -2,8 +2,8 @@- Each starts exactly at 0 and ends exactly at 1 (the there-and-back family at 0), and holdsits ends outside [0, 1]: an animation lands exactly where it is going.-- Each is continuous, the exponential and elastic eases at their ends too, and the easing- family is monotone.+- Each is continuous, the exponential and elastic eases at their ends too; the designated+ monotone functions never go backward.- An ease-out is its ease-in turned around, and an ease-in-out runs its ease-in at doublespeed up to the middle: the thirty formulas are one family.- The extremes their docstrings give are their extremes.diff --git a/tests/unit/animation/test_matching.py b/tests/unit/animation/test_matching.pyindex b23f1495..fbfe0e6c 100644--- a/tests/unit/animation/test_matching.py+++ b/tests/unit/animation/test_matching.py@@ -9,6 +9,7 @@ is a law of every animation: `test_timeline.py`'s registry laws.)from collections.abc import Hashable+import pytestfrom hypothesis import givenfrom hypothesis import strategies as st@@ -46,3 +47,44 @@ def test_parts_are_gathered_by_key_in_their_own_order(indices: list[int]) -> Nonlast = {i: p for p, i in enumerate(indices)} # each token's last placeexpected = sorted({i for i in indices if i % 3 == key}, key=last.__getitem__)assert [id(x) for x in group.submobjects] == [id(tokens[i]) for i in expected]++[email protected]("mismatches", ["fade", "transform", "crossfade"])+@given(+ source_keys=st.lists(st.integers(0, 2), unique=True),+ target_keys=st.lists(st.integers(0, 2), unique=True),+ mapped_keys=st.lists(st.integers(0, 3), unique=True),+ destinations=st.permutations(range(4)),+)+def test_explicit_matches_and_automatic_matches_partition_the_parts(+ mismatches: str,+ source_keys: list[int],+ target_keys: list[int],+ mapped_keys: list[int],+ destinations: list[int],+) -> None:+ source = m.Group(*(Token(key) for key in source_keys))+ target = m.Group(*(Token(key) for key in target_keys))+ key_map = dict(zip(mapped_keys, destinations, strict=False))+ animation = Matcher(+ source,+ target,+ key_map=key_map,+ transform_mismatches=mismatches == "transform",+ fade_transform_mismatches=mismatches == "crossfade",+ )+ # Every original part has one owner, including parts with explicit matches.+ owners = [+ part for child in animation.animations for part in child.mobject.get_family()+ ]+ assert all(sum(part is owned for owned in owners) == 1 for part in source)+ reserved = {+ key+ for first, second in key_map.items()+ if first in source_keys and second in target_keys+ for key in (first, second)+ }+ automatic = animation.animations[0].mobject.get_family()+ assert {part.value for part in automatic if isinstance(part, Token)} == (+ set(source_keys) & set(target_keys)+ ) - reserveddiff --git a/tests/unit/animation/test_timeline.py b/tests/unit/animation/test_timeline.pyindex 075b2e8b..5f8ac633 100644--- a/tests/unit/animation/test_timeline.py+++ b/tests/unit/animation/test_timeline.py@@ -420,6 +420,7 @@ class TestLayout:),lag=st.floats(0, 2),)+ @example(times=[2.5, 0.0], lag=1.0000004191481406)def test_a_group_lasts_until_its_last_part_ends(self, times: list[float], lag: float) -> None:@@ -432,6 +433,19 @@ class TestLayout:sum(times), abs=1e-6)+ @given(times=st.lists(st.floats(0, 5), min_size=2, max_size=5))+ @example(times=[2.500001047870352, 1e-8, 1 / 3])+ def test_nested_successions_keep_exact_durations(self, times: list[float]) -> None:+ parts = [m.Wait(t) for t in times]+ flat = m.Succession(*parts)+ nested = m.Succession(parts[0], m.Succession(*parts[1:]))+ expected = sum((clock.rational(t) for t in times), Fraction(0))+ assert flat._duration == nested._duration == expected+ flat_windows, nested_windows = windows(flat), windows(nested)+ assert [w.opens * flat._duration for w in flat_windows] == [+ w.opens * nested._duration for w in nested_windows+ ]+@given(parts=st.lists(leaves(3), min_size=2, max_size=3),lag=st.sampled_from([0.25, 0.5, 1.0]),@@ -608,8 +622,24 @@ def nodes(speedinfo: dict[float, float]) -> list[tuple[float, float, float]]:return out+def test_a_speed_profile_composes_its_duration_exactly() -> None:+ change = m.ChangeSpeed(m.Wait(2), speedinfo={0.4: 1, 0.5: 0.2, 0.8: 0.2, 1: 1})+ assert change._duration == Fraction(24, 5)+ assert m.Succession(change, m.Wait(0.2))._duration == 5++class TestProfile:+ @given(at=st.floats(0.05, 0.95), speed=st.floats(0.2, 4))+ def test_splitting_a_constant_speed_profile_preserves_its_duration(+ self, at: float, speed: float+ ) -> None:+ part = m.Wait(0.3)+ whole = m.ChangeSpeed(part, speedinfo={0: speed, 1: speed})+ split = m.ChangeSpeed(part, speedinfo={0: speed, at: speed, 1: speed})+ assert split._duration == whole._duration+@given(speedinfo=speedinfos)+ @example(speedinfo={0.5954991299724285: 2.0, 0.3026788225275667: 2.318359375})def test_it_reaches_each_point_when_the_stretches_before_it_have_played(self, speedinfo: dict[float, float]) -> None:diff --git a/tests/unit/animation/test_transform.py b/tests/unit/animation/test_transform.pyindex 784b18c3..ba7b403f 100644--- a/tests/unit/animation/test_transform.py+++ b/tests/unit/animation/test_transform.py@@ -2,7 +2,8 @@together on one mobject compose; a replacement leaves its target in its mobject's place.- `.animate` and `ApplyMethod` take their arguments as written, and carry the calls out on the- mobject as it is when the animation begins.+ mobject as it is when the animation begins. A function given to `.animate` is a call too:+ tried at once, and carried out with them.- An animation's `keys` (functions of the mobject) are applied when it begins, to a copy.- A mobject's override (`override_animation`) plays in place of the animation it overrides,the animation given in a list or a generator too.@@ -15,9 +16,20 @@ together on one mobject compose; a replacement leaves its target in its mobject'- Played, a transform made to replace its mobject (`replace_mobject_with_target_in_scene`, asa scene gives it) leaves the scene holding its target where the mobject was; one with notarget of its own leaves the mobject (a remover, nothing): never an object of its own making.+- `.animate` and `.always` are typed by a table of the library's methods (`_Methods`), not by+ their `__getattr__`, which a type checker doesn't see: every public method of a mobject+ class that returns the mobject is in it, typed with the class's own parameters."""+import ast+import importlib+import inspect+import pkgutil+import textwrapfrom collections.abc import Callable, Iterator+from functools import cache+from pathlib import Path+from typing import Selfimport numpy as npimport pytest@@ -57,6 +69,24 @@ def test_recorded_calls_snapshot_arguments_but_replay_on_the_current_mobject(np.testing.assert_allclose(square.get_center(), wanted, atol=1e-12)+def test_a_function_given_to_animate_is_a_call() -> None:+ # any change, with a method of the scene's own class too+ class Box(m.Square):+ def grow(self) -> Self:+ return self.scale(2)++ box = Box()+ animation = box.animate(lambda b: b.grow().shift(m.RIGHT), run_time=2)+ assert animation.run_time == 2+ box.shift(m.UP)+ animation.begin()+ animation.finish()+ assert box.width == pytest.approx(4)+ np.testing.assert_allclose(box.get_center(), m.UP + m.RIGHT, atol=1e-12)+ with pytest.raises(AttributeError): # tried at once: it fails where it is written+ m.Square().animate(lambda s: s.shfit(m.RIGHT)) # ty: ignore[unresolved-attribute]++def test_keys_are_applied_as_the_animation_begins_to_a_copy() -> None:square = m.Square()copies: list[m.Mobject] = []@@ -163,8 +193,9 @@ REPLACING: dict[str, Callable[[m.Square, m.Circle], m.Transform]] = {"MoveAlongPath": lambda sq, c: m.MoveAlongPath(sq, m.Line(m.LEFT, m.RIGHT), **REPLACE),- "Create": lambda sq, c: m.Create(sq, **REPLACE),- "DrawBorderThenFill": lambda sq, c: m.DrawBorderThenFill(sq, **REPLACE),+ # not transforms: they have no target, and leave the square where it is+ "Create": lambda sq, c: m.Create(sq),+ "DrawBorderThenFill": lambda sq, c: m.DrawBorderThenFill(sq),"CyclicReplace": lambda sq, c: m.CyclicReplace(sq, **REPLACE),}@@ -187,3 +218,125 @@ def test_a_replacement_leaves_its_target_in_its_mobjects_place(name: str) -> Nonelse:middle = [] if animation.is_remover() else [square]assert [id(x) for x in told.mobjects] == [id(x) for x in (before, *middle, after)]+++class _Unquoted(ast.NodeTransformer):+ """An annotation as its type reads, written in quotes or not."""++ def visit_Constant(self, node: ast.Constant) -> ast.AST:+ if isinstance(node.value, str):+ return self.visit(ast.parse(node.value, mode="eval").body)+ return node+++def _text(node: ast.expr | None) -> str:+ return "" if node is None else ast.unparse(_Unquoted().visit(node))+++def _parameters(args: ast.arguments) -> tuple[tuple[str, str, bool], ...]:+ """A method's parameters but `self`: each one's name, type, and whether it has a default."""+ every = [*args.posonlyargs, *args.args]+ defaults = [False] * (len(every) - len(args.defaults)) + [True] * len(args.defaults)+ found = [+ (a.arg, _text(a.annotation), d) for a, d in zip(every, defaults, strict=True)+ ]+ found += [(f"*{a.arg}", _text(a.annotation), False) for a in [args.vararg] if a]+ found += [+ (a.arg, _text(a.annotation), d is not None)+ for a, d in zip(args.kwonlyargs, args.kw_defaults, strict=True)+ ]+ found += [(f"**{a.arg}", _text(a.annotation), False) for a in [args.kwarg] if a]+ return tuple(found[1:])+++@cache+def _defined(cls: type) -> dict[str, ast.FunctionDef]:+ """The methods a class's own body defines, by name (an overloaded one's implementation)."""+ body = ast.parse(textwrap.dedent(inspect.getsource(cls))).body[0]+ assert isinstance(body, ast.ClassDef)+ return {+ node.name: node+ for node in body.body+ if isinstance(node, ast.FunctionDef)+ and not any(ast.unparse(d) == "overload" for d in node.decorator_list)+ }+++def _table() -> dict[str, list[str]]:+ """The names `.animate` types, each with the kinds of mobject it is typed for, in the+ order a type checker tries them (empty: a method typed by hand)."""+ source = Path(inspect.getfile(m.Animate)).read_text(encoding="utf-8")+ methods = next(+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.ClassDef) and node.name == "_Methods"+ )+ table: dict[str, list[str]] = {}+ for node in ast.walk(methods):+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call):+ name = node.targets[0]+ assert isinstance(name, ast.Name)+ table[name.id] = [+ ast.unparse(arg.value.args[0]).split("[")[0]+ for arg in node.value.args+ if isinstance(arg, ast.Attribute) and isinstance(arg.value, ast.Call)+ ]+ elif isinstance(node, ast.FunctionDef):+ table[node.name] = []+ return table+++def _mobject_classes() -> dict[str, type[m.Mobject]]:+ """Every mobject class the package defines, by name: its private bases too."""+ found: dict[str, type[m.Mobject]] = {}+ for module in pkgutil.walk_packages(m.__path__, "manimgx."):+ if module.name.endswith("__main__"): # the command line, run when imported+ continue+ for value in vars(importlib.import_module(module.name)).values():+ if (+ isinstance(value, type)+ and issubclass(value, m.Mobject)+ and value.__module__ == module.name+ ):+ assert found.setdefault(value.__name__, value) is value+ return found+++def test_animate_types_every_method_that_returns_the_mobject() -> None:+ table, classes = _table(), _mobject_classes()+ shadowed = set(dir(m.Animate)) # the animation's own attributes come first+ # a copy is another mobject: through `.animate`, there is nothing to record, and ty says so+ unchanging = {"copy"}++ def parameters(cls: type, name: str) -> tuple[tuple[str, str, bool], ...]:+ owner = next(c for c in cls.__mro__ if name in _defined(c))+ return _parameters(_defined(owner)[name].args)++ problems = []+ for cls in classes.values():+ for name, method in _defined(cls).items():+ decorators = [ast.unparse(d) for d in method.decorator_list]+ if (+ name.startswith("_")+ or _text(method.returns) != "Self"+ or any(d.startswith("deprecated") for d in decorators)+ or {"classmethod", "staticmethod"} & set(decorators) # makes another+ or name in shadowed | unchanging+ ):+ continue+ if name not in table:+ problems.append(f"{cls.__name__}.{name}: not in the table")+ continue+ kinds = [classes[kind] for kind in table[name]]+ if not kinds: # typed by hand+ continue+ first = next((kind for kind in kinds if issubclass(cls, kind)), None)+ if first is None:+ problems.append(+ f"{cls.__name__}.{name}: none of the table's kinds is it"+ )+ elif parameters(first, name) != parameters(cls, name):+ problems.append(+ f"{cls.__name__}.{name}: typed with {first.__name__}'s parameters"+ )+ assert not problems, "\n".join(problems)