Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding type annotations to manim.utils.* #3999

Open
wants to merge 26 commits into
base: main
Choose a base branch
from

Conversation

henrikmidtiby
Copy link
Contributor

Overview: What does this pull request change?

The PR adds type annotations to some of the elements in manim/utils

Motivation and Explanation: Why and how do your changes improve the library?

Type annotations are a good thing.

Further Information and Comments

I have chosen to go for smaller PR regarding adding type annotations.
The endeavor of #3981 is a bit frightening...

Reviewer Checklist

  • The PR title is descriptive enough for the changelog, and the PR is labeled correctly
  • If applicable: newly added non-private functions and classes have a docstring including a short summary and a PARAMETERS section
  • If applicable: newly added functions and classes are tested

manim/utils/bezier.py Dismissed Show dismissed Hide dismissed
manim/utils/bezier.py Dismissed Show dismissed Hide dismissed
manim/utils/bezier.py Dismissed Show dismissed Hide dismissed
manim/utils/bezier.py Dismissed Show dismissed Hide dismissed
def inverse_interpolate(start: float, end: float, value: Point3D) -> Point3D: ...
def inverse_interpolate(
start: float, end: float, value: InternalPoint3D
) -> InternalPoint3D: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.
def inverse_interpolate(start: Point3D, end: Point3D, value: Point3D) -> Point3D: ...
def inverse_interpolate(
start: InternalPoint3D, end: InternalPoint3D, value: InternalPoint3D
) -> Point3D: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.
manim/utils/color/core.py Fixed Show fixed Hide fixed
manim/scene/scene_file_writer.py Fixed Show fixed Hide fixed
manim/scene/scene_file_writer.py Fixed Show fixed Hide fixed


def clip(a, min_a, max_a):
@overload
def clip(a: float, min_a: float, max_a: float) -> float: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.


@overload
def clip(a: str, min_a: str, max_a: str) -> str: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.
@henrikmidtiby
Copy link
Contributor Author

@JasonGrace2282 Would you take a look at this PR?

@JasonGrace2282
Copy link
Member

I'll take a look when I find the time.

manim/utils/family_ops.py Dismissed Show dismissed Hide dismissed
manim/utils/caching.py Dismissed Show dismissed Hide dismissed
__all__ = ["scene_classes_from_file"]


def get_module(file_name: Path):
def get_module(file_name: Path) -> types.ModuleType:

Check notice

Code scanning / CodeQL

Explicit returns mixed with implicit (fall through) returns Note

Mixing implicit and explicit returns may indicate an error as implicit returns always return None.
@henrikmidtiby henrikmidtiby mentioned this pull request Nov 14, 2024
22 tasks
Copy link
Contributor

@chopan050 chopan050 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, this is a huge PR! It will take a long time to review. I added 47 comments and I'm not finished yet, but I hope to continue reviewing soon.

A new PR (#4027) has been merged. This renames InternalPoint3D (the NumPy array) to Point3D, and Point3D (anything resembling a 3D point) to Point3DLike. Something similar happened with the other type aliases. You might wanna take a look at it.

@@ -692,7 +692,7 @@ def digest_parser(self, parser: configparser.ConfigParser) -> Self:

return self

def digest_args(self, args: argparse.Namespace) -> Self:
def digest_args(self, args: argparse.Namespace | list[str]) -> Self:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

args cannot be a list[str] in this case. args is an object with multiple attributes which a list doesn't have, as it can be seen in lines such as:

if args.file.suffix == ".cfg":
	args.config_file = args.file
Suggested change
def digest_args(self, args: argparse.Namespace | list[str]) -> Self:
def digest_args(self, args: argparse.Namespace) -> Self:

@@ -1395,7 +1395,7 @@ def renderer(self, value: str | RendererType) -> None:
self._set_from_enum("renderer", renderer, RendererType)

@property
def media_dir(self) -> str:
def media_dir(self) -> str | Path:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line 29 in manim/cli/render/output_options.py describes how the --media_dir option is parsed:

    option(
        "--media_dir",
        type=Path(),
        default=None,
        help="Path to store rendered videos and latex.",
    ),

which means it will be always parsed as a Path. Thus, this property should return and receive a Path.

Technically, all those properties can return None, because ManimConfig.__init__() initializes the internal ._d dictionary whose values are all None in the beginning, before digesting any arguments. This makes the config even harder to use with type checking. Currently, the Manim configuration is very convoluted and I don't think that MyPy errors can stop being ignored right now in mypy.ini, but there have been multiple attempts to refactor and clean the config, so I would wait for those PRs. In the meantime, I would say that simply returning Path is fine.

Suggested change
def media_dir(self) -> str | Path:
def media_dir(self) -> Path:

@@ -160,7 +161,7 @@ def render(self, scene, time, moving_mobjects):
self.update_frame(scene, moving_mobjects)
self.add_frame(self.get_frame())

def get_frame(self):
def get_frame(self) -> npt.NDArray:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a type alias in manim.utils.typing for this specific case:

Suggested change
def get_frame(self) -> npt.NDArray:
def get_frame(self) -> RGBPixelArray:

@@ -486,7 +486,7 @@ def add(self, *mobjects: Mobject):
self.moving_mobjects += mobjects
return self

def add_mobjects_from_animations(self, animations):
def add_mobjects_from_animations(self, animations: list) -> None:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a parameter or return type is a list, you can (and should) specify its contents explicitly. In this case:

Suggested change
def add_mobjects_from_animations(self, animations: list) -> None:
def add_mobjects_from_animations(self, animations: list[Animation]) -> None:

def __init__(self, renderer, scene_name, **kwargs):
def __init__(
self,
renderer: Any,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
renderer: Any,
renderer: CairoRenderer | OpenGLRenderer,

In this way, the type checker can detect the .num_plays attribute which is referenced twice in this file.

Comment on lines +107 to 108
def prompt_user_for_choice(scene_classes: list[Any]) -> list[Any]:
num_to_class = {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def prompt_user_for_choice(scene_classes: list[Any]) -> list[Any]:
num_to_class = {}
def prompt_user_for_choice(scene_classes: list[type[Scene]]) -> list[type[Scene]]:
num_to_class: dict[int, type[Scene]] = {}

@@ -125,8 +132,8 @@ def prompt_user_for_choice(scene_classes):


def scene_classes_from_file(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one could be overloaded like this:

@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: bool = False, full_list: bool = False
) -> type[Scene] | list[type[Scene]]:
    # the rest

@@ -22,17 +27,17 @@
]


def matrix_to_shader_input(matrix):
def matrix_to_shader_input(matrix: npt.NDArray) -> tuple:
Copy link
Contributor

@chopan050 chopan050 Dec 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All these functions use 4x4 matrices. Maybe we could define a Matrix4x4: TypeAlias = MatrixMN in manim.typing. I do suggest defining FlattenedMatrix4x4, because many functions here use it.

Suggested change
def matrix_to_shader_input(matrix: npt.NDArray) -> tuple:
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:

near: float = 1,
far: float = depth + 1,
format_: bool = True,
) -> npt.NDArray | tuple:
Copy link
Contributor

@chopan050 chopan050 Dec 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
) -> npt.NDArray | tuple:
) -> MatrixMN | FlattenedMatrix4x4:

