Convert all types of parameters in docstrings to proper type annotations (#2988)

* Converted types in docstrings to type annotations

* `isort .`

* `black .`

* Additional docstrings type annotation fixes

Co-authored-by: Benjamin Hackl <devel@benjamin-hackl.at>
This commit is contained in:
NotWearingPants 2022-11-10 08:17:21 +02:00 committed by GitHub
commit 95bca6f24b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
48 changed files with 1046 additions and 901 deletions

View file

@ -49,7 +49,7 @@ def tempconfig(temp: ManimConfig | dict) -> _GeneratorContextManager:
Parameters
----------
temp : Union[:class:`ManimConfig`, :class:`dict`]
temp
Object whose keys will be used to temporarily update the global
``config``.

View file

@ -56,10 +56,10 @@ def make_logger(
Parameters
----------
parser : :class:`configparser.ConfigParser`
parser
A parser containing any .cfg files in use.
verbosity : :class:`str`
verbosity
The verbosity level of the logger.
Returns
@ -106,7 +106,7 @@ def parse_theme(parser: configparser.ConfigParser) -> Theme:
Parameters
----------
parser : :class:`configparser.ConfigParser`
parser
A parser containing any .cfg files in use.
Returns
@ -148,9 +148,12 @@ def set_file_logger(scene_name: str, module_name: str, log_dir: Path) -> None:
Parameters
----------
config : :class:`ManimConfig`
The global config, used to determine the log file path.
scene_name
The name of the scene, used in the name of the log file.
module_name
The name of the module, used in the name of the log file.
log_dir
Path to the folder where log files are stored.
"""
# Note: The log file name will be
# <name_of_animation_file>_<name_of_scene>.log, gotten from config. So it

View file

@ -342,7 +342,7 @@ class ManimConfig(MutableMapping):
Parameters
----------
obj : Union[:class:`ManimConfig`, :class:`dict`]
obj
The object to copy values from.
Returns
@ -490,7 +490,7 @@ class ManimConfig(MutableMapping):
Parameters
----------
parser : :class:`ConfigParser`
parser
An object reflecting the contents of one or many ``.cfg`` files. In
particular, it may reflect the contents of multiple files that have
been parsed in a cascading fashion.
@ -664,7 +664,7 @@ class ManimConfig(MutableMapping):
Parameters
----------
args : :class:`argparse.Namespace`
args
An object returned by :func:`.main_utils.parse_args()`.
Returns
@ -1316,11 +1316,11 @@ class ManimConfig(MutableMapping):
Parameters
----------
key : :class:`str`
key
The config option to be resolved. Must be an option ending in
``'_dir'``, for example ``'media_dir'`` or ``'video_dir'``.
kwargs : :class:`str`
kwargs
Any strings to be used when resolving the directory.
Returns

View file

@ -415,9 +415,8 @@ class Animation:
Parameters
----------
run_time
The new time the animation should take in seconds.
rate_func
The new function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`).
Returns
-------

View file

@ -138,7 +138,7 @@ class Create(ShowPartial):
Parameters
----------
mobject : :class:`~.VMobject`
mobject
The VMobject to animate.
Raises
@ -374,7 +374,7 @@ class Unwrite(Write):
Parameters
----------
reverse : :class:`bool`
reverse
Set True to have the animation start erasing from the last submobject first.
Examples
@ -542,7 +542,7 @@ class AddTextLetterByLetter(ShowIncreasingSubsets):
Parameters
----------
time_per_char : :class:`float`
time_per_char
Frequency of appearance of the letters.
.. tip::
@ -585,7 +585,7 @@ class RemoveTextLetterByLetter(AddTextLetterByLetter):
Parameters
----------
time_per_char : :class:`float`
time_per_char
Frequency of appearance of the letters.
.. tip::

View file

@ -77,7 +77,7 @@ class FocusOn(Transform):
The color of the spotlight.
run_time
The duration of the animation.
kwargs : Any
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples
@ -132,7 +132,7 @@ class Indicate(Transform):
The color the mobject temporally takes.
rate_func
The function definig the animation progress at every point in time.
kwargs : Any
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples
@ -186,7 +186,7 @@ class Flash(AnimationGroup):
The time width used for the flash lines. See :class:`.~ShowPassingFlash` for more details.
run_time
The duration of the animation.
kwargs : Any
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples
@ -486,7 +486,7 @@ class Wiggle(Animation):
Parameters
----------
mobject : Mobject
mobject
The mobject to wiggle.
scale_value
The factor by which the mobject will be temporarily scaled.
@ -581,7 +581,7 @@ class Circumscribe(Succession):
The color of the surrounding shape.
run_time
The duration of the entire animation.
kwargs : Any
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples

View file

@ -11,7 +11,7 @@ import operator as op
import pathlib
import time
from functools import reduce
from typing import Any
from typing import Any, Callable, Iterable
import cairo
import numpy as np
@ -36,42 +36,38 @@ class Camera:
This is the object which takes care of what exactly is displayed
on screen at any given moment.
Some important configuration values and local variables to note are:
background_image : :class:`str`, optional
The path to an image that should be the background image.
If not set, the background is filled with `self.background_color`
pixel_height : :class:`int`, optional
The height of the scene in pixels.
"""
def __init__(
self,
background_image=None,
frame_center=ORIGIN,
image_mode="RGBA",
n_channels=4,
pixel_array_dtype="uint8",
z_buff_func=lambda m: np.round(m.get_center()[2], 2),
cairo_line_width_multiple=0.01,
use_z_index=True,
background=None,
pixel_height=None,
pixel_width=None,
frame_height=None,
frame_width=None,
frame_rate=None,
background_image: str | None = None,
frame_center: np.ndarray = ORIGIN,
image_mode: str = "RGBA",
n_channels: int = 4,
pixel_array_dtype: str = "uint8",
cairo_line_width_multiple: float = 0.01,
use_z_index: bool = True,
background: np.ndarray | None = None,
pixel_height: int | None = None,
pixel_width: int | None = None,
frame_height: float | None = None,
frame_width: float | None = None,
frame_rate: float | None = None,
**kwargs,
):
"""Initialises the Camera.
Parameters
----------
background : optional
background_image
The path to an image that should be the background image.
If not set, the background is filled with `self.background_color`
background
What self.background should be, by default None as will be set later.
pixel_height
The height of the scene in pixels.
pixel_width
The width of the scene in pixels.
**kwargs
Any local variables to be set.
"""
@ -80,7 +76,6 @@ class Camera:
self.image_mode = image_mode
self.n_channels = n_channels
self.pixel_array_dtype = pixel_array_dtype
self.z_buff_func = z_buff_func
self.cairo_line_width_multiple = cairo_line_width_multiple
self.use_z_index = use_z_index
self.background = background
@ -149,7 +144,7 @@ class Camera:
self._background_opacity = alpha
self.init_background()
def type_or_raise(self, mobject):
def type_or_raise(self, mobject: Mobject):
"""Return the type of mobject, if it is a type that can be rendered.
If `mobject` is an instance of a class that inherits from a class that
@ -159,7 +154,7 @@ class Camera:
Parameters
----------
mobject : :class:`~.Mobject`
mobject
The object to take the type of.
Notes
@ -190,15 +185,15 @@ class Camera:
return _type
raise TypeError(f"Displaying an object of class {_type} is not supported")
def reset_pixel_shape(self, new_height, new_width):
def reset_pixel_shape(self, new_height: float, new_width: float):
"""This method resets the height and width
of a single pixel to the passed new_height and new_width.
Parameters
----------
new_height : int, float
new_height
The new height of the entire scene in pixels
new_width : int, float
new_width
The new width of the entire scene in pixels
"""
self.pixel_width = new_width
@ -207,7 +202,7 @@ class Camera:
self.resize_frame_shape()
self.reset()
def resize_frame_shape(self, fixed_dimension=0):
def resize_frame_shape(self, fixed_dimension: int = 0):
"""
Changes frame_shape to match the aspect ratio
of the pixels, where fixed_dimension determines
@ -216,7 +211,7 @@ class Camera:
Parameters
----------
fixed_dimension : int
fixed_dimension
If 0, height is scaled with respect to width
else, width is scaled with respect to height.
"""
@ -258,14 +253,14 @@ class Camera:
)
self.background[:, :] = background_rgba
def get_image(self, pixel_array=None):
def get_image(self, pixel_array: np.ndarray | list | tuple | None = None):
"""Returns an image from the passed
pixel array, or from the current frame
if the passed pixel array is none.
Parameters
----------
pixel_array : np.array, list, tuple, optional
pixel_array
The pixel array from which to get an image, by default None
Returns
@ -277,15 +272,17 @@ class Camera:
pixel_array = self.pixel_array
return Image.fromarray(pixel_array, mode=self.image_mode)
def convert_pixel_array(self, pixel_array, convert_from_floats=False):
def convert_pixel_array(
self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False
):
"""Converts a pixel array from values that have floats in then
to proper RGB values.
Parameters
----------
pixel_array : np.array, list, tuple
pixel_array
Pixel array to convert.
convert_from_floats : bool, optional
convert_from_floats
Whether or not to convert float values to ints, by default False
Returns
@ -302,14 +299,16 @@ class Camera:
)
return retval
def set_pixel_array(self, pixel_array, convert_from_floats=False):
def set_pixel_array(
self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False
):
"""Sets the pixel array of the camera to the passed pixel array.
Parameters
----------
pixel_array : np.array, list, tuple
pixel_array
The pixel array to convert and then set as the camera's pixel array.
convert_from_floats : bool, optional
convert_from_floats
Whether or not to convert float values to proper RGB values, by default False
"""
converted_array = self.convert_pixel_array(pixel_array, convert_from_floats)
@ -322,21 +321,25 @@ class Camera:
# Set in place
self.pixel_array[:, :, :] = converted_array[:, :, :]
def set_background(self, pixel_array, convert_from_floats=False):
def set_background(
self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False
):
"""Sets the background to the passed pixel_array after converting
to valid RGB values.
Parameters
----------
pixel_array : np.array, list, tuple
pixel_array
The pixel array to set the background to.
convert_from_floats : bool, optional
convert_from_floats
Whether or not to convert floats values to proper RGB valid ones, by default False
"""
self.background = self.convert_pixel_array(pixel_array, convert_from_floats)
# TODO, this should live in utils, not as a method of Camera
def make_background_from_func(self, coords_to_colors_func):
def make_background_from_func(
self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray]
):
"""
Makes a pixel array for the background by using coords_to_colors_func to determine each pixel's color. Each input
pixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not
@ -344,7 +347,7 @@ class Camera:
Parameters
----------
coords_to_colors_func : function
coords_to_colors_func
The function whose input is an (x,y) pair of coordinates and
whose return values must be the colors for that point
@ -361,7 +364,9 @@ class Camera:
return self.convert_pixel_array(new_background, convert_from_floats=True)
def set_background_from_func(self, coords_to_colors_func):
def set_background_from_func(
self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray]
):
"""
Sets the background to a pixel array using coords_to_colors_func to determine each pixel's color. Each input
pixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not
@ -369,7 +374,7 @@ class Camera:
Parameters
----------
coords_to_colors_func : function
coords_to_colors_func
The function whose input is an (x,y) pair of coordinates and
whose return values must be the colors for that point
"""
@ -383,7 +388,7 @@ class Camera:
-------
Camera
The camera object after setting the pixel array.
""" ""
"""
self.set_pixel_array(self.background)
return self
@ -394,20 +399,20 @@ class Camera:
def get_mobjects_to_display(
self,
mobjects,
include_submobjects=True,
excluded_mobjects=None,
mobjects: Iterable[Mobject],
include_submobjects: bool = True,
excluded_mobjects: list | None = None,
):
"""Used to get the list of mobjects to display
with the camera.
Parameters
----------
mobjects : Mobject
mobjects
The Mobjects
include_submobjects : bool, optional
include_submobjects
Whether or not to include the submobjects of mobjects, by default True
excluded_mobjects : list, optional
excluded_mobjects
Any mobjects to exclude, by default None
Returns
@ -427,15 +432,15 @@ class Camera:
use_z_index=self.use_z_index,
)
mobjects = list_difference_update(mobjects, all_excluded)
return mobjects
return list(mobjects)
def is_in_frame(self, mobject):
def is_in_frame(self, mobject: Mobject):
"""Checks whether the passed mobject is in
frame or not.
Parameters
----------
mobject : Mobject
mobject
The mobject for which the checking needs to be done.
Returns
@ -472,7 +477,7 @@ class Camera:
"""
return self.capture_mobjects([mobject], **kwargs)
def capture_mobjects(self, mobjects, **kwargs):
def capture_mobjects(self, mobjects: Iterable[Mobject], **kwargs):
"""Capture mobjects by printing them on :attr:`pixel_array`.
This is the essential function that converts the contents of a Scene
@ -480,10 +485,10 @@ class Camera:
Parameters
----------
mobjects : :class:`~.Mobject`
mobjects
Mobjects to capture.
kwargs : Any
kwargs
Keyword arguments to be passed to :meth:`get_mobjects_to_display`.
Notes
@ -507,13 +512,13 @@ class Camera:
# NOTE: None of the methods below have been mentioned outside of their definitions. Their DocStrings are not as
# detailed as possible.
def get_cached_cairo_context(self, pixel_array):
def get_cached_cairo_context(self, pixel_array: np.ndarray):
"""Returns the cached cairo context of the passed
pixel array if it exists, and None if it doesn't.
Parameters
----------
pixel_array : np.array
pixel_array
The pixel array to check.
Returns
@ -523,19 +528,19 @@ class Camera:
"""
return self.pixel_array_to_cairo_context.get(id(pixel_array), None)
def cache_cairo_context(self, pixel_array, ctx):
def cache_cairo_context(self, pixel_array: np.ndarray, ctx: cairo.Context):
"""Caches the passed Pixel array into a Cairo Context
Parameters
----------
pixel_array : np.array
pixel_array
The pixel array to cache
ctx : cairo.Context
ctx
The context to cache it into.
"""
self.pixel_array_to_cairo_context[id(pixel_array)] = ctx
def get_cairo_context(self, pixel_array):
def get_cairo_context(self, pixel_array: np.ndarray):
"""Returns the cairo context for a pixel array after
caching it to self.pixel_array_to_cairo_context
If that array has already been cached, it returns the
@ -543,7 +548,7 @@ class Camera:
Parameters
----------
pixel_array : np.array
pixel_array
The Pixel array to get the cairo context of.
Returns
@ -580,14 +585,16 @@ class Camera:
self.cache_cairo_context(pixel_array, ctx)
return ctx
def display_multiple_vectorized_mobjects(self, vmobjects, pixel_array):
def display_multiple_vectorized_mobjects(
self, vmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple VMobjects in the pixel_array
Parameters
----------
vmobjects : list
vmobjects
list of VMobjects to display
pixel_array : np.array
pixel_array
The pixel array
"""
if len(vmobjects) == 0:
@ -602,29 +609,31 @@ class Camera:
pixel_array,
)
def display_multiple_non_background_colored_vmobjects(self, vmobjects, pixel_array):
def display_multiple_non_background_colored_vmobjects(
self, vmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple VMobjects in the cairo context, as long as they don't have
background colors.
Parameters
----------
vmobjects : list
vmobjects
list of the VMobjects
pixel_array : np.ndarray
pixel_array
The Pixel array to add the VMobjects to.
"""
ctx = self.get_cairo_context(pixel_array)
for vmobject in vmobjects:
self.display_vectorized(vmobject, ctx)
def display_vectorized(self, vmobject, ctx):
def display_vectorized(self, vmobject: VMobject, ctx: cairo.Context):
"""Displays a VMobject in the cairo context
Parameters
----------
vmobject : VMobject
vmobject
The Vectorized Mobject to display
ctx : cairo.Context
ctx
The cairo context to use.
Returns
@ -638,14 +647,14 @@ class Camera:
self.apply_stroke(ctx, vmobject)
return self
def set_cairo_context_path(self, ctx, vmobject):
def set_cairo_context_path(self, ctx: cairo.Context, vmobject: VMobject):
"""Sets a path for the cairo context with the vmobject passed
Parameters
----------
ctx : cairo.Context
ctx
The cairo context
vmobject : VMobject
vmobject
The VMobject
Returns
@ -672,16 +681,18 @@ class Camera:
ctx.close_path()
return self
def set_cairo_context_color(self, ctx, rgbas, vmobject):
def set_cairo_context_color(
self, ctx: cairo.Context, rgbas: np.ndarray, vmobject: VMobject
):
"""Sets the color of the cairo context
Parameters
----------
ctx : cairo.Context
ctx
The cairo context
rgbas : np.ndarray
rgbas
The RGBA array with which to color the context.
vmobject : VMobject
vmobject
The VMobject with which to set the color.
Returns
@ -704,14 +715,14 @@ class Camera:
ctx.set_source(pat)
return self
def apply_fill(self, ctx, vmobject):
def apply_fill(self, ctx: cairo.Context, vmobject: VMobject):
"""Fills the cairo context
Parameters
----------
ctx : cairo.Context
ctx
The cairo context
vmobject : VMobject
vmobject
The VMobject
Returns
@ -723,16 +734,18 @@ class Camera:
ctx.fill_preserve()
return self
def apply_stroke(self, ctx, vmobject, background=False):
def apply_stroke(
self, ctx: cairo.Context, vmobject: VMobject, background: bool = False
):
"""Applies a stroke to the VMobject in the cairo context.
Parameters
----------
ctx : cairo.Context
ctx
The cairo context
vmobject : VMobject
vmobject
The VMobject
background : bool, optional
background
Whether or not to consider the background when applying this
stroke width, by default False
@ -758,15 +771,15 @@ class Camera:
ctx.stroke_preserve()
return self
def get_stroke_rgbas(self, vmobject, background=False):
def get_stroke_rgbas(self, vmobject: VMobject, background: bool = False):
"""Gets the RGBA array for the stroke of the passed
VMobject.
Parameters
----------
vmobject : VMobject
vmobject
The VMobject
background : bool, optional
background
Whether or not to consider the background when getting the stroke
RGBAs, by default False
@ -777,12 +790,12 @@ class Camera:
"""
return vmobject.get_stroke_rgbas(background)
def get_fill_rgbas(self, vmobject):
def get_fill_rgbas(self, vmobject: VMobject):
"""Returns the RGBA array of the fill of the passed VMobject
Parameters
----------
vmobject : VMobject
vmobject
The VMobject
Returns
@ -808,14 +821,16 @@ class Camera:
setattr(self, bcvd, BackgroundColoredVMobjectDisplayer(self))
return getattr(self, bcvd)
def display_multiple_background_colored_vmobjects(self, cvmobjects, pixel_array):
def display_multiple_background_colored_vmobjects(
self, cvmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple vmobjects that have the same color as the background.
Parameters
----------
cvmobjects : list
cvmobjects
List of Colored VMobjects
pixel_array : np.array
pixel_array
The pixel array.
Returns
@ -833,14 +848,16 @@ class Camera:
# NOTE: Out of the following methods, only `transform_points_pre_display` and `points_to_pixel_coords` have been mentioned outside of their definitions.
# As a result, the other methods do not have as detailed docstrings as would be preferred.
def display_multiple_point_cloud_mobjects(self, pmobjects, pixel_array):
def display_multiple_point_cloud_mobjects(
self, pmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple PMobjects by modifying the passed pixel array.
Parameters
----------
pmobjects : list
pmobjects
List of PMobjects
pixel_array : np.array
pixel_array
The pixel array to modify.
"""
for pmobject in pmobjects:
@ -852,20 +869,27 @@ class Camera:
pixel_array,
)
def display_point_cloud(self, pmobject, points, rgbas, thickness, pixel_array):
def display_point_cloud(
self,
pmobject: PMobject,
points: list,
rgbas: np.ndarray,
thickness: float,
pixel_array: np.ndarray,
):
"""Displays a PMobject by modifying the Pixel array suitably..
TODO: Write a description for the rgbas argument.
Parameters
----------
pmobject : PMobject
pmobject
Point Cloud Mobject
points : list
points
The points to display in the point cloud mobject
rgbas : np.array
rgbas
thickness : int, float
thickness
The thickness of each point of the PMobject
pixel_array : np.array
pixel_array
The pixel array to modify.
"""
@ -896,27 +920,31 @@ class Camera:
new_pa[indices] = rgbas
pixel_array[:, :] = new_pa.reshape((ph, pw, rgba_len))
def display_multiple_image_mobjects(self, image_mobjects, pixel_array):
def display_multiple_image_mobjects(
self, image_mobjects: list, pixel_array: np.ndarray
):
"""Displays multiple image mobjects by modifying the passed pixel_array.
Parameters
----------
image_mobjects : list
image_mobjects
list of ImageMobjects
pixel_array : np.array
pixel_array
The pixel array to modify.
"""
for image_mobject in image_mobjects:
self.display_image_mobject(image_mobject, pixel_array)
def display_image_mobject(self, image_mobject: AbstractImageMobject, pixel_array):
def display_image_mobject(
self, image_mobject: AbstractImageMobject, pixel_array: np.ndarray
):
"""Displays an ImageMobject by changing the pixel_array suitably.
Parameters
----------
image_mobject : ImageMobject
image_mobject
The imageMobject to display
pixel_array : np.ndarray
pixel_array
The Pixel array to put the imagemobject in.
"""
corner_coords = self.points_to_pixel_coords(image_mobject, image_mobject.points)
@ -966,26 +994,26 @@ class Camera:
# Paint on top of existing pixel array
self.overlay_PIL_image(pixel_array, full_image)
def overlay_rgba_array(self, pixel_array, new_array):
def overlay_rgba_array(self, pixel_array: np.ndarray, new_array: np.ndarray):
"""Overlays an RGBA array on top of the given Pixel array.
Parameters
----------
pixel_array : np.array
pixel_array
The original pixel array to modify.
new_array : np.array
new_array
The new pixel array to overlay.
"""
self.overlay_PIL_image(pixel_array, self.get_image(new_array))
def overlay_PIL_image(self, pixel_array, image):
def overlay_PIL_image(self, pixel_array: np.ndarray, image: Image):
"""Overlays a PIL image on the passed pixel array.
Parameters
----------
pixel_array : np.ndarray
pixel_array
The Pixel array
image : PIL.Image
image
The Image to overlay.
"""
pixel_array[:, :] = np.array(
@ -993,13 +1021,13 @@ class Camera:
dtype="uint8",
)
def adjust_out_of_range_points(self, points):
def adjust_out_of_range_points(self, points: np.ndarray):
"""If any of the points in the passed array are out of
the viable range, they are adjusted suitably.
Parameters
----------
points : np.array
points
The points to adjust
Returns
@ -1061,13 +1089,13 @@ class Camera:
result[:, 1] = shifted_points[:, 1] * height_mult + height_add
return result.astype("int")
def on_screen_pixels(self, pixel_coords):
def on_screen_pixels(self, pixel_coords: np.ndarray):
"""Returns array of pixels that are on the screen from a given
array of pixel_coordinates
Parameters
----------
pixel_coords : np.array
pixel_coords
The pixel coords to check.
Returns
@ -1085,12 +1113,12 @@ class Camera:
],
)
def adjusted_thickness(self, thickness):
def adjusted_thickness(self, thickness: float):
"""
Parameters
----------
thickness : int, float
thickness
Returns
-------
@ -1103,12 +1131,12 @@ class Camera:
factor = big_sum / this_sum
return 1 + (thickness - 1) * factor
def get_thickening_nudges(self, thickness):
def get_thickening_nudges(self, thickness: float):
"""
Parameters
----------
thickness : int, float
thickness
Returns
-------
@ -1119,15 +1147,15 @@ class Camera:
_range = list(range(-thickness // 2 + 1, thickness // 2 + 1))
return np.array(list(it.product(_range, _range)))
def thickened_coordinates(self, pixel_coords, thickness):
def thickened_coordinates(self, pixel_coords: np.ndarray, thickness: float):
"""Returns thickened coordinates for a passed array of pixel coords and
a thickness to thicken by.
Parameters
----------
pixel_coords : np.array
pixel_coords
Pixel coordinates
thickness : int, float
thickness
Thickness
Returns
@ -1178,11 +1206,11 @@ class Camera:
# NOTE: The methods of the following class have not been mentioned outside of their definitions.
# Their DocStrings are not as detailed as preferred.
class BackgroundColoredVMobjectDisplayer:
def __init__(self, camera):
def __init__(self, camera: Camera):
"""
Parameters
----------
camera : Camera
camera
Camera object to use.
"""
self.camera = camera
@ -1195,22 +1223,22 @@ class BackgroundColoredVMobjectDisplayer:
def resize_background_array(
self,
background_array,
new_width,
new_height,
mode="RGBA",
background_array: np.ndarray,
new_width: float,
new_height: float,
mode: str = "RGBA",
):
"""Resizes the pixel array representing the background.
Parameters
----------
background_array : np.array
background_array
The pixel
new_width : int, float
new_width
The new width of the background
new_height : int, float
new_height
The new height of the background
mode : str, optional
mode
The PIL image mode, by default "RGBA"
Returns
@ -1223,14 +1251,16 @@ class BackgroundColoredVMobjectDisplayer:
resized_image = image.resize((new_width, new_height))
return np.array(resized_image)
def resize_background_array_to_match(self, background_array, pixel_array):
def resize_background_array_to_match(
self, background_array: np.ndarray, pixel_array: np.ndarray
):
"""Resizes the background array to match the passed pixel array.
Parameters
----------
background_array : np.array
background_array
The prospective pixel array.
pixel_array : np.array
pixel_array
The pixel array whose width and height should be matched.
Returns
@ -1271,12 +1301,12 @@ class BackgroundColoredVMobjectDisplayer:
self.file_name_to_pixel_array_map[image_key] = back_array
return back_array
def display(self, *cvmobjects):
def display(self, *cvmobjects: VMobject):
"""Displays the colored VMobjects.
Parameters
----------
*cvmobjects : VMobject
*cvmobjects
The VMobjects
Returns

View file

@ -10,6 +10,8 @@ from __future__ import annotations
__all__ = ["MovingCamera"]
import numpy as np
from .. import config
from ..camera.camera import Camera
from ..constants import DOWN, LEFT, RIGHT, UP
@ -87,34 +89,34 @@ class MovingCamera(Camera):
return self.frame.get_center()
@frame_height.setter
def frame_height(self, frame_height):
def frame_height(self, frame_height: float):
"""Sets the height of the frame in MUnits.
Parameters
----------
frame_height : int, float
frame_height
The new frame_height.
"""
self.frame.stretch_to_fit_height(frame_height)
@frame_width.setter
def frame_width(self, frame_width):
def frame_width(self, frame_width: float):
"""Sets the width of the frame in MUnits.
Parameters
----------
frame_width : int, float
frame_width
The new frame_width.
"""
self.frame.stretch_to_fit_width(frame_width)
@frame_center.setter
def frame_center(self, frame_center):
def frame_center(self, frame_center: np.ndarray | list | tuple | Mobject):
"""Sets the centerpoint of the frame.
Parameters
----------
frame_center : np.array, list, tuple, Mobject
frame_center
The point to which the frame must be moved.
If is of type mobject, the frame will be moved to
the center of that mobject.

View file

@ -5,6 +5,8 @@ from __future__ import annotations
__all__ = ["MultiCamera"]
from manim.mobject.types.image_mobject import ImageMobject
from ..camera.moving_camera import MovingCamera
from ..utils.iterables import list_difference_update
@ -14,7 +16,7 @@ class MultiCamera(MovingCamera):
def __init__(
self,
image_mobjects_from_cameras=None,
image_mobjects_from_cameras: ImageMobject | None = None,
allow_cameras_to_capture_their_own_display=False,
**kwargs,
):
@ -22,7 +24,7 @@ class MultiCamera(MovingCamera):
Parameters
----------
image_mobjects_from_cameras : ImageMobject
image_mobjects_from_cameras
kwargs
Any valid keyword arguments of MovingCamera.
@ -36,13 +38,13 @@ class MultiCamera(MovingCamera):
)
super().__init__(**kwargs)
def add_image_mobject_from_camera(self, image_mobject_from_camera):
def add_image_mobject_from_camera(self, image_mobject_from_camera: ImageMobject):
"""Adds an ImageMobject that's been obtained from the camera
into the list ``self.image_mobject_from_cameras``
Parameters
----------
image_mobject_from_camera : ImageMobject
image_mobject_from_camera
The ImageMobject to add to self.image_mobject_from_cameras
"""
# A silly method to have right now, but maybe there are things

View file

@ -5,8 +5,11 @@ from __future__ import annotations
__all__ = ["ThreeDCamera"]
from typing import Callable
import numpy as np
from manim.mobject.mobject import Mobject
from manim.mobject.three_d.three_d_utils import (
get_3d_vmob_end_corner,
get_3d_vmob_end_corner_unit_normal,
@ -43,8 +46,6 @@ class ThreeDCamera(Camera):
Parameters
----------
*args
Any argument of Camera
*kwargs
Any keyword argument of Camera.
"""
@ -197,52 +198,52 @@ class ThreeDCamera(Camera):
"""
return self.zoom_tracker.get_value()
def set_phi(self, value):
def set_phi(self, value: float):
"""Sets the polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.
Parameters
----------
value : int, float
value
The new value of the polar angle in radians.
"""
self.phi_tracker.set_value(value)
def set_theta(self, value):
def set_theta(self, value: float):
"""Sets the azimuthal angle i.e the angle that spins the camera around Z_AXIS in radians.
Parameters
----------
value : int, float
value
The new value of the azimuthal angle in radians.
"""
self.theta_tracker.set_value(value)
def set_focal_distance(self, value):
def set_focal_distance(self, value: float):
"""Sets the focal_distance of the Camera.
Parameters
----------
value : int, float
value
The focal_distance of the Camera.
"""
self.focal_distance_tracker.set_value(value)
def set_gamma(self, value):
def set_gamma(self, value: float):
"""Sets the angle of rotation of the camera about the vector from the ORIGIN to the Camera.
Parameters
----------
value : int, float
value
The new angle of rotation of the camera.
"""
self.gamma_tracker.set_value(value)
def set_zoom(self, value):
def set_zoom(self, value: float):
"""Sets the zoom amount of the camera.
Parameters
----------
value : int, float
value
The zoom amount of the camera.
"""
self.zoom_tracker.set_value(value)
@ -284,13 +285,13 @@ class ThreeDCamera(Camera):
result = np.dot(matrix, result)
return result
def project_points(self, points):
def project_points(self, points: np.ndarray | list):
"""Applies the current rotation_matrix as a projection
matrix to the passed array of points.
Parameters
----------
points : np.array, list
points
The list of points to project.
Returns
@ -321,13 +322,13 @@ class ThreeDCamera(Camera):
points[:, i] *= factor * zoom
return points
def project_point(self, point):
def project_point(self, point: list | np.ndarray):
"""Applies the current rotation_matrix as a projection
matrix to the passed point.
Parameters
----------
point : list, np.array
point
The point to project.
Returns
@ -357,7 +358,10 @@ class ThreeDCamera(Camera):
return self.project_points(points)
def add_fixed_orientation_mobjects(
self, *mobjects, use_static_center_func=False, center_func=None
self,
*mobjects: Mobject,
use_static_center_func: bool = False,
center_func: Callable[[], np.ndarray] | None = None,
):
"""This method allows the mobject to have a fixed orientation,
even when the camera moves around.
@ -367,12 +371,12 @@ class ThreeDCamera(Camera):
Parameters
----------
*mobjects : Mobject
*mobjects
The mobject whose orientation must be fixed.
use_static_center_func : bool, optional
use_static_center_func
Whether or not to use the function that takes the mobject's
center as centerpoint, by default False
center_func : func, optional
center_func
The function which returns the centerpoint
with respect to which the mobject will be oriented, by default None
"""
@ -392,7 +396,7 @@ class ThreeDCamera(Camera):
for submob in mobject.get_family():
self.fixed_orientation_mobjects[submob] = func
def add_fixed_in_frame_mobjects(self, *mobjects):
def add_fixed_in_frame_mobjects(self, *mobjects: Mobject):
"""This method allows the mobject to have a fixed position,
even when the camera moves around.
E.G If it was passed through this method, at the top of the frame, it
@ -402,34 +406,34 @@ class ThreeDCamera(Camera):
Parameters
----------
**mobjects : Mobject
**mobjects
The mobject to fix in frame.
"""
for mobject in extract_mobject_family_members(mobjects):
self.fixed_in_frame_mobjects.add(mobject)
def remove_fixed_orientation_mobjects(self, *mobjects):
def remove_fixed_orientation_mobjects(self, *mobjects: Mobject):
"""If a mobject was fixed in its orientation by passing it through
:meth:`.add_fixed_orientation_mobjects`, then this undoes that fixing.
The Mobject will no longer have a fixed orientation.
Parameters
----------
mobjects : :class:`Mobject`
mobjects
The mobjects whose orientation need not be fixed any longer.
"""
for mobject in extract_mobject_family_members(mobjects):
if mobject in self.fixed_orientation_mobjects:
del self.fixed_orientation_mobjects[mobject]
def remove_fixed_in_frame_mobjects(self, *mobjects):
def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject):
"""If a mobject was fixed in frame by passing it through
:meth:`.add_fixed_in_frame_mobjects`, then this undoes that fixing.
The Mobject will no longer be fixed in frame.
Parameters
----------
mobjects : :class:`Mobject`
mobjects
The mobjects which need not be fixed in frame any longer.
"""
for mobject in extract_mobject_family_members(mobjects):

View file

@ -33,7 +33,7 @@ def value_from_string(value: str) -> str | int | bool:
"""Extracts the literal of proper datatype from a string.
Parameters
----------
value : :class:`str`
value
The value to check get the literal from.
Returns
@ -54,12 +54,12 @@ def _is_expected_datatype(value: str, expected: str, style: bool = False) -> boo
Parameters
----------
value : :class:`str`
value
The string of the value to check (obtained from reading the user input).
expected : :class:`str`
expected
The string of the literal datatype must be matched by `value`. Obtained from
reading the cfg file.
style : :class:`bool`, optional
style
Whether or not to confirm if `value` is a style, by default False
Returns
@ -77,7 +77,7 @@ def is_valid_style(style: str) -> bool:
"""Checks whether the entered color is a valid color according to rich
Parameters
----------
style : :class:`str`
style
The style to check whether it is valid.
Returns
-------
@ -95,7 +95,7 @@ def replace_keys(default: dict) -> dict:
"""Replaces _ to . and vice versa in a dictionary for rich
Parameters
----------
default : :class:`dict`
default
The dictionary to check and replace
Returns
-------

View file

@ -54,14 +54,14 @@ def select_resolution():
return [res for res in resolution_options if f"{res[0]}p" == choice][0]
def update_cfg(cfg_dict, project_cfg_path):
def update_cfg(cfg_dict: dict, project_cfg_path: Path):
"""Updates the manim.cfg file after reading it from the project_cfg_path.
Parameters
----------
cfg : :class:`dict`
cfg_dict
values used to update manim.cfg found project_cfg_path.
project_cfg_path : :class:`Path`
project_cfg_path
Path of manim.cfg file.
"""
config = configparser.ConfigParser()

View file

@ -47,14 +47,14 @@ def select_resolution():
return [res for res in resolution_options if f"{res[0]}p" == choice][0]
def update_cfg(cfg_dict, project_cfg_path):
def update_cfg(cfg_dict: dict, project_cfg_path: Path):
"""Updates the manim.cfg file after reading it from the project_cfg_path.
Parameters
----------
cfg : :class:`dict`
cfg_dict
values used to update manim.cfg found project_cfg_path.
project_cfg_path : :class:`Path`
project_cfg_path
Path of manim.cfg file.
"""
config = configparser.ConfigParser()

View file

@ -14,7 +14,7 @@ __all__ = [
"RightAngle",
]
from typing import Sequence
from typing import Any, Sequence
import numpy as np
from colour import Color
@ -28,6 +28,7 @@ from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from manim.mobject.types.vectorized_mobject import DashedVMobject, VGroup, VMobject
from manim.utils.color import *
from manim.utils.color import Colors
from manim.utils.space_ops import angle_of_vector, line_intersection, normalize
@ -190,13 +191,13 @@ class DashedLine(Line):
Parameters
----------
args : Any
args
Arguments to be passed to :class:`Line`
dash_length : :class:`float`, optional
dash_length
The length of each individual dash of the line.
dashed_ratio : :class:`float`, optional
dashed_ratio
The ratio of dash space to empty space. Range of 0-1.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Line`
@ -221,9 +222,9 @@ class DashedLine(Line):
def __init__(
self,
*args,
dash_length=DEFAULT_DASH_LENGTH,
dashed_ratio=0.5,
*args: Any,
dash_length: float = DEFAULT_DASH_LENGTH,
dashed_ratio: float = 0.5,
**kwargs,
):
self.dash_length = dash_length
@ -318,15 +319,15 @@ class TangentLine(Line):
Parameters
----------
vmob : :class:`~.VMobject`
vmob
The VMobject on which the tangent line is drawn.
alpha : :class:`float`
alpha
How far along the shape that the line will be constructed. range: 0-1.
length : :class:`float`, optional
length
Length of the tangent line.
d_alpha: :class:`float`, optional
d_alpha
The ``dx`` value
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Line`
@ -346,7 +347,14 @@ class TangentLine(Line):
self.add(circle, line_1, line_2)
"""
def __init__(self, vmob, alpha, length=1, d_alpha=1e-6, **kwargs):
def __init__(
self,
vmob: VMobject,
alpha: float,
length: float = 1,
d_alpha: float = 1e-6,
**kwargs,
):
self.length = length
self.d_alpha = d_alpha
da = self.d_alpha
@ -363,11 +371,11 @@ class Elbow(VMobject, metaclass=ConvertToOpenGL):
Parameters
----------
width : :class:`float`, optional
width
The length of the elbow's sides.
angle : :class:`float`, optional
angle
The rotation of the elbow.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.VMobject`
.. seealso::
@ -388,7 +396,7 @@ class Elbow(VMobject, metaclass=ConvertToOpenGL):
self.add(elbow_group)
"""
def __init__(self, width=0.2, angle=0, **kwargs):
def __init__(self, width: float = 0.2, angle: float = 0, **kwargs):
self.angle = angle
super().__init__(**kwargs)
self.set_points_as_corners([UP, UP + RIGHT, RIGHT])
@ -401,17 +409,17 @@ class Arrow(Line):
Parameters
----------
args : Any
args
Arguments to be passed to :class:`Line`.
stroke_width : :class:`float`, optional
stroke_width
The thickness of the arrow. Influenced by :attr:`max_stroke_width_to_length_ratio`.
buff : :class:`float`, optional
buff
The distance of the arrow from its start and end points.
max_tip_length_to_length_ratio : :class:`float`, optional
max_tip_length_to_length_ratio
:attr:`tip_length` scales with the length of the arrow. Increasing this ratio raises the max value of :attr:`tip_length`.
max_stroke_width_to_length_ratio : :class:`float`, optional
max_stroke_width_to_length_ratio
:attr:`stroke_width` scales with the length of the arrow. Increasing this ratio ratios the max value of :attr:`stroke_width`.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Line`.
@ -486,11 +494,11 @@ class Arrow(Line):
def __init__(
self,
*args,
stroke_width=6,
buff=MED_SMALL_BUFF,
max_tip_length_to_length_ratio=0.25,
max_stroke_width_to_length_ratio=5,
*args: Any,
stroke_width: float = 6,
buff: float = MED_SMALL_BUFF,
max_tip_length_to_length_ratio: float = 0.25,
max_stroke_width_to_length_ratio: float = 5,
**kwargs,
):
self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio
@ -608,11 +616,11 @@ class Vector(Arrow):
Parameters
----------
direction : Union[:class:`list`, :class:`numpy.ndarray`]
direction
The direction of the arrow.
buff : :class:`float`
buff
The distance of the vector from its endpoints.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Arrow`
Examples
@ -628,7 +636,7 @@ class Vector(Arrow):
self.add(plane, vector_1, vector_2)
"""
def __init__(self, direction=RIGHT, buff=0, **kwargs):
def __init__(self, direction: list | np.ndarray = RIGHT, buff: float = 0, **kwargs):
self.buff = buff
if len(direction) == 2:
direction = np.hstack([direction, 0])
@ -704,9 +712,9 @@ class DoubleArrow(Arrow):
Parameters
----------
args : Any
args
Arguments to be passed to :class:`Arrow`
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Arrow`
@ -744,7 +752,7 @@ class DoubleArrow(Arrow):
self.add(box, d1, d2, d3)
"""
def __init__(self, *args, **kwargs):
def __init__(self, *args: Any, **kwargs):
if "tip_shape_end" in kwargs:
kwargs["tip_shape"] = kwargs.pop("tip_shape_end")
tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip)
@ -763,7 +771,7 @@ class Angle(VMobject, metaclass=ConvertToOpenGL):
The second line.
radius :
The radius of the :class:`Arc`.
quadrant : Sequence[:class:`int`]
quadrant
A sequence of two :class:`int` numbers determining which of the 4 quadrants should be used.
The first value indicates whether to anchor the arc on the first line closer to the end point (1)
or start point (-1), and the second value functions similarly for the
@ -773,16 +781,16 @@ class Angle(VMobject, metaclass=ConvertToOpenGL):
Toggles between the two possible angles defined by two points and an arc center. If set to
False (default), the arc will always go counterclockwise from the point on line1 until
the point on line2 is reached. If set to True, the angle will go clockwise from line1 to line2.
dot : :class:`bool`
dot
Allows for a :class:`Dot` in the arc. Mainly used as an convention to indicate a right angle.
The dot can be customized in the next three parameters.
dot_radius : :class:`float`
dot_radius
The radius of the :class:`Dot`. If not specified otherwise, this radius will be 1/10 of the arc radius.
dot_distance : :class:`float`
dot_distance
Relative distance from the center to the arc: 0 puts the dot in the center and 1 on the arc itself.
dot_color : :class:`~.Colors`
dot_color
The color of the :class:`Dot`.
elbow : :class:`bool`
elbow
Produces an elbow-type mobject indicating a right angle, see :class:`RightAngle` for more information
and a shorthand.
**kwargs
@ -866,13 +874,13 @@ class Angle(VMobject, metaclass=ConvertToOpenGL):
line1: Line,
line2: Line,
radius: float = None,
quadrant=(1, 1),
quadrant: Sequence[int] = (1, 1),
other_angle: bool = False,
dot=False,
dot_radius=None,
dot_distance=0.55,
dot_color=WHITE,
elbow=False,
dot: bool = False,
dot_radius: float | None = None,
dot_distance: float = 0.55,
dot_color: Colors = WHITE,
elbow: bool = False,
**kwargs,
):
super().__init__(**kwargs)

