Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add type annotations to manim.utils.* (#3999)

Henrik Skov Midtiby17d4a7f635a7
diff --git a/manim/mobject/text/numbers.py b/manim/mobject/text/numbers.py
index 5283c24a2..1c74cf5f0 100644
--- a/manim/mobject/text/numbers.py
+++ b/manim/mobject/text/numbers.py
@@ -5,6 +5,7 @@ from __future__ import annotations
__all__ = ["DecimalNumber", "Integer", "Variable"]
from collections.abc import Sequence
+from typing import Any
import numpy as np
@@ -327,7 +328,9 @@ class Integer(DecimalNumber):
self.add(Integer(number=6.28).set_x(-1.5).set_y(-2).set_color(YELLOW).scale(1.4))
"""
- def __init__(self, number=0, num_decimal_places=0, **kwargs):
+ def __init__(
+ self, number: float = 0, num_decimal_places: int = 0, **kwargs: Any
+ ) -> None:
super().__init__(number=number, num_decimal_places=num_decimal_places, **kwargs)
def get_value(self):
diff --git a/manim/renderer/cairo_renderer.py b/manim/renderer/cairo_renderer.py
index 6625a49eb..7efd7b022 100644
--- a/manim/renderer/cairo_renderer.py
+++ b/manim/renderer/cairo_renderer.py
@@ -19,6 +19,8 @@ if typing.TYPE_CHECKING:
from manim.animation.animation import Animation
from manim.scene.scene import Scene
+ from ..typing import PixelArray
+
__all__ = ["CairoRenderer"]
@@ -158,7 +160,7 @@ class CairoRenderer:
self.update_frame(scene, moving_mobjects)
self.add_frame(self.get_frame())
- def get_frame(self):
+ def get_frame(self) -> PixelArray:
"""
Gets the current frame as NumPy array.
diff --git a/manim/renderer/opengl_renderer.py b/manim/renderer/opengl_renderer.py
index 2f0ad398f..7d4b6a446 100644
--- a/manim/renderer/opengl_renderer.py
+++ b/manim/renderer/opengl_renderer.py
@@ -388,7 +388,7 @@ class OpenGLRenderer:
return self.path_to_texture_id[repr(path)]
- def update_skipping_status(self):
+ def update_skipping_status(self) -> None:
"""
This method is used internally to check if the current
animation needs to be skipped or not. It also checks if
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index bf8e526bf..fc3d3ede5 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -488,7 +488,7 @@ class Scene:
self.moving_mobjects += mobjects
return self
- def add_mobjects_from_animations(self, animations):
+ def add_mobjects_from_animations(self, animations: list[Animation]) -> None:
curr_mobjects = self.get_mobject_family_members()
for animation in animations:
if animation.is_introducer():
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index 4293de710..d256afb73 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -20,7 +20,7 @@ from PIL import Image
from pydub import AudioSegment
from manim import __version__
-from manim.typing import PixelArray
+from manim.typing import PixelArray, StrPath
from .. import config, logger
from .._config.logger_utils import set_file_logger
@@ -38,6 +38,7 @@ from ..utils.sounds import get_full_sound_file_path
from .section import DefaultSectionType, Section
if TYPE_CHECKING:
+ from manim.renderer.cairo_renderer import CairoRenderer
from manim.renderer.opengl_renderer import OpenGLRenderer
@@ -104,7 +105,12 @@ class SceneFileWriter:
force_output_as_scene_name = False
- def __init__(self, renderer, scene_name, **kwargs):
+ def __init__(
+ self,
+ renderer: CairoRenderer | OpenGLRenderer,
+ scene_name: StrPath,
+ **kwargs: Any,
+ ) -> None:
self.renderer = renderer
self.init_output_directories(scene_name)
self.init_audio()
@@ -118,7 +124,7 @@ class SceneFileWriter:
name="autocreated", type_=DefaultSectionType.NORMAL, skip_animations=False
)
- def init_output_directories(self, scene_name):
+ def init_output_directories(self, scene_name: StrPath) -> None:
"""Initialise output directories.
Notes
@@ -378,7 +384,9 @@ class SceneFileWriter:
self.add_audio_segment(new_segment, time, **kwargs)
# Writers
- def begin_animation(self, allow_write: bool = False, file_path=None):
+ def begin_animation(
+ self, allow_write: bool = False, file_path: StrPath | None = None
+ ) -> None:
"""
Used internally by manim to stream the animation to FFMPEG for
displaying or writing to a file.
@@ -391,7 +399,7 @@ class SceneFileWriter:
if write_to_movie() and allow_write:
self.open_partial_movie_stream(file_path=file_path)
- def end_animation(self, allow_write: bool = False):
+ def end_animation(self, allow_write: bool = False) -> None:
"""
Internally used by Manim to stop streaming to
FFMPEG gracefully.
diff --git a/manim/utils/bezier.py b/manim/utils/bezier.py
index b089a1b03..129c26b3c 100644
--- a/manim/utils/bezier.py
+++ b/manim/utils/bezier.py
@@ -29,15 +29,12 @@ import numpy as np
from manim.utils.simple_functions import choose
if TYPE_CHECKING:
- import numpy.typing as npt
-
from manim.typing import (
BezierPoints,
BezierPoints_Array,
BezierPointsLike,
BezierPointsLike_Array,
ColVector,
- ManimFloat,
MatrixMN,
Point3D,
Point3D_Array,
@@ -64,7 +61,9 @@ def bezier(
) -> Callable[[float | ColVector], Point3D_Array]: ...
-def bezier(points):
+def bezier(
+ points: Point3D_Array | Sequence[Point3D_Array],
+) -> Callable[[float | ColVector], Point3D_Array]:
"""Classic implementation of a Bézier curve.
Parameters
@@ -118,21 +117,21 @@ def bezier(points):
if degree == 0:
- def zero_bezier(t):
+ def zero_bezier(t: float | ColVector) -> Point3D | Point3D_Array:
return np.ones_like(t) * P[0]
return zero_bezier
if degree == 1:
- def linear_bezier(t):
+ def linear_bezier(t: float | ColVector) -> Point3D | Point3D_Array:
return P[0] + t * (P[1] - P[0])
return linear_bezier
if degree == 2:
- def quadratic_bezier(t):
+ def quadratic_bezier(t: float | ColVector) -> Point3D | Point3D_Array:
t2 = t * t
mt = 1 - t
mt2 = mt * mt
@@ -142,7 +141,7 @@ def bezier(points):
if degree == 3:
- def cubic_bezier(t):
+ def cubic_bezier(t: float | ColVector) -> Point3D | Point3D_Array:
t2 = t * t
t3 = t2 * t
mt = 1 - t
@@ -152,11 +151,12 @@ def bezier(points):
return cubic_bezier
- def nth_grade_bezier(t):
+ def nth_grade_bezier(t: float | ColVector) -> Point3D | Point3D_Array:
is_scalar = not isinstance(t, np.ndarray)
if is_scalar:
B = np.empty((1, *P.shape))
else:
+ assert isinstance(t, np.ndarray)
t = t.reshape(-1, *[1 for dim in P.shape])
B = np.empty((t.shape[0], *P.shape))
B[:] = P
@@ -169,7 +169,8 @@ def bezier(points):
# In the end, there shall be the evaluation at t of a single Bezier curve of
# grade d, stored in the first slot of B
if is_scalar:
- return B[0, 0]
+ val: Point3D = B[0, 0]
+ return val
return B[:, 0]
return nth_grade_bezier
@@ -1026,7 +1027,11 @@ def interpolate(start: Point3D, end: Point3D, alpha: float) -> Point3D: ...
def interpolate(start: Point3D, end: Point3D, alpha: ColVector) -> Point3D_Array: ...
-def interpolate(start, end, alpha):
+def interpolate(
+ start: float | Point3D,
+ end: float | Point3D,
+ alpha: float | ColVector,
+) -> float | ColVector | Point3D | Point3D_Array:
"""Linearly interpolates between two values ``start`` and ``end``.
Parameters
@@ -1139,7 +1144,9 @@ def inverse_interpolate(start: Point3D, end: Point3D, value: Point3D) -> Point3D
def inverse_interpolate(
- start: float | Point3D, end: float | Point3D, value: float | Point3D
+ start: float | Point3D,
+ end: float | Point3D,
+ value: float | Point3D,
) -> float | Point3D:
"""Perform inverse interpolation to determine the alpha
values that would produce the specified ``value``
@@ -1234,7 +1241,7 @@ def match_interpolate(
return interpolate(
new_start,
new_end,
- old_alpha, # type: ignore[arg-type]
+ old_alpha,
)
@@ -1270,7 +1277,8 @@ def get_smooth_cubic_bezier_handle_points(
# they can only be an interpolation of these two anchors with alphas
# 1/3 and 2/3, which will draw a straight line between the anchors.
if n_anchors == 2:
- return interpolate(anchors[0], anchors[1], np.array([[1 / 3], [2 / 3]]))
+ val = interpolate(anchors[0], anchors[1], np.array([[1 / 3], [2 / 3]]))
+ return (val[0], val[1])
# Handle different cases depending on whether the points form a closed
# curve or not
@@ -1745,7 +1753,12 @@ def get_quadratic_approximation_of_cubic(
) -> QuadraticBezierPath: ...
-def get_quadratic_approximation_of_cubic(a0, h0, h1, a1):
+def get_quadratic_approximation_of_cubic(
+ a0: Point3D | Point3D_Array,
+ h0: Point3D | Point3D_Array,
+ h1: Point3D | Point3D_Array,
+ a1: Point3D | Point3D_Array,
+) -> QuadraticSpline | QuadraticBezierPath:
r"""If ``a0``, ``h0``, ``h1`` and ``a1`` are the control points of a cubic
Bézier curve, approximate the curve with two quadratic Bézier curves and
return an array of 6 points, where the first 3 points represent the first
@@ -1849,33 +1862,33 @@ def get_quadratic_approximation_of_cubic(a0, h0, h1, a1):
If ``a0``, ``h0``, ``h1`` and ``a1`` have different dimensions, or
if their number of dimensions is not 1 or 2.
"""
- a0 = np.asarray(a0)
- h0 = np.asarray(h0)
- h1 = np.asarray(h1)
- a1 = np.asarray(a1)
-
- if all(arr.ndim == 1 for arr in (a0, h0, h1, a1)):
- num_curves, dim = 1, a0.shape[0]
- elif all(arr.ndim == 2 for arr in (a0, h0, h1, a1)):
- num_curves, dim = a0.shape
+ a0c = np.asarray(a0)
+ h0c = np.asarray(h0)
+ h1c = np.asarray(h1)
+ a1c = np.asarray(a1)
+
+ if all(arr.ndim == 1 for arr in (a0c, h0c, h1c, a1c)):
+ num_curves, dim = 1, a0c.shape[0]
+ elif all(arr.ndim == 2 for arr in (a0c, h0c, h1c, a1c)):
+ num_curves, dim = a0c.shape
else:
raise ValueError("All arguments must be Point3D or Point3D_Array.")
- m0 = 0.25 * (3 * h0 + a0)
- m1 = 0.25 * (3 * h1 + a1)
+ m0 = 0.25 * (3 * h0c + a0c)
+ m1 = 0.25 * (3 * h1c + a1c)
k = 0.5 * (m0 + m1)
result = np.empty((6 * num_curves, dim))
- result[0::6] = a0
+ result[0::6] = a0c
result[1::6] = m0
result[2::6] = k
result[3::6] = k
result[4::6] = m1
- result[5::6] = a1
+ result[5::6] = a1c
return result
-def is_closed(points: Point3DLike_Array) -> bool:
+def is_closed(points: Point3D_Array) -> bool:
"""Returns ``True`` if the spline given by ``points`` is closed, by
checking if its first and last points are close to each other, or``False``
otherwise.
@@ -1952,7 +1965,7 @@ def proportions_along_bezier_curve_for_point(
point: Point3DLike,
control_points: BezierPointsLike,
round_to: float = 1e-6,
-) -> npt.NDArray[ManimFloat]:
+) -> MatrixMN:
"""Obtains the proportion along the bezier curve corresponding to a given point
given the bezier curve's control points.
diff --git a/manim/utils/caching.py b/manim/utils/caching.py
index a0e677244..177bb11c5 100644
--- a/manim/utils/caching.py
+++ b/manim/utils/caching.py
@@ -1,14 +1,20 @@
from __future__ import annotations
-from typing import Callable
+from typing import TYPE_CHECKING, Callable
from .. import config, logger
from ..utils.hashing import get_hash_from_play_call
__all__ = ["handle_caching_play"]
+if TYPE_CHECKING:
+ from typing import Any
-def handle_caching_play(func: Callable[..., None]):
+ from manim.renderer.opengl_renderer import OpenGLRenderer
+ from manim.scene.scene import Scene
+
+
+def handle_caching_play(func: Callable[..., None]) -> Callable[..., None]:
"""Decorator that returns a wrapped version of func that will compute
the hash of the play invocation.
@@ -28,7 +34,7 @@ def handle_caching_play(func: Callable[..., None]):
# the play logic of the latter has to be refactored in the same way the cairo renderer has been, and thus this
# method has to be deleted.
- def wrapper(self, scene, *args, **kwargs):
+ def wrapper(self: OpenGLRenderer, scene: Scene, *args: Any, **kwargs: Any) -> None:
self.skip_animations = self._original_skipping_status
self.update_skipping_status()
animations = scene.compile_animations(*args, **kwargs)
@@ -43,8 +49,9 @@ def handle_caching_play(func: Callable[..., None]):
return
if not config["disable_caching"]:
mobjects_on_scene = scene.mobjects
+ # TODO: the first argument seems wrong. Shouldn't it be scene instead?
hash_play = get_hash_from_play_call(
- self,
+ self, # type: ignore[arg-type]
self.camera,
animations,
mobjects_on_scene,
diff --git a/manim/utils/color/core.py b/manim/utils/color/core.py
index 23864921e..d742dbb33 100644
--- a/manim/utils/color/core.py
+++ b/manim/utils/color/core.py
@@ -237,7 +237,12 @@ class ManimColor:
self.__value: ManimColorInternal = value
@classmethod
- def _construct_from_space(cls, _space) -> Self:
+ def _construct_from_space(
+ cls,
+ _space: npt.NDArray[ManimFloat]
+ | tuple[float, float, float]
+ | tuple[float, float, float, float],
+ ) -> Self:
"""
This function is used as a proxy for constructing a color with an internal value,
this can be used by subclasses to hook into the construction of new objects using the internal value format
@@ -560,7 +565,7 @@ class ManimColor:
"""
return np.array(colorsys.rgb_to_hls(*self.to_rgb()))
- def invert(self, with_alpha=False) -> Self:
+ def invert(self, with_alpha: bool = False) -> Self:
"""Returns an linearly inverted version of the color (no inplace changes)
Parameters
@@ -888,10 +893,10 @@ class ManimColor:
Either a list of colors or a singular color depending on the input
"""
- def is_sequence(colors) -> TypeGuard[Sequence[ParsableManimColor]]:
+ def is_sequence(colors: Any) -> TypeGuard[Sequence[ParsableManimColor]]:
return isinstance(colors, (list, tuple))
- def is_parsable(color) -> TypeGuard[ParsableManimColor]:
+ def is_parsable(color: Any) -> TypeGuard[ParsableManimColor]:
return not isinstance(color, (list, tuple))
if is_sequence(color):
@@ -900,9 +905,11 @@ class ManimColor:
]
elif is_parsable(color):
return cls._from_internal(ManimColor(color, alpha)._internal_value)
+ else:
+ return cls._from_internal(ManimColor("WHITE", alpha)._internal_value)
@staticmethod
- def gradient(colors: list[ManimColor], length: int):
+ def gradient(colors: list[ManimColor], length: int) -> None:
"""This is not implemented by now refer to :func:`color_gradient` for a working implementation for now"""
# TODO: implement proper gradient, research good implementation for this or look at 3b1b implementation
raise NotImplementedError
@@ -918,7 +925,8 @@ class ManimColor:
raise TypeError(
f"Cannot compare {self.__class__.__name__} with {other.__class__.__name__}"
)
- return np.allclose(self._internal_value, other._internal_value)
+ value: bool = np.allclose(self._internal_value, other._internal_value)
+ return value
def __add__(self, other: int | float | Self) -> Self:
if isinstance(other, (int, float)):
@@ -1004,7 +1012,8 @@ class ManimColor:
return self.to_integer()
def __getitem__(self, index: int) -> float:
- return self._internal_space[index]
+ value: float = self._internal_space[index]
+ return value
def __and__(self, other: Self) -> Self:
return self._construct_from_space(
@@ -1038,7 +1047,7 @@ class HSV(ManimColor):
if len(hsv) == 3:
self.__hsv: HSVA_Array_Float = np.asarray((*hsv, alpha))
elif len(hsv) == 4:
- self.__hsv: HSVA_Array_Float = np.asarray(hsv)
+ self.__hsv = np.asarray(hsv)
else:
raise ValueError("HSV Color must be an array of 3 values")
@@ -1051,48 +1060,54 @@ class HSV(ManimColor):
@property
def hue(self) -> float:
- return self.__hsv[0]
-
- @property
- def saturation(self) -> float:
- return self.__hsv[1]
-
- @property
- def value(self) -> float:
- return self.__hsv[2]
+ value: float = self.__hsv[0]
+ return value
@hue.setter
def hue(self, value: float) -> None:
self.__hsv[0] = value
+ @property
+ def saturation(self) -> float:
+ value: float = self.__hsv[1]
+ return value
+
@saturation.setter
def saturation(self, value: float) -> None:
self.__hsv[1] = value
+ @property
+ def value(self) -> float:
+ value: float = self.__hsv[2]
+ return value
+
@value.setter
def value(self, value: float) -> None:
self.__hsv[2] = value
@property
def h(self) -> float:
- return self.__hsv[0]
-
- @property
- def s(self) -> float:
- return self.__hsv[1]
-
- @property
- def v(self) -> float:
- return self.__hsv[2]
+ value: float = self.__hsv[0]
+ return value
@h.setter
def h(self, value: float) -> None:
self.__hsv[0] = value
+ @property
+ def s(self) -> float:
+ value: float = self.__hsv[1]
+ return value
+
@s.setter
def s(self, value: float) -> None:
self.__hsv[1] = value
+ @property
+ def v(self) -> float:
+ value: float = self.__hsv[2]
+ return value
+
@v.setter
def v(self, value: float) -> None:
self.__hsv[2] = value
diff --git a/manim/utils/commands.py b/manim/utils/commands.py
index 8a1588951..b8154ca8b 100644
--- a/manim/utils/commands.py
+++ b/manim/utils/commands.py
@@ -4,9 +4,12 @@ import os
from collections.abc import Generator
from pathlib import Path
from subprocess import run
+from typing import TypedDict
import av
+from manim.typing import StrOrBytesPath
+
__all__ = [
"capture",
"get_video_metadata",
@@ -14,7 +17,9 @@ __all__ = [
]
-def capture(command, cwd=None, command_input=None):
+def capture(
+ command: str, cwd: StrOrBytesPath | None = None, command_input: str | None = None
+) -> tuple[str, str, int]:
p = run(
command,
cwd=cwd,
@@ -27,7 +32,17 @@ def capture(command, cwd=None, command_input=None):
return out, err, p.returncode
-def get_video_metadata(path_to_video: str | os.PathLike) -> dict[str]:
+class VideoMetadata(TypedDict):
+ width: int
+ height: int
+ nb_frames: str
+ duration: str
+ avg_frame_rate: str
+ codec_name: str
+ pix_fmt: str
+
+
+def get_video_metadata(path_to_video: str | os.PathLike) -> VideoMetadata:
with av.open(str(path_to_video)) as container:
stream = container.streams.video[0]
ctxt = stream.codec_context
diff --git a/manim/utils/config_ops.py b/manim/utils/config_ops.py
index 6e1f09990..401144d55 100644
--- a/manim/utils/config_ops.py
+++ b/manim/utils/config_ops.py
@@ -10,11 +10,12 @@ __all__ = [
import itertools as it
+from typing import Any
-import numpy as np
+import numpy.typing as npt
-def merge_dicts_recursively(*dicts):
+def merge_dicts_recursively(*dicts: dict[Any, Any]) -> dict[Any, Any]:
"""
Creates a dict whose keyset is the union of all the
input dictionaries. The value for each key is based
@@ -24,7 +25,7 @@ def merge_dicts_recursively(*dicts):
When values are dictionaries, it is applied recursively
"""
- result = {}
+ result: dict = {}
all_items = it.chain(*(d.items() for d in dicts))
for key, value in all_items:
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
@@ -34,7 +35,9 @@ def merge_dicts_recursively(*dicts):
return result
-def update_dict_recursively(current_dict, *others):
+def update_dict_recursively(
+ current_dict: dict[Any, Any], *others: dict[Any, Any]
+) -> None:
updated_dict = merge_dicts_recursively(current_dict, *others)
current_dict.update(updated_dict)
@@ -44,7 +47,7 @@ def update_dict_recursively(current_dict, *others):
class DictAsObject:
- def __init__(self, dictin):
+ def __init__(self, dictin: dict[str, Any]):
self.__dict__ = dictin
@@ -53,13 +56,14 @@ class _Data:
self.data attributes must be arrays.
"""
- def __set_name__(self, obj, name):
+ def __set_name__(self, obj: Any, name: str) -> None:
self.name = name
- def __get__(self, obj, owner):
- return obj.data[self.name]
+ def __get__(self, obj: Any, owner: Any) -> npt.NDArray[Any]:
+ value: npt.NDArray[Any] = obj.data[self.name]
+ return value
- def __set__(self, obj, array: np.ndarray):
+ def __set__(self, obj: Any, array: npt.NDArray[Any]) -> None:
obj.data[self.name] = array
@@ -68,11 +72,12 @@ class _Uniforms:
self.uniforms attributes must be floats.
"""
- def __set_name__(self, obj, name):
+ def __set_name__(self, obj: Any, name: str) -> None:
self.name = name
- def __get__(self, obj, owner):
- return obj.__dict__["uniforms"][self.name]
+ def __get__(self, obj: Any, owner: Any) -> float:
+ val: float = obj.__dict__["uniforms"][self.name]
+ return val
- def __set__(self, obj, num: float):
+ def __set__(self, obj: Any, num: float) -> None:
obj.__dict__["uniforms"][self.name] = num
diff --git a/manim/utils/debug.py b/manim/utils/debug.py
index a2c56a69d..bca9537a7 100644
--- a/manim/utils/debug.py
+++ b/manim/utils/debug.py
@@ -5,14 +5,17 @@ from __future__ import annotations
__all__ = ["print_family", "index_labels"]
+from typing import Any
+
from manim.mobject.mobject import Mobject
from manim.mobject.text.numbers import Integer
+from manim.utils.color import ManimColor
from ..mobject.types.vectorized_mobject import VGroup
from .color import BLACK
-def print_family(mobject, n_tabs=0):
+def print_family(mobject: Mobject, n_tabs: int = 0) -> None:
"""For debugging purposes"""
print("\t" * n_tabs, mobject, id(mobject))
for submob in mobject.submobjects:
@@ -22,10 +25,10 @@ def print_family(mobject, n_tabs=0):
def index_labels(
mobject: Mobject,
label_height: float = 0.15,
- background_stroke_width=5,
- background_stroke_color=BLACK,
- **kwargs,
-):
+ background_stroke_width: float = 5,
+ background_stroke_color: ManimColor = BLACK,
+ **kwargs: Any,
+) -> VGroup:
r"""Returns a :class:`~.VGroup` of :class:`~.Integer` mobjects
that shows the index of each submobject.
diff --git a/manim/utils/deprecation.py b/manim/utils/deprecation.py
index afa9cb41a..98906b461 100644
--- a/manim/utils/deprecation.py
+++ b/manim/utils/deprecation.py
@@ -9,14 +9,14 @@ import inspect
import logging
import re
from collections.abc import Iterable
-from typing import Any, Callable
+from typing import Any, Callable, TypeVar, overload
from decorator import decorate, decorator
logger = logging.getLogger("manim")
-def _get_callable_info(callable_: Callable, /) -> tuple[str, str]:
+def _get_callable_info(callable_: Callable[..., Any], /) -> tuple[str, str]:
"""Returns type and name of a callable.
Parameters
@@ -40,9 +40,9 @@ def _get_callable_info(callable_: Callable, /) -> tuple[str, str]:
def _deprecation_text_component(
- since: str | None,
- until: str | None,
- message: str,
+ since: str | None = None,
+ until: str | None = None,
+ message: str | None = None,
) -> str:
"""Generates a text component used in deprecation messages.
@@ -70,13 +70,37 @@ def _deprecation_text_component(
return f"deprecated {since}and {until}.{msg}"
+# TODO: Use ParamSpec to type decorated functions when Python 3.9 is out of life
+T = TypeVar("T")
+
+
+@overload
def deprecated(
- func: Callable = None,
+ func: Callable[..., T],
since: str | None = None,
until: str | None = None,
replacement: str | None = None,
message: str | None = "",
-) -> Callable:
+) -> Callable[..., T]: ...
+
+
+@overload
+def deprecated(
+ func: None = None,
+ since: str | None = None,
+ until: str | None = None,
+ replacement: str | None = None,
+ message: str | None = "",
+) -> Callable[[Callable[..., T]], Callable[..., T]]: ...
+
+
+def deprecated(
+ func: Callable[..., T] | None = None,
+ since: str | None = None,
+ until: str | None = None,
+ replacement: str | None = None,
+ message: str | None = "",
+) -> Callable[..., T] | Callable[[Callable[..., T]], Callable[..., T]]:
"""Decorator to mark a callable as deprecated.
The decorated callable will cause a warning when used. The docstring of the
@@ -187,7 +211,7 @@ def deprecated(
deprecated = _deprecation_text_component(since, until, msg)
return f"The {what} {name} has been {deprecated}"
- def deprecate_docs(func: Callable):
+ def deprecate_docs(func: Callable) -> None:
"""Adjust docstring to indicate the deprecation.
Parameters
@@ -199,7 +223,7 @@ def deprecated(
doc_string = func.__doc__ or ""
func.__doc__ = f"{doc_string}\n\n.. attention:: Deprecated\n {warning}"
- def deprecate(func: Callable, *args, **kwargs):
+ def deprecate(func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
"""The actual decorator used to extend the callables behavior.
Logs a warning message.
@@ -224,7 +248,10 @@ def deprecated(
if type(func).__name__ != "function":
deprecate_docs(func)
- func.__init__ = decorate(func.__init__, deprecate)
+ # The following line raises this mypy error:
+ # Accessing "__init__" on an instance is unsound, since instance.__init__
+ # could be from an incompatible subclass [misc]</pre>
+ func.__init__ = decorate(func.__init__, deprecate) # type: ignore[misc]
return func
func = decorate(func, deprecate)
@@ -236,10 +263,10 @@ def deprecated_params(
params: str | Iterable[str] | None = None,
since: str | None = None,
until: str | None = None,
- message: str | None = "",
+ message: str = "",
redirections: None
| (Iterable[tuple[str, str] | Callable[..., dict[str, Any]]]) = None,
-) -> Callable:
+) -> Callable[..., T]:
"""Decorator to mark parameters of a callable as deprecated.
It can also be used to automatically redirect deprecated parameter values to their
@@ -426,7 +453,7 @@ def deprecated_params(
redirections = list(redirections)
- def warning_msg(func: Callable, used: list[str]):
+ def warning_msg(func: Callable[..., T], used: list[str]) -> str:
"""Generate the deprecation warning message.
Parameters
@@ -449,7 +476,7 @@ def deprecated_params(
deprecated = _deprecation_text_component(since, until, message)
return f"The parameter{parameter_s} {used_} of {what} {name} {has_have_been} {deprecated}"
- def redirect_params(kwargs: dict, used: list[str]):
+ def redirect_params(kwargs: dict[str, Any], used: list[str]) -> None:
"""Adjust the keyword arguments as defined by the redirections.
Parameters
@@ -473,7 +500,7 @@ def deprecated_params(
if len(redirector_args) > 0:
kwargs.update(redirector(**redirector_args))
- def deprecate_params(func, *args, **kwargs):
+ def deprecate_params(func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
"""The actual decorator function used to extend the callables behavior.
Logs a warning message when a deprecated parameter is used and redirects it if
@@ -505,4 +532,4 @@ def deprecated_params(
redirect_params(kwargs, used)
return func(*args, **kwargs)
- return decorator(deprecate_params)
+ return decorator(deprecate_params) # type: ignore[return-value]
diff --git a/manim/utils/docbuild/autocolor_directive.py b/manim/utils/docbuild/autocolor_directive.py
index 3a699f54d..476dcb132 100644
--- a/manim/utils/docbuild/autocolor_directive.py
+++ b/manim/utils/docbuild/autocolor_directive.py
@@ -26,7 +26,9 @@ class ManimColorModuleDocumenter(Directive):
has_content = True
def add_directive_header(self, sig: str) -> None:
- super().add_directive_header(sig)
+ # TODO: The Directive class has no method named
+ # add_directive_header.
+ super().add_directive_header(sig) # type: ignore[misc]
def run(self) -> list[nodes.Element]:
module_name = self.arguments[0]
@@ -37,7 +39,7 @@ class ManimColorModuleDocumenter(Directive):
except ImportError:
return [
nodes.error(
- None,
+ None, # type: ignore[arg-type]
nodes.paragraph(text=f"Failed to import module '{module_name}'"),
)
]
@@ -53,13 +55,13 @@ class ManimColorModuleDocumenter(Directive):
# Create header rows for the table
thead = nodes.thead()
- row = nodes.row()
+ header_row = nodes.row()
for _ in range(num_color_cols):
- col1 = nodes.paragraph(text="Color Name")
- col2 = nodes.paragraph(text="RGB Hex Code")
- row += nodes.entry("", col1)
- row += nodes.entry("", col2)
- thead += row
+ header_col1 = nodes.paragraph(text="Color Name")
+ header_col2 = nodes.paragraph(text="RGB Hex Code")
+ header_row += nodes.entry("", header_col1)
+ header_row += nodes.entry("", header_col2)
+ thead += header_row
tgroup += thead
color_elements = []
diff --git a/manim/utils/docbuild/manim_directive.py b/manim/utils/docbuild/manim_directive.py
index 8d68f2aa5..4ce22e028 100644
--- a/manim/utils/docbuild/manim_directive.py
+++ b/manim/utils/docbuild/manim_directive.py
@@ -88,7 +88,7 @@ import sys
import textwrap
from pathlib import Path
from timeit import timeit
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, TypedDict
import jinja2
from docutils import nodes
@@ -101,12 +101,18 @@ from manim import __version__ as manim_version
if TYPE_CHECKING:
from sphinx.application import Sphinx
+
__all__ = ["ManimDirective"]
classnamedict: dict[str, int] = {}
+class SetupMetadata(TypedDict):
+ parallel_read_safe: bool
+ parallel_write_safe: bool
+
+
class SkipManimNode(nodes.Admonition, nodes.Element):
"""Auxiliary node class that is used when the ``skip-manim`` tag is present
or ``.pot`` files are being built.
@@ -118,13 +124,15 @@ class SkipManimNode(nodes.Admonition, nodes.Element):
def visit(self: SkipManimNode, node: nodes.Element, name: str = "") -> None:
- self.visit_admonition(node, name)
+ # TODO: Parent classes don't have a visit_admonition() method.
+ self.visit_admonition(node, name) # type: ignore[attr-defined]
if not isinstance(node[0], nodes.title):
node.insert(0, nodes.title("skip-manim", "Example Placeholder"))
def depart(self: SkipManimNode, node: nodes.Element) -> None:
- self.depart_admonition(node)
+ # TODO: Parent classes don't have a depart_admonition() method.
+ self.depart_admonition(node) # type: ignore[attr-defined]
def process_name_list(option_input: str, reference_type: str) -> list[str]:
@@ -239,13 +247,13 @@ class ManimDirective(Directive):
document = state_machine.document
source_file_name = Path(document.attributes["source"])
- source_rel_name = source_file_name.relative_to(setup.confdir)
+ source_rel_name = source_file_name.relative_to(setup.confdir) # type: ignore[attr-defined]
source_rel_dir = source_rel_name.parents[0]
- dest_dir = Path(setup.app.builder.outdir, source_rel_dir).absolute()
+ dest_dir = Path(setup.app.builder.outdir, source_rel_dir).absolute() # type: ignore[attr-defined]
if not dest_dir.exists():
dest_dir.mkdir(parents=True, exist_ok=True)
- source_block = [
+ source_block_in = [
".. code-block:: python",
"",
" from manim import *\n",
@@ -258,13 +266,13 @@ class ManimDirective(Directive):
"",
" </pre>",
]
- source_block = "\n".join(source_block)
+ source_block = "\n".join(source_block_in)
- config.media_dir = (Path(setup.confdir) / "media").absolute()
+ config.media_dir = (Path(setup.confdir) / "media").absolute() # type: ignore[attr-defined,assignment]
config.images_dir = "{media_dir}/images"
config.video_dir = "{media_dir}/videos/{quality}"
output_file = f"{clsname}-{classnamedict[clsname]}"
- config.assets_dir = Path("_static")
+ config.assets_dir = Path("_static") # type: ignore[assignment]
config.progress_bar = "none"
config.verbosity = "WARNING"
@@ -282,7 +290,7 @@ class ManimDirective(Directive):
if save_as_gif:
example_config["format"] = "gif"
- user_code = self.content
+ user_code = list(self.content)
if user_code[0].startswith(">>> "): # check whether block comes from doctest
user_code = [
line[4:] for line in user_code if line.startswith((">>> ", "... "))
@@ -326,7 +334,7 @@ class ManimDirective(Directive):
clsname=clsname,
clsname_lowercase=clsname.lower(),
hide_source=hide_source,
- filesrc_rel=Path(filesrc).relative_to(setup.confdir).as_posix(),
+ filesrc_rel=Path(filesrc).relative_to(setup.confdir).as_posix(), # type: ignore[attr-defined]
no_autoplay=no_autoplay,
output_file=output_file,
save_last_frame=save_last_frame,
@@ -345,7 +353,7 @@ class ManimDirective(Directive):
rendering_times_file_path = Path("../rendering_times.csv")
-def _write_rendering_stats(scene_name: str, run_time: str, file_name: str) -> None:
+def _write_rendering_stats(scene_name: str, run_time: float, file_name: str) -> None:
with rendering_times_file_path.open("a") as file:
csv.writer(file).writerow(
[
@@ -369,9 +377,9 @@ def _log_rendering_times(*args: tuple[Any]) -> None:
data = [row for row in data if row]
max_file_length = max(len(row[0]) for row in data)
- for key, group in it.groupby(data, key=lambda row: row[0]):
+ for key, group_iter in it.groupby(data, key=lambda row: row[0]):
key = key.ljust(max_file_length + 1, ".")
- group = list(group)
+ group = list(group_iter)
if len(group) == 1:
row = group[0]
print(f"{key}{row[2].rjust(7, '.')}s {row[1]}")
@@ -390,12 +398,12 @@ def _delete_rendering_times(*args: tuple[Any]) -> None:
rendering_times_file_path.unlink()
-def setup(app: Sphinx) -> dict[str, Any]:
+def setup(app: Sphinx) -> SetupMetadata:
app.add_node(SkipManimNode, html=(visit, depart))
- setup.app = app
- setup.config = app.config
- setup.confdir = app.confdir
+ setup.app = app # type: ignore[attr-defined]
+ setup.config = app.config # type: ignore[attr-defined]
+ setup.confdir = app.confdir # type: ignore[attr-defined]
app.add_directive("manim", ManimDirective)
@@ -412,7 +420,10 @@ def setup(app: Sphinx) -> dict[str, Any]:
).strip(),
)
- metadata = {"parallel_read_safe": False, "parallel_write_safe": True}
+ metadata: SetupMetadata = {
+ "parallel_read_safe": False,
+ "parallel_write_safe": True,
+ }
return metadata
diff --git a/manim/utils/docbuild/module_parsing.py b/manim/utils/docbuild/module_parsing.py
index 24e44be21..78769eb56 100644
--- a/manim/utils/docbuild/module_parsing.py
+++ b/manim/utils/docbuild/module_parsing.py
@@ -4,7 +4,9 @@ from __future__ import annotations
import ast
import sys
+from ast import Attribute, Name, Subscript
from pathlib import Path
+from typing import Any
from typing_extensions import TypeAlias
@@ -87,10 +89,10 @@ def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]:
return ALIAS_DOCS_DICT, DATA_DICT, TYPEVAR_DICT
for module_path in MANIM_ROOT.rglob("*.py"):
- module_name = module_path.resolve().relative_to(MANIM_ROOT)
- module_name = list(module_name.parts)
- module_name[-1] = module_name[-1].removesuffix(".py")
- module_name = ".".join(module_name)
+ module_name_t1 = module_path.resolve().relative_to(MANIM_ROOT)
+ module_name_t2 = list(module_name_t1.parts)
+ module_name_t2[-1] = module_name_t2[-1].removesuffix(".py")
+ module_name = ".".join(module_name_t2)
module_content = module_path.read_text(encoding="utf-8")
@@ -154,7 +156,7 @@ def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]:
)
)
):
- inner_nodes = node.body
+ inner_nodes: list[Any] = node.body
else:
inner_nodes = [node]
@@ -172,8 +174,11 @@ def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]:
and node.value is not None
)
if is_type_alias or is_annotated_assignment_with_value:
- alias_name = node.name.id if is_type_alias else node.target.id
- definition_node = node.value
+ # TODO: ast.TypeAlias does not exist before Python 3.12, and that
+ # could be the reason why MyPy does not recognize these as
+ # attributes of node.
+ alias_name = node.name.id if is_type_alias else node.target.id # type: ignore[attr-defined]
+ definition_node = node.value # type: ignore[attr-defined]
# If the definition is a Union, replace with vertical bar notation.
# Instead of "Union[Type1, Type2]", we'll have "Type1 | Type2".
@@ -182,7 +187,7 @@ def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]:
and type(definition_node.value) is ast.Name
and definition_node.value.id == "Union"
):
- union_elements = definition_node.slice.elts
+ union_elements = definition_node.slice.elts # type: ignore[attr-defined]
definition = " | ".join(
ast.unparse(elem) for elem in union_elements
)
@@ -217,7 +222,7 @@ def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]:
# Does the assignment have a target of type Name? Then
# it could be considered a definition of a module attribute.
if type(node) is ast.AnnAssign:
- target = node.target
+ target: Name | Attribute | Subscript | ast.expr | None = node.target
elif type(node) is ast.Assign and len(node.targets) == 1:
target = node.targets[0]
else:
diff --git a/manim/utils/family.py b/manim/utils/family.py
index 17b39f347..89c93d5eb 100644
--- a/manim/utils/family.py
+++ b/manim/utils/family.py
@@ -11,9 +11,9 @@ __all__ = ["extract_mobject_family_members"]
def extract_mobject_family_members(
mobjects: Iterable[Mobject],
- use_z_index=False,
+ use_z_index: bool = False,
only_those_with_points: bool = False,
-):
+) -> list[Mobject]:
"""Returns a list of the types of mobjects and their family members present.
A "family" in this context refers to a mobject, its submobjects, and their
submobjects, recursively.
diff --git a/manim/utils/family_ops.py b/manim/utils/family_ops.py
index 8d4af9d5a..e7cf01116 100644
--- a/manim/utils/family_ops.py
+++ b/manim/utils/family_ops.py
@@ -2,20 +2,26 @@ from __future__ import annotations
import itertools as it
+from manim.mobject.mobject import Mobject
+
__all__ = [
"extract_mobject_family_members",
"restructure_list_to_exclude_certain_family_members",
]
-def extract_mobject_family_members(mobject_list, only_those_with_points=False):
+def extract_mobject_family_members(
+ mobject_list: list[Mobject], only_those_with_points: bool = False
+) -> list[Mobject]:
result = list(it.chain(*(mob.get_family() for mob in mobject_list)))
if only_those_with_points:
result = [mob for mob in result if mob.has_points()]
return result
-def restructure_list_to_exclude_certain_family_members(mobject_list, to_remove):
+def restructure_list_to_exclude_certain_family_members(
+ mobject_list: list[Mobject], to_remove: list[Mobject]
+) -> list[Mobject]:
"""
Removes anything in to_remove from mobject_list, but in the event that one of
the items to be removed is a member of the family of an item in mobject_list,
@@ -25,10 +31,12 @@ def restructure_list_to_exclude_certain_family_members(mobject_list, to_remove):
but one of its submobjects is removed, e.g. scene.remove(m1), it's useful
for the list of mobject_list to be edited to contain other submobjects, but not m1.
"""
- new_list = []
+ new_list: list[Mobject] = []
to_remove = extract_mobject_family_members(to_remove)
- def add_safe_mobjects_from_list(list_to_examine, set_to_remove):
+ def add_safe_mobjects_from_list(
+ list_to_examine: list[Mobject], set_to_remove: set[Mobject]
+ ) -> None:
for mob in list_to_examine:
if mob in set_to_remove:
continue
diff --git a/manim/utils/file_ops.py b/manim/utils/file_ops.py
index e4fbdebfe..5e239be54 100644
--- a/manim/utils/file_ops.py
+++ b/manim/utils/file_ops.py
@@ -47,7 +47,8 @@ def is_mp4_format() -> bool:
``True`` if format is set as mp4
"""
- return config["format"] == "mp4"
+ val: bool = config["format"] == "mp4"
+ return val
def is_gif_format() -> bool:
@@ -60,7 +61,8 @@ def is_gif_format() -> bool:
``True`` if format is set as gif
"""
- return config["format"] == "gif"
+ val: bool = config["format"] == "gif"
+ return val
def is_webm_format() -> bool:
@@ -73,7 +75,8 @@ def is_webm_format() -> bool:
``True`` if format is set as webm
"""
- return config["format"] == "webm"
+ val: bool = config["format"] == "webm"
+ return val
def is_mov_format() -> bool:
@@ -86,7 +89,8 @@ def is_mov_format() -> bool:
``True`` if format is set as mov
"""
- return config["format"] == "mov"
+ val: bool = config["format"] == "mov"
+ return val
def is_png_format() -> bool:
@@ -99,7 +103,8 @@ def is_png_format() -> bool:
``True`` if format is set as png
"""
- return config["format"] == "png"
+ val: bool = config["format"] == "png"
+ return val
def write_to_movie() -> bool:
@@ -126,7 +131,7 @@ def write_to_movie() -> bool:
def ensure_executable(path_to_exe: Path) -> bool:
if path_to_exe.parent == Path("."):
- executable = shutil.which(path_to_exe.stem)
+ executable: StrPath | None = shutil.which(path_to_exe.stem)
if executable is None:
return False
else:
@@ -191,7 +196,9 @@ def modify_atime(file_path: str) -> None:
def open_file(file_path: Path, in_browser: bool = False) -> None:
current_os = platform.system()
if current_os == "Windows":
- os.startfile(file_path if not in_browser else file_path.parent)
+ # The method os.startfile is only available in Windows,
+ # ignoring type error caused by this.
+ os.startfile(file_path if not in_browser else file_path.parent) # type: ignore[attr-defined]
else:
if current_os == "Linux":
commands = ["xdg-open"]
@@ -207,7 +214,7 @@ def open_file(file_path: Path, in_browser: bool = False) -> None:
# check after so that file path is set correctly
if config.preview_command:
commands = [config.preview_command]
- commands.append(file_path)
+ commands.append(str(file_path))
sp.run(commands)
diff --git a/manim/utils/hashing.py b/manim/utils/hashing.py
index 92b519150..ca5d840cf 100644
--- a/manim/utils/hashing.py
+++ b/manim/utils/hashing.py
@@ -14,13 +14,13 @@ from typing import Any
import numpy as np
-from manim.animation.animation import Animation
-from manim.camera.camera import Camera
-from manim.mobject.mobject import Mobject
-
-from .. import config, logger
+from manim._config import config, logger
if typing.TYPE_CHECKING:
+ from manim.animation.animation import Animation
+ from manim.camera.camera import Camera
+ from manim.mobject.mobject import Mobject
+ from manim.opengl.opengl_renderer import OpenGLCamera
from manim.scene.scene import Scene
__all__ = ["KEYS_TO_FILTER_OUT", "get_hash_from_play_call", "get_json"]
@@ -324,7 +324,7 @@ def get_json(obj: dict):
def get_hash_from_play_call(
scene_object: Scene,
- camera_object: Camera,
+ camera_object: Camera | OpenGLCamera,
animations_list: typing.Iterable[Animation],
current_mobjects_list: typing.Iterable[Mobject],
) -> str:
diff --git a/manim/utils/images.py b/manim/utils/images.py
index 7e0accf4c..dd5c57858 100644
--- a/manim/utils/images.py
+++ b/manim/utils/images.py
@@ -15,11 +15,13 @@ from typing import TYPE_CHECKING
import numpy as np
from PIL import Image
+from manim.typing import RGBPixelArray
+
from .. import config
from ..utils.file_ops import seek_full_path_from_defaults
if TYPE_CHECKING:
- import numpy.typing as npt
+ pass
def get_full_raster_image_path(image_file_name: str | PurePath) -> Path:
@@ -53,7 +55,7 @@ def invert_image(image: np.array) -> Image:
return Image.fromarray(arr)
-def change_to_rgba_array(image: npt.NDArray, dtype="uint8") -> npt.NDArray:
+def change_to_rgba_array(image: RGBPixelArray, dtype: str = "uint8") -> RGBPixelArray:
"""Converts an RGB array into RGBA with the alpha value opacity maxed."""
pa = image
if len(pa.shape) == 2:
diff --git a/manim/utils/ipython_magic.py b/manim/utils/ipython_magic.py
index 1b6c7b316..ce6c93d55 100644
--- a/manim/utils/ipython_magic.py
+++ b/manim/utils/ipython_magic.py
@@ -34,15 +34,15 @@ else:
class ManimMagic(Magics):
def __init__(self, shell: InteractiveShell) -> None:
super().__init__(shell)
- self.rendered_files = {}
+ self.rendered_files: dict[Path, Path] = {}
@needs_local_scope
@line_cell_magic
def manim(
self,
line: str,
- cell: str = None,
- local_ns: dict[str, Any] = None,
+ cell: str | None = None,
+ local_ns: dict[str, Any] | None = None,
) -> None:
r"""Render Manim scenes contained in IPython cells.
Works as a line or cell magic.
@@ -127,8 +127,9 @@ else:
modified_args = self.add_additional_args(args)
args = main(modified_args, standalone_mode=False, prog_name="manim")
+ assert isinstance(local_ns, dict)
with tempconfig(local_ns.get("config", {})):
- config.digest_args(args)
+ config.digest_args(args) # type: ignore[arg-type]
renderer = None
if config.renderer == RendererType.OPENGL:
@@ -167,6 +168,7 @@ else:
shutil.copy(local_path, tmpfile)
file_type = mimetypes.guess_type(config["output_file"])[0]
+ assert isinstance(file_type, str)
embed = config["media_embed"]
if not embed:
# videos need to be embedded when running in google colab.
@@ -194,4 +196,7 @@ else:
def _generate_file_name() -> str:
- return config["scene_names"][0] + "@" + datetime.now().strftime("%Y-%m-%d@%H-%M-%S")
+ val: str = (
+ config["scene_names"][0] + "@" + datetime.now().strftime("%Y-%m-%d@%H-%M-%S")
+ )
+ return val
diff --git a/manim/utils/module_ops.py b/manim/utils/module_ops.py
index 03f297030..1b03e374f 100644
--- a/manim/utils/module_ops.py
+++ b/manim/utils/module_ops.py
@@ -7,14 +7,26 @@ import sys
import types
import warnings
from pathlib import Path
+from typing import TYPE_CHECKING, Literal, overload
-from .. import config, console, constants, logger
-from ..scene.scene_file_writer import SceneFileWriter
+from manim._config import config, console, logger
+from manim.constants import (
+ CHOOSE_NUMBER_MESSAGE,
+ INVALID_NUMBER_MESSAGE,
+ NO_SCENE_MESSAGE,
+ SCENE_NOT_FOUND_MESSAGE,
+)
+from manim.scene.scene_file_writer import SceneFileWriter
+
+if TYPE_CHECKING:
+ from typing import Any
+
+ from manim.scene.scene import Scene
__all__ = ["scene_classes_from_file"]
-def get_module(file_name: Path):
+def get_module(file_name: Path) -> types.ModuleType:
if str(file_name) == "-":
module = types.ModuleType("input_scenes")
logger.info(
@@ -47,19 +59,22 @@ def get_module(file_name: Path):
)
spec = importlib.util.spec_from_file_location(module_name, file_name)
- module = importlib.util.module_from_spec(spec)
- sys.modules[module_name] = module
- sys.path.insert(0, str(file_name.parent.absolute()))
- spec.loader.exec_module(module)
- return module
+ if isinstance(spec, importlib.machinery.ModuleSpec):
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ sys.path.insert(0, str(file_name.parent.absolute()))
+ assert spec.loader
+ spec.loader.exec_module(module)
+ return module
+ raise FileNotFoundError(f"{file_name} not found")
else:
raise FileNotFoundError(f"{file_name} not found")
-def get_scene_classes_from_module(module):
+def get_scene_classes_from_module(module: types.ModuleType) -> list[type[Scene]]:
from ..scene.scene import Scene
- def is_child_scene(obj, module):
+ def is_child_scene(obj: Any, module: types.ModuleType) -> bool:
return (
inspect.isclass(obj)
and issubclass(obj, Scene)
@@ -73,9 +88,9 @@ def get_scene_classes_from_module(module):
]
-def get_scenes_to_render(scene_classes):
+def get_scenes_to_render(scene_classes: list[type[Scene]]) -> list[type[Scene]]:
if not scene_classes:
- logger.error(constants.NO_SCENE_MESSAGE)
+ logger.error(NO_SCENE_MESSAGE)
return []
if config["write_all"]:
return scene_classes
@@ -88,7 +103,7 @@ def get_scenes_to_render(scene_classes):
found = True
break
if not found and (scene_name != ""):
- logger.error(constants.SCENE_NOT_FOUND_MESSAGE.format(scene_name))
+ logger.error(SCENE_NOT_FOUND_MESSAGE.format(scene_name))
if result:
return result
if len(scene_classes) == 1:
@@ -97,7 +112,7 @@ def get_scenes_to_render(scene_classes):
return prompt_user_for_choice(scene_classes)
-def prompt_user_for_choice(scene_classes):
+def prompt_user_for_choice(scene_classes: list[type[Scene]]) -> list[type[Scene]]:
num_to_class = {}
SceneFileWriter.force_output_as_scene_name = True
for count, scene_class in enumerate(scene_classes, 1):
@@ -106,7 +121,7 @@ def prompt_user_for_choice(scene_classes):
num_to_class[count] = scene_class
try:
user_input = console.input(
- f"[log.message] {constants.CHOOSE_NUMBER_MESSAGE} [/log.message]",
+ f"[log.message] {CHOOSE_NUMBER_MESSAGE} [/log.message]",
)
scene_classes = [
num_to_class[int(num_str)]
@@ -115,7 +130,7 @@ def prompt_user_for_choice(scene_classes):
config["scene_names"] = [scene_class.__name__ for scene_class in scene_classes]
return scene_classes
except KeyError:
- logger.error(constants.INVALID_NUMBER_MESSAGE)
+ logger.error(INVALID_NUMBER_MESSAGE)
sys.exit(2)
except EOFError:
sys.exit(1)
@@ -124,9 +139,31 @@ def prompt_user_for_choice(scene_classes):
sys.exit(1)
+@overload
+def scene_classes_from_file(
+ file_path: Path, require_single_scene: bool, full_list: Literal[True]
+) -> list[type[Scene]]: ...
+
+
+@overload
+def scene_classes_from_file(
+ file_path: Path,
+ require_single_scene: Literal[True],
+ full_list: Literal[False] = False,
+) -> type[Scene]: ...
+
+
+@overload
+def scene_classes_from_file(
+ file_path: Path,
+ require_single_scene: Literal[False] = False,
+ full_list: Literal[False] = False,
+) -> list[type[Scene]]: ...
+
+
def scene_classes_from_file(
- file_path: Path, require_single_scene=False, full_list=False
-):
+ file_path: Path, require_single_scene: bool = False, full_list: bool = False
+) -> type[Scene] | list[type[Scene]]:
module = get_module(file_path)
all_scene_classes = get_scene_classes_from_module(module)
if full_list:
diff --git a/manim/utils/opengl.py b/manim/utils/opengl.py
index d48817b76..8616dfd78 100644
--- a/manim/utils/opengl.py
+++ b/manim/utils/opengl.py
@@ -1,9 +1,19 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
import numpy as np
import numpy.linalg as linalg
-from .. import config
+from manim._config import config
+from manim.typing import ManimFloat
+
+if TYPE_CHECKING:
+ import numpy.typing as npt
+ from typing_extensions import TypeAlias
+
+ from manim.typing import MatrixMN, Point3D
+
depth = 20
@@ -22,17 +32,37 @@ __all__ = [
]
-def matrix_to_shader_input(matrix):
+FlattenedMatrix4x4: TypeAlias = tuple[
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+ float,
+]
+
+
+def matrix_to_shader_input(matrix: MatrixMN) -> FlattenedMatrix4x4:
return tuple(matrix.T.ravel())
def orthographic_projection_matrix(
- width=None,
- height=None,
- near=1,
- far=depth + 1,
- format_=True,
-):
+ width: float | None = None,
+ height: float | None = None,
+ near: float = 1,
+ far: float = depth + 1,
+ format_: bool = True,
+) -> MatrixMN | FlattenedMatrix4x4:
if width is None:
width = config["frame_width"]
if height is None:
@@ -52,8 +82,12 @@ def orthographic_projection_matrix(
def perspective_projection_matrix(
- width=None, height=None, near=2, far=50, format_=True
-):
+ width: float | None = None,
+ height: float | None = None,
+ near: float = 2,
+ far: float = 50,
+ format_: bool = True,
+) -> MatrixMN | FlattenedMatrix4x4:
if width is None:
width = config["frame_width"] / 6
if height is None:
@@ -66,13 +100,13 @@ def perspective_projection_matrix(
[0, 0, -1, 0],
],
)
- if format:
+ if format_:
return matrix_to_shader_input(projection_matrix)
else:
return projection_matrix
-def translation_matrix(x=0, y=0, z=0):
+def translation_matrix(x: float = 0, y: float = 0, z: float = 0) -> MatrixMN:
return np.array(
[
[1, 0, 0, x],
@@ -80,10 +114,11 @@ def translation_matrix(x=0, y=0, z=0):
[0, 0, 1, z],
[0, 0, 0, 1],
],
+ dtype=ManimFloat,
)
-def x_rotation_matrix(x=0):
+def x_rotation_matrix(x: float = 0) -> MatrixMN:
return np.array(
[
[1, 0, 0, 0],
@@ -94,7 +129,7 @@ def x_rotation_matrix(x=0):
)
-def y_rotation_matrix(y=0):
+def y_rotation_matrix(y: float = 0) -> MatrixMN:
return np.array(
[
[np.cos(y), 0, np.sin(y), 0],
@@ -105,7 +140,7 @@ def y_rotation_matrix(y=0):
)
-def z_rotation_matrix(z=0):
+def z_rotation_matrix(z: float = 0) -> MatrixMN:
return np.array(
[
[np.cos(z), -np.sin(z), 0, 0],
@@ -117,7 +152,9 @@ def z_rotation_matrix(z=0):
# TODO: When rotating around the x axis, rotation eventually stops.
-def rotate_in_place_matrix(initial_position, x=0, y=0, z=0):
+def rotate_in_place_matrix(
+ initial_position: Point3D, x: float = 0, y: float = 0, z: float = 0
+) -> MatrixMN:
return np.matmul(
translation_matrix(*-initial_position),
np.matmul(
@@ -127,14 +164,14 @@ def rotate_in_place_matrix(initial_position, x=0, y=0, z=0):
)
-def rotation_matrix(x=0, y=0, z=0):
+def rotation_matrix(x: float = 0, y: float = 0, z: float = 0) -> MatrixMN:
return np.matmul(
np.matmul(x_rotation_matrix(x), y_rotation_matrix(y)),
z_rotation_matrix(z),
)
-def scale_matrix(scale_factor=1):
+def scale_matrix(scale_factor: float = 1) -> npt.NDArray:
return np.array(
[
[scale_factor, 0, 0, 0],
@@ -142,15 +179,16 @@ def scale_matrix(scale_factor=1):
[0, 0, scale_factor, 0],
[0, 0, 0, 1],
],
+ dtype=ManimFloat,
)
def view_matrix(
- translation=None,
- x_rotation=0,
- y_rotation=0,
- z_rotation=0,
-):
+ translation: Point3D | None = None,
+ x_rotation: float = 0,
+ y_rotation: float = 0,
+ z_rotation: float = 0,
+) -> MatrixMN:
if translation is None:
translation = np.array([0, 0, depth / 2 + 1])
model_matrix = np.matmul(
diff --git a/manim/utils/parameter_parsing.py b/manim/utils/parameter_parsing.py
index 7966906bb..d3676c730 100644
--- a/manim/utils/parameter_parsing.py
+++ b/manim/utils/parameter_parsing.py
@@ -23,7 +23,7 @@ def flatten_iterable_parameters(
:class:`list`
The flattened list of parameters.
"""
- flattened_parameters = []
+ flattened_parameters: list[T] = []
for arg in args:
if isinstance(arg, (Iterable, GeneratorType)):
flattened_parameters.extend(arg)
diff --git a/manim/utils/paths.py b/manim/utils/paths.py
index 4cf867b42..aa3973288 100644
--- a/manim/utils/paths.py
+++ b/manim/utils/paths.py
@@ -19,13 +19,13 @@ from ..utils.bezier import interpolate
from ..utils.space_ops import rotation_matrix
if TYPE_CHECKING:
- from manim.typing import PathFuncType, Vector3D
+ from manim.typing import PathFuncType, Point3D_Array, Vector3D
STRAIGHT_PATH_THRESHOLD = 0.01
-def straight_path():
+def straight_path() -> PathFuncType:
"""Simplest path function. Each point in a set goes in a straight path toward its destination.
Examples
@@ -136,7 +136,9 @@ def path_along_circles(
axis = OUT
unit_axis = axis / np.linalg.norm(axis)
- def path(start_points: np.ndarray, end_points: np.ndarray, alpha: float):
+ def path(
+ start_points: Point3D_Array, end_points: Point3D_Array, alpha: float
+ ) -> Point3D_Array:
detransformed_end_points = circles_centers + np.dot(
end_points - circles_centers, rotation_matrix(-arc_angle, unit_axis).T
)
@@ -206,7 +208,9 @@ def path_along_arc(arc_angle: float, axis: Vector3D = OUT) -> PathFuncType:
axis = OUT
unit_axis = axis / np.linalg.norm(axis)
- def path(start_points: np.ndarray, end_points: np.ndarray, alpha: float):
+ def path(
+ start_points: Point3D_Array, end_points: Point3D_Array, alpha: float
+ ) -> Point3D_Array:
vects = end_points - start_points
centers = start_points + 0.5 * vects
if arc_angle != np.pi:
@@ -365,7 +369,9 @@ def spiral_path(angle: float, axis: Vector3D = OUT) -> PathFuncType:
axis = OUT
unit_axis = axis / np.linalg.norm(axis)
- def path(start_points: np.ndarray, end_points: np.ndarray, alpha: float):
+ def path(
+ start_points: Point3D_Array, end_points: Point3D_Array, alpha: float
+ ) -> Point3D_Array:
rot_matrix = rotation_matrix((alpha - 1) * angle, unit_axis)
return start_points + alpha * np.dot(end_points - start_points, rot_matrix.T)
diff --git a/manim/utils/polylabel.py b/manim/utils/polylabel.py
index 03c87a9f6..9b40f2942 100644
--- a/manim/utils/polylabel.py
+++ b/manim/utils/polylabel.py
@@ -58,7 +58,9 @@ class Polygon:
"""Compute the minimum distance from a point to the polygon."""
scalars = np.einsum("ij,ij->i", self.norm, point - self.start)
clips = np.clip(scalars, 0, 1).reshape(-1, 1)
- d = np.min(np.linalg.norm(self.start + self.diff * clips - point, axis=1))
+ d: float = np.min(
+ np.linalg.norm(self.start + self.diff * clips - point, axis=1)
+ )
return d if self.inside(point) else -d
def inside(self, point: Point2DLike) -> bool:
@@ -71,7 +73,8 @@ class Polygon:
# Count Crossings (enforce short-circuit)
c = (y > py) != (yr > py)
c = px < x[c] + (py - y[c]) * (xr[c] - x[c]) / (yr[c] - y[c])
- return np.sum(c) % 2 == 1
+ c_sum: int = np.sum(c)
+ return c_sum % 2 == 1
class Cell:
@@ -137,7 +140,7 @@ def polylabel(rings: Sequence[Point3DLike_Array], precision: float = 0.01) -> Ce
h = s / 2.0
# Initial Grid
- queue = PriorityQueue()
+ queue: PriorityQueue[Cell] = PriorityQueue()
xv, yv = np.meshgrid(np.arange(mins[0], maxs[0], s), np.arange(mins[1], maxs[1], s))
for corner in np.vstack([xv.ravel(), yv.ravel()]).T:
queue.put(Cell(corner + h, h, polygon))
diff --git a/manim/utils/qhull.py b/manim/utils/qhull.py
index 215f114b5..463a3dd30 100644
--- a/manim/utils/qhull.py
+++ b/manim/utils/qhull.py
@@ -16,8 +16,13 @@ class QuickHullPoint:
def __hash__(self) -> int:
return hash(self.coordinates.tobytes())
- def __eq__(self, other: QuickHullPoint) -> bool:
- return np.array_equal(self.coordinates, other.coordinates)
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, QuickHullPoint):
+ raise ValueError
+ are_coordinates_equal: bool = np.array_equal(
+ self.coordinates, other.coordinates
+ )
+ return are_coordinates_equal
class SubFacet:
@@ -28,14 +33,16 @@ class SubFacet:
def __hash__(self) -> int:
return hash(self.points)
- def __eq__(self, other: SubFacet) -> bool:
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, SubFacet):
+ raise ValueError
return self.points == other.points
class Facet:
def __init__(self, coordinates: PointND_Array, internal: PointND) -> None:
self.coordinates = coordinates
- self.center = np.mean(coordinates, axis=0)
+ self.center: PointND = np.mean(coordinates, axis=0)
self.normal = self.compute_normal(internal)
self.subfacets = frozenset(
SubFacet(np.delete(self.coordinates, i, axis=0))
@@ -45,7 +52,7 @@ class Facet:
def compute_normal(self, internal: PointND) -> PointND:
centered = self.coordinates - self.center
_, _, vh = np.linalg.svd(centered)
- normal = vh[-1, :]
+ normal: PointND = vh[-1, :]
normal /= np.linalg.norm(normal)
# If the normal points towards the internal point, flip it!
@@ -57,7 +64,9 @@ class Facet:
def __hash__(self) -> int:
return hash(self.subfacets)
- def __eq__(self, other: Facet) -> bool:
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Facet):
+ raise ValueError
return self.subfacets == other.subfacets
@@ -97,7 +106,7 @@ class QuickHull:
def __init__(self, tolerance: float = 1e-5) -> None:
self.facets: list[Facet] = []
self.removed: set[Facet] = set()
- self.outside: dict[Facet, tuple[PointND_Array, PointND | None]] = {}
+ self.outside: dict[Facet, tuple[PointND_Array | None, PointND | None]] = {}
self.neighbors: dict[SubFacet, set[Facet]] = {}
self.unclaimed: PointND_Array | None = None
self.internal: PointND | None = None
@@ -109,11 +118,12 @@ class QuickHull:
np.random.choice(points.shape[0], points.shape[1] + 1, replace=False)
]
self.unclaimed = points
- self.internal = np.mean(simplex, axis=0)
+ new_internal: PointND = np.mean(simplex, axis=0)
+ self.internal = new_internal
# Build Simplex
for c in range(simplex.shape[0]):
- facet = Facet(np.delete(simplex, c, axis=0), internal=self.internal)
+ facet = Facet(np.delete(simplex, c, axis=0), internal=new_internal)
self.classify(facet)
self.facets.append(facet)
@@ -123,6 +133,10 @@ class QuickHull:
self.neighbors.setdefault(sf, set()).add(f)
def classify(self, facet: Facet) -> None:
+ assert (
+ self.unclaimed is not None
+ ), "Call .initialize() before using .classify()."
+
if not self.unclaimed.size:
self.outside[facet] = (None, None)
return
@@ -143,24 +157,24 @@ class QuickHull:
self._recursive_horizon(eye, start_facet, horizon)
return horizon
- def _recursive_horizon(self, eye: PointND, facet: Facet, horizon: Horizon) -> int:
+ def _recursive_horizon(self, eye: PointND, facet: Facet, horizon: Horizon) -> bool:
visible = np.dot(facet.normal, eye - facet.center) > 0
if not visible:
return False
- # If the eye is visible from the facet...
- else:
- # Label the facet as visible and cross each edge
- horizon.facets.add(facet)
- for subfacet in facet.subfacets:
- neighbor = (self.neighbors[subfacet] - {facet}).pop()
- # If the neighbor is not visible, then the edge shared must be on the boundary
- if neighbor not in horizon.facets and not self._recursive_horizon(
- eye, neighbor, horizon
- ):
- horizon.boundary.append(subfacet)
- return True
-
- def build(self, points: PointND_Array):
+
+ # If the eye is visible from the facet:
+ # Label the facet as visible and cross each edge
+ horizon.facets.add(facet)
+ for subfacet in facet.subfacets:
+ neighbor = (self.neighbors[subfacet] - {facet}).pop()
+ # If the neighbor is not visible, then the edge shared must be on the boundary
+ if neighbor not in horizon.facets and not self._recursive_horizon(
+ eye, neighbor, horizon
+ ):
+ horizon.boundary.append(subfacet)
+ return True
+
+ def build(self, points: PointND_Array) -> None:
num, dim = points.shape
if (dim == 0) or (num < dim + 1):
raise ValueError("Not enough points supplied to build Convex Hull!")
@@ -168,6 +182,11 @@ class QuickHull:
raise ValueError("The Convex Hull of 1D data is its min-max!")
self.initialize(points)
+
+ # This helps the type checker.
+ assert self.unclaimed is not None
+ assert self.internal is not None
+
while True:
updated = False
for facet in self.facets:
@@ -178,7 +197,10 @@ class QuickHull:
updated = True
horizon = self.compute_horizon(eye, facet)
for f in horizon.facets:
- self.unclaimed = np.vstack((self.unclaimed, self.outside[f][0]))
+ points_to_append = self.outside[f][0]
+ # TODO: is this always true?
+ assert points_to_append is not None
+ self.unclaimed = np.vstack((self.unclaimed, points_to_append))
self.removed.add(f)
for sf in f.subfacets:
self.neighbors[sf].discard(f)
diff --git a/manim/utils/rate_functions.py b/manim/utils/rate_functions.py
index ab8cabc98..dfc79c3f7 100644
--- a/manim/utils/rate_functions.py
+++ b/manim/utils/rate_functions.py
@@ -105,21 +105,25 @@ __all__ = [
"exponential_decay",
]
-import typing
from functools import wraps
from math import sqrt
+from typing import Any, Protocol
import numpy as np
-from ..utils.bezier import bezier
-from ..utils.simple_functions import sigmoid
+from manim.utils.simple_functions import sigmoid
+
+
+# TODO: rewrite this to use ParamSpec when Python 3.9 is out of life
+class RateFunction(Protocol):
+ def __call__(self, t: float, *args: Any, **kwargs: Any) -> float: ...
# This is a decorator that makes sure any function it's used on will
# return 0 if t<0 and 1 if t>1.
-def unit_interval(function):
+def unit_interval(function: RateFunction) -> RateFunction:
@wraps(function)
- def wrapper(t, *args, **kwargs):
+ def wrapper(t: float, *args: Any, **kwargs: Any) -> float:
if 0 <= t <= 1:
return function(t, *args, **kwargs)
elif t < 0:
@@ -132,9 +136,9 @@ def unit_interval(function):
# This is a decorator that makes sure any function it's used on will
# return 0 if t<0 or t>1.
-def zero(function):
+def zero(function: RateFunction) -> RateFunction:
@wraps(function)
- def wrapper(t, *args, **kwargs):
+ def wrapper(t: float, *args: Any, **kwargs: Any) -> float:
if 0 <= t <= 1:
return function(t, *args, **kwargs)
else:
@@ -178,7 +182,7 @@ def smoothererstep(t: float) -> float:
The 1st, 2nd and 3rd derivatives (speed, acceleration and jerk) are zero at the endpoints.
https://en.wikipedia.org/wiki/Smoothstep
"""
- alpha = 0
+ alpha: float = 0
if 0 < t < 1:
alpha = 35 * t**4 - 84 * t**5 + 70 * t**6 - 20 * t**7
elif t >= 1:
@@ -198,7 +202,8 @@ def rush_from(t: float, inflection: float = 10.0) -> float:
@unit_interval
def slow_into(t: float) -> float:
- return np.sqrt(1 - (1 - t) * (1 - t))
+ val: float = np.sqrt(1 - (1 - t) * (1 - t))
+ return val
@unit_interval
@@ -230,40 +235,60 @@ def there_and_back_with_pause(t: float, pause_ratio: float = 1.0 / 3) -> float:
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)
+) -> float:
+ t2 = t * t
+ t3 = t2 * t
+ t4 = t3 * t
+ t5 = t4 * t
+ t6 = t5 * t
+ mt = 1 - t
+ mt2 = mt * mt
+ mt3 = mt2 * mt
+ mt4 = mt3 * mt
+
+ # This is equivalent to creating a Bézier with [0, 0, pull_factor, pull_factor, 1, 1, 1]
+ # and evaluating it at t.
+ return (
+ 15 * t2 * mt4 * pull_factor
+ + 20 * t3 * mt3 * pull_factor
+ + 15 * t4 * mt2
+ + 6 * t5 * mt
+ + t6
+ )
def not_quite_there(
- func: typing.Callable[[float], float] = smooth,
+ func: RateFunction = smooth,
proportion: float = 0.7,
-) -> typing.Callable[[float], float]:
- def result(t):
- return proportion * func(t)
+) -> RateFunction:
+ def result(t: float, *args: Any, **kwargs: Any) -> float:
+ return proportion * func(t, *args, **kwargs)
return result
@zero
def wiggle(t: float, wiggles: float = 2) -> float:
- return there_and_back(t) * np.sin(wiggles * np.pi * t)
+ val: float = np.sin(wiggles * np.pi * t)
+ return there_and_back(t) * val
def squish_rate_func(
- func: typing.Callable[[float], float],
+ func: RateFunction,
a: float = 0.4,
b: float = 0.6,
-) -> typing.Callable[[float], float]:
- def result(t):
+) -> RateFunction:
+ def result(t: float, *args: Any, **kwargs: Any) -> float:
if a == b:
return a
if t < a:
- return func(0)
+ new_t = 0.0
elif t > b:
- return func(1)
+ new_t = 1.0
else:
- return func((t - a) / (b - a))
+ new_t = (t - a) / (b - a)
+ return func(new_t, *args, **kwargs)
return result
@@ -276,29 +301,37 @@ def squish_rate_func(
@unit_interval
def lingering(t: float) -> float:
- return squish_rate_func(lambda t: t, 0, 0.8)(t)
+ def identity(t: float) -> float:
+ return t
+
+ # TODO: Isn't this just 0.8 * t?
+ return squish_rate_func(identity, 0, 0.8)(t)
@unit_interval
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)
+ val: float = 1 - np.exp(-t / half_life)
+ return val
@unit_interval
def ease_in_sine(t: float) -> float:
- return 1 - np.cos((t * np.pi) / 2)
+ val: float = 1 - np.cos((t * np.pi) / 2)
+ return val
@unit_interval
def ease_out_sine(t: float) -> float:
- return np.sin((t * np.pi) / 2)
+ val: float = np.sin((t * np.pi) / 2)
+ return val
@unit_interval
def ease_in_out_sine(t: float) -> float:
- return -(np.cos(np.pi * t) - 1) / 2
+ val: float = -(np.cos(np.pi * t) - 1) / 2
+ return val
@unit_interval
@@ -435,7 +468,8 @@ def ease_in_elastic(t: float) -> float:
elif t == 1:
return 1
else:
- return -pow(2, 10 * t - 10) * np.sin((t * 10 - 10.75) * c4)
+ val: float = -pow(2, 10 * t - 10) * np.sin((t * 10 - 10.75) * c4)
+ return val
@unit_interval
@@ -446,7 +480,8 @@ def ease_out_elastic(t: float) -> float:
elif t == 1:
return 1
else:
- return pow(2, -10 * t) * np.sin((t * 10 - 0.75) * c4) + 1
+ val: float = pow(2, -10 * t) * np.sin((t * 10 - 0.75) * c4) + 1
+ return val
@unit_interval
@@ -457,9 +492,11 @@ def ease_in_out_elastic(t: float) -> float:
elif t == 1:
return 1
elif t < 0.5:
- return -(pow(2, 20 * t - 10) * np.sin((20 * t - 11.125) * c5)) / 2
+ val: float = -(pow(2, 20 * t - 10) * np.sin((20 * t - 11.125) * c5)) / 2
+ return val
else:
- return (pow(2, -20 * t + 10) * np.sin((20 * t - 11.125) * c5)) / 2 + 1
+ val = (pow(2, -20 * t + 10) * np.sin((20 * t - 11.125) * c5)) / 2 + 1
+ return val
@unit_interval
diff --git a/manim/utils/simple_functions.py b/manim/utils/simple_functions.py
index 10c9a1587..78951c105 100644
--- a/manim/utils/simple_functions.py
+++ b/manim/utils/simple_functions.py
@@ -11,19 +11,19 @@ __all__ = [
from functools import lru_cache
-from typing import Callable
+from typing import Any, Callable, Protocol, TypeVar
import numpy as np
from scipy import special
def binary_search(
- function: Callable[[int | float], int | float],
- target: int | float,
- lower_bound: int | float,
- upper_bound: int | float,
- tolerance: int | float = 1e-4,
-) -> int | float | None:
+ function: Callable[[float], float],
+ target: float,
+ lower_bound: float,
+ upper_bound: float,
+ tolerance: float = 1e-4,
+) -> float | None:
"""Searches for a value in a range by repeatedly dividing the range in half.
To be more precise, performs numerical binary search to determine the
@@ -54,7 +54,7 @@ def binary_search(
"""
lh = lower_bound
rh = upper_bound
- mh = np.mean(np.array([lh, rh]))
+ mh: float = np.mean(np.array([lh, rh]))
while abs(rh - lh) > tolerance:
mh = np.mean(np.array([lh, rh]))
lx, mx, rx = (function(h) for h in (lh, mh, rh))
@@ -88,10 +88,20 @@ def choose(n: int, k: int) -> int:
- https://en.wikipedia.org/wiki/Combination
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.comb.html
"""
- return special.comb(n, k, exact=True)
+ value: int = special.comb(n, k, exact=True)
+ return value
-def clip(a, min_a, max_a):
+class Comparable(Protocol):
+ def __lt__(self, other: Any) -> bool: ...
+
+ def __gt__(self, other: Any) -> bool: ...
+
+
+ComparableT = TypeVar("ComparableT", bound=Comparable) # noqa: Y001
+
+
+def clip(a: ComparableT, min_a: ComparableT, max_a: ComparableT) -> ComparableT:
"""Clips ``a`` to the interval [``min_a``, ``max_a``].
Accepts any comparable objects (i.e. those that support <, >).
@@ -125,4 +135,5 @@ def sigmoid(x: float) -> float:
- https://en.wikipedia.org/wiki/Sigmoid_function
- https://en.wikipedia.org/wiki/Logistic_function
"""
- return 1.0 / (1 + np.exp(-x))
+ value: float = 1.0 / (1 + np.exp(-x))
+ return value
diff --git a/manim/utils/sounds.py b/manim/utils/sounds.py
index 5e0ea060f..de7b6be80 100644
--- a/manim/utils/sounds.py
+++ b/manim/utils/sounds.py
@@ -6,13 +6,19 @@ __all__ = [
"get_full_sound_file_path",
]
+from typing import TYPE_CHECKING
from .. import config
from ..utils.file_ops import seek_full_path_from_defaults
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from manim.typing import StrPath
+
# Still in use by add_sound() function in scene_file_writer.py
-def get_full_sound_file_path(sound_file_name):
+def get_full_sound_file_path(sound_file_name: StrPath) -> Path:
return seek_full_path_from_defaults(
sound_file_name,
default_dir=config.get_dir("assets_dir"),
diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.py
index d64ec6fe0..963c0811e 100644
--- a/manim/utils/space_ops.py
+++ b/manim/utils/space_ops.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import itertools as it
from collections.abc import Sequence
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Callable
import numpy as np
from mapbox_earcut import triangulate_float32 as earcut
@@ -18,8 +18,13 @@ if TYPE_CHECKING:
from manim.typing import (
ManimFloat,
+ MatrixMN,
+ Point2D_Array,
Point3D,
+ Point3DLike,
Point3DLike_Array,
+ PointND,
+ PointNDLike_Array,
Vector2D,
Vector2D_Array,
Vector3D,
@@ -61,7 +66,8 @@ __all__ = [
def norm_squared(v: float) -> float:
- return np.dot(v, v)
+ val: float = np.dot(v, v)
+ return val
def cross(v1: Vector3D, v2: Vector3D) -> Vector3D:
@@ -202,7 +208,7 @@ def rotate_vector(
return rotation_matrix(angle, axis) @ vector
-def thick_diagonal(dim: int, thickness=2) -> np.ndarray:
+def thick_diagonal(dim: int, thickness: int = 2) -> MatrixMN:
row_indices = np.arange(dim).repeat(dim).reshape((dim, dim))
col_indices = np.transpose(row_indices)
return (np.abs(row_indices - col_indices) < thickness).astype("uint8")
@@ -320,8 +326,10 @@ def angle_of_vector(vector: Sequence[float] | np.ndarray) -> float:
c_vec = np.empty(vector.shape[1], dtype=np.complex128)
c_vec.real = vector[0]
c_vec.imag = vector[1]
- return np.angle(c_vec)
- return np.angle(complex(*vector[:2]))
+ val1: float = np.angle(c_vec)
+ return val1
+ val: float = np.angle(complex(*vector[:2]))
+ return val
def angle_between_vectors(v1: np.ndarray, v2: np.ndarray) -> float:
@@ -340,13 +348,17 @@ def angle_between_vectors(v1: np.ndarray, v2: np.ndarray) -> float:
float
The angle between the vectors.
"""
- return 2 * np.arctan2(
+ val: float = 2 * np.arctan2(
np.linalg.norm(normalize(v1) - normalize(v2)),
np.linalg.norm(normalize(v1) + normalize(v2)),
)
+ return val
-def normalize(vect: np.ndarray | tuple[float], fall_back=None) -> np.ndarray:
+
+def normalize(
+ vect: np.ndarray | tuple[float], fall_back: np.ndarray | None = None
+) -> np.ndarray:
norm = np.linalg.norm(vect)
if norm > 0:
return np.array(vect) / norm
@@ -489,11 +501,13 @@ def R3_to_complex(point: Sequence[float]) -> np.ndarray:
return complex(*point[:2])
-def complex_func_to_R3_func(complex_func):
+def complex_func_to_R3_func(
+ complex_func: Callable[[complex], complex],
+) -> Callable[[Point3DLike], Point3D]:
return lambda p: complex_to_R3(complex_func(R3_to_complex(p)))
-def center_of_mass(points: Sequence[float]) -> np.ndarray:
+def center_of_mass(points: PointNDLike_Array) -> PointND:
"""Gets the center of mass of the points in space.
Parameters
@@ -621,15 +635,16 @@ def get_winding_number(points: Sequence[np.ndarray]) -> float:
>>> get_winding_number(polygon.get_vertices())
np.float64(0.0)
"""
- total_angle = 0
+ total_angle: float = 0
for p1, p2 in adjacent_pairs(points):
d_angle = angle_of_vector(p2) - angle_of_vector(p1)
d_angle = ((d_angle + PI) % TAU) - PI
total_angle += d_angle
- return total_angle / TAU
+ val: float = total_angle / TAU
+ return val
-def shoelace(x_y: np.ndarray) -> float:
+def shoelace(x_y: Point2D_Array) -> float:
"""2D implementation of the shoelace formula.
Returns
@@ -639,10 +654,11 @@ def shoelace(x_y: np.ndarray) -> float:
"""
x = x_y[:, 0]
y = x_y[:, 1]
- return np.trapz(y, x)
+ val: float = np.trapz(y, x)
+ return val
-def shoelace_direction(x_y: np.ndarray) -> str:
+def shoelace_direction(x_y: Point2D_Array) -> str:
"""
Uses the area determined by the shoelace method to determine whether
the input set of points is directed clockwise or counterclockwise.
@@ -760,7 +776,7 @@ def earclip_triangulation(verts: np.ndarray, ring_ends: list) -> list:
raise Exception("Could not find a ring to attach")
# Setup linked list
- after = []
+ after: list[int] = []
end0 = 0
for end1 in ring_ends:
after.extend(range(end0 + 1, end1))
@@ -831,7 +847,7 @@ def spherical_to_cartesian(spherical: Sequence[float]) -> np.ndarray:
def perpendicular_bisector(
line: Sequence[np.ndarray],
- norm_vector=OUT,
+ norm_vector: Vector3D = OUT,
) -> Sequence[np.ndarray]:
"""Returns a list of two points that correspond
to the ends of the perpendicular bisector of the
diff --git a/manim/utils/testing/_frames_testers.py b/manim/utils/testing/_frames_testers.py
index bef618493..aa382bb7b 100644
--- a/manim/utils/testing/_frames_testers.py
+++ b/manim/utils/testing/_frames_testers.py
@@ -3,10 +3,13 @@ from __future__ import annotations
import contextlib
import logging
import warnings
+from collections.abc import Generator
from pathlib import Path
import numpy as np
+from manim.typing import PixelArray
+
from ._show_diff import show_diff_helper
FRAME_ABSOLUTE_TOLERANCE = 1.01
@@ -16,7 +19,7 @@ logger = logging.getLogger("manim")
class _FramesTester:
- def __init__(self, file_path: Path, show_diff=False) -> None:
+ def __init__(self, file_path: Path, show_diff: bool = False) -> None:
self._file_path = file_path
self._show_diff = show_diff
self._frames: np.ndarray
@@ -24,7 +27,7 @@ class _FramesTester:
self._frames_compared = 0
@contextlib.contextmanager
- def testing(self):
+ def testing(self) -> Generator[None, None, None]:
with np.load(self._file_path) as data:
self._frames = data["frame_data"]
# For backward compatibility, when the control data contains only one frame (<= v0.8.0)
@@ -38,7 +41,7 @@ class _FramesTester:
f"when there are {self._number_frames} control frames for this test."
)
- def check_frame(self, frame_number: int, frame: np.ndarray):
+ def check_frame(self, frame_number: int, frame: PixelArray) -> None:
assert frame_number < self._number_frames, (
f"The tested scene is at frame number {frame_number} "
f"when there are {self._number_frames} control frames."
@@ -86,17 +89,17 @@ class _ControlDataWriter(_FramesTester):
self._number_frames_written: int = 0
# Actually write a frame.
- def check_frame(self, index: int, frame: np.ndarray):
+ def check_frame(self, index: int, frame: PixelArray) -> None:
frame = frame[np.newaxis, ...]
self.frames = np.concatenate((self.frames, frame))
self._number_frames_written += 1
@contextlib.contextmanager
- def testing(self):
+ def testing(self) -> Generator[None, None, None]:
yield
self.save_contol_data()
- def save_contol_data(self):
+ def save_contol_data(self) -> None:
self.frames = self.frames.astype("uint8")
np.savez_compressed(self.file_path, frame_data=self.frames)
logger.info(
diff --git a/manim/utils/testing/_show_diff.py b/manim/utils/testing/_show_diff.py
index 0cb2aab0f..e1783a401 100644
--- a/manim/utils/testing/_show_diff.py
+++ b/manim/utils/testing/_show_diff.py
@@ -5,13 +5,15 @@ import warnings
import numpy as np
+from manim.typing import PixelArray
+
def show_diff_helper(
frame_number: int,
- frame_data: np.ndarray,
- expected_frame_data: np.ndarray,
+ frame_data: PixelArray,
+ expected_frame_data: PixelArray,
control_data_filename: str,
-):
+) -> None:
"""Will visually display with matplotlib differences between frame generated and the one expected."""
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
diff --git a/manim/utils/testing/_test_class_makers.py b/manim/utils/testing/_test_class_makers.py
index fe127be1c..084aab487 100644
--- a/manim/utils/testing/_test_class_makers.py
+++ b/manim/utils/testing/_test_class_makers.py
@@ -1,9 +1,12 @@
from __future__ import annotations
-from typing import Callable
+from typing import Any, Callable
+from manim.renderer.cairo_renderer import CairoRenderer
+from manim.renderer.opengl_renderer import OpenGLRenderer
from manim.scene.scene import Scene
from manim.scene.scene_file_writer import SceneFileWriter
+from manim.typing import PixelArray, StrPath
from ._frames_testers import _FramesTester
@@ -11,13 +14,14 @@ from ._frames_testers import _FramesTester
def _make_test_scene_class(
base_scene: type[Scene],
construct_test: Callable[[Scene], None],
- test_renderer,
+ test_renderer: CairoRenderer | OpenGLRenderer | None,
) -> type[Scene]:
- class _TestedScene(base_scene):
- def __init__(self, *args, **kwargs):
+ # TODO: Get the type annotation right for the base_scene argument.
+ class _TestedScene(base_scene): # type: ignore[valid-type, misc]
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, renderer=test_renderer, **kwargs)
- def construct(self):
+ def construct(self) -> None:
construct_test(self)
# Manim hack to render the very last frame (normally the last frame is not the very end of the animation)
@@ -28,7 +32,7 @@ def _make_test_scene_class(
return _TestedScene
-def _make_test_renderer_class(from_renderer):
+def _make_test_renderer_class(from_renderer: type) -> Any:
# Just for inheritance.
class _TestRenderer(from_renderer):
pass
@@ -39,38 +43,49 @@ def _make_test_renderer_class(from_renderer):
class DummySceneFileWriter(SceneFileWriter):
"""Delegate of SceneFileWriter used to test the frames."""
- def __init__(self, renderer, scene_name, **kwargs):
+ def __init__(
+ self,
+ renderer: CairoRenderer | OpenGLRenderer,
+ scene_name: StrPath,
+ **kwargs: Any,
+ ) -> None:
super().__init__(renderer, scene_name, **kwargs)
self.i = 0
- def init_output_directories(self, scene_name):
+ def init_output_directories(self, scene_name: StrPath) -> None:
pass
- def add_partial_movie_file(self, hash_animation):
+ def add_partial_movie_file(self, hash_animation: str) -> None:
pass
- def begin_animation(self, allow_write=True):
+ def begin_animation(
+ self, allow_write: bool = True, file_path: StrPath | None = None
+ ) -> Any:
pass
- def end_animation(self, allow_write):
+ def end_animation(self, allow_write: bool = False) -> None:
pass
- def combine_to_movie(self):
+ def combine_to_movie(self) -> None:
pass
- def combine_to_section_videos(self):
+ def combine_to_section_videos(self) -> None:
pass
- def clean_cache(self):
+ def clean_cache(self) -> None:
pass
- def write_frame(self, frame_or_renderer, num_frames=1):
+ def write_frame(
+ self, frame_or_renderer: PixelArray | OpenGLRenderer, num_frames: int = 1
+ ) -> None:
self.i += 1
def _make_scene_file_writer_class(tester: _FramesTester) -> type[SceneFileWriter]:
class TestSceneFileWriter(DummySceneFileWriter):
- def write_frame(self, frame_or_renderer, num_frames=1):
+ def write_frame(
+ self, frame_or_renderer: PixelArray | OpenGLRenderer, num_frames: int = 1
+ ) -> None:
tester.check_frame(self.i, frame_or_renderer)
super().write_frame(frame_or_renderer, num_frames=num_frames)
diff --git a/manim/utils/testing/frames_comparison.py b/manim/utils/testing/frames_comparison.py
index a298585b2..7b5f23f8c 100644
--- a/manim/utils/testing/frames_comparison.py
+++ b/manim/utils/testing/frames_comparison.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import functools
import inspect
from pathlib import Path
-from typing import Callable
+from typing import Any, Callable
import cairo
import pytest
@@ -14,7 +14,9 @@ from manim._config import tempconfig
from manim._config.utils import ManimConfig
from manim.camera.three_d_camera import ThreeDCamera
from manim.renderer.cairo_renderer import CairoRenderer
+from manim.renderer.opengl_renderer import OpenGLRenderer
from manim.scene.three_d_scene import ThreeDScene
+from manim.typing import StrPath
from ._frames_testers import _ControlDataWriter, _FramesTester
from ._test_class_makers import (
@@ -31,13 +33,13 @@ MIN_CAIRO_VERSION = 11800
def frames_comparison(
- func=None,
+ func: Callable | None = None,
*,
last_frame: bool = True,
- renderer_class=CairoRenderer,
- base_scene=Scene,
- **custom_config,
-):
+ renderer_class: type[CairoRenderer | OpenGLRenderer] = CairoRenderer,
+ base_scene: type[Scene] = Scene,
+ **custom_config: Any,
+) -> Callable:
"""Compares the frames generated by the test with control frames previously registered.
If there is no control frames for this test, the test will fail. To generate
@@ -60,7 +62,7 @@ def frames_comparison(
If the scene has a moving animation, then the test must set last_frame to False.
"""
- def decorator_maker(tested_scene_construct):
+ def decorator_maker(tested_scene_construct: Callable) -> Callable:
if (
SCENE_PARAMETER_NAME
not in inspect.getfullargspec(tested_scene_construct).args
@@ -79,11 +81,14 @@ def frames_comparison(
"There is no module test name indicated for the graphical unit test. You have to declare __module_test__ in the test file.",
)
module_name = tested_scene_construct.__globals__.get("__module_test__")
+ assert isinstance(module_name, str)
test_name = tested_scene_construct.__name__[len("test_") :]
@functools.wraps(tested_scene_construct)
# The "request" parameter is meant to be used as a fixture by pytest. See below.
- def wrapper(*args, request: FixtureRequest, tmp_path, **kwargs):
+ def wrapper(
+ *args: Any, request: FixtureRequest, tmp_path: StrPath, **kwargs: Any
+ ) -> None:
# check for cairo version
if (
renderer_class is CairoRenderer
@@ -146,13 +151,13 @@ def frames_comparison(
inspect.Parameter("tmp_path", inspect.Parameter.KEYWORD_ONLY),
]
new_sig = old_sig.replace(parameters=parameters)
- wrapper.__signature__ = new_sig
+ wrapper.__signature__ = new_sig # type: ignore[attr-defined]
# Reach a bit into pytest internals to hoist the marks from our wrapped
# function.
- wrapper.pytestmark = []
+ wrapper.pytestmark = [] # type: ignore[attr-defined]
new_marks = getattr(tested_scene_construct, "pytestmark", [])
- wrapper.pytestmark = new_marks
+ wrapper.pytestmark = new_marks # type: ignore[attr-defined]
return wrapper
# Case where the decorator is called with and without parentheses.
@@ -193,7 +198,9 @@ def _make_test_comparing_frames(
The pytest test.
"""
if is_set_test_data_test:
- frames_tester = _ControlDataWriter(file_path, size_frame=size_frame)
+ frames_tester: _FramesTester = _ControlDataWriter(
+ file_path, size_frame=size_frame
+ )
else:
frames_tester = _FramesTester(file_path, show_diff=show_diff)
@@ -204,7 +211,7 @@ def _make_test_comparing_frames(
)
testRenderer = _make_test_renderer_class(renderer_class)
- def real_test():
+ def real_test() -> None:
with frames_tester.testing():
sceneTested = _make_test_scene_class(
base_scene=base_scene,
diff --git a/manim/utils/tex.py b/manim/utils/tex.py
index 41e19bcd5..39ef55d8f 100644
--- a/manim/utils/tex.py
+++ b/manim/utils/tex.py
@@ -36,6 +36,9 @@ class TexTemplate:
tex_compiler: str = "latex"
"""The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``."""
+ description: str = ""
+ """A description of the template"""
+
output_format: str = ".dvi"
"""The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``."""
diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.py
index 45e84d490..8c2c9c8c0 100644
--- a/manim/utils/tex_file_writing.py
+++ b/manim/utils/tex_file_writing.py
@@ -12,8 +12,10 @@ import hashlib
import re
import subprocess
import unicodedata
-from collections.abc import Iterable
+from collections.abc import Generator, Iterable, Sequence
from pathlib import Path
+from re import Match
+from typing import Any
from manim.utils.tex import TexTemplate
@@ -22,7 +24,7 @@ from .. import config, logger
__all__ = ["tex_to_svg_file"]
-def tex_hash(expression):
+def tex_hash(expression: Any) -> str:
id_str = str(expression)
hasher = hashlib.sha256()
hasher.update(id_str.encode())
@@ -34,7 +36,7 @@ def tex_to_svg_file(
expression: str,
environment: str | None = None,
tex_template: TexTemplate | None = None,
-):
+) -> Path:
r"""Takes a tex expression and returns the svg version of the compiled tex
Parameters
@@ -165,14 +167,14 @@ def make_tex_compilation_command(
return command
-def insight_inputenc_error(matching):
+def insight_inputenc_error(matching: Match[str]) -> Generator[str]:
code_point = chr(int(matching[1], 16))
name = unicodedata.name(code_point)
yield f"TexTemplate does not support character '{name}' (U+{matching[1]})."
yield "See the documentation for manim.mobject.svg.tex_mobject for details on using a custom TexTemplate."
-def insight_package_not_found_error(matching):
+def insight_package_not_found_error(matching: Match[str]) -> Generator[str]:
yield f"You do not have package {matching[1]} installed."
yield f"Install {matching[1]} it using your LaTeX package manager, or check for typos."
@@ -215,7 +217,7 @@ def compile_tex(tex_file: Path, tex_compiler: str, output_format: str) -> Path:
return result
-def convert_to_svg(dvi_file: Path, extension: str, page: int = 1):
+def convert_to_svg(dvi_file: Path, extension: str, page: int = 1) -> Path:
"""Converts a .dvi, .xdv, or .pdf file into an svg using dvisvgm.
Parameters
@@ -304,7 +306,11 @@ LATEX_ERROR_INSIGHTS = [
]
-def print_tex_error(tex_compilation_log, error_start_index, tex_source):
+def print_tex_error(
+ tex_compilation_log: Sequence[str],
+ error_start_index: int,
+ tex_source: Sequence[str],
+) -> None:
logger.error(
f"LaTeX compilation error: {tex_compilation_log[error_start_index][2:]}",
)
@@ -338,8 +344,8 @@ def print_tex_error(tex_compilation_log, error_start_index, tex_source):
context += tex_source[line_of_tex_error - 3 : line_of_tex_error + 3]
context[-4] = "-> " + context[-4]
- context = "".join(context)
- logger.error(context)
+ context_joined = "".join(context)
+ logger.error(context_joined)
for insights in LATEX_ERROR_INSIGHTS:
prob, get_insight = insights
diff --git a/manim/utils/tex_templates.py b/manim/utils/tex_templates.py
index ed9db91c3..7273b67d0 100644
--- a/manim/utils/tex_templates.py
+++ b/manim/utils/tex_templates.py
@@ -12,7 +12,7 @@ from .tex import *
# This file makes TexTemplateLibrary and TexFontTemplates available for use in manim Tex and MathTex objects.
-def _new_ams_template():
+def _new_ams_template() -> TexTemplate:
"""Returns a simple Tex Template with only basic AMS packages"""
preamble = r"""
\usepackage[english]{babel}
diff --git a/manim/utils/unit.py b/manim/utils/unit.py
index f629e070d..c4755f019 100644
--- a/manim/utils/unit.py
+++ b/manim/utils/unit.py
@@ -5,20 +5,21 @@ from __future__ import annotations
import numpy as np
from .. import config, constants
+from ..typing import Vector3D
__all__ = ["Pixels", "Degrees", "Munits", "Percent"]
class _PixelUnits:
- def __mul__(self, val):
+ def __mul__(self, val: float) -> float:
return val * config.frame_width / config.pixel_width
- def __rmul__(self, val):
+ def __rmul__(self, val: float) -> float:
return val * config.frame_width / config.pixel_width
class Percent:
- def __init__(self, axis):
+ def __init__(self, axis: Vector3D) -> None:
if np.array_equal(axis, constants.X_AXIS):
self.length = config.frame_width
if np.array_equal(axis, constants.Y_AXIS):
@@ -26,10 +27,10 @@ class Percent:
if np.array_equal(axis, constants.Z_AXIS):
raise NotImplementedError("length of Z axis is undefined")
- def __mul__(self, val):
+ def __mul__(self, val: float) -> float:
return val / 100 * self.length
- def __rmul__(self, val):
+ def __rmul__(self, val: float) -> float:
return val / 100 * self.length
diff --git a/mypy.ini b/mypy.ini
index 160daf488..4d4d586c9 100644
--- a/mypy.ini
+++ b/mypy.ini
@@ -71,7 +71,7 @@ ignore_errors = True
ignore_errors = True
[mypy-manim.mobject.geometry.*]
-ignore_errors = False
+ignore_errors = True
[mypy-manim.renderer.*]
ignore_errors = True
@@ -79,11 +79,10 @@ ignore_errors = True
[mypy-manim.scene.*]
ignore_errors = True
-[mypy-manim.utils.*]
+[mypy-manim.utils.hashing.*]
ignore_errors = True
[mypy-manim.utils.iterables]
-ignore_errors = False
warn_return_any = False