Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Fix type errors and add typings for `Mobject.apply_function()`, its derivatives, and other utility functions (#4228)

godalming123a1bca6c3b9ef
diff --git a/manim/mobject/geometry/arc.py b/manim/mobject/geometry/arc.py
index 7193c6940..d47e859c9 100644
--- a/manim/mobject/geometry/arc.py
+++ b/manim/mobject/geometry/arc.py
@@ -185,7 +185,7 @@ class TipableVMobject(VMobject, metaclass=ConvertToOpenGL):
else:
handle = self.get_last_handle()
anchor = self.get_end()
- angles = cartesian_to_spherical((handle - anchor).tolist())
+ angles = cartesian_to_spherical(handle - anchor)
tip.rotate(
angles[1] - PI - tip.tip_angle,
) # Rotates the tip along the azimuthal
diff --git a/manim/mobject/geometry/boolean_ops.py b/manim/mobject/geometry/boolean_ops.py
index ea5aa38ef..0a3cea68e 100644
--- a/manim/mobject/geometry/boolean_ops.py
+++ b/manim/mobject/geometry/boolean_ops.py
@@ -57,7 +57,7 @@ class _BooleanOps(VMobject, metaclass=ConvertToOpenGL):
list_of_points = list(points)
for i, point in enumerate(list_of_points):
if len(point) == 2:
- list_of_points[i] = np.array(list(point) + [z_dim])
+ list_of_points[i] = np.append(point, z_dim)
return np.asarray(list_of_points)
def _convert_vmobject_to_skia_path(self, vmobject: VMobject) -> SkiaPath:
@@ -76,10 +76,10 @@ class _BooleanOps(VMobject, metaclass=ConvertToOpenGL):
"""
path = SkiaPath()
- if not np.all(np.isfinite(vmobject.points)):
- points = np.zeros((1, 3)) # point invalid?
- else:
+ if np.all(np.isfinite(vmobject.points)):
points = vmobject.points
+ else:
+ points = np.zeros((1, 3)) # point invalid?
if len(points) == 0: # what? No points so return empty path
return path
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index e25f7d0b6..73e9ce58e 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -46,6 +46,7 @@ if TYPE_CHECKING:
from manim.typing import (
FunctionOverride,
MappingFunction,
+ MatrixMN,
MultiMappingFunction,
PathFuncType,
PixelArray,
@@ -1226,7 +1227,13 @@ class Mobject:
return self
- def scale(self, scale_factor: float, **kwargs) -> Self:
+ def scale(
+ self,
+ scale_factor: float,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
r"""Scale the size by a factor.
Default behavior is to scale about the center of the mobject.
@@ -1237,9 +1244,10 @@ class Mobject:
The scaling factor :math:`\alpha`. If :math:`0 < |\alpha| < 1`, the mobject
will shrink, and for :math:`|\alpha| > 1` it will grow. Furthermore,
if :math:`\alpha < 0`, the mobject is also flipped.
- kwargs
- Additional keyword arguments passed to
- :meth:`apply_points_function_about_point`.
+ about_point
+ The point about which to apply the scaling.
+ about_edge
+ The edge about which to apply the scaling.
Returns
-------
@@ -1268,7 +1276,7 @@ class Mobject:
"""
self.apply_points_function_about_point(
- lambda points: scale_factor * points, **kwargs
+ lambda points: scale_factor * points, about_point, about_edge
)
return self
@@ -1280,8 +1288,9 @@ class Mobject:
self,
angle: float,
axis: Vector3DLike = OUT,
+ *,
about_point: Point3DLike | None = None,
- **kwargs,
+ about_edge: Vector3DLike | None = None,
) -> Self:
"""Rotates the :class:`~.Mobject` around a specified axis and point.
@@ -1295,9 +1304,8 @@ class Mobject:
about_point
The point about which the mobject rotates. If ``None``, rotation occurs around
the center of the mobject.
- **kwargs
- Additional keyword arguments passed to :meth:`apply_points_function_about_point`,
- such as ``about_edge``.
+ about_edge
+ The edge about which to apply the scaling.
Returns
-------
@@ -1343,11 +1351,17 @@ class Mobject:
"""
rot_matrix = rotation_matrix(angle, axis)
self.apply_points_function_about_point(
- lambda points: np.dot(points, rot_matrix.T), about_point, **kwargs
+ lambda points: np.dot(points, rot_matrix.T), about_point, about_edge
)
return self
- def flip(self, axis: Vector3DLike = UP, **kwargs) -> Self:
+ def flip(
+ self,
+ axis: Vector3DLike = UP,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
"""Flips/Mirrors an mobject about its center.
Examples
@@ -1364,26 +1378,45 @@ class Mobject:
self.add(s2)
"""
- return self.rotate(TAU / 2, axis, **kwargs)
+ return self.rotate(
+ TAU / 2, axis, about_point=about_point, about_edge=about_edge
+ )
- def stretch(self, factor: float, dim: int, **kwargs) -> Self:
+ def stretch(
+ self,
+ factor: float,
+ dim: int,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
def func(points: Point3D_Array) -> Point3D_Array:
points[:, dim] *= factor
return points
- self.apply_points_function_about_point(func, **kwargs)
+ self.apply_points_function_about_point(func, about_point, about_edge)
return self
- def apply_function(self, function: MappingFunction, **kwargs) -> Self:
+ def apply_function(
+ self,
+ function: MappingFunction,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
# Default to applying matrix about the origin, not mobjects center
- if len(kwargs) == 0:
- kwargs["about_point"] = ORIGIN
+ if about_point is None and about_edge is None:
+ about_point = ORIGIN
def multi_mapping_function(points: Point3D_Array) -> Point3D_Array:
result: Point3D_Array = np.apply_along_axis(function, 1, points)
return result
- self.apply_points_function_about_point(multi_mapping_function, **kwargs)
+ self.apply_points_function_about_point(
+ multi_mapping_function,
+ about_point,
+ about_edge,
+ )
return self
def apply_function_to_position(self, function: MappingFunction) -> Self:
@@ -1395,20 +1428,30 @@ class Mobject:
submob.apply_function_to_position(function)
return self
- def apply_matrix(self, matrix, **kwargs) -> Self:
+ def apply_matrix(
+ self,
+ matrix: MatrixMN,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
# Default to applying matrix about the origin, not mobjects center
- if ("about_point" not in kwargs) and ("about_edge" not in kwargs):
- kwargs["about_point"] = ORIGIN
+ if about_point is None and about_edge is None:
+ about_point = ORIGIN
full_matrix = np.identity(self.dim)
matrix = np.array(matrix)
full_matrix[: matrix.shape[0], : matrix.shape[1]] = matrix
self.apply_points_function_about_point(
- lambda points: np.dot(points, full_matrix.T), **kwargs
+ lambda points: np.dot(points, full_matrix.T), about_point, about_edge
)
return self
def apply_complex_function(
- self, function: Callable[[complex], complex], **kwargs
+ self,
+ function: Callable[[complex], complex],
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
) -> Self:
"""Applies a complex function to a :class:`Mobject`.
The x and y Point3Ds correspond to the real and imaginary parts respectively.
@@ -1441,7 +1484,9 @@ class Mobject:
xy_complex = function(complex(x, y))
return [xy_complex.real, xy_complex.imag, z]
- return self.apply_function(R3_func)
+ return self.apply_function(
+ R3_func, about_point=about_point, about_edge=about_edge
+ )
def reverse_points(self) -> Self:
for mob in self.family_members_with_points():
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index 69c3f5906..d529be779 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -472,7 +472,14 @@ class VMobject(Mobject):
self.set_stroke(opacity=opacity, family=family, background=True)
return self
- def scale(self, scale_factor: float, scale_stroke: bool = False, **kwargs) -> Self:
+ def scale(
+ self,
+ scale_factor: float,
+ scale_stroke: bool = False,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
r"""Scale the size by a factor.
Default behavior is to scale about the center of the vmobject.
@@ -527,7 +534,7 @@ class VMobject(Mobject):
width=abs(scale_factor) * self.get_stroke_width(background=True),
background=True,
)
- super().scale(scale_factor, **kwargs)
+ super().scale(scale_factor, about_point=about_point, about_edge=about_edge)
return self
def fade(self, darkness: float = 0.5, family: bool = True) -> Self:
@@ -593,7 +600,6 @@ class VMobject(Mobject):
def get_stroke_width(self, background: bool = False) -> float:
if background:
- self.background_stroke_width: float
width = self.background_stroke_width
else:
width = self.stroke_width
@@ -1177,7 +1183,13 @@ class VMobject(Mobject):
self.points = self.points[:-1]
self.append_points(vectorized_mobject.points)
- def apply_function(self, function: MappingFunction) -> Self:
+ def apply_function(
+ self,
+ function: MappingFunction,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
factor = self.pre_function_handle_to_anchor_scale_factor
self.scale_handle_to_anchor_distances(factor)
super().apply_function(function)
@@ -1190,11 +1202,12 @@ class VMobject(Mobject):
self,
angle: float,
axis: Vector3DLike = OUT,
+ *,
about_point: Point3DLike | None = None,
- **kwargs,
+ about_edge: Vector3DLike | None = None,
) -> Self:
self.rotate_sheen_direction(angle, axis)
- super().rotate(angle, axis, about_point, **kwargs)
+ super().rotate(angle, axis, about_point=about_point, about_edge=about_edge)
return self
def scale_handle_to_anchor_distances(self, factor: float) -> Self:
diff --git a/manim/utils/bezier.py b/manim/utils/bezier.py
index b50c7e236..551795873 100644
--- a/manim/utils/bezier.py
+++ b/manim/utils/bezier.py
@@ -915,10 +915,10 @@ def subdivide_bezier(points: BezierPointsLike, n_divisions: int) -> Spline:
:class:`~.Spline`
An array containing the points defining the new :math:`n` subcurves.
"""
+ points = np.asarray(points)
if n_divisions == 1:
return points
- points = np.asarray(points)
N, dim = points.shape
if N <= 4:
diff --git a/manim/utils/images.py b/manim/utils/images.py
index f3f49268f..eb634777a 100644
--- a/manim/utils/images.py
+++ b/manim/utils/images.py
@@ -15,13 +15,13 @@ from typing import TYPE_CHECKING
import numpy as np
from PIL import Image
-from manim.typing import RGBAPixelArray, RGBPixelArray
-
from .. import config
from ..utils.file_ops import seek_full_path_from_defaults
if TYPE_CHECKING:
- pass
+ from collections.abc import Sequence
+
+ from manim.typing import PixelArray, RGBAPixelArray, RGBPixelArray
def get_full_raster_image_path(image_file_name: str | PurePath) -> Path:
@@ -40,16 +40,16 @@ def get_full_vector_image_path(image_file_name: str | PurePath) -> Path:
)
-def drag_pixels(frames: list[np.array]) -> list[np.array]:
+def drag_pixels(frames: Sequence[PixelArray]) -> list[np.ndarray]:
curr = frames[0]
- new_frames = []
+ new_frames: list[np.ndarray] = []
for frame in frames:
curr += (curr == 0) * np.array(frame)
new_frames.append(np.array(curr))
return new_frames
-def invert_image(image: np.array) -> Image:
+def invert_image(image: PixelArray) -> Image:
arr = np.array(image)
arr = (255 * np.ones(arr.shape)).astype(arr.dtype) - arr
return Image.fromarray(arr)
diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.py
index 0ac648cb8..21ae9400e 100644
--- a/manim/utils/space_ops.py
+++ b/manim/utils/space_ops.py
@@ -806,18 +806,18 @@ def earclip_triangulation(verts: np.ndarray, ring_ends: list) -> list:
return [indices[mi] for mi in meta_indices]
-def cartesian_to_spherical(vec: Sequence[float]) -> np.ndarray:
+def cartesian_to_spherical(vec: Vector3DLike) -> np.ndarray:
"""Returns an array of numbers corresponding to each
polar coordinate value (distance, phi, theta).
Parameters
----------
vec
- A numpy array ``[x, y, z]``.
+ A numpy array or a sequence of floats ``[x, y, z]``.
"""
norm = np.linalg.norm(vec)
if norm == 0:
- return 0, 0, 0
+ return np.zeros(3)
r = norm
phi = np.arccos(vec[2] / r)
theta = np.arctan2(vec[1], vec[0])