View file

@ -478,7 +478,7 @@ class Triangle(RegularPolygon):
Parameters
----------
kwargs : Any
kwargs
Additional arguments to be passed to :class:`RegularPolygon`
Examples
@ -503,21 +503,21 @@ class Rectangle(Polygon):
Parameters
----------
color : :class:`~.Colors`, optional
color
The color of the rectangle.
height : :class:`float`, optional
height
The vertical height of the rectangle.
width : :class:`float`, optional
width
The horizontal width of the rectangle.
grid_xstep : :class:`float`, optional
grid_xstep
Space between vertical grid lines.
grid_ystep : :class:`float`, optional
grid_ystep
Space between horizontal grid lines.
mark_paths_closed : :class:`bool`, optional
mark_paths_closed
No purpose.
close_new_points : :class:`bool`, optional
close_new_points
No purpose.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Polygon`
Examples
@ -541,8 +541,8 @@ class Rectangle(Polygon):
width: float = 4.0,
grid_xstep: float | None = None,
grid_ystep: float | None = None,
mark_paths_closed=True,
close_new_points=True,
mark_paths_closed: bool = True,
close_new_points: bool = True,
**kwargs,
):
super().__init__(UR, UL, DL, DR, color=color, **kwargs)
@ -586,9 +586,9 @@ class Square(Rectangle):
Parameters
----------
side_length : :class:`float`, optional
side_length
The length of the sides of the square.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Rectangle`.
Examples
@ -604,7 +604,7 @@ class Square(Rectangle):
self.add(square_1, square_2, square_3)
"""
def __init__(self, side_length=2.0, **kwargs):
def __init__(self, side_length: float = 2.0, **kwargs):
self.side_length = side_length
super().__init__(height=side_length, width=side_length, **kwargs)
@ -614,9 +614,9 @@ class RoundedRectangle(Rectangle):
Parameters
----------
corner_radius : :class:`float`, optional
corner_radius
The curvature of the corners of the rectangle.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`Rectangle`
Examples
@ -633,7 +633,7 @@ class RoundedRectangle(Rectangle):
self.add(rect_group)
"""
def __init__(self, corner_radius=0.5, **kwargs):
def __init__(self, corner_radius: float = 0.5, **kwargs):
super().__init__(**kwargs)
self.corner_radius = corner_radius
self.round_corners(self.corner_radius)
@ -644,9 +644,9 @@ class Cutout(VMobject, metaclass=ConvertToOpenGL):
Parameters
----------
main_shape : :class:`~.VMobject`
main_shape
The primary shape from which cutouts are made.
mobjects : :class:`~.VMobject`
mobjects
The smaller shapes which are to be cut out of the ``main_shape``.
kwargs
Further keyword arguments that are passed to the constructor of
@ -674,7 +674,7 @@ class Cutout(VMobject, metaclass=ConvertToOpenGL):
self.wait()
"""
def __init__(self, main_shape, *mobjects, **kwargs):
def __init__(self, main_shape: VMobject, *mobjects: VMobject, **kwargs):
super().__init__(**kwargs)
self.append_points(main_shape.points)
if main_shape.get_direction() == "CW":

View file

@ -169,11 +169,6 @@ class Cross(VGroup):
class Underline(Line):
"""Creates an underline.
Parameters
----------
Line
The underline.
Examples
--------
.. manim:: UnderLine

