A community-maintained Python framework for creating mathematical animations.
Add typings for _config and vector_field.py
Syrus Dark13a6c5b880b8
diff --git a/manim/_config/__init__.py b/manim/_config/__init__.pyindex 7dbf32234..17a513bba 100644--- a/manim/_config/__init__.py+++ b/manim/_config/__init__.py@@ -2,9 +2,10 @@import loggingfrom contextlib import contextmanager+from typing import Generator, Unionfrom .logger_utils import make_logger-from .utils import make_config_parser, ManimConfig, ManimFrame+from .utils import ManimConfig, ManimFrame, make_config_parser__all__ = ["logger",@@ -30,7 +31,7 @@ frame = ManimFrame(config)# This has to go here because it needs access to this module's config@contextmanager-def tempconfig(temp):+def tempconfig(temp:Union[ManimConfig,dict]) -> Generator[int, float, None]: #doubtful"""Context manager that temporarily modifies the global ``config`` object.Inside the ``with`` statement, the modified config will be used. Afterdiff --git a/manim/_config/cfg_subcmds.py b/manim/_config/cfg_subcmds.pyindex 6427836de..1d0a7af75 100644--- a/manim/_config/cfg_subcmds.py+++ b/manim/_config/cfg_subcmds.py@@ -9,22 +9,25 @@ The functions below can be called via the `manim cfg` subcommand.import osfrom ast import literal_eval+from typing import Union-from manim import console, config+from manim import config, consolefrom manim._config.utils import config_file_paths, make_config_parserfrom manim.utils.file_ops import guarantee_existence, open_file+from rich.errors import StyleSyntaxError+from rich.style import Style__all__ = ["write", "show", "export"]-RICH_COLOUR_INSTRUCTIONS = """+RICH_COLOUR_INSTRUCTIONS:str = """[red]The default colour is used by the input statement.If left empty, the default colour will be used.[/red][magenta] For a full list of styles, visit[/magenta] [green]https://rich.readthedocs.io/en/latest/style.html[/green]"""-RICH_NON_STYLE_ENTRIES = ["log.width", "log.height", "log.timestamps"]+RICH_NON_STYLE_ENTRIES:str = ["log.width", "log.height", "log.timestamps"]-def value_from_string(value):+def value_from_string(value:str) -> Union[str,int,bool]:"""Extracts the literal of proper datatype from a string.Parameters----------@@ -43,7 +46,7 @@ def value_from_string(value):return value-def _is_expected_datatype(value, expected, style=False):+def _is_expected_datatype(value:str, expected:str, style:bool=False) -> bool:"""Checks whether `value` is the same datatype as `expected`,and checks if it is a valid `style` if `style` is true.@@ -68,7 +71,7 @@ def _is_expected_datatype(value, expected, style=False):return isinstance(value, expected) and (is_valid_style(value) if style else True)-def is_valid_style(style):+def is_valid_style(style:str) -> bool:"""Checks whether the entered color is a valid color according to richParameters----------@@ -86,7 +89,7 @@ def is_valid_style(style):return False-def replace_keys(default):+def replace_keys(default:dict) -> dict:"""Replaces _ to . and viceversa in a dictionary for richParameters----------@@ -111,7 +114,7 @@ def replace_keys(default):return default-def write(level=None, openfile=False):+def write(level:str=None, openfile:bool=False)-> None:config_paths = config_file_paths()console.print("[yellow bold]Manim Configuration File Writer[/yellow bold]", justify="center"@@ -205,7 +208,7 @@ modify write_cfg_subcmd_input to account for it."""open_file(cfg_file_path)-def show():+def show() -> None:parser = make_config_parser()rich_non_style_entries = [a.replace(".", "_") for a in RICH_NON_STYLE_ENTRIES]for category in parser:diff --git a/manim/_config/logger_utils.py b/manim/_config/logger_utils.pyindex 82d83132f..2e520a047 100644--- a/manim/_config/logger_utils.py+++ b/manim/_config/logger_utils.py@@ -10,11 +10,13 @@ format."""+from manim._config.utils import ManimConfigimport osimport loggingimport jsonimport copy-+import configparser+import typingfrom rich.console import Consolefrom rich.logging import RichHandlerfrom rich.theme import Theme@@ -43,7 +45,9 @@ Loading the default color configuration.[/logging.level.error]"""-def make_logger(parser, verbosity):+def make_logger(+ parser: configparser.ConfigParser, verbosity: str+) -> typing.Tuple[logging.Logger, Console]:"""Make the manim logger and console.Parameters@@ -70,7 +74,7 @@ def make_logger(parser, verbosity):configuring the logger at the top level."""- # Throughout the codebase, use Console.print() instead of print()+ # Throughout the codebase, use console.print() instead of print()theme = parse_theme(parser)console = Console(theme=theme)@@ -88,7 +92,7 @@ def make_logger(parser, verbosity):return logger, console-def parse_theme(parser):+def parse_theme(parser: configparser.ConfigParser) -> Theme:"""Configure the rich style of logger and console output.Parameters@@ -128,7 +132,7 @@ def parse_theme(parser):return custom_theme-def set_file_logger(config, verbosity):+def set_file_logger(config: ManimConfig, verbosity: str) -> None:"""Add a file handler to manim logger.The path to the file is built using ``config.log_dir``.@@ -179,7 +183,7 @@ class JSONFormatter(logging.Formatter):"""- def format(self, record):+ def format(self, record: dict) -> str:"""Format the record in a custom JSON format."""record_c = copy.deepcopy(record)if record_c.args:diff --git a/manim/_config/main_utils.py b/manim/_config/main_utils.pyindex 970fc6004..fddc73c87 100644--- a/manim/_config/main_utils.py+++ b/manim/_config/main_utils.py@@ -2,14 +2,14 @@import osimport argparse-+import typingfrom manim import constants__all__ = ["parse_args"]-def _find_subcommand(args):+def _find_subcommand(args:list) -> typing.Union[str,None]:"""Return the subcommand that has been passed, if any.Parameters@@ -19,7 +19,7 @@ def _find_subcommand(args):Returns-------- Optional[:class:`str`]+ typing.Union[:class:`str`,None]If a subcommand is found, returns the string of its name. Returns Noneotherwise.@@ -40,7 +40,7 @@ def _find_subcommand(args):return None-def _init_cfg_subcmd(subparsers):+def _init_cfg_subcmd(subparsers:argparse._SubParsersAction) -> argparse.ArgumentParser:"""Initialises the subparser for the `cfg` subcommand.Parameters@@ -74,7 +74,7 @@ def _init_cfg_subcmd(subparsers):return cfg_related-def _str2bool(s):+def _str2bool(s:str) -> bool:"""Helper function that handles boolean CLI arguments."""if s == "True":return True@@ -84,7 +84,7 @@ def _str2bool(s):raise argparse.ArgumentTypeError("True or False expected")-def parse_args(args):+def parse_args(args:list)->argparse.Namespace:"""Parse CLI arguments.Parameters@@ -115,7 +115,7 @@ def parse_args(args):return _parse_args_no_subcmd(args)-def _parse_args_cfg_subcmd(args):+def _parse_args_cfg_subcmd(args:list) -> argparse.Namespace:"""Parse arguments of the form 'manim cfg <subcmd> <args>'."""parser = argparse.ArgumentParser(description="Animation engine for explanatory math videos",@@ -153,7 +153,7 @@ def _parse_args_cfg_subcmd(args):return parsed-def _parse_args_plugins(args):+def _parse_args_plugins(args:list) -> argparse.Namespace:"""Parse arguments of the form 'manim plugins <args>'."""parser = argparse.ArgumentParser(description="Utility command for managing plugins",@@ -173,7 +173,7 @@ def _parse_args_plugins(args):return parsed-def _parse_args_no_subcmd(args):+def _parse_args_no_subcmd(args:list)->argparse.Namespace:"""Parse arguments of the form 'manim <args>', when no command is present."""parser = argparse.ArgumentParser(description="Animation engine for explanatory math videos",diff --git a/manim/_config/utils.py b/manim/_config/utils.pyindex 328328561..4eb0011f0 100644--- a/manim/_config/utils.py+++ b/manim/_config/utils.py@@ -10,23 +10,25 @@ See :doc:`/tutorials/configuration` for an introduction to Manim's configuration"""-import os-import sys+import configparserimport copyimport logging-import configparser-from pathlib import Path+import os+import sys+import typingfrom collections.abc import Mapping, MutableMapping+from pathlib import Path-import numpy as npimport colour+import numpy as np+import numpy.typing as nptfrom .. import constantsfrom ..utils.tex import TexTemplate, TexTemplateFromFilefrom .logger_utils import set_file_logger-def config_file_paths():+def config_file_paths() -> typing.List[Path]:"""The paths where ``.cfg`` files will be searched for.When manim is first imported, it processes any ``.cfg`` files it finds. This@@ -69,7 +71,7 @@ def config_file_paths():return [library_wide, user_wide, folder_wide]-def make_config_parser(custom_file=None):+def make_config_parser(custom_file: str = None) -> configparser.ConfigParser:"""Make a :class:`ConfigParser` object and load any ``.cfg`` files.The user-wide file, if it exists, overrides the library-wide file. The@@ -112,7 +114,7 @@ def make_config_parser(custom_file=None):return parser-def _determine_quality(args):+def _determine_quality(args) -> str: # what is args type??old_qualities = {"k": "fourk_quality","e": "high_quality",@@ -291,30 +293,30 @@ class ManimConfig(MutableMapping):"write_to_movie",}- def __init__(self):+ def __init__(self) -> None:self._d = {k: None for k in self._OPTS}# behave like a dict- def __iter__(self):+ def __iter__(self) -> typing.Iterator[str]:return iter(self._d)- def __len__(self):+ def __len__(self) -> int:return len(self._d)- def __contains__(self, key):+ def __contains__(self, key) -> bool:try:self.__getitem__(key)return Trueexcept AttributeError:return False- def __getitem__(self, key):+ def __getitem__(self, key) -> typing.Any:return getattr(self, key)- def __setitem__(self, key, val):+ def __setitem__(self, key, val) -> None: # what is the type here?getattr(ManimConfig, key).fset(self, val) # fset is the property's setter- def update(self, obj):+ def update(self, obj: typing.Union[ManimConfig, dict]) -> None:"""Digest the options found in another :class:`ManimConfig` or in a dict.Similar to :meth:`dict.update`, replaces the values of this object with@@ -356,14 +358,14 @@ class ManimConfig(MutableMapping):self[k] = v# don't allow to delete anything- def __delitem__(self, key):+ def __delitem__(self, key): # typing?raise AttributeError("'ManimConfig' object does not support item deletion")- def __delattr__(self, key):+ def __delattr__(self, key): # typing?raise AttributeError("'ManimConfig' object does not support item deletion")# copy functions- def copy(self):+ def copy(self) -> ManimConfig:"""Deepcopy the contents of this ManimConfig.Returns@@ -382,11 +384,11 @@ class ManimConfig(MutableMapping):"""return copy.deepcopy(self)- def __copy__(self):+ def __copy__(self) -> ManimConfig:"""See ManimConfig.copy()."""return copy.deepcopy(self)- def __deepcopy__(self, memo):+ def __deepcopy__(self, memo) -> ManimConfig: # typing?"""See ManimConfig.copy()."""c = ManimConfig()# Deepcopying the underlying dict is enough because all properties@@ -396,21 +398,23 @@ class ManimConfig(MutableMapping):return c# helper type-checking methods- def _set_from_list(self, key, val, values):+ def _set_from_list(+ self, key: str, val: typing.Union[str, int], values: list+ ) -> None: # correct?"""Set ``key`` to ``val`` if ``val`` is contained in ``values``."""if val in values:self._d[key] = valelse:raise ValueError(f"attempted to set {key} to {val}; must be in {values}")- def _set_boolean(self, key, val):+ def _set_boolean(self, key: typing.Union[str, int], val: typing.Any) -> None:"""Set ``key`` to ``val`` if ``val`` is Boolean."""if val in [True, False]:self._d[key] = valelse:raise ValueError(f"{key} must be boolean")- def _set_str(self, key, val):+ def _set_str(self, key: typing.Union[str, int], val: typing.Any) -> None:"""Set ``key`` to ``val`` if ``val`` is a string."""if isinstance(val, str):self._d[key] = val@@ -419,14 +423,18 @@ class ManimConfig(MutableMapping):else:raise ValueError(f"{key} must be str or falsy value")- def _set_between(self, key, val, lo, hi):+ def _set_between(+ self, key: typing.Union[str, int], val: int, lo: int, hi: int+ ) -> None:"""Set ``key`` to ``val`` if lo <= val <= hi."""if lo <= val <= hi:self._d[key] = valelse:raise ValueError(f"{key} must be {lo} <= {key} <= {hi}")- def _set_pos_number(self, key, val, allow_inf):+ def _set_pos_number(+ self, key: typing.Union[str, int], val: int, allow_inf: bool+ ) -> None:"""Set ``key`` to ``val`` if ``val`` is a positive integer."""if isinstance(val, int) and val > -1:self._d[key] = val@@ -438,7 +446,7 @@ class ManimConfig(MutableMapping):)# builders- def digest_parser(self, parser):+ def digest_parser(self, parser: configparser.ConfigParser) -> ManimConfig:"""Process the config options present in a :class:`ConfigParser` object.This method processes arbitrary parsers, not only those read from a@@ -561,7 +569,7 @@ class ManimConfig(MutableMapping):return self- def digest_args(self, args):+ def digest_args(self, args: argparse.Namespace) -> ManimConfig:"""Process the config options present in CLI arguments.Parameters@@ -683,7 +691,7 @@ class ManimConfig(MutableMapping):return self- def digest_file(self, filename):+ def digest_file(self, filename: str) -> ManimConfig:"""Process the config options present in a ``.cfg`` file.This method processes a single ``.cfg`` file, whereas@@ -748,7 +756,7 @@ class ManimConfig(MutableMapping):return self._d["log_to_file"]@log_to_file.setter- def log_to_file(self, val):+ def log_to_file(self, val: str) -> None:self._set_boolean("log_to_file", val)if val:if not os.path.exists(self["log_dir"]):@@ -797,7 +805,7 @@ class ManimConfig(MutableMapping):return self._d["verbosity"]@verbosity.setter- def verbosity(self, val):+ def verbosity(self, val: str) -> None:"""Verbosity level of the logger."""self._set_from_list("verbosity",@@ -964,7 +972,7 @@ class ManimConfig(MutableMapping):return None@quality.setter- def quality(self, qual):+ def quality(self, qual: str) -> None:if qual not in constants.QUALITIES:raise KeyError(f"quality must be one of {list(constants.QUALITIES.keys())}")q = constants.QUALITIES[qual]@@ -977,7 +985,7 @@ class ManimConfig(MutableMapping):return self._d["background_opacity"] == 0.0@transparent.setter- def transparent(self, val):+ def transparent(self, val: bool) -> None:if val:self.png_mode = "RGBA"self.movie_file_extension = ".mov"@@ -999,7 +1007,7 @@ class ManimConfig(MutableMapping):)@dry_run.setter- def dry_run(self, val):+ def dry_run(self, val: bool) -> None:if val:self.write_to_movie = Falseself.write_all = False@@ -1020,7 +1028,7 @@ class ManimConfig(MutableMapping):self._d["use_js_renderer"]@use_js_renderer.setter- def use_js_renderer(self, val):+ def use_js_renderer(self, val: bool) -> None:self._d["use_js_renderer"] = valif val:self["disable_caching"] = True@@ -1037,7 +1045,7 @@ class ManimConfig(MutableMapping):doc="Main output directory. See :meth:`ManimConfig.get_dir`.",)- def get_dir(self, key, **kwargs):+ def get_dir(self, key: str, **kwargs: str) -> Path:"""Resolve a config option that stores a directory.Config options that store directories may depend on one another. This@@ -1185,7 +1193,7 @@ class ManimConfig(MutableMapping):return Path(path) if path else None- def _set_dir(self, key, val):+ def _set_dir(self, key: typing.Union[str, int], val: typing.Union[str, Path]):if isinstance(val, Path):self._d.__setitem__(key, str(val))else:@@ -1269,7 +1277,7 @@ class ManimConfig(MutableMapping):return self._tex_template@tex_template.setter- def tex_template(self, val):+ def tex_template(self, val: typing.Union[TexTemplateFromFile, TexTemplate]) -> None:if isinstance(val, (TexTemplateFromFile, TexTemplate)):self._tex_template = val@@ -1279,7 +1287,7 @@ class ManimConfig(MutableMapping):return self._d["tex_template_file"]@tex_template_file.setter- def tex_template_file(self, val):+ def tex_template_file(self, val: str) -> None:if val:if not os.access(val, os.R_OK):logging.getLogger("manim").warning(@@ -1294,7 +1302,7 @@ class ManimConfig(MutableMapping):class ManimFrame(Mapping):- _OPTS = {+ _OPTS: set[str] = {"pixel_width","pixel_height","aspect_ratio",@@ -1307,7 +1315,7 @@ class ManimFrame(Mapping):"left_side","right_side",}- _CONSTANTS = {+ _CONSTANTS: dict[str, npt.ArrayLike] = {"UP": np.array((0.0, 1.0, 0.0)),"DOWN": np.array((0.0, -1.0, 0.0)),"RIGHT": np.array((1.0, 0.0, 0.0)),@@ -1324,7 +1332,7 @@ class ManimFrame(Mapping):"DR": np.array((1.0, -1.0, 0.0)),}- def __init__(self, c):+ def __init__(self, c: ManimConfig) -> None:if not isinstance(c, ManimConfig):raise TypeError("argument must be instance of 'ManimConfig'")# need to use __dict__ directly because setting attributes is not@@ -1332,7 +1340,7 @@ class ManimFrame(Mapping):self.__dict__["_c"] = c# there are required by parent class Mapping to behave like a dict- def __getitem__(self, key):+ def __getitem__(self, key: typing.Union[str, int]) -> typing.Any:if key in self._OPTS:return self._c[key]elif key in self._CONSTANTS:@@ -1340,20 +1348,20 @@ class ManimFrame(Mapping):else:raise KeyError(key)- def __iter__(self):+ def __iter__(self) -> typing.Iterable:return iter(list(self._OPTS) + list(self._CONSTANTS))- def __len__(self):+ def __len__(self) -> int:return len(self._OPTS)# make this truly immutable- def __setattr__(self, attr, val):+ def __setattr__(self, attr, val) -> None:raise TypeError("'ManimFrame' object does not support item assignment")- def __setitem__(self, key, val):+ def __setitem__(self, key, val) -> None:raise TypeError("'ManimFrame' object does not support item assignment")- def __delitem__(self, key):+ def __delitem__(self, key) -> None:raise TypeError("'ManimFrame' object does not support item deletion")diff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.pyindex 0c27b82ee..f48c28819 100644--- a/manim/mobject/vector_field.py+++ b/manim/mobject/vector_field.py@@ -13,7 +13,8 @@ __all__ = ["move_points_along_vector_field",]-+from typing import Callable+import numpy.typing as nptimport numpy as npimport osimport itertools as it@@ -34,17 +35,18 @@ from ..utils.color import rgb_to_colorfrom ..utils.rate_functions import linearfrom ..utils.simple_functions import sigmoidfrom ..utils.space_ops import get_norm+from ..mobject.mobject import Mobject# from ..utils.space_ops import normalize-DEFAULT_SCALAR_FIELD_COLORS = [BLUE_E, GREEN, YELLOW, RED]+DEFAULT_SCALAR_FIELD_COLORS: list = [BLUE_E, GREEN, YELLOW, RED]def get_colored_background_image(- scalar_field_func,- number_to_rgb_func,-):+ scalar_field_func: Callable, # TODO: What is taken as parameters?+ number_to_rgb_func: Callable,+) -> Image:ph = config["pixel_height"]pw = config["pixel_width"]fw = config["frame_width"]@@ -65,14 +67,14 @@ def get_colored_background_image(def get_rgb_gradient_function(- min_value=0,- max_value=1,- colors=[BLUE, RED],- flip_alphas=True, # Why?-):+ min_value: int = 0,+ max_value: int = 1,+ colors: list = [BLUE, RED],+ flip_alphas: bool = True, # Why?+) -> Callable[[npt.ArrayLike], float]:rgbs = np.array(list(map(color_to_rgb, colors)))- def func(values):+ def func(values: npt.ArrayLike):alphas = inverse_interpolate(min_value, max_value, np.array(values))alphas = np.clip(alphas, 0, 1)# if flip_alphas:@@ -89,8 +91,11 @@ def get_rgb_gradient_function(def get_color_field_image_file(- scalar_func, min_value=0, max_value=2, colors=DEFAULT_SCALAR_FIELD_COLORS-):+ scalar_func: Callable[[npt.ArrayLike],np.ndarray],+ min_value: int = 0,+ max_value: int = 2,+ colors: list = DEFAULT_SCALAR_FIELD_COLORS,+) -> str:# try_hashnp.random.seed(0)sample_inputs = 5 * np.random.random(size=(10, 3)) - 10@@ -110,12 +115,12 @@ def get_color_field_image_file(return full_path-def move_along_vector_field(mobject, func):+def move_along_vector_field(mobject: Mobject, func: Callable) -> Mobject:mobject.add_updater(lambda m, dt: m.shift(func(m.get_center()) * dt))return mobject-def move_submobjects_along_vector_field(mobject, func):+def move_submobjects_along_vector_field(mobject: Mobject, func: Callable) -> Mobject:def apply_nudge(mob, dt):for submob in mob:x, y = submob.get_center()[:2]@@ -126,7 +131,7 @@ def move_submobjects_along_vector_field(mobject, func):return mobject-def move_points_along_vector_field(mobject, func):+def move_points_along_vector_field(mobject: Mobject, func: Callable) -> Mobject:def apply_nudge(self, dt):self.mobject.apply_function(lambda p: p + func(p) * dt)@@ -140,7 +145,7 @@ def move_points_along_vector_field(mobject, func):class VectorField(VGroup):def __init__(self,- func,+ func: Callable,delta_x=0.5,delta_y=0.5,min_magnitude=0,diff --git a/manim/utils/bezier.py b/manim/utils/bezier.pyindex 3c9157b6d..90b35bfd7 100644--- a/manim/utils/bezier.py+++ b/manim/utils/bezier.py@@ -16,7 +16,7 @@ __all__ = [from scipy import linalgimport numpy as np-+from typing import Unionfrom ..utils.simple_functions import chooseCLOSED_THRESHOLD = 0.001@@ -53,7 +53,7 @@ def partial_bezier_points(points, a, b):# Linear interpolation variants-def interpolate(start, end, alpha):+def interpolate(start:int, end:int, alpha:float) -> float:return (1 - alpha) * start + alpha * end@@ -82,7 +82,7 @@ def mid(start, end):return (start + end) / 2.0-def inverse_interpolate(start, end, value):+def inverse_interpolate(start, end, value) -> np.ndarray:return np.true_divide(value - start, end - start)