near: float = 2,
far: float = 50,
format_: bool = True,
) -> npt.NDArray | tuple:
Copy link
Contributor

@chopan050 chopan050 Dec 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
) -> npt.NDArray | tuple:
) -> MatrixMN | FlattenedMatrix4x4:

Copy link
Contributor

@chopan050 chopan050 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Part 2 of 3:

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) -> npt.NDArray:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def translation_matrix(x: float = 0, y: float = 0, z: float = 0) -> npt.NDArray:
def translation_matrix(x: float = 0, y: float = 0, z: float = 0) -> MatrixMN:

@@ -83,7 +92,7 @@ def translation_matrix(x=0, y=0, z=0):
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If x, y and z all happen to be integers, then this array would be interpreted as an matrix of integers rather than floats.
I suggest adding the float dtype explicitly.

Suggested change
)
dtype=ManimFloat,
)

@@ -83,7 +92,7 @@ def translation_matrix(x=0, y=0, z=0):
)


def x_rotation_matrix(x=0):
def x_rotation_matrix(x: float = 0) -> npt.NDArray:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def x_rotation_matrix(x: float = 0) -> npt.NDArray:
def x_rotation_matrix(x: float = 0) -> MatrixMN:

@@ -94,7 +103,7 @@ def x_rotation_matrix(x=0):
)


def y_rotation_matrix(y=0):
def y_rotation_matrix(y: float = 0) -> npt.NDArray:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def y_rotation_matrix(y: float = 0) -> npt.NDArray:
def y_rotation_matrix(y: float = 0) -> MatrixMN:

@@ -105,7 +114,7 @@ def y_rotation_matrix(y=0):
)


def z_rotation_matrix(z=0):
def z_rotation_matrix(z: float = 0) -> npt.NDArray:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def z_rotation_matrix(z: float = 0) -> npt.NDArray:
def z_rotation_matrix(z: float = 0) -> MatrixMN:

@@ -637,7 +645,8 @@ 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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def shoelace_direction(x_y: np.ndarray) -> str:
def shoelace_direction(x_y: Point2D_Array) -> str:

@@ -758,7 +767,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 = []
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
after: list = []
after: list[int] = []

@@ -829,7 +838,7 @@ def spherical_to_cartesian(spherical: Sequence[float]) -> np.ndarray:

def perpendicular_bisector(
line: Sequence[np.ndarray],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
line: Sequence[np.ndarray],
line: Point3DLike_Array,

@@ -829,7 +838,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]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
) -> Sequence[np.ndarray]:
) -> list[Point3D]:

self._file_path = file_path
self._show_diff = show_diff
self._frames: np.ndarray
self._number_frames: int = 0
self._frames_compared = 0

@contextlib.contextmanager
def testing(self):
def testing(self) -> Generator[Any, Any, Any]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this be

Suggested change
def testing(self) -> Generator[Any, Any, Any]:
def testing(self) -> Generator[None, None, None]:

since it yields nothing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: 👀 In review
Development

Successfully merging this pull request may close these issues.

3 participants