View file

@ -592,14 +592,12 @@ class NumberLine(Line):
self, label_tex: str | float | VMobject, **kwargs
) -> VMobject:
"""Checks if the label is a :class:`~.VMobject`, otherwise, creates a
label according to the ``label_constructor``.
label according to :attr:`label_constructor`.
Parameters
----------
label_tex
The label to be compared against the above types.
label_constructor
The VMobject class used to construct the label.
Returns
-------

View file

@ -122,7 +122,7 @@ class LogBase(_ScaleBase):
----------
base
The base of the log, by default 10.
custom_labels : bool, optional
custom_labels
For use with :class:`~.Axes`:
Whetherer or not to include ``LaTeX`` axis labels, by default True.

View file

@ -44,6 +44,7 @@ from typing import Iterable, Sequence
import numpy as np
from manim.mobject.mobject import Mobject
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.text.numbers import DecimalNumber, Integer
from manim.mobject.text.tex_mobject import MathTex, Tex
@ -227,16 +228,16 @@ class Matrix(VMobject, metaclass=ConvertToOpenGL):
)
return self
def _add_brackets(self, left="[", right="]", **kwargs):
def _add_brackets(self, left: str = "[", right: str = "]", **kwargs):
"""Adds the brackets to the Matrix mobject.
See Latex document for various bracket types.
Parameters
----------
left : :class:`str`, optional
left
the left bracket, by default "["
right : :class:`str`, optional
right
the right bracket, by default "]"
Returns
@ -310,12 +311,12 @@ class Matrix(VMobject, metaclass=ConvertToOpenGL):
)
)
def set_column_colors(self, *colors):
def set_column_colors(self, *colors: str):
"""Set individual colors for each columns of the matrix.
Parameters
----------
colors : :class:`str`
colors
The list of colors; each color specified corresponds to a column.
Returns
@ -362,12 +363,12 @@ class Matrix(VMobject, metaclass=ConvertToOpenGL):
"""
return VGroup(*(VGroup(*row) for row in self.mob_matrix))
def set_row_colors(self, *colors):
def set_row_colors(self, *colors: str):
"""Set individual colors for each row of the matrix.
Parameters
----------
colors : :class:`str`
colors
The list of colors; each color specified corresponds to a row.
Returns
@ -487,9 +488,9 @@ class DecimalMatrix(Matrix):
def __init__(
self,
matrix,
element_to_mobject=DecimalNumber,
element_to_mobject_config={"num_decimal_places": 1},
matrix: Iterable,
element_to_mobject: Mobject = DecimalNumber,
element_to_mobject_config: dict[str, Mobject] = {"num_decimal_places": 1},
**kwargs,
):
"""
@ -497,11 +498,11 @@ class DecimalMatrix(Matrix):
Parameters
----------
matrix : :class:`typing.Iterable`
matrix
A numpy 2d array or list of lists
element_to_mobject : :class:`~.Mobject`, optional
element_to_mobject
Mobject to use, by default DecimalNumber
element_to_mobject_config : Dict[:class:`str`, :class:`~.Mobject`], optional
element_to_mobject_config
Config for the desired mobject, by default {"num_decimal_places": 1}
"""
super().__init__(
@ -530,15 +531,17 @@ class IntegerMatrix(Matrix):
self.add(m0)
"""
def __init__(self, matrix, element_to_mobject=Integer, **kwargs):
def __init__(
self, matrix: Iterable, element_to_mobject: Mobject = Integer, **kwargs
):
"""
Will round if there are decimal entries in the matrix.
Parameters
----------
matrix : :class:`typing.Iterable`
matrix
A numpy 2d array or list of lists
element_to_mobject : :class:`~.Mobject`, optional
element_to_mobject
Mobject to use, by default Integer
"""
super().__init__(matrix, element_to_mobject=element_to_mobject, **kwargs)
@ -568,25 +571,25 @@ class MobjectMatrix(Matrix):
def get_det_text(
matrix,
determinant=None,
background_rect=False,
initial_scale_factor=2,
matrix: Matrix,
determinant: int | str | None = None,
background_rect: bool = False,
initial_scale_factor: float = 2,
):
r"""Helper function to create determinant.
Parameters
----------
matrix : :class:`~.Matrix`
matrix
The matrix whose determinant is to be created
determinant : :class:`int|str`
determinant
The value of the determinant of the matrix
background_rect : :class:`bool`
background_rect
The background rectangle
initial_scale_factor : :class:`float`
initial_scale_factor
The scale of the text `det` w.r.t the matrix
Returns

View file

@ -202,7 +202,7 @@ class OpenGLVMobject(OpenGLMobject):
Fill color of the :class:`OpenGLVMobject`.
opacity
Fill opacity of the :class:`OpenGLVMobject`.
family
recurse
If ``True``, the fill color of all submobjects is also set.
Returns
@ -491,7 +491,7 @@ class OpenGLVMobject(OpenGLMobject):
Parameters
----------
point : Sequence[float]
point
end of the straight line.
"""
end = self.points[-1]
@ -572,7 +572,7 @@ class OpenGLVMobject(OpenGLMobject):
Parameters
----------
points : Iterable[float]
points
Array of points that will be set as corners.
Returns
@ -674,13 +674,13 @@ class OpenGLVMobject(OpenGLMobject):
return np.linalg.norm(p1 - p0) < self.tolerance_for_point_equality
# Information about the curve
def force_direction(self, target_direction):
def force_direction(self, target_direction: str):
"""Makes sure that points are either directed clockwise or
counterclockwise.
Parameters
----------
target_direction : :class:`str`
target_direction
Either ``"CW"`` or ``"CCW"``.
"""
if target_direction not in ("CW", "CCW"):
@ -760,7 +760,7 @@ class OpenGLVMobject(OpenGLMobject):
Parameters
----------
n : int
n
index of the desired bezier curve.
Returns
@ -777,7 +777,7 @@ class OpenGLVMobject(OpenGLMobject):
Parameters
----------
n : int
n
index of the desired curve.
Returns
@ -1260,9 +1260,9 @@ class OpenGLVMobject(OpenGLMobject):
Parameters
----------
n : int
n
Number of desired curves.
points : np.ndarray
points
Starting points.
Returns
@ -1319,13 +1319,13 @@ class OpenGLVMobject(OpenGLMobject):
Parameters
----------
vmobject : OpenGLVMobject
vmobject
The vmobject that will serve as a model.
a : float
a
upper-bound.
b : float
b
lower-bound
remap : bool
remap
if the point amount should be kept the same (True)
This option should be manually set to False if keeping the number of points is not needed
"""
@ -1699,12 +1699,12 @@ class OpenGLVGroup(OpenGLVMobject):
f"submobject{'s' if len(self.submobjects) > 0 else ''}"
)
def add(self, *vmobjects):
def add(self, *vmobjects: OpenGLVMobject):
"""Checks if all passed elements are an instance of OpenGLVMobject and then add them to submobjects
Parameters
----------
vmobjects : :class:`~.OpenGLVMobject`
vmobjects
List of OpenGLVMobject to add
Returns

View file

@ -12,6 +12,7 @@ import svgelements as se
from manim._config import config
from manim.mobject.geometry.arc import Arc
from manim.mobject.geometry.line import Line
from manim.mobject.mobject import Mobject
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.text.tex_mobject import MathTex, Tex
@ -32,7 +33,7 @@ class Brace(VMobjectFromSVGPath):
Parameters
----------
mobject : :class:`~.Mobject`
mobject
The mobject adjacent to which the brace is placed.
direction :
The direction from which the brace faces the mobject.
@ -61,7 +62,7 @@ class Brace(VMobjectFromSVGPath):
def __init__(
self,
mobject,
mobject: Mobject,
direction: Sequence[float] | None = DOWN,
buff=0.2,
sharpness=2,

View file

@ -206,7 +206,7 @@ class Table(VGroup):
Dict passed to :meth:`~.Mobject.arrange_in_grid`, customizes the arrangement of the table.
line_config
Dict passed to :class:`~.Line`, customizes the lines of the table.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.VGroup`.
"""
@ -773,7 +773,7 @@ class Table(VGroup):
pos
The position of a specific entry on the table. ``(1,1)`` being the top left entry
of the table.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.Polygon`.
Returns
@ -834,7 +834,7 @@ class Table(VGroup):
of the table.
color
The color used to highlight the cell.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.BackgroundRectangle`.
Examples
@ -870,7 +870,7 @@ class Table(VGroup):
of the table.
color
The color used to highlight the cell.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.BackgroundRectangle`.
Examples
@ -901,15 +901,13 @@ class Table(VGroup):
line_animation: Callable[[VMobject | VGroup], Animation] = Create,
label_animation: Callable[[VMobject | VGroup], Animation] = Write,
element_animation: Callable[[VMobject | VGroup], Animation] = Create,
entry_animation=FadeIn,
entry_animation: Callable[[VMobject | VGroup], Animation] = FadeIn,
**kwargs,
) -> AnimationGroup:
"""Customized create-type function for tables.
Parameters
----------
run_time
The run time of the line creation and the writing of the elements.
lag_ratio
The lag ratio of the animation.
line_animation
@ -918,7 +916,9 @@ class Table(VGroup):
The animation style of the table labels, see :mod:`~.creation` for examples.
element_animation
The animation style of the table elements, see :mod:`~.creation` for examples.
kwargs : Any
entry_animation
The entry animation of the table background, see :mod:`~.creation` for examples.
kwargs
Further arguments passed to the creation animations.
Returns
@ -1015,7 +1015,7 @@ class MathTable(Table):
for :class:`~.MathTex`.
element_to_mobject
The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.MathTex`.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.Table`.
"""
super().__init__(
@ -1069,7 +1069,7 @@ class MobjectTable(Table):
A 2D array or list of lists. Content of the table must be of type :class:`~.Mobject`.
element_to_mobject
The :class:`~.Mobject` class applied to the table entries. Set as ``lambda m : m`` to return itself.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.Table`.
"""
super().__init__(table, element_to_mobject=element_to_mobject, **kwargs)
@ -1118,7 +1118,7 @@ class IntegerTable(Table):
for :class:`~.Integer`.
element_to_mobject
The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.Integer`.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.Table`.
"""
super().__init__(table, element_to_mobject=element_to_mobject, **kwargs)
@ -1166,7 +1166,7 @@ class DecimalTable(Table):
The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.DecimalNumber`.
element_to_mobject_config
Element to mobject config, here set as {"num_decimal_places": 1}.
kwargs : Any
kwargs
Additional arguments to be passed to :class:`~.Table`.
"""
super().__init__(

View file

@ -7,6 +7,7 @@ __all__ = [
]
import html
import os
import re
from pathlib import Path
@ -90,45 +91,45 @@ class Code(VGroup):
----------
file_name
Name of the code file to display.
code : :class:`str`
code
If ``file_name`` is not specified, a code string can be
passed directly.
tab_width : :class:`int`, optional
tab_width
Number of space characters corresponding to a tab character. Defaults to 3.
line_spacing : :class:`float`, optional
line_spacing
Amount of space between lines in relation to font size. Defaults to 0.3, which means 30% of font size.
font_size : class:`float`, optional
font_size
A number which scales displayed code. Defaults to 24.
font : :class:`str`, optional
font
The name of the text font to be used. Defaults to ``"Monospac821 BT"``.
stroke_width : class:`float`, optional
stroke_width
Stroke width for text. 0 is recommended, and the default.
margin: class :`float`, optional
margin
Inner margin of text from the background. Defaults to 0.3.
indentation_chars : :class:`str`, optional
indentation_chars
"Indentation chars" refers to the spaces/tabs at the beginning of a given code line. Defaults to ``" "`` (spaces).
background : :class:`str`, optional
background
Defines the background's type. Currently supports only ``"rectangle"`` (default) and ``"window"``.
background_stroke_width : class:`float`, optional
background_stroke_width
Defines the stroke width of the background. Defaults to 1.
background_stroke_color : class:`str`, optional
background_stroke_color
Defines the stroke color for the background. Defaults to ``WHITE``.
corner_radius : :class:`float`, optional
corner_radius
Defines the corner radius for the background. Defaults to 0.2.
insert_line_no : :class:`bool`, optional
insert_line_no
Defines whether line numbers should be inserted in displayed code. Defaults to ``True``.
line_no_from : :class:`int`, optional
line_no_from
Defines the first line's number in the line count. Defaults to 1.
line_no_buff : :class:`float`, optional
line_no_buff
Defines the spacing between line numbers and displayed code. Defaults to 0.4.
style : :class:`str`, optional
style
Defines the style type of displayed code. You can see possible names of styles in with :attr:`styles_list`. Defaults to ``"vim"``.
language : Optional[:class:`str`], optional
language
Specifies the programming language the given code was written in. If ``None``
(the default), the language will be automatically detected. For the list of
possible options, visit https://pygments.org/docs/lexers/ and look for
'aliases or short names'.
generate_html_file : :class:`bool`, optional
generate_html_file
Defines whether to generate highlighted html code to the folder `assets/codes/generated_html_files`. Defaults to `False`.
Attributes
@ -153,25 +154,25 @@ class Code(VGroup):
def __init__(
self,
file_name: str | os.PathLike = None,
code=None,
tab_width=3,
line_spacing=0.3,
font_size=24,
font="Monospac821 BT",
stroke_width=0,
margin=0.3,
indentation_chars=" ",
background="rectangle", # or window
background_stroke_width=1,
background_stroke_color=WHITE,
corner_radius=0.2,
insert_line_no=True,
line_no_from=1,
line_no_buff=0.4,
style="vim",
language=None,
generate_html_file=False,
file_name: str | os.PathLike | None = None,
code: str | None = None,
tab_width: int = 3,
line_spacing: float = 0.3,
font_size: float = 24,
font: str = "Monospac821 BT",
stroke_width: float = 0,
margin: float = 0.3,
indentation_chars: str = " ",
background: str = "rectangle", # or window
background_stroke_width: float = 1,
background_stroke_color: str = WHITE,
corner_radius: float = 0.2,
insert_line_no: bool = True,
line_no_from: int = 1,
line_no_buff: float = 0.4,
style: str = "vim",
language: str | None = None,
generate_html_file: bool = False,
**kwargs,
):
super().__init__(
@ -472,12 +473,12 @@ class Code(VGroup):
self.code_json[code_json_line_index].append([text, color])
# print(self.code_json)
def _correct_non_span(self, line_str):
def _correct_non_span(self, line_str: str):
"""Function put text color to those strings that don't have one according to background_color of displayed code.
Parameters
---------
line_str : :class:`str`
line_str
Takes a html element's string to put color to it according to background_color of displayed code.
Returns
@ -525,31 +526,31 @@ class Code(VGroup):
def _hilite_me(
code,
language,
style,
insert_line_no,
divstyles,
file_path,
line_no_from,
code: str,
language: str,
style: str,
insert_line_no: bool,
divstyles: str,
file_path: Path,
line_no_from: int,
):
"""Function to highlight code from string to html.
Parameters
---------
code : :class:`str`
code
Code string.
language : :class:`str`
language
The name of the programming language the given code was written in.
style : :class:`str`
style
Code style name.
insert_line_no : :class:`bool`
insert_line_no
Defines whether line numbers should be inserted in the html file.
divstyles : :class:`str`
divstyles
Some html css styles.
file_path : :class:`pathlib.Path`
file_path
Path of code file.
line_no_from : :class:`int`
line_no_from
Defines the first line's number in the line count.
"""
style = style or "colorful"
@ -578,14 +579,14 @@ def _hilite_me(
return html
def _insert_line_numbers_in_html(html, line_no_from):
def _insert_line_numbers_in_html(html: str, line_no_from: int):
"""Function that inserts line numbers in the highlighted HTML code.
Parameters
---------
html : :class:`str`
html
html string of highlighted code.
line_no_from : :class:`int`
line_no_from
Defines the first line's number in the line count.
Returns

View file

@ -11,7 +11,8 @@ import numpy as np
from manim import config
from manim.constants import *
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.text.tex_mobject import MathTex, SingleStringMathTex
from manim.mobject.text.tex_mobject import MathTex, SingleStringMathTex, Tex
from manim.mobject.text.text_mobject import Text
from manim.mobject.types.vectorized_mobject import VMobject
from manim.mobject.value_tracker import ValueTracker
@ -299,16 +300,16 @@ class Variable(VMobject, metaclass=ConvertToOpenGL):
Parameters
----------
var : Union[:class:`int`, :class:`float`]
var
The initial value you need to keep track of and display.
label : Union[:class:`str`, :class:`~.Tex`, :class:`~.MathTex`, :class:`~.Text`, :class:`~.SingleStringMathTex`]
label
The label for your variable. Raw strings are convertex to :class:`~.MathTex` objects.
var_type : Union[:class:`DecimalNumber`, :class:`Integer`], optional
var_type
The class used for displaying the number. Defaults to :class:`DecimalNumber`.
num_decimal_places : :class:`int`, optional
num_decimal_places
The number of decimal places to display in your variable. Defaults to 2.
If `var_type` is an :class:`Integer`, this parameter is ignored.
kwargs : Any
kwargs
Other arguments to be passed to `~.Mobject`.
Attributes
@ -397,7 +398,12 @@ class Variable(VMobject, metaclass=ConvertToOpenGL):
"""
def __init__(
self, var, label, var_type=DecimalNumber, num_decimal_places=2, **kwargs
self,
var: float,
label: str | Tex | MathTex | Text | SingleStringMathTex,
var_type: DecimalNumber | Integer = DecimalNumber,
num_decimal_places: int = 2,
**kwargs,
):
self.label = MathTex(label) if isinstance(label, str) else label

View file

@ -31,6 +31,7 @@ from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from manim.mobject.types.vectorized_mobject import VGroup, VMobject
from manim.utils.color import *
from manim.utils.color import Colors
from manim.utils.deprecation import deprecated_params
from manim.utils.iterables import tuplify
from manim.utils.space_ops import normalize, perpendicular_bisector, z_to_vector
@ -348,11 +349,11 @@ class Dot3D(Sphere):
Parameters
--------
point : Union[:class:`list`, :class:`numpy.ndarray`], optional
point
The location of the dot.
radius : :class:`float`, optional
radius
The radius of the dot.
color : :class:`~.Colors`, optional
color
The color of the :class:`Dot3D`
Examples
@ -374,9 +375,9 @@ class Dot3D(Sphere):
def __init__(
self,
point=ORIGIN,
radius=DEFAULT_DOT_RADIUS,
color=WHITE,
point: list | np.ndarray = ORIGIN,
radius: float = DEFAULT_DOT_RADIUS,
color: Colors = WHITE,
resolution=(8, 8),
**kwargs,
):
@ -464,31 +465,31 @@ class Cone(Surface):
Parameters
--------
base_radius : :class:`float`
base_radius
The base radius from which the cone tapers.
height : :class:`float`
height
The height measured from the plane formed by the base_radius to the apex of the cone.
direction : :class:`numpy.array`
direction
The direction of the apex.
show_base : :class:`bool`
show_base
Whether to show the base plane or not.
v_range : :class:`Sequence[float]`
v_range
The azimuthal angle to start and end at.
u_min : :class:`float`
u_min
The radius at the apex.
checkerboard_colors : :class:`bool`
checkerboard_colors
Show checkerboard grid texture on the cone.
"""
def __init__(
self,
base_radius=1,
height=1,
direction=Z_AXIS,
show_base=False,
v_range=[0, TAU],
u_min=0,
checkerboard_colors=False,
base_radius: float = 1,
height: float = 1,
direction: np.ndarray = Z_AXIS,
show_base: bool = False,
v_range: Sequence[float] = [0, TAU],
u_min: float = 0,
checkerboard_colors: bool = False,
**kwargs,
):
self.direction = direction
@ -517,13 +518,13 @@ class Cone(Surface):
self._rotate_to_direction()
def func(self, u, v):
def func(self, u: float, v: float):
"""Converts from spherical coordinates to cartesian.
Parameters
---------
u : :class:`float`
u
The radius.
v : :class:`float`
v
The azimuthal angle.
"""
r = u
@ -594,25 +595,25 @@ class Cylinder(Surface):
Parameters
---------
radius : :class:`float`
radius
The radius of the cylinder.
height : :class:`float`
height
The height of the cylinder.
direction : :class:`numpy.array`
direction
The direction of the central axis of the cylinder.
v_range : :class:`Sequence[float]`
v_range
The height along the height axis (given by direction) to start and end on.
show_ends : :class:`bool`
show_ends
Whether to show the end caps or not.
"""
def __init__(
self,
radius=1,
height=2,
direction=Z_AXIS,
v_range=[0, TAU],
show_ends=True,
radius: float = 1,
height: float = 2,
direction: np.ndarray = Z_AXIS,
v_range: Sequence[float] = [0, TAU],
show_ends: bool = True,
resolution=(24, 24),
**kwargs,
):
@ -631,13 +632,13 @@ class Cylinder(Surface):
self._current_theta = 0
self.set_direction(direction)
def func(self, u, v):
def func(self, u: float, v: float):
"""Converts from cylindrical coordinates to cartesian.
Parameters
---------
u : :class:`float`
u
The height.
v : :class:`float`
v
The azimuthal angle.
"""
height = u
@ -728,15 +729,22 @@ class Line3D(Cylinder):
Parameters
---------
start : :class:`numpy.array`
start
The start position of the line.
end : :class:`numpy.array`
end
The end position of the line.
thickness : :class:`float`
thickness
The thickness of the line.
"""
def __init__(self, start=LEFT, end=RIGHT, thickness=0.02, color=None, **kwargs):
def __init__(
self,
start: np.ndarray = LEFT,
end: np.ndarray = RIGHT,
thickness: float = 0.02,
color=None,
**kwargs,
):
self.thickness = thickness
self.set_start_and_end_attrs(start, end, **kwargs)
if color is not None:
@ -882,25 +890,25 @@ class Arrow3D(Line3D):
Parameters
---------
start : :class:`numpy.array`
start
The start position of the arrow.
end : :class:`numpy.array`
end
The end position of the arrow.
thickness : :class:`float`
thickness
The thickness of the arrow.
height : :class:`float`
height
The height of the conical tip.
base_radius: :class:`float`
base_radius
The base radius of the conical tip.
"""
def __init__(
self,
start=LEFT,
end=RIGHT,
thickness=0.02,
height=0.3,
base_radius=0.08,
start: np.ndarray = LEFT,
end: np.ndarray = RIGHT,
thickness: float = 0.02,
height: float = 0.3,
base_radius: float = 0.08,
color=WHITE,
**kwargs,
):
@ -940,16 +948,16 @@ class Torus(Surface):
Parameters
---------
major_radius : :class:`float`
major_radius
Distance from the center of the tube to the center of the torus.
minor_radius : :class:`float`
minor_radius
Radius of the tube.
"""
def __init__(
self,
major_radius=3,
minor_radius=1,
major_radius: float = 3,
minor_radius: float = 1,
u_range=(0, TAU),
v_range=(0, TAU),
resolution=None,

View file

@ -27,7 +27,7 @@ class AbstractImageMobject(Mobject):
Parameters
----------
scale_to_resolution : :class:`int`
scale_to_resolution
At this resolution the image is placed pixel by pixel onto the screen, so it
will look the sharpest and best.
This is a custom parameter of ImageMobject so that rendering a scene with
@ -37,7 +37,7 @@ class AbstractImageMobject(Mobject):
def __init__(
self,
scale_to_resolution,
scale_to_resolution: int,
pixel_array_dtype="uint8",
resampling_algorithm=Resampling.BICUBIC,
**kwargs,
@ -54,7 +54,7 @@ class AbstractImageMobject(Mobject):
# Likely to be implemented in subclasses, but no obligation
pass
def set_resampling_algorithm(self, resampling_algorithm):
def set_resampling_algorithm(self, resampling_algorithm: int):
"""
Sets the interpolation method for upscaling the image. By default the image is
interpolated using bicubic algorithm. This method lets you change it.
@ -63,15 +63,16 @@ class AbstractImageMobject(Mobject):
Parameters
----------
resampling_algorithm : :class:`int`, an integer constant described in the
Pillow library, or one from the RESAMPLING_ALGORITHMS global dictionary, under
the following keys:
* 'bicubic' or 'cubic'
* 'nearest' or 'none'
* 'box'
* 'bilinear' or 'linear'
* 'hamming'
* 'lanczos' or 'antialias'
resampling_algorithm
An integer constant described in the Pillow library,
or one from the RESAMPLING_ALGORITHMS global dictionary,
under the following keys:
* 'bicubic' or 'cubic'
* 'nearest' or 'none'
* 'box'
* 'bilinear' or 'linear'
* 'hamming'
* 'lanczos' or 'antialias'
"""
if isinstance(resampling_algorithm, int):
self.resampling_algorithm = resampling_algorithm
@ -107,7 +108,7 @@ class ImageMobject(AbstractImageMobject):
Parameters
----------
scale_to_resolution : :class:`int`
scale_to_resolution
At this resolution the image is placed pixel by pixel onto the screen, so it
will look the sharpest and best.
This is a custom parameter of ImageMobject so that rendering a scene with
@ -167,7 +168,7 @@ class ImageMobject(AbstractImageMobject):
def __init__(
self,
filename_or_array,
scale_to_resolution=QUALITIES[DEFAULT_QUALITY]["pixel_height"],
scale_to_resolution: int = QUALITIES[DEFAULT_QUALITY]["pixel_height"],
invert=False,
image_mode="RGBA",
**kwargs,
@ -205,12 +206,12 @@ class ImageMobject(AbstractImageMobject):
self.color = color
return self
def set_opacity(self, alpha):
def set_opacity(self, alpha: float):
"""Sets the image's opacity.
Parameters
----------
alpha : float
alpha
The alpha value of the object, 1 being opaque and 0 being
transparent.
"""
@ -219,34 +220,36 @@ class ImageMobject(AbstractImageMobject):
self.stroke_opacity = alpha
return self
def fade(self, darkness=0.5, family=True):
def fade(self, darkness: float = 0.5, family: bool = True):
"""Sets the image's opacity using a 1 - alpha relationship.
Parameters
----------
darkness : float
darkness
The alpha value of the object, 1 being transparent and 0 being
opaque.
family : Boolean
family
Whether the submobjects of the ImageMobject should be affected.
"""
self.set_opacity(1 - darkness)
super().fade(darkness, family)
return self
def interpolate_color(self, mobject1, mobject2, alpha):
def interpolate_color(
self, mobject1: ImageMobject, mobject2: ImageMobject, alpha: float
):
"""Interpolates the array of pixel color values from one ImageMobject
into an array of equal size in the target ImageMobject.
Parameters
----------
mobject1 : ImageMobject
mobject1
The ImageMobject to transform from.
mobject2 : ImageMobject
mobject2
The ImageMobject to transform into.
alpha : float
alpha
Used to track the lerp relationship. Not opacity related.
"""
assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, (

View file

@ -68,7 +68,7 @@ class VMobject(Mobject):
close_new_points
Indicates that it will not be displayed, but
that it should count in parent mobject's path
tolerance_point_for_equality
tolerance_for_point_equality
This is within a pixel
"""
@ -460,7 +460,7 @@ class VMobject(Mobject):
Parameters
----------
direction : :class:`numpy.ndarray`, optional
direction
Direction from where the gradient is applied.
Examples
@ -483,14 +483,14 @@ class VMobject(Mobject):
self.sheen_direction = direction
return self
def rotate_sheen_direction(self, angle: np.ndarray, axis: float = OUT, family=True):
def rotate_sheen_direction(self, angle: float, axis: np.ndarray = OUT, family=True):
"""Rotates the direction of the applied sheen.
Parameters
----------
angle : :class:`float`
angle
Angle by which the direction of sheen is rotated.
axis : :class:`numpy.ndarray`
axis
Axis of rotation.
Examples
@ -514,16 +514,16 @@ class VMobject(Mobject):
self.sheen_direction = rotate_vector(self.sheen_direction, angle, axis)
return self
def set_sheen(self, factor, direction: np.ndarray = None, family=True):
def set_sheen(self, factor: float, direction: np.ndarray = None, family=True):
"""Applies a color gradient from a direction.
Parameters
----------
factor : :class:`float`
factor
The extent of lustre/gradient to apply. If negative, the gradient
starts from black, if positive the gradient starts from white and
changes to the current color.
direction : :class:`numpy.ndarray`, optional
direction
Direction from where the gradient is applied.
Examples
@ -668,11 +668,11 @@ class VMobject(Mobject):
Parameters
----------
handle1 : np.ndarray
handle1
first handle
handle2 : np.ndarray
handle2
second handle
anchor : np.ndarray
anchor
anchor
Returns
@ -720,7 +720,7 @@ class VMobject(Mobject):
Parameters
----------
point : np.ndarray
point
end of the straight line.
Returns
@ -743,7 +743,7 @@ class VMobject(Mobject):
Parameters
----------
points: np.array
points
Points (anchor and handle, or just anchor) to add a smooth curve from
Returns
@ -809,7 +809,7 @@ class VMobject(Mobject):
Parameters
----------
points : Iterable[float]
points
Array of points that will be set as corners.
Returns
@ -947,9 +947,9 @@ class VMobject(Mobject):
2D point case. NumPy is overkill for such a small question.
Parameters
----------
p0 : np.ndarray
p0
first point
p1 : np.ndarray
p1
second point
Returns
@ -979,7 +979,7 @@ class VMobject(Mobject):
Parameters
----------
points : np.ndarray
points
Points from which control points will be extracted.
Returns
@ -1011,9 +1011,9 @@ class VMobject(Mobject):
Parameters
----------
points : np.ndarray
points
points defining the bezier curve.
filter_func : typing.Callable[int, bool]
filter_func
Filter-func defining the relation.
Returns
@ -1061,7 +1061,7 @@ class VMobject(Mobject):
Parameters
----------
n : int
n
index of the desired bezier curve.
Returns
@ -1078,7 +1078,7 @@ class VMobject(Mobject):
Parameters
----------
n : int
n
index of the desired curve.
Returns
@ -1492,9 +1492,9 @@ class VMobject(Mobject):
Parameters
----------
n : int
n
Number of desired curves.
points : np.ndarray
points
Starting points.
Returns
@ -1592,11 +1592,11 @@ class VMobject(Mobject):
Parameters
----------
vmobject : VMobject
vmobject
The vmobject that will serve as a model.
a : float
a
upper-bound.
b : float
b
lower-bound
Returns
@ -1716,13 +1716,13 @@ class VMobject(Mobject):
self.points = self.points[::-1]
return self
def force_direction(self, target_direction):
def force_direction(self, target_direction: str):
"""Makes sure that points are either directed clockwise or
counterclockwise.
Parameters
----------
target_direction : :class:`str`
target_direction
Either ``"CW"`` or ``"CCW"``.
"""
if target_direction not in ("CW", "CCW"):
@ -1809,12 +1809,12 @@ class VGroup(VMobject, metaclass=ConvertToOpenGL):
f"submobject{'s' if len(self.submobjects) > 0 else ''}"
)
def add(self, *vmobjects):
def add(self, *vmobjects: VMobject):
"""Checks if all passed elements are an instance of VMobject and then add them to submobjects
Parameters
----------
vmobjects : :class:`~.VMobject`
vmobjects
List of VMobject to add
Returns
@ -1907,14 +1907,14 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
Parameters
----------
mapping_or_iterable : Union[:class:`Mapping`, Iterable[Tuple[Hashable, :class:`~.VMobject`]]], optional
mapping_or_iterable
The parameter specifying the key-value mapping of keys and mobjects.
show_keys : :class:`bool`, optional
show_keys
Whether to also display the key associated with
the mobject. This might be useful when debugging,
especially when there are a lot of mobjects in the
:class:`VDict`. Defaults to False.
kwargs : Any
kwargs
Other arguments to be passed to `Mobject`.
Attributes
@ -1999,7 +1999,15 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
self.wait()
"""
def __init__(self, mapping_or_iterable={}, show_keys=False, **kwargs):
def __init__(
self,
mapping_or_iterable: Union[
typing.Mapping[typing.Hashable, VMobject],
typing.Iterable[typing.Tuple[typing.Hashable, VMobject]],
] = {},
show_keys: bool = False,
**kwargs,
):
super().__init__(**kwargs)
self.show_keys = show_keys
self.submob_dict = {}
@ -2008,7 +2016,13 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
def __repr__(self):
return __class__.__name__ + "(" + repr(self.submob_dict) + ")"
def add(self, mapping_or_iterable):
def add(
self,
mapping_or_iterable: Union[
typing.Mapping[typing.Hashable, VMobject],
typing.Iterable[typing.Tuple[typing.Hashable, VMobject]],
],
):
"""Adds the key-value pairs to the :class:`VDict` object.
Also, it internally adds the value to the `submobjects` :class:`list`
@ -2016,7 +2030,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
Parameters
---------
mapping_or_iterable : Union[:class:`Mapping`, Iterable[Tuple[Hashable, :class:`~.VMobject`]]], optional
mapping_or_iterable
The parameter specifying the key-value mapping of keys and mobjects.
Returns
@ -2036,7 +2050,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
return self
def remove(self, key):
def remove(self, key: typing.Hashable):
"""Removes the mobject from the :class:`VDict` object having the key `key`
Also, it internally removes the mobject from the `submobjects` :class:`list`
@ -2044,7 +2058,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
Parameters
----------
key : :class:`typing.Hashable`
key
The key of the submoject to be removed.
Returns
@ -2064,12 +2078,12 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
del self.submob_dict[key]
return self
def __getitem__(self, key):
def __getitem__(self, key: typing.Hashable):
"""Override the [] operator for item retrieval.
Parameters
----------
key : :class:`typing.Hashable`
key
The key of the submoject to be accessed
Returns
@ -2086,14 +2100,14 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
submob = self.submob_dict[key]
return submob
def __setitem__(self, key, value):
def __setitem__(self, key: typing.Hashable, value: VMobject):
"""Override the [] operator for item assignment.
Parameters
----------
key : :class:`typing.Hashable`
key
The key of the submoject to be assigned
value : :class:`VMobject`
value
The submobject to bind the key to
Returns
@ -2111,12 +2125,12 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
self.remove(key)
self.add([(key, value)])
def __delitem__(self, key):
def __delitem__(self, key: typing.Hashable):
"""Override the del operator for deleting an item.
Parameters
----------
key : :class:`typing.Hashable`
key
The key of the submoject to be deleted
Returns
@ -2143,12 +2157,12 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
"""
del self.submob_dict[key]
def __contains__(self, key):
def __contains__(self, key: typing.Hashable):
"""Override the in operator.
Parameters
----------
key : :class:`typing.Hashable`
key
The key to check membership of.
Returns
@ -2185,15 +2199,15 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
submobjects = self.submob_dict.values()
return submobjects
def add_key_value_pair(self, key, value):
def add_key_value_pair(self, key: typing.Hashable, value: VMobject):
"""A utility function used by :meth:`add` to add the key-value pair
to :attr:`submob_dict`. Not really meant to be used externally.
Parameters
----------
key : :class:`typing.Hashable`
key
The key of the submobject to be added.
value : :class:`~.VMobject`
value
The mobject associated with the key
Returns

View file

@ -58,7 +58,7 @@ class VectorField(VGroup):
The value of the color_scheme function to be mapped to the last color in `colors`. Higher values also result in the last color of the gradient.
colors
The colors defining the color gradient of the vector field.
kwargs : Any
kwargs
Additional arguments to be passed to the :class:`~.VGroup` constructor
"""
@ -143,7 +143,7 @@ class VectorField(VGroup):
----------
func
The function defining a vector field.
shift_vector
scalar
The scalar to be applied to the vector field.
Examples
@ -486,7 +486,7 @@ class ArrowVectorField(VectorField):
The opacity of the arrows.
vector_config
Additional arguments to be passed to the :class:`~.Vector` constructor
kwargs : Any
kwargs
Additional arguments to be passed to the :class:`~.VGroup` constructor
Examples
@ -611,8 +611,6 @@ class ArrowVectorField(VectorField):
----------
point
The root point of the vector.
kwargs : Any
Additional arguments to be passed to the :class:`~.Vector` constructor
"""
output = np.asarray(self.func(point))
@ -907,7 +905,7 @@ class StreamLines(VectorField):
def start_animation(
self,
warm_up=True,
warm_up: bool = True,
flow_speed: float = 1,
time_width: float = 0.3,
rate_func: Callable[[float], float] = linear,
@ -920,7 +918,7 @@ class StreamLines(VectorField):
Parameters
----------
warm_up : bool, optional
warm_up
If `True` the animation is initialized line by line. Otherwise it starts with all lines shown.
flow_speed
At `flow_speed=1` the distance the flow moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of this flow.

View file

@ -14,6 +14,9 @@ from ..scene.scene_file_writer import SceneFileWriter
from ..utils.exceptions import EndSceneEarlyException
from ..utils.iterables import list_update
if typing.TYPE_CHECKING:
from manim.scene.scene import Scene
class CairoRenderer:
"""A renderer using Cairo.
@ -106,24 +109,23 @@ class CairoRenderer:
def update_frame( # TODO Description in Docstring
self,
scene,
mobjects=None,
include_submobjects=True,
ignore_skipping=True,
mobjects: typing.Iterable[Mobject] | None = None,
include_submobjects: bool = True,
ignore_skipping: bool = True,
**kwargs,
):
"""Update the frame.
Parameters
----------
mobjects: list, optional
scene
mobjects
list of mobjects
background: np.ndarray, optional
Pixel Array for Background.
include_submobjects
include_submobjects: bool, optional
ignore_skipping : bool, optional
ignore_skipping
**kwargs
@ -159,15 +161,15 @@ class CairoRenderer:
"""
return np.array(self.camera.pixel_array)
def add_frame(self, frame, num_frames=1):
def add_frame(self, frame: np.ndarray, num_frames: int = 1):
"""
Adds a frame to the video_file_stream
Parameters
----------
frame : numpy.ndarray
frame
The frame to add, as a pixel array.
num_frames: int
num_frames
The number of times to add frame.
"""
dt = 1 / self.camera.frame_rate
@ -182,7 +184,7 @@ class CairoRenderer:
Parameters
----------
duration : float
duration
[description]
"""
dt = 1 / self.camera.frame_rate
@ -201,23 +203,23 @@ class CairoRenderer:
def save_static_frame_data(
self,
scene,
scene: Scene,
static_mobjects: typing.Iterable[Mobject],
) -> typing.Iterable[Mobject] | None:
"""Compute and save the static frame, that will be reused at each frame to avoid to unecesseraly computer
static mobjects.
"""Compute and save the static frame, that will be reused at each frame
to avoid unnecessarily computing static mobjects.
Parameters
----------
scene : Scene
scene
The scene played.
static_mobjects : typing.Iterable[Mobject]
static_mobjects
Static mobjects of the scene. If None, self.static_image is set to None
Returns
-------
typing.Iterable[Mobject]
the static image computed.
The static image computed.
"""
self.static_image = None
if not static_mobjects:

View file

@ -70,6 +70,8 @@ from __future__ import annotations
__all__ = ["MovingCameraScene"]
from manim.animation.animation import Animation
from ..camera.moving_camera import MovingCamera
from ..scene.scene import Scene
from ..utils.family import extract_mobject_family_members
@ -89,14 +91,14 @@ class MovingCameraScene(Scene):
def __init__(self, camera_class=MovingCamera, **kwargs):
super().__init__(camera_class=camera_class, **kwargs)
def get_moving_mobjects(self, *animations):
def get_moving_mobjects(self, *animations: Animation):
"""
This method returns a list of all of the Mobjects in the Scene that
are moving, that are also in the animations passed.
Parameters
----------
*animations : Animation
*animations
The Animations whose mobjects will be checked.
"""
moving_mobjects = super().get_moving_mobjects(*animations)

View file

@ -30,6 +30,7 @@ from tqdm import tqdm
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from manim.mobject.mobject import Mobject
from manim.mobject.opengl.opengl_mobject import OpenGLPoint
from .. import config, logger
@ -208,13 +209,13 @@ class Scene:
result.mobject_updater_lists.append((mobject_clone, cloned_updaters))
return result
def render(self, preview=False):
def render(self, preview: bool = False):
"""
Renders this Scene.
Parameters
---------
preview : bool
preview
If true, opens scene in a file viewer.
"""
self.setup()
@ -312,13 +313,13 @@ class Scene:
def __str__(self):
return self.__class__.__name__
def get_attrs(self, *keys):
def get_attrs(self, *keys: str):
"""
Gets attributes of a scene given the attribute's identifier/name.
Parameters
----------
*keys : str
*keys
Name(s) of the argument(s) to return the attribute of.
Returns
@ -328,13 +329,13 @@ class Scene:
"""
return [getattr(self, key) for key in keys]
def update_mobjects(self, dt):
def update_mobjects(self, dt: float):
"""
Begins updating all mobjects in the Scene.
Parameters
----------
dt: int or float
dt
Change in time between updates. Defaults (mostly) to 1/frames_per_second
"""
for mobject in self.mobjects:
@ -434,14 +435,14 @@ class Scene:
use_z_index=self.renderer.camera.use_z_index,
)
def add(self, *mobjects):
def add(self, *mobjects: Mobject):
"""
Mobjects will be displayed, from background to
foreground in the order with which they are added.
Parameters
---------
*mobjects : Mobject
*mobjects
Mobjects to add.
Returns
@ -486,7 +487,7 @@ class Scene:
self.add(mob)
curr_mobjects += mob.get_family()
def remove(self, *mobjects):
def remove(self, *mobjects: Mobject):
"""
Removes mobjects in the passed list of mobjects
from the scene and the foreground, by removing them
@ -494,7 +495,7 @@ class Scene:
Parameters
----------
*mobjects : Mobject
*mobjects
The mobjects to remove.
"""
if config.renderer == "opengl":
@ -566,9 +567,9 @@ class Scene:
def restructure_mobjects(
self,
to_remove,
mobject_list_name="mobjects",
extract_families=True,
to_remove: Mobject,
mobject_list_name: str = "mobjects",
extract_families: bool = True,
):
"""
tl:wr
@ -583,13 +584,13 @@ class Scene:
Parameters
----------
to_remove : Mobject
to_remove
The Mobject to remove.
mobject_list_name : str, optional
mobject_list_name
The list of mobjects ("mobjects", "foreground_mobjects" etc) to remove from.
extract_families : bool, optional
extract_families
Whether the mobject's families should be recursively extracted.
Returns
@ -607,7 +608,7 @@ class Scene:
setattr(self, mobject_list_name, new_list)
return self
def get_restructured_mobject_list(self, mobjects, to_remove):
def get_restructured_mobject_list(self, mobjects: list, to_remove: list):
"""
Given a list of mobjects and a list of mobjects to be removed, this
filters out the removable mobjects from the list of mobjects.
@ -615,10 +616,10 @@ class Scene:
Parameters
----------
mobjects : list
mobjects
The Mobjects to check.
to_remove : list
to_remove
The list of mobjects to remove.
Returns
@ -643,14 +644,14 @@ class Scene:
return new_mobjects
# TODO, remove this, and calls to this
def add_foreground_mobjects(self, *mobjects):
def add_foreground_mobjects(self, *mobjects: Mobject):
"""
Adds mobjects to the foreground, and internally to the list
foreground_mobjects, and mobjects.
Parameters
----------
*mobjects : Mobject
*mobjects
The Mobjects to add to the foreground.
Returns
@ -662,14 +663,14 @@ class Scene:
self.add(*mobjects)
return self
def add_foreground_mobject(self, mobject):
def add_foreground_mobject(self, mobject: Mobject):
"""
Adds a single mobject to the foreground, and internally to the list
foreground_mobjects, and mobjects.
Parameters
----------
mobject : Mobject
mobject
The Mobject to add to the foreground.
Returns
@ -679,14 +680,14 @@ class Scene:
"""
return self.add_foreground_mobjects(mobject)
def remove_foreground_mobjects(self, *to_remove):
def remove_foreground_mobjects(self, *to_remove: Mobject):
"""
Removes mobjects from the foreground, and internally from the list
foreground_mobjects.
Parameters
----------
*to_remove : Mobject
*to_remove
The mobject(s) to remove from the foreground.
Returns
@ -697,14 +698,14 @@ class Scene:
self.restructure_mobjects(to_remove, "foreground_mobjects")
return self
def remove_foreground_mobject(self, mobject):
def remove_foreground_mobject(self, mobject: Mobject):
"""
Removes a single mobject from the foreground, and internally from the list
foreground_mobjects.
Parameters
----------
mobject : Mobject
mobject
The mobject to remove from the foreground.
Returns
@ -714,14 +715,14 @@ class Scene:
"""
return self.remove_foreground_mobjects(mobject)
def bring_to_front(self, *mobjects):
def bring_to_front(self, *mobjects: Mobject):
"""
Adds the passed mobjects to the scene again,
pushing them to he front of the scene.
Parameters
----------
*mobjects : Mobject
*mobjects
The mobject(s) to bring to the front of the scene.
Returns
@ -733,14 +734,14 @@ class Scene:
self.add(*mobjects)
return self
def bring_to_back(self, *mobjects):
def bring_to_back(self, *mobjects: Mobject):
"""
Removes the mobject from the scene and
adds them to the back of the scene.
Parameters
----------
*mobjects : Mobject
*mobjects
The mobject(s) to push to the back of the scene.
Returns
@ -769,13 +770,13 @@ class Scene:
self.foreground_mobjects = []
return self
def get_moving_mobjects(self, *animations):
def get_moving_mobjects(self, *animations: Animation):
"""
Gets all moving mobjects in the passed animation(s).
Parameters
----------
*animations : Animation
*animations
The animations to check for moving mobjects.
Returns
@ -818,14 +819,14 @@ class Scene:
)
return all_moving_mobject_families, static_mobjects
def compile_animations(self, *args, **kwargs):
def compile_animations(self, *args: Animation, **kwargs):
"""
Creates _MethodAnimations from any _AnimationBuilders and updates animation
kwargs with kwargs passed to play().
Parameters
----------
*args : Tuple[:class:`Animation`]
*args
Animations to be played.
**kwargs
Configuration for the call to play().
@ -856,7 +857,9 @@ class Scene:
return animations
def _get_animation_time_progression(self, animations, duration):
def _get_animation_time_progression(
self, animations: list[Animation], duration: float
):
"""
You will hardly use this when making your own animations.
This method is for Manim's internal use.
@ -867,11 +870,11 @@ class Scene:
Parameters
----------
animations : List[:class:`~.Animation`, ...]
animations
The list of animations to get
the time progression for.
duration : int or float
duration
duration of wait time
Returns
@ -908,10 +911,10 @@ class Scene:
def get_time_progression(
self,
run_time,
run_time: float,
description,
n_iterations=None,
override_skip_animations=False,
n_iterations: int | None = None,
override_skip_animations: bool = False,
):
"""
You will hardly use this when making your own animations.
@ -925,13 +928,13 @@ class Scene:
Parameters
----------
run_time : float
run_time
The ``run_time`` of the animation.
n_iterations : int, optional
n_iterations
The number of iterations in the animation.
override_skip_animations : bool, optional
override_skip_animations
Whether or not to show skipped animations in the progress bar.
Returns
@ -954,13 +957,13 @@ class Scene:
)
return time_progression
def get_run_time(self, animations):
def get_run_time(self, animations: list[Animation]):
"""
Gets the total run time for a list of animations.
Parameters
----------
animations : List[:class:`Animation`, ...]
animations
A list of the animations whose total
``run_time`` is to be calculated.
@ -1093,7 +1096,7 @@ class Scene:
"""
self.wait(duration=duration, frozen_frame=True)
def wait_until(self, stop_condition, max_time=60):
def wait_until(self, stop_condition: Callable[[], bool], max_time: float = 60):
"""
Like a wrapper for wait().
You pass a function that determines whether to continue waiting,
@ -1101,10 +1104,10 @@ class Scene:
Parameters
----------
stop_condition : function
stop_condition
The function whose boolean return value determines whether to continue waiting
max_time : int or float, optional
max_time
The maximum wait time in seconds, if the stop_condition is never fulfilled.
"""
self.wait(max_time, stop_condition=stop_condition)
@ -1117,8 +1120,11 @@ class Scene:
Parameters
----------
skip_rendering : bool, optional
Whether the rendering should be skipped, by default False
animations
Animation or mobject with mobject method and params
play_kwargs
named parameters affecting what was passed in ``animations``,
e.g. ``run_time``, ``lag_ratio`` and so on.
Returns
-------
@ -1172,7 +1178,7 @@ class Scene:
and self.animations[0].is_static_wait
)
def play_internal(self, skip_rendering=False):
def play_internal(self, skip_rendering: bool = False):
"""
This method is used to prep the animations for rendering,
apply the arguments and parameters required to them,
@ -1180,11 +1186,8 @@ class Scene:
Parameters
----------
args
Animation or mobject with mobject method and params
kwargs
named parameters affecting what was passed in ``args``,
e.g. ``run_time``, ``lag_ratio`` and so on.
skip_rendering
Whether the rendering should be skipped, by default False
"""
self.duration = self.get_run_time(self.animations)
self.time_progression = self._get_animation_time_progression(
@ -1479,19 +1482,25 @@ class Scene:
)
self.renderer.file_writer.subcaptions.append(subtitle)
def add_sound(self, sound_file, time_offset=0, gain=None, **kwargs):
def add_sound(
self,
sound_file: str,
time_offset: float = 0,
gain: float | None = None,
**kwargs,
):
"""
This method is used to add a sound to the animation.
Parameters
----------
sound_file : str
sound_file
The path to the sound file.
time_offset : int,float, optional
time_offset
The offset in the sound file after which
the sound can be played.
gain : float
gain
Amplification of the sound.
Examples

View file

@ -10,7 +10,7 @@ import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any
import numpy as np
import srt
@ -36,6 +36,9 @@ from ..utils.file_ops import (
from ..utils.sounds import get_full_sound_file_path
from .section import DefaultSectionType, Section
if TYPE_CHECKING:
from manim.renderer.opengl_renderer import OpenGLRenderer
class SceneFileWriter:
"""
@ -200,13 +203,13 @@ class SceneFileWriter:
),
)
def add_partial_movie_file(self, hash_animation):
def add_partial_movie_file(self, hash_animation: str):
"""Adds a new partial movie file path to `scene.partial_movie_files` and current section from a hash.
This method will compute the path from the hash. In addition to that it adds the new animation to the current section.
Parameters
----------
hash_animation : str
hash_animation
Hash of the animation.
"""
if not hasattr(self, "partial_movie_directory") or not write_to_movie():
@ -267,21 +270,26 @@ class SceneFileWriter:
"""
self.audio_segment = AudioSegment.silent()
def add_audio_segment(self, new_segment, time=None, gain_to_background=None):
def add_audio_segment(
self,
new_segment: AudioSegment,
time: float | None = None,
gain_to_background: float | None = None,
):
"""
This method adds an audio segment from an
AudioSegment type object and suitable parameters.
Parameters
----------
new_segment : AudioSegment
new_segment
The audio segment to add
time : int, float, optional
time
the timestamp at which the
sound should be added.
gain_to_background : optional
gain_to_background
The gain of the segment from the background.
"""
if not self.includes_sound:
@ -307,19 +315,25 @@ class SceneFileWriter:
gain_during_overlay=gain_to_background,
)
def add_sound(self, sound_file, time=None, gain=None, **kwargs):
def add_sound(
self,
sound_file: str,
time: float | None = None,
gain: float | None = None,
**kwargs,
):
"""
This method adds an audio segment from a sound file.
Parameters
----------
sound_file : str
sound_file
The path to the sound file.
time : float or int, optional
time
The timestamp at which the audio should be added.
gain : optional
gain
The gain of the given audio segment.
**kwargs
@ -334,40 +348,40 @@ class SceneFileWriter:
self.add_audio_segment(new_segment, time, **kwargs)
# Writers
def begin_animation(self, allow_write=False, file_path=None):
def begin_animation(self, allow_write: bool = False, file_path=None):
"""
Used internally by manim to stream the animation to FFMPEG for
displaying or writing to a file.
Parameters
----------
allow_write : bool, optional
allow_write
Whether or not to write to a video file.
"""
if write_to_movie() and allow_write:
self.open_movie_pipe(file_path=file_path)
def end_animation(self, allow_write=False):
def end_animation(self, allow_write: bool = False):
"""
Internally used by Manim to stop streaming to
FFMPEG gracefully.
Parameters
----------
allow_write : bool, optional
allow_write
Whether or not to write to a video file.
"""
if write_to_movie() and allow_write:
self.close_movie_pipe()
def write_frame(self, frame_or_renderer):
def write_frame(self, frame_or_renderer: np.ndarray | OpenGLRenderer):
"""
Used internally by Manim to write a frame to
the FFMPEG input buffer.
Parameters
----------
frame : np.array
frame_or_renderer
Pixel array of the frame.
"""
if config.renderer == "opengl":
@ -379,7 +393,7 @@ class SceneFileWriter:
if is_png_format() and not config["dry_run"]:
self.output_image_from_array(frame)
def write_opengl_frame(self, renderer):
def write_opengl_frame(self, renderer: OpenGLRenderer):
if write_to_movie():
self.writing_process.stdin.write(
renderer.get_raw_frame_buffer_object_data(),
@ -411,14 +425,14 @@ class SceneFileWriter:
image.save(f"{target_dir}{self.frame_count}{ext}")
self.frame_count += 1
def save_final_image(self, image):
def save_final_image(self, image: np.ndarray):
"""
The name is a misnomer. This method saves the image
passed to it as an in the default image directory.
Parameters
----------
image : np.array
image
The pixel array of the image to save.
"""
if config["dry_run"]:
@ -516,12 +530,12 @@ class SceneFileWriter:
{"path": f"'{self.partial_movie_file_path}'"},
)
def is_already_cached(self, hash_invocation):
def is_already_cached(self, hash_invocation: str):
"""Will check if a file named with `hash_invocation` exists.
Parameters
----------
hash_invocation : :class:`str`
hash_invocation
The hash corresponding to an invocation to either `scene.play` or `scene.wait`.
Returns

View file

@ -67,22 +67,22 @@ class ThreeDScene(Scene):
Parameters
----------
phi : int or float, optional
phi
The polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.
theta : int or float, optional
theta
The azimuthal angle i.e the angle that spins the camera around the Z_AXIS.
focal_distance : int or float, optional
focal_distance
The focal_distance of the Camera.
gamma : int or float, optional
gamma
The rotation of the camera about the vector from the ORIGIN to the Camera.
zoom : float, optional
zoom
The zoom factor of the scene.
frame_center : list, tuple or np.array, optional
frame_center
The new center of the camera frame in cartesian coordinates.
"""
@ -100,17 +100,17 @@ class ThreeDScene(Scene):
if frame_center is not None:
self.renderer.camera._frame_center.move_to(frame_center)
def begin_ambient_camera_rotation(self, rate=0.02, about="theta"):
def begin_ambient_camera_rotation(self, rate: float = 0.02, about: str = "theta"):
"""
This method begins an ambient rotation of the camera about the Z_AXIS,
in the anticlockwise direction
Parameters
----------
rate : int or float, optional
rate
The rate at which the camera should rotate about the Z_AXIS.
Negative rate means clockwise rotation.
about: (str)
about
one of 3 options: ["theta", "phi", "gamma"]. defaults to theta.
"""
# TODO, use a ValueTracker for rate, so that it
@ -230,25 +230,25 @@ class ThreeDScene(Scene):
Parameters
----------
phi : int or float, optional
phi
The polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.
theta : int or float, optional
theta
The azimuthal angle i.e the angle that spins the camera around the Z_AXIS.
focal_distance : int or float, optional
focal_distance
The radial focal_distance between ORIGIN and Camera.
gamma : int or float, optional
gamma
The rotation of the camera about the vector from the ORIGIN to the Camera.
zoom : int or float, optional
zoom
The zoom factor of the camera.
frame_center : list, tuple or np.array, optional
frame_center
The new center of the camera frame in cartesian coordinates.
added_anims : list, optional
added_anims
Any other animations to be played at the same time.
"""
@ -315,14 +315,14 @@ class ThreeDScene(Scene):
if frame_center is not None and config.renderer != "opengl":
self.remove(self.camera._frame_center)
def get_moving_mobjects(self, *animations):
def get_moving_mobjects(self, *animations: Animation):
"""
This method returns a list of all of the Mobjects in the Scene that
are moving, that are also in the animations passed.
Parameters
----------
*animations : Animation
*animations
The animations whose mobjects will be checked.
"""
moving_mobjects = super().get_moving_mobjects(*animations)
@ -333,7 +333,7 @@ class ThreeDScene(Scene):
return self.mobjects
return moving_mobjects
def add_fixed_orientation_mobjects(self, *mobjects, **kwargs):
def add_fixed_orientation_mobjects(self, *mobjects: Mobject, **kwargs):
"""
This method is used to prevent the rotation and tilting
of mobjects as the camera moves around. The mobject can
@ -343,7 +343,7 @@ class ThreeDScene(Scene):
Parameters
----------
*mobjects : Mobject
*mobjects
The Mobject(s) whose orientation must be fixed.
**kwargs
@ -360,7 +360,7 @@ class ThreeDScene(Scene):
mob.fix_orientation()
self.add(mob)
def add_fixed_in_frame_mobjects(self, *mobjects):
def add_fixed_in_frame_mobjects(self, *mobjects: Mobject):
"""
This method is used to prevent the rotation and movement
of mobjects as the camera moves around. The mobject is
@ -369,7 +369,7 @@ class ThreeDScene(Scene):
Parameters
----------
*mobjects : Mobjects
*mobjects
The Mobjects whose orientation must be fixed.
"""
if config.renderer != "opengl":
@ -382,7 +382,7 @@ class ThreeDScene(Scene):
mob.fix_in_frame()
self.add(mob)
def remove_fixed_orientation_mobjects(self, *mobjects):
def remove_fixed_orientation_mobjects(self, *mobjects: Mobject):
"""
This method "unfixes" the orientation of the mobjects
passed, meaning they will no longer be at the same angle
@ -391,7 +391,7 @@ class ThreeDScene(Scene):
Parameters
----------
*mobjects : Mobjects
*mobjects
The Mobjects whose orientation must be unfixed.
"""
if config.renderer != "opengl":
@ -402,7 +402,7 @@ class ThreeDScene(Scene):
mob.unfix_orientation()
self.remove(mob)
def remove_fixed_in_frame_mobjects(self, *mobjects):
def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject):
"""
This method undoes what add_fixed_in_frame_mobjects does.
It allows the mobject to be affected by the movement of
@ -410,7 +410,7 @@ class ThreeDScene(Scene):
Parameters
----------
*mobjects : Mobjects
*mobjects
The Mobjects whose position and orientation must be unfixed.
"""
if config.renderer != "opengl":

View file

@ -4,6 +4,8 @@ from __future__ import annotations
__all__ = ["VectorScene", "LinearTransformationScene"]
from typing import Callable
import numpy as np
from colour import Color
@ -46,13 +48,13 @@ class VectorScene(Scene):
super().__init__(**kwargs)
self.basis_vector_stroke_width = basis_vector_stroke_width
def add_plane(self, animate=False, **kwargs):
def add_plane(self, animate: bool = False, **kwargs):
"""
Adds a NumberPlane object to the background.
Parameters
----------
animate : bool, optional
animate
Whether or not to animate the addition of the plane via Create.
**kwargs
Any valid keyword arguments accepted by NumberPlane.
@ -68,15 +70,15 @@ class VectorScene(Scene):
self.add(plane)
return plane
def add_axes(self, animate=False, color=WHITE, **kwargs):
def add_axes(self, animate: bool = False, color: bool = WHITE, **kwargs):
"""
Adds a pair of Axes to the Scene.
Parameters
----------
animate : bool, optional
animate
Whether or not to animate the addition of the axes through Create.
color : bool, optional
color
The color of the axes. Defaults to WHITE.
"""
axes = Axes(color=color, axis_config={"unit_size": 1})
@ -85,17 +87,17 @@ class VectorScene(Scene):
self.add(axes)
return axes
def lock_in_faded_grid(self, dimness=0.7, axes_dimness=0.5):
def lock_in_faded_grid(self, dimness: float = 0.7, axes_dimness: float = 0.5):
"""
This method freezes the NumberPlane and Axes that were already
in the background, and adds new, manipulatable ones to the foreground.
Parameters
----------
dimness : int, float, optional
dimness
The required dimness of the NumberPlane
axes_dimness : int, float, optional
axes_dimness
The required dimness of the Axes.
"""
plane = self.add_plane()
@ -109,13 +111,13 @@ class VectorScene(Scene):
self.renderer.camera = Camera(self.renderer.get_frame())
self.clear()
def get_vector(self, numerical_vector, **kwargs):
def get_vector(self, numerical_vector: np.ndarray | list | tuple, **kwargs):
"""
Returns an arrow on the Plane given an input numerical vector.
Parameters
----------
numerical_vector : np.array, list, tuple
numerical_vector
The Vector to plot.
**kwargs
Any valid keyword argument of Arrow.
@ -132,22 +134,28 @@ class VectorScene(Scene):
**kwargs,
)
def add_vector(self, vector, color=YELLOW, animate=True, **kwargs):
def add_vector(
self,
vector: Arrow | list | tuple | np.ndarray,
color: str = YELLOW,
animate: bool = True,
**kwargs,
):
"""
Returns the Vector after adding it to the Plane.
Parameters
----------
vector : Arrow, list, tuple, np.array
vector
It can be a pre-made graphical vector, or the
coordinates of one.
color : str
color
The string of the hex color of the vector.
This is only taken into consideration if
'vector' is not an Arrow. Defaults to YELLOW.
animate : bool
animate
Whether or not to animate the addition of the vector
by using GrowArrow
@ -168,25 +176,18 @@ class VectorScene(Scene):
self.add(vector)
return vector
def write_vector_coordinates(self, vector, **kwargs):
def write_vector_coordinates(self, vector: Arrow, **kwargs):
"""
Returns a column matrix indicating the vector coordinates,
after writing them to the screen.
Parameters
----------
vector : :class:`.Arrow`
vector
The arrow representing the vector.
**kwargs
Any valid keyword arguments of :meth:`~.geometry.Vector.coordinate_label`:
integer_labels : :class:`bool`
Whether or not to round the coordinates to integers. Default: ``True``.
n_dim : :class:`int`
The number of dimensions of the vector. Default: ``2``.
color
The color of the label. Default: ``WHITE``.
Any valid keyword arguments of :meth:`~.Vector.coordinate_label`:
Returns
-------
@ -197,16 +198,16 @@ class VectorScene(Scene):
self.play(Write(coords))
return coords
def get_basis_vectors(self, i_hat_color=X_COLOR, j_hat_color=Y_COLOR):
def get_basis_vectors(self, i_hat_color: str = X_COLOR, j_hat_color: str = Y_COLOR):
"""
Returns a VGroup of the Basis Vectors (1,0) and (0,1)
Parameters
----------
i_hat_color : str
i_hat_color
The hex colour to use for the basis vector in the x direction
j_hat_color : str
j_hat_color
The hex colour to use for the basis vector in the y direction
Returns
@ -252,32 +253,32 @@ class VectorScene(Scene):
def get_vector_label(
self,
vector,
vector: Vector,
label,
at_tip=False,
direction="left",
rotate=False,
color=None,
label_scale_factor=LARGE_BUFF - 0.2,
at_tip: bool = False,
direction: str = "left",
rotate: bool = False,
color: str | None = None,
label_scale_factor: float = LARGE_BUFF - 0.2,
):
"""
Returns naming labels for the passed vector.
Parameters
----------
vector : Vector
vector
Vector Object for which to get the label.
at_tip : bool
at_tip
Whether or not to place the label at the tip of the vector.
direction : {"left"}
direction
If the label should be on the "left" or right of the vector.
rotate : bool
rotate
Whether or not to rotate it to align it with the vector.
color : str
color
The color to give the label.
label_scale_factor (Union[int,float])
label_scale_factor
How much to scale the label by.
Returns
@ -311,20 +312,22 @@ class VectorScene(Scene):
label.shift((vector.get_end() - vector.get_start()) / 2)
return label
def label_vector(self, vector, label, animate=True, **kwargs):
def label_vector(
self, vector: Vector, label: MathTex | str, animate: bool = True, **kwargs
):
"""
Shortcut method for creating, and animating the addition of
a label for the vector.
Parameters
----------
vector : Vector
vector
The vector for which the label must be added.
label : MathTex, str
label
The MathTex/string of the label.
animate : bool, optional
animate
Whether or not to animate the labelling w/ Write
**kwargs
@ -361,7 +364,12 @@ class VectorScene(Scene):
y_coord.set_color(Y_COLOR)
return y_coord
def coords_to_vector(self, vector, coords_start=2 * RIGHT + 2 * UP, clean_up=True):
def coords_to_vector(
self,
vector: np.ndarray | list | tuple,
coords_start: np.ndarray | list | tuple = 2 * RIGHT + 2 * UP,
clean_up: bool = True,
):
"""
This method writes the vector as a column matrix (henceforth called the label),
takes the values in it one by one, and form the corresponding
@ -370,16 +378,16 @@ class VectorScene(Scene):
Parameters
----------
vector : np.ndarray, list, tuple
vector
The vector to show.
coords_start : np.ndarray,list,tuple, optional
coords_start
The starting point of the location of
the label of the vector that shows it
numerically.
Defaults to 2 * RIGHT + 2 * UP or (2,2)
clean_up : bool, optional
clean_up
Whether or not to remove whatever
this method did after it's done.
@ -419,7 +427,12 @@ class VectorScene(Scene):
self.clear()
self.add(*starting_mobjects)
def vector_to_coords(self, vector, integer_labels=True, clean_up=True):
def vector_to_coords(
self,
vector: np.ndarray | list | tuple,
integer_labels: bool = True,
clean_up: bool = True,
):
"""
This method displays vector as a Vector() based vector, and then shows
the corresponding lines that make up the x and y components of the vector.
@ -428,14 +441,14 @@ class VectorScene(Scene):
Parameters
----------
vector : np.ndarray, list, tuple
vector
The vector to show.
integer_label : bool, optional
integer_labels
Whether or not to round the value displayed.
in the vector's label to the nearest integer
clean_up : bool, optional
clean_up
Whether or not to remove whatever
this method did after it's done.
@ -477,7 +490,7 @@ class VectorScene(Scene):
self.add(*starting_mobjects)
return array, x_line, y_line
def show_ghost_movement(self, vector):
def show_ghost_movement(self, vector: Arrow | list | tuple | np.ndarray):
"""
This method plays an animation that partially shows the entire plane moving
in the direction of a particular vector. This is useful when you wish to
@ -486,7 +499,7 @@ class VectorScene(Scene):
Parameters
----------
vector : Arrow, list, tuple, np.ndarray
vector
The vector which indicates the direction of movement.
"""
if isinstance(vector, Arrow):
@ -641,18 +654,18 @@ class LinearTransformationScene(VectorScene):
self.i_hat, self.j_hat = self.basis_vectors
self.add(self.basis_vectors)
def add_special_mobjects(self, mob_list, *mobs_to_add):
def add_special_mobjects(self, mob_list: list, *mobs_to_add: Mobject):
"""
Adds mobjects to a separate list that can be tracked,
if these mobjects have some extra importance.
Parameters
----------
mob_list : list
mob_list
The special list to which you want to add
these mobjects.
*mobs_to_add : Mobject
*mobs_to_add
The mobjects to add.
"""
@ -661,44 +674,46 @@ class LinearTransformationScene(VectorScene):
mob_list.append(mobject)
self.add(mobject)
def add_background_mobject(self, *mobjects):
def add_background_mobject(self, *mobjects: Mobject):
"""
Adds the mobjects to the special list
self.background_mobjects.
Parameters
----------
*mobjects : Mobject
*mobjects
The mobjects to add to the list.
"""
self.add_special_mobjects(self.background_mobjects, *mobjects)
# TODO, this conflicts with Scene.add_fore
def add_foreground_mobject(self, *mobjects):
def add_foreground_mobject(self, *mobjects: Mobject):
"""
Adds the mobjects to the special list
self.foreground_mobjects.
Parameters
----------
*mobjects : Mobject
*mobjects
The mobjects to add to the list
"""
self.add_special_mobjects(self.foreground_mobjects, *mobjects)
def add_transformable_mobject(self, *mobjects):
def add_transformable_mobject(self, *mobjects: Mobject):
"""
Adds the mobjects to the special list
self.transformable_mobjects.
Parameters
----------
*mobjects : Mobject
*mobjects
The mobjects to add to the list.
"""
self.add_special_mobjects(self.transformable_mobjects, *mobjects)
def add_moving_mobject(self, mobject, target_mobject=None):
def add_moving_mobject(
self, mobject: Mobject, target_mobject: Mobject | None = None
):
"""
Adds the mobject to the special list
self.moving_mobject, and adds a property
@ -708,28 +723,30 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
mobject : Mobject
mobject
The mobjects to add to the list
target_mobject : Mobject, optional
target_mobject
What the moving_mobject goes to, etc.
"""
mobject.target = target_mobject
self.add_special_mobjects(self.moving_mobjects, mobject)
def get_unit_square(self, color=YELLOW, opacity=0.3, stroke_width=3):
def get_unit_square(
self, color: str = YELLOW, opacity: float = 0.3, stroke_width: float = 3
):
"""
Returns a unit square for the current NumberPlane.
Parameters
----------
color : str, optional
color
The string of the hex color code of the color wanted.
opacity : float, int, optional
opacity
The opacity of the square
stroke_width : int, float, optional
stroke_width
The stroke_width in pixels of the border of the square
Returns
@ -748,14 +765,14 @@ class LinearTransformationScene(VectorScene):
square.move_to(self.plane.coords_to_point(0, 0), DL)
return square
def add_unit_square(self, animate=False, **kwargs):
def add_unit_square(self, animate: bool = False, **kwargs):
"""
Adds a unit square to the scene via
self.get_unit_square.
Parameters
----------
animate (bool)
animate
Whether or not to animate the addition
with DrawBorderThenFill.
**kwargs
@ -778,18 +795,20 @@ class LinearTransformationScene(VectorScene):
self.square = square
return self
def add_vector(self, vector, color=YELLOW, **kwargs):
def add_vector(
self, vector: Arrow | list | tuple | np.ndarray, color: str = YELLOW, **kwargs
):
"""
Adds a vector to the scene, and puts it in the special
list self.moving_vectors.
Parameters
----------
vector : Arrow,list,tuple,np.ndarray
vector
It can be a pre-made graphical vector, or the
coordinates of one.
color : str
color
The string of the hex color of the vector.
This is only taken into consideration if
'vector' is not an Arrow. Defaults to YELLOW.
@ -806,7 +825,7 @@ class LinearTransformationScene(VectorScene):
self.moving_vectors.append(vector)
return vector
def write_vector_coordinates(self, vector, **kwargs):
def write_vector_coordinates(self, vector: Arrow, **kwargs):
"""
Returns a column matrix indicating the vector coordinates,
after writing them to the screen, and adding them to the
@ -814,7 +833,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
vector : Arrow
vector
The arrow representing the vector.
**kwargs
@ -830,7 +849,12 @@ class LinearTransformationScene(VectorScene):
return coords
def add_transformable_label(
self, vector, label, transformation_name="L", new_label=None, **kwargs
self,
vector: Vector,
label: MathTex | str,
transformation_name: str | MathTex = "L",
new_label: str | MathTex | None = None,
**kwargs,
):
"""
Method for creating, and animating the addition of
@ -838,16 +862,16 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
vector : Vector
vector
The vector for which the label must be added.
label : Union[:class:`~.MathTex`, :class:`str`]
label
The MathTex/string of the label.
transformation_name : Union[:class:`str`, :class:`~.MathTex`], optional
transformation_name
The name to give the transformation as a label.
new_label : Union[:class:`str`, :class:`~.MathTex`], optional
new_label
What the label should display after a Linear Transformation
**kwargs
@ -873,7 +897,12 @@ class LinearTransformationScene(VectorScene):
self.transformable_labels.append(label_mob)
return label_mob
def add_title(self, title, scale_factor=1.5, animate=False):
def add_title(
self,
title: str | MathTex | Tex,
scale_factor: float = 1.5,
animate: bool = False,
):
"""
Adds a title, after scaling it, adding a background rectangle,
moving it to the top and adding it to foreground_mobjects adding
@ -881,13 +910,13 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
title : Union[:class:`str`, :class:`~.MathTex`, :class:`~.Tex`]
title
What the title should be.
scale_factor : int, float, optional
scale_factor
How much the title should be scaled by.
animate : bool
animate
Whether or not to animate the addition.
Returns
@ -905,19 +934,21 @@ class LinearTransformationScene(VectorScene):
self.title = title
return self
def get_matrix_transformation(self, matrix):
def get_matrix_transformation(self, matrix: np.ndarray | list | tuple):
"""
Returns a function corresponding to the linear
transformation represented by the matrix passed.
Parameters
----------
matrix : np.ndarray, list, tuple
matrix
The matrix.
"""
return self.get_transposed_matrix_transformation(np.array(matrix).T)
def get_transposed_matrix_transformation(self, transposed_matrix):
def get_transposed_matrix_transformation(
self, transposed_matrix: np.ndarray | list | tuple
):
"""
Returns a function corresponding to the linear
transformation represented by the transposed
@ -925,7 +956,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
matrix : np.ndarray, list, tuple
transposed_matrix
The matrix.
"""
transposed_matrix = np.array(transposed_matrix)
@ -937,7 +968,7 @@ class LinearTransformationScene(VectorScene):
raise ValueError("Matrix has bad dimensions")
return lambda point: np.dot(point, transposed_matrix)
def get_piece_movement(self, pieces):
def get_piece_movement(self, pieces: list | tuple | np.ndarray):
"""
This method returns an animation that moves an arbitrary
mobject in "pieces" to its corresponding .target value.
@ -946,7 +977,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
pieces : list, tuple, np.array
pieces
The pieces for which the movement must be shown.
Returns
@ -960,7 +991,7 @@ class LinearTransformationScene(VectorScene):
self.add(start.copy().fade(0.7))
return Transform(start, target, lag_ratio=0)
def get_moving_mobject_movement(self, func):
def get_moving_mobject_movement(self, func: Callable[[np.ndarray], np.ndarray]):
"""
This method returns an animation that moves a mobject
in "self.moving_mobjects" to its corresponding .target value.
@ -969,7 +1000,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
func : function
func
The function that determines where the .target of
the moving mobject goes.
@ -985,7 +1016,7 @@ class LinearTransformationScene(VectorScene):
m.target.move_to(target_point)
return self.get_piece_movement(self.moving_mobjects)
def get_vector_movement(self, func):
def get_vector_movement(self, func: Callable[[np.ndarray], np.ndarray]):
"""
This method returns an animation that moves a mobject
in "self.moving_vectors" to its corresponding .target value.
@ -994,7 +1025,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
func : function
func
The function that determines where the .target of
the moving mobject goes.
@ -1026,7 +1057,7 @@ class LinearTransformationScene(VectorScene):
)
return self.get_piece_movement(self.transformable_labels)
def apply_matrix(self, matrix, **kwargs):
def apply_matrix(self, matrix: np.ndarray | list | tuple, **kwargs):
"""
Applies the transformation represented by the
given matrix to the number plane, and each vector/similar
@ -1034,14 +1065,14 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
matrix : np.ndarray, list, tuple
matrix
The matrix.
**kwargs
Any valid keyword argument of self.apply_transposed_matrix()
"""
self.apply_transposed_matrix(np.array(matrix).T, **kwargs)
def apply_inverse(self, matrix, **kwargs):
def apply_inverse(self, matrix: np.ndarray | list | tuple, **kwargs):
"""
This method applies the linear transformation
represented by the inverse of the passed matrix
@ -1049,14 +1080,16 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
matrix : np.ndarray, list, tuple
matrix
The matrix whose inverse is to be applied.
**kwargs
Any valid keyword argument of self.apply_matrix()
"""
self.apply_matrix(np.linalg.inv(matrix), **kwargs)
def apply_transposed_matrix(self, transposed_matrix, **kwargs):
def apply_transposed_matrix(
self, transposed_matrix: np.ndarray | list | tuple, **kwargs
):
"""
Applies the transformation represented by the
given transposed matrix to the number plane,
@ -1064,7 +1097,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
matrix : np.ndarray, list, tuple
transposed_matrix
The matrix.
**kwargs
Any valid keyword argument of self.apply_function()
@ -1077,7 +1110,7 @@ class LinearTransformationScene(VectorScene):
kwargs["path_arc"] = net_rotation
self.apply_function(func, **kwargs)
def apply_inverse_transpose(self, t_matrix, **kwargs):
def apply_inverse_transpose(self, t_matrix: np.ndarray | list | tuple, **kwargs):
"""
Applies the inverse of the transformation represented
by the given transposed matrix to the number plane and each
@ -1085,7 +1118,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
matrix : np.ndarray, list, tuple
t_matrix
The matrix.
**kwargs
Any valid keyword argument of self.apply_transposed_matrix()
@ -1093,7 +1126,9 @@ class LinearTransformationScene(VectorScene):
t_inv = np.linalg.inv(np.array(t_matrix).T).T
self.apply_transposed_matrix(t_inv, **kwargs)
def apply_nonlinear_transformation(self, function, **kwargs):
def apply_nonlinear_transformation(
self, function: Callable[[np.ndarray], np.ndarray], **kwargs
):
"""
Applies the non-linear transformation represented
by the given function to the number plane and each
@ -1101,7 +1136,7 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
function : Function
function
The function.
**kwargs
Any valid keyword argument of self.apply_function()
@ -1109,7 +1144,12 @@ class LinearTransformationScene(VectorScene):
self.plane.prepare_for_nonlinear_transform()
self.apply_function(function, **kwargs)
def apply_function(self, function, added_anims=[], **kwargs):
def apply_function(
self,
function: Callable[[np.ndarray], np.ndarray],
added_anims: list = [],
**kwargs,
):
"""
Applies the given function to each of the mobjects in
self.transformable_mobjects, and plays the animation showing
@ -1117,11 +1157,11 @@ class LinearTransformationScene(VectorScene):
Parameters
----------
function : Function
function
The function that affects each point
of each mobject in self.transformable_mobjects.
added_anims : list, optional
added_anims
Any other animations that need to be played
simultaneously with this.

View file

@ -132,14 +132,14 @@ class ZoomedScene(MovingCameraScene):
self.zoomed_camera = zoomed_camera
self.zoomed_display = zoomed_display
def activate_zooming(self, animate=False):
def activate_zooming(self, animate: bool = False):
"""
This method is used to activate the zooming for
the zoomed_camera.
Parameters
----------
animate : bool, optional
animate
Whether or not to animate the activation
of the zoomed camera.
"""
@ -153,13 +153,13 @@ class ZoomedScene(MovingCameraScene):
self.zoomed_display,
)
def get_zoom_in_animation(self, run_time=2, **kwargs):
def get_zoom_in_animation(self, run_time: float = 2, **kwargs):
"""
Returns the animation of camera zooming in.
Parameters
----------
run_time : int or float, optional
run_time
The run_time of the animation of the camera zooming in.
**kwargs
Any valid keyword arguments of ApplyMethod()

View file

@ -38,7 +38,7 @@ def bezier(
Parameters
----------
points : np.ndarray
points
points defining the desired bezier curve.
Returns
@ -78,11 +78,11 @@ def partial_bezier_points(points: np.ndarray, a: float, b: float) -> np.ndarray:
Parameters
----------
points : np.ndarray
points
set of points defining the bezier curve.
a : float
a
lower bound of the desired partial bezier curve.
b : float
b
upper bound of the desired partial bezier curve.
Returns
@ -353,7 +353,7 @@ def get_smooth_handle_points(
Parameters
----------
points : np.ndarray
points
Anchors.
Returns

View file

@ -1,10 +1,12 @@
from __future__ import annotations
from typing import Callable
from .. import config, logger
from ..utils.hashing import get_hash_from_play_call
def handle_caching_play(func):
def handle_caching_play(func: Callable[..., None]):
"""Decorator that returns a wrapped version of func that will compute
the hash of the play invocation.
@ -14,7 +16,7 @@ def handle_caching_play(func):
Parameters
----------
func : Callable[[...], None]
func
The play like function that has to be written to the video file stream.
Take the same parameters as `scene.play`.
"""

View file

@ -1,15 +1,16 @@
from __future__ import annotations
import itertools as it
from typing import Iterable
from ..mobject.mobject import Mobject
from ..utils.iterables import remove_list_redundancies
def extract_mobject_family_members(
mobjects,
mobjects: Iterable[Mobject],
use_z_index=False,
only_those_with_points=False,
only_those_with_points: bool = False,
):
"""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
@ -17,9 +18,9 @@ def extract_mobject_family_members(
Parameters
----------
mobjects : Mobject
mobjects
The Mobjects currently in the Scene
only_those_with_points : bool, optional
only_those_with_points
Whether or not to only do this for
those mobjects that have points. By default False

View file

@ -175,12 +175,12 @@ def seek_full_path_from_defaults(
raise OSError(error)
def modify_atime(file_path) -> None:
def modify_atime(file_path: str) -> None:
"""Will manually change the accessed time (called `atime`) of the file, as on a lot of OS the accessed time refresh is disabled by default.
Parameters
----------
file_path : :class:`str`
file_path
The path of the file.
"""
os.utime(file_path, times=(time.time(), os.path.getmtime(file_path)))
@ -248,12 +248,12 @@ def get_template_path() -> Path:
return Path.resolve(Path(__file__).parent.parent / "templates")
def add_import_statement(file):
def add_import_statement(file: Path):
"""Prepends an import statement in a file
Parameters
----------
file : :class:`Path`
file
"""
with file.open("r+") as f:
import_line = "from manim import *"
@ -269,9 +269,9 @@ def copy_template_files(
Parameters
----------
project_dir : :class:`Path`
project_dir
Path to project directory.
template_name : :class:`str`
template_name
Name of template.
"""
template_cfg_path = Path.resolve(

View file

@ -14,8 +14,15 @@ 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
if typing.TYPE_CHECKING:
from manim.scene.scene import Scene
# Sometimes there are elements that are not suitable for hashing (too long or
# run-dependent). This is used to filter them out.
KEYS_TO_FILTER_OUT = {
@ -50,14 +57,14 @@ class _Memoizer:
cls._already_processed.clear()
@classmethod
def check_already_processed_decorator(cls: _Memoizer, is_method=False):
def check_already_processed_decorator(cls: _Memoizer, is_method: bool = False):
"""Decorator to handle the arguments that goes through the decorated function.
Returns _ALREADY_PROCESSED_PLACEHOLDER if the obj has been processed, or lets
the decorated function call go ahead.
Parameters
----------
is_method : bool, optional
is_method
Whether the function passed is a method, by default False.
"""
@ -81,7 +88,7 @@ class _Memoizer:
Parameters
----------
obj : Any
obj
The object to check.
Returns
@ -98,7 +105,7 @@ class _Memoizer:
Parameters
----------
obj : Any
obj
The object to mark as processed.
"""
cls._handle_already_processed(obj, lambda x: x)
@ -164,7 +171,7 @@ class _Memoizer:
class _CustomEncoder(json.JSONEncoder):
def default(self, obj):
def default(self, obj: Any):
"""
This method is used to serialize objects to JSON format.
@ -178,7 +185,7 @@ class _CustomEncoder(json.JSONEncoder):
Parameters
----------
obj : Any
obj
Arbitrary object to convert
Returns
@ -225,7 +232,7 @@ class _CustomEncoder(json.JSONEncoder):
# Serialize it with only the type of the object. You can change this to whatever string when debugging the serialization process.
return str(type(obj))
def _cleaned_iterable(self, iterable):
def _cleaned_iterable(self, iterable: typing.Iterable[Any]):
"""Check for circular reference at each iterable that will go through the JSONEncoder, as well as key of the wrong format.
If a key with a bad format is found (i.e not a int, string, or float), it gets replaced byt its hash using the same process implemented here.
@ -233,7 +240,7 @@ class _CustomEncoder(json.JSONEncoder):
Parameters
----------
iterable : Iterable[Any]
iterable
The iterable to check.
"""
@ -278,12 +285,12 @@ class _CustomEncoder(json.JSONEncoder):
elif isinstance(iterable, dict):
return _iter_check_dict(iterable)
def encode(self, obj):
def encode(self, obj: Any):
"""Overriding of :meth:`JSONEncoder.encode`, to make our own process.
Parameters
----------
obj: Any
obj
The object to encode in JSON.
Returns
@ -297,12 +304,12 @@ class _CustomEncoder(json.JSONEncoder):
return super().encode(obj)
def get_json(obj):
def get_json(obj: dict):
"""Recursively serialize `object` to JSON using the :class:`CustomEncoder` class.
Parameters
----------
dict_config : :class:`dict`
obj
The dict to flatten
Returns
@ -314,25 +321,25 @@ def get_json(obj):
def get_hash_from_play_call(
scene_object,
camera_object,
animations_list,
current_mobjects_list,
scene_object: Scene,
camera_object: Camera,
animations_list: typing.Iterable[Animation],
current_mobjects_list: typing.Iterable[Mobject],
) -> str:
"""Take the list of animations and a list of mobjects and output their hashes. This is meant to be used for `scene.play` function.
Parameters
-----------
scene_object : :class:`~.Scene`
scene_object
The scene object.
camera_object : :class:`~.Camera`
camera_object
The camera object used in the scene.
animations_list : Iterable[:class:`~.Animation`]
animations_list
The list of animations.
current_mobjects_list : Iterable[:class:`~.Mobject`]
current_mobjects_list
The list of mobjects.
Returns

View file

@ -114,7 +114,7 @@ def quaternion_from_angle_axis(
The angle for the quaternion.
axis
The axis for the quaternion
axis_normalized : bool, optional
axis_normalized
Checks whether the axis is normalized, by default False
Returns
@ -267,7 +267,7 @@ def rotation_about_z(angle: float) -> np.ndarray:
Parameters
----------
angle : float
angle
Angle for the rotation matrix.
Returns

View file

@ -45,10 +45,6 @@ def frames_comparison(
Parameters
----------
test_name
The name of the test.
module_name
The module which the test belongs to.
last_frame
whether the test should test the last frame, by default True.
renderer_class
@ -161,7 +157,7 @@ def _make_test_comparing_frames(
file_path: Path,
base_scene: type[Scene],
construct: Callable[[Scene], None],
renderer_class, # Renderer type, there is no superclass renderer yet .....
renderer_class: type, # Renderer type, there is no superclass renderer yet .....
is_set_test_data_test: bool,
last_frame: bool,
show_diff: bool,
@ -171,15 +167,15 @@ def _make_test_comparing_frames(
Parameters
----------
file_path : Path
file_path
The path of the control frames.
base_scene : Type[Scene]
base_scene
The base scene class.
construct : Callable[[Scene], None]
construct
The construct method (= the test function)
renderer_class : [type]
renderer_class
The renderer base class.
show_diff : bool
show_diff
whether to visually show_diff (see --show_diff)
Returns

View file

@ -18,17 +18,17 @@ class TexTemplate:
Parameters
----------
tex_compiler : Optional[:class:`str`], optional
tex_compiler
The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``
output_format : Optional[:class:`str`], optional
output_format
The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``
documentclass : Optional[:class:`str`], optional
documentclass
The command defining the documentclass, e.g. ``\\documentclass[preview]{standalone}``
preamble : Optional[:class:`str`], optional
preamble
The document's preamble, i.e. the part between ``\\documentclass`` and ``\\begin{document}``
placeholder_text : Optional[:class:`str`], optional
placeholder_text
Text in the document that will be replaced by the expression to be rendered
post_doc_commands : Optional[:class:`str`], optional
post_doc_commands
Text (definitions, commands) to be inserted at right after ``\\begin{document}``, e.g. ``\\boldmath``
Attributes
@ -60,12 +60,12 @@ class TexTemplate:
def __init__(
self,
tex_compiler=None,
output_format=None,
documentclass=None,
preamble=None,
placeholder_text=None,
post_doc_commands=None,
tex_compiler: str | None = None,
output_format: str | None = None,
documentclass: str | None = None,
preamble: str | None = None,
placeholder_text: str | None = None,
post_doc_commands: str | None = None,
**kwargs,
):
self.tex_compiler = (
@ -124,14 +124,14 @@ class TexTemplate:
+ "\n"
)
def add_to_preamble(self, txt, prepend=False):
def add_to_preamble(self, txt: str, prepend: bool = False):
"""Adds stuff to the TeX template's preamble (e.g. definitions, packages). Text can be inserted at the beginning or at the end of the preamble.
Parameters
----------
txt : :class:`string`
txt
String containing the text to be added, e.g. ``\\usepackage{hyperref}``
prepend : Optional[:class:`bool`], optional
prepend
Whether the text should be added at the beginning of the preamble, i.e. right after ``\\documentclass``. Default is to add it at the end of the preamble, i.e. right before ``\\begin{document}``
"""
if prepend:
@ -140,23 +140,23 @@ class TexTemplate:
self.preamble += "\n" + txt
self._rebuild()
def add_to_document(self, txt):
def add_to_document(self, txt: str):
"""Adds txt to the TeX template just after \\begin{document}, e.g. ``\\boldmath``
Parameters
----------
txt : :class:`str`
txt
String containing the text to be added.
"""
self.post_doc_commands += "\n" + txt + "\n"
self._rebuild()
def get_texcode_for_expression(self, expression):
def get_texcode_for_expression(self, expression: str):
"""Inserts expression verbatim into TeX template.
Parameters
----------
expression : :class:`str`
expression
The string containing the expression to be typeset, e.g. ``$\\sqrt{2}$``
Returns
@ -166,13 +166,13 @@ class TexTemplate:
"""
return self.body.replace(self.placeholder_text, expression)
def _texcode_for_environment(self, environment):
def _texcode_for_environment(self, environment: str):
"""Processes the tex_environment string to return the correct ``\\begin{environment}[extra]{extra}`` and
``\\end{environment}`` strings
Parameters
----------
environment : :class:`str`
environment
The tex_environment as a string. Acceptable formats include:
``{align*}``, ``align*``, ``{tabular}[t]{cccl}``, ``tabular}{cccl``, ``\\begin{tabular}[t]{cccl}``.
@ -204,14 +204,14 @@ class TexTemplate:
return begin, end
def get_texcode_for_expression_in_env(self, expression, environment):
def get_texcode_for_expression_in_env(self, expression: str, environment: str):
r"""Inserts expression into TeX template wrapped in \begin{environment} and \end{environment}
Parameters
----------
expression : :class:`str`
expression
The string containing the expression to be typeset, e.g. ``$\\sqrt{2}$``
environment : :class:`str`
environment
The string containing the environment in which the expression should be typeset, e.g. ``align*``
Returns
@ -231,25 +231,10 @@ class TexTemplateFromFile(TexTemplate):
Parameters
----------
tex_compiler : Optional[:class:`str`], optional
The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``
output_format : Optional[:class:`str`], optional
The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``
documentclass : Optional[:class:`str`], optional
The command defining the documentclass, e.g. ``\\documentclass[preview]{standalone}``
preamble : Optional[:class:`str`], optional
The document's preamble, i.e. the part between ``\\documentclass`` and ``\\begin{document}``
placeholder_text : Optional[:class:`str`], optional
Text in the document that will be replaced by the expression to be rendered
post_doc_commands : Optional[:class:`str`], optional
Text (definitions, commands) to be inserted at right after ``\\begin{document}``, e.g. ``\\boldmath``
kwargs : :class:`str`
The kwargs specified can only be strings.
Other Parameters
----------------
tex_filename
Path to a valid TeX template file
kwargs
Arguments for :class:`~.TexTemplate`.
Attributes
----------

View file

@ -14,6 +14,8 @@ import re
import unicodedata
from pathlib import Path
from manim.utils.tex import TexTemplate
from .. import config, logger
@ -25,16 +27,20 @@ def tex_hash(expression):
return hasher.hexdigest()[:16]
def tex_to_svg_file(expression, environment=None, tex_template=None):
def tex_to_svg_file(
expression: str,
environment: str | None = None,
tex_template: TexTemplate | None = None,
):
"""Takes a tex expression and returns the svg version of the compiled tex
Parameters
----------
expression : :class:`str`
expression
String containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo``
environment : Optional[:class:`str`], optional
environment
The string containing the environment in which the expression should be typeset, e.g. ``align*``
tex_template : Optional[:class:`~.TexTemplate`], optional
tex_template
Template class used to typesetting. If not set, use default template set via `config["tex_template"]`
Returns
@ -53,17 +59,21 @@ def tex_to_svg_file(expression, environment=None, tex_template=None):
return convert_to_svg(dvi_file, tex_template.output_format)
def generate_tex_file(expression, environment=None, tex_template=None):
def generate_tex_file(
expression: str,
environment: str | None = None,
tex_template: TexTemplate | None = None,
):
"""Takes a tex expression (and an optional tex environment),
and returns a fully formed tex file ready for compilation.
Parameters
----------
expression : :class:`str`
expression
String containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo``
environment : Optional[:class:`str`], optional
environment
The string containing the environment in which the expression should be typeset, e.g. ``align*``
tex_template : Optional[:class:`~.TexTemplate`], optional
tex_template
Template class used to typesetting. If not set, use default template set via `config["tex_template"]`
Returns
@ -196,16 +206,16 @@ def compile_tex(tex_file: Path, tex_compiler: str, output_format: str) -> Path:
return result
def convert_to_svg(dvi_file, extension, page=1):
def convert_to_svg(dvi_file: Path, extension: str, page: int = 1):
"""Converts a .dvi, .xdv, or .pdf file into an svg using dvisvgm.
Parameters
----------
dvi_file : :class:`Path`
dvi_file
File name of the input file to be converted.
extension : :class:`str`
extension
String containing the file extension and thus indicating the file type, e.g. ``.dvi`` or ``.pdf``
page : Optional[:class:`int`], optional
page
Page to be converted if input file is multi-page.
Returns

View file

@ -13,7 +13,7 @@ class SomeClass:
Parameters
----------
scale_factor : :class:`float`
scale_factor
The factor used for scaling.
Returns

View file

@ -9,17 +9,18 @@ from pathlib import Path
import numpy as np
from manim import config, logger
from manim.scene.scene import Scene
def set_test_scene(scene_object, module_name):
def set_test_scene(scene_object: type[Scene], module_name: str):
"""Function used to set up the test data for a new feature. This will basically set up a pre-rendered frame for a scene. This is meant to be used only
when setting up tests. Please refer to the wiki.
Parameters
----------
scene_object : :class:`~.Scene`
scene_object
The scene with which we want to set up a new test.
module_name : :class:`str`
module_name
The name of the module in which the functionality tested is contained. For example, ``Write`` is contained in the module ``creation``. This will be used in the folder architecture
of ``/tests_data``.

View file

@ -8,6 +8,7 @@ import numpy as np
from manim import config, tempconfig
from manim.renderer.opengl_renderer import OpenGLRenderer
from manim.scene.scene import Scene
class GraphicalUnitTester:
@ -15,11 +16,9 @@ class GraphicalUnitTester:
Parameters
----------
scene_class : :class:`~.Scene`
scene_class
The scene to be tested
config_scene : :class:`dict`
The configuration of the scene
module_tested : :class:`str`
module_tested
The name of the module tested. i.e if we are testing functions of creation.py, the module will be "creation"
Attributes
@ -32,7 +31,9 @@ class GraphicalUnitTester:
The scene tested
"""
def __init__(self, scene_class, module_tested, tmpdir, rgb_atol=0):
def __init__(
self, scene_class: type[Scene], module_tested: str, tmpdir, rgb_atol=0
):
# Disable the the logs, (--quiet is broken) TODO
logging.disable(logging.CRITICAL)
tests_directory = Path(__file__).absolute().parent.parent

View file

@ -4,12 +4,12 @@ import inspect
import sys
def get_scenes_to_test(module_name):
def get_scenes_to_test(module_name: str):
"""Get all Test classes of the module from which it is called. Used to fetch all the SceneTest of the module.
Parameters
----------
module_name : :class:`str`
module_name
The name of the module tested.
Returns