Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Document config system (#659)

Leo Torresd0e04f8cc604
diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst
index aa2c4b892..fc43fe5d7 100644
--- a/docs/source/changelog.rst
+++ b/docs/source/changelog.rst
@@ -11,6 +11,16 @@ v0.2.0
Changes since Manim Community release v0.1.0
+Configuration
+^^^^^^^^^^^^^
+
+#. The global ``config`` dict has been replaced by a global ``config`` instance
+ of the new class :class:`~.ManimConfig`. This class has a dict-like API, so
+ this should not break user code, only make it more robust. See the
+ Configuration tutorial for details.
+
+
+
Mobjects, Scenes, and Animations
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -142,6 +152,3 @@ Other Changes
#. Rename package from manimlib to manim
#. Move all imports to :code:`__init__`, so :code:`from manim import *` replaces :code:`from manimlib.imports import *`
#. Global dir variable handling has been removed. Instead :code:`initialize_directories`, if needed, overrides the values from the cfg files at runtime.
-
-
-
diff --git a/docs/source/reference.rst b/docs/source/reference.rst
index 3dfc8cc6e..967871a6c 100644
--- a/docs/source/reference.rst
+++ b/docs/source/reference.rst
@@ -95,6 +95,19 @@ Cameras
~camera.three_d_camera
+*************
+Configuration
+*************
+
+.. autosummary::
+ :toctree: reference
+
+ ~_config
+ ~_config.utils
+ ~_config.main_utils
+ ~_config.logger_utils
+
+
*********
Utilities
*********
@@ -126,6 +139,5 @@ Other modules
.. autosummary::
:toctree: reference
- config
constants
container
diff --git a/docs/source/tutorials/configuration.rst b/docs/source/tutorials/configuration.rst
index 2fd3cd7a6..ddfec0a69 100644
--- a/docs/source/tutorials/configuration.rst
+++ b/docs/source/tutorials/configuration.rst
@@ -1,12 +1,60 @@
Configuration
-=============
+#############
Manim provides an extensive configuration system that allows it to adapt to
-many different use cases. The easiest way to do this is through the use of
-command line (or *CLI*) arguments.
+many different use cases. There are many configuration options that can be
+configured at different times during the scene rendering process. Each option
+can be configured programatically via `the ManimConfig class`_, or at the time
+of command invocation via `command line arguments`_, or at the time the library
+is first imported via `the config files`_.
-Command Line Arguments
+The ManimConfig class
+*********************
+
+The most direct way of configuring manim is via the global ``config`` object,
+which is an instance of :class:`.ManimConfig`. Each property of this class is
+a config option that can be accessed either with standard attribute syntax, or
+with dict-like syntax:
+
+.. code-block:: python
+
+ >>> from manim import *
+ >>> config.background_color = WHITE
+ >>> config['background_color'] = WHITE
+
+The former is preferred; the latter is provided mostly for backwards
+compatibility.
+
+Most classes, including :class:`.Camera`, :class:`.Mobject`, and
+:class:`.Animation`, read some of their default configuration from the global
+``config``.
+
+.. code-block:: python
+
+ >>> Camera({}).background_color
+ <Color white>
+ >>> config.background_color = RED # 0xfc6255
+ >>> Camera({}).background_color
+ <Color #fc6255>
+
+:class:`.ManimConfig` is designed to keep internal consistency. For example,
+setting ``frame_y_radius`` will affect ``frame_height``:
+
+.. code-block:: python
+
+ >>> config.frame_height
+ 8.0
+ >>> config.frame_y_radius = 5.0
+ >>> config.frame_height
+ 10.0
+
+The global ``config`` object is mean to be the single source of truth for all
+config options. All of the other ways of setting config options ultimately
+change the values of the global ``config`` object.
+
+
+Command line arguments
**********************
Usually, manim is ran from the command line by executing
@@ -22,98 +70,23 @@ high, and 4k quality, respectively.
.. code-block:: bash
- $ manim <file.py> SceneName -l
+ $ manim <file.py> SceneName -ql
-Another frequent flag is :code:`-p`, which makes manim show the rendered video
-right after it's done rendering.
-
-There are in fact many more command line flags that manim accepts. All the
-possible flags are shown by the following command.
-
-.. code-block:: bash
+These flags set the values of the config options ``config.pixel_width``,
+``config.pixel_height``, ``config.frame_rate``, and ``config.quality``.
- $ manim -h
+Another frequent flag is ``-p`` ("preview"), which makes manim show the rendered video
+right after it's done rendering.
-The output looks as follows.
+.. note:: The ``-p`` flag does not change any properties of the global
+ ``config`` dict. The ``-p`` flag is only a command line convenience.
-.. testcode::
- :hide:
- import subprocess
- result = subprocess.run(['manim', '-h'], stdout=subprocess.PIPE)
- print(result.stdout.decode('utf-8'))
-
-.. testoutput::
- :options: -ELLIPSIS, +NORMALIZE_WHITESPACE
+Examples
+========
- usage: manim file [flags] [scene [scene ...]]
- manim {cfg,init} [opts]
-
- Animation engine for explanatory math videos
-
- positional arguments:
- file Path to file holding the python code for the scene
- scene_names Name of the Scene class you want to see
-
- optional arguments:
- -h, --help show this help message and exit
- -o OUTPUT_FILE, --output_file OUTPUT_FILE
- Specify the name of the output file, if it should be different from the scene class name
- -p, --preview Automatically open the saved file once its done
- -f, --show_in_file_browser
- Show the output file in the File Browser
- --sound Play a success/failure sound
- --leave_progress_bars
- Leave progress bars displayed in terminal
- -a, --write_all Write all the scenes from a file
- -w, --write_to_movie Render the scene as a movie file (this is on by default)
- -s, --save_last_frame
- Save the last frame only (no movie file is generated)
- -g, --save_pngs Save each frame as a png
- -i, --save_as_gif Save the video as gif
- --disable_caching Disable caching (will generate partial-movie-files anyway)
- --flush_cache Remove all cached partial-movie-files
- --log_to_file Log terminal output to file
- -c BACKGROUND_COLOR, --background_color BACKGROUND_COLOR
- Specify background color
- --media_dir MEDIA_DIR
- Directory to store media (including video files)
- --log_dir LOG_DIR Directory to store log files
- --tex_template TEX_TEMPLATE
- Specify a custom TeX template file
- --dry_run Do a dry run (render scenes but generate no output files)
- -t, --transparent Render a scene with an alpha channel
- -q {k,p,h,m,l}, --quality {k,p,h,m,l}
- Render at specific quality, short form of the --*_quality flags
- --low_quality Render at low quality
- --medium_quality Render at medium quality
- --high_quality Render at high quality
- --production_quality Render at default production quality
- --fourk_quality Render at 4K quality
- -l DEPRECATED: USE -ql or --quality l
- -m DEPRECATED: USE -qm or --quality m
- -e DEPRECATED: USE -qh or --quality h
- -k DEPRECATED: USE -qk or --quality k
- -r RESOLUTION, --resolution RESOLUTION
- Resolution, passed as "height,width". Overrides the -l, -m, -e, and -k flags, if present
- -n FROM_ANIMATION_NUMBER, --from_animation_number FROM_ANIMATION_NUMBER
- Start rendering at the specified animation index, instead of the first animation. If you pass in two comma separated values, e.g. '3,6', it will end
- the rendering at the second value
- --use_js_renderer Render animations using the javascript frontend
- --js_renderer_path JS_RENDERER_PATH
- Path to the javascript frontend
- --config_file CONFIG_FILE
- Specify the configuration file
- --custom_folders Use the folders defined in the [custom_folders] section of the config file to define the output folder structure
- -v {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --verbosity {DEBUG,INFO,WARNING,ERROR,CRITICAL}
- Verbosity level. Also changes the ffmpeg log level unless the latter is specified in the config
- --progress_bar True/False
- Display the progress bar
-
- Made with <3 by the manim community devs
-
-For example, to render a scene in high quality, but only output the last frame
-of the scene instead of the whole video, you can execute
+To render a scene in high quality, but only output the last frame of the scene
+instead of the whole video, you can execute
.. code-block:: bash
@@ -129,76 +102,88 @@ open the file after it is rendered.
$ manim <file.py> SceneName -o myscene -i -n 0,10 -c WHITE
+.. tip:: There are many more command line flags that manim accepts. All the
+ possible flags are shown by executing ``manim -h``. A complete list
+ of CLI flags is at the end of this document.
The config files
****************
As the last example shows, executing manim from the command line may involve
-using many flags at the same. This may become a nuisance if you must execute
-the same file many times in a short time period, for example when making small
-incremental tweaks to your scene script. For this purpose, manim can also be
-configured using a configuration file.
+using many flags at the same time. This may become a nuisance if you must
+execute the same script many times in a short time period, for example when
+making small incremental tweaks to your scene script. For this purpose, manim
+can also be configured using a configuration file. A configuration file is a
+file ending with the suffix ``.cfg``.
To use a configuration file when rendering your scene, you must create a file
-with name :code:`manim.cfg` in the same directory as your scene code.
+with name ``manim.cfg`` in the same directory as your scene code.
-.. warning:: The config file **must** be named :code:`manim.cfg`. Currently,
- manim does not support config files with any other name.
+.. warning:: The config file **must** be named ``manim.cfg``. Currently, manim
+ does not support config files with any other name.
-The config file must start with a section header, usually :code:`[CLI]`. The
+The config file must start with the section header ``[CLI]``. The
configuration options under this header have the same name as the CLI flags,
and serve the same purpose. Take for example the following config file.
.. code-block::
[CLI]
+ # my config file
output_file = myscene
save_as_gif = True
background_color = WHITE
-Executing :code:`manim <file.py> SceneName` on a directory that contains this
-config file is equivalent to executing
+Config files are read with the standard python library ``configparser``. In
+particular, they will ignore any line that starts with a pound symbol ``#``.
+
+Now, executing the following command
.. code-block:: bash
$ manim <file.py> SceneName -o myscene -i -c WHITE
-on a directory that does not contain a config file.
+is equivalent to executing the following command, provided that ``manim.cfg``
+is in the same directory as <file.py>,
+
+.. code-block:: bash
-.. note:: The names of the configuration options admissible in config files are
- exactly the same as the **long names** of the corresponding command
- line flags. For example, the :code:`-c` and
- :code:`--background_color` flags are interchangeable, but the config
- file only accepts :code:`background_color` as an admissible option.
+ $ manim <file.py> SceneName
-.. note:: Configuration options that do not have command line analogues will be
- ignored. For a list of all the command line flags, see `Command Line
- Arguments`_.
+.. tip:: The names of the configuration options admissible in config files are
+ exactly the same as the **long names** of the corresponding command
+ line flags. For example, the ``-c`` and ``--background_color`` flags
+ are interchangeable, but the config file only accepts
+ :code:`background_color` as an admissible option.
-Manim will look for a :code:`manim.cfg` config file in the same directory as
-the file being rendered, and **not** in the directory of execution. For
-example,
+Since config files are meant to replace CLI flags, all CLI flags can be set via
+a config file. Moreover, any config option can be set via a config file,
+whether or not it has an associated CLI flag. For a list of all CLI flags and
+all config options, see the bottom of this document.
+
+Manim will look for a ``manim.cfg`` config file in the same directory as the
+file being rendered, and **not** in the directory of execution. For example,
.. code-block:: bash
- $ manim <file.py> path/to/SceneName -o myscene -i -c WHITE
+ $ manim <path/to/file.py> SceneName -o myscene -i -c WHITE
-will use the config file found in :code:`path/to/SceneName`, if any. It will
-**not** use the config file found in the current working directory, even if it
-exists. In this way, the user may keep different config files for different
-scenes or projects, and execute them with the right configuration from anywhere
-in the system.
+will use the config file found in ``path/to/file.py``, if any. It will **not**
+use the config file found in the current working directory, even if it exists.
+In this way, the user may keep different config files for different scenes or
+projects, and execute them with the right configuration from anywhere in the
+system.
-.. note:: Config files will ignore any line that starts with a pound symbol
- :code:`#`.
+The file described here is called the **folder-wide** config file, because it
+affects all scene scripts found in the same folder.
The user config file
-********************
+====================
As explained in the previous section, a :code:`manim.cfg` config file only
-affects the scene scripts in its same directory. However, the user may also
+affects the scene scripts in its same folder. However, the user may also
create a special config file that will apply to all scenes rendered by that
user. This is referred to as the **user-wide** config file, and it will apply
regardless of where manim is executed from, and regardless of where the scene
@@ -214,11 +199,9 @@ system.
Here, :code:`UserDirectory` is the user's home folder.
-.. note:: Config files that only apply to their own folder, explained in the
- previous section, are called **folder-wide** config files. A user
- may have many folder-wide config files, one per folder, but only one
- **user-wide** config file. Different users in the same computer may
- each have their own user-wide config file.
+.. note:: A user may have many **folder-wide** config files, one per folder,
+ but only one **user-wide** config file. Different users in the same
+ computer may each have their own user-wide config file.
.. warning:: Do not store scene scripts in the same folder as the user-wide
config file. In this case, the behavior is undefined.
@@ -228,7 +211,7 @@ user-wide config file and read its configuration.
Cascading config files
-**********************
+======================
What happens if you execute manim and it finds both a folder-wide config file
and a user-wide config file? Manim will read both files, but if they are
@@ -267,12 +250,172 @@ SceneName -c RED` is equivalent to not using any config files and executing
manim <file.py> SceneName -o myscene -c RED
-To summarize, the order of precedence for configuration options is: *user-wide
-config file < folder-wide config file < CLI flags*.
+There is also a **library-wide** config file that determines manim's default
+behavior, and applies to every user of the library. It has the least
+precedence, so any config options in the user-wide and any folder-wide files
+will override the library-wide file. This is referred to as the *cascading*
+config file system.
+
+.. warning:: **The user should not try to modify the library-wide file**.
+ Contributors should receive explicit confirmation from the core
+ developer team before modifying it.
+
+
+Order of operations
+*******************
+
+With so many different ways of configuring manim, it can be difficult to know
+when each config option is being set. In fact, this will depend on how manim
+is being used.
+
+If manim is imported from a module, then the configuration system will follow
+these steps:
+
+1. The library-wide config file is loaded.
+2. The user-wide and folder-wide files are loaded, if they exist.
+3. All files found in the previous two steps are parsed in a single
+ :class:`ConfigParser` object, called ``parser``. This is where *cascading*
+ happens.
+4. :class:`logging.Logger` is instantiated to create manim's global ``logger``
+ object. It is configured using the "logger" section of the parser,
+ i.e. ``parser['logger']``.
+5. :class:`ManimConfig` is instantiated to create the global ``config`` object.
+6. The ``parser`` from step 3 is fed into the ``config`` from step 5 via
+ :meth:`ManimConfig.digest_parser`.
+6. Both ``logger`` and ``config`` are exposed to the user.
+
+If manim is being invoked from the command line, all of the previous steps
+happen, and are complemented by:
+
+7. The CLI flags are parsed and fed into ``config`` via
+ :meth:`~ManimConfig.digest_args`.
+8. If the ``--config_file`` flag was used, a new :class:`ConfigParser` object
+ is created with the contents of the library-wide file, the user-wide file if
+ it exists, and the file passed via ``--config_file``. In this case, the
+ folder-wide file, if it exists, is ignored.
+9. The new parser is fed into ``config``.
+10. The rest of the CLI flags are processed.
+
+To summarize, the order of precedence for configuration options, from lowest to
+highest precedence, is:
+
+1. Library-wide config file,
+2. user-wide config file, if it exists,
+3. folder-wide config file, if it exists OR custom config file, if passed via
+ ``--config_file``,
+4. other CLI flags, and
+5. any programmatic changes made after the config system is set.
+
+
+A list of all config options
+****************************
+
+.. testcode::
+ :hide:
+
+ from manim._config import ManimConfig
+ from inspect import getmembers
+ sorted([n for n, _ in getmembers(ManimConfig, lambda v: isinstance(v, property))])
+
+.. testoutput::
+ :options: -ELLIPSIS, +NORMALIZE_WHITESPACE
+
+ ['aspect_ratio', 'background_color', 'background_opacity', 'bottom',
+ 'custom_folders', 'disable_caching', 'dry_run', 'ffmpeg_loglevel',
+ 'flush_cache', 'frame_height', 'frame_rate', 'frame_size', 'frame_width',
+ 'frame_x_radius', 'frame_y_radius', 'from_animation_number', 'images_dir',
+ 'input_file', 'js_renderer_path', 'leave_progress_bars', 'left_side',
+ 'log_dir', 'log_to_file', 'max_files_cached', 'media_dir',
+ 'movie_file_extension', 'output_file', 'partial_movie_dir', 'pixel_height',
+ 'pixel_width', 'png_mode', 'preview', 'progress_bar', 'quality',
+ 'right_side', 'save_as_gif', 'save_last_frame', 'save_pngs', 'scene_names',
+ 'show_in_file_browser', 'skip_animations', 'sound', 'tex_dir',
+ 'tex_template', 'tex_template_file', 'text_dir', 'top', 'transparent',
+ 'upto_animation_number', 'use_js_renderer', 'verbosity', 'video_dir',
+ 'write_all', 'write_to_movie']
+
+
+A list of all CLI flags
+***********************
+
+.. testcode::
+ :hide:
+ import subprocess
+ result = subprocess.run(['manim', '-h'], stdout=subprocess.PIPE)
+ print(result.stdout.decode('utf-8'))
+
+.. testoutput::
+ :options: -ELLIPSIS, +NORMALIZE_WHITESPACE
-.. note:: There is also a **library-wide** config file that determines manim's
- default behavior, and applies to every user of the library. It has
- the least precedence, and **the user should not try to modify it**.
- Developers should receive explicit confirmation from the core
- developer team before modifying it.
+ usage: manim [-h] [-o OUTPUT_FILE] [-p] [-f] [--leave_progress_bars] [-a] [-w] [-s] [-g] [-i] [--disable_caching] [--flush_cache] [--log_to_file] [-c BACKGROUND_COLOR]
+ [--background_opacity BACKGROUND_OPACITY] [--media_dir MEDIA_DIR] [--log_dir LOG_DIR] [--tex_template TEX_TEMPLATE] [--dry_run] [-t] [-q {k,p,h,m,l}]
+ [--low_quality] [--medium_quality] [--high_quality] [--production_quality] [--fourk_quality] [-l] [-m] [-e] [-k] [-r RESOLUTION] [-n FROM_ANIMATION_NUMBER]
+ [--use_js_renderer] [--js_renderer_path JS_RENDERER_PATH] [--config_file CONFIG_FILE] [--custom_folders] [-v {DEBUG,INFO,WARNING,ERROR,CRITICAL}]
+ [--progress_bar True/False]
+ {cfg} ... file [scene_names [scene_names ...]]
+
+ Animation engine for explanatory math videos
+
+ positional arguments:
+ {cfg}
+ file path to file holding the python code for the scene
+ scene_names Name of the Scene class you want to see
+
+ optional arguments:
+ -h, --help show this help message and exit
+ -o OUTPUT_FILE, --output_file OUTPUT_FILE
+ Specify the name of the output file, if it should be different from the scene class name
+ -p, --preview Automatically open the saved file once its done
+ -f, --show_in_file_browser
+ Show the output file in the File Browser
+ --leave_progress_bars
+ Leave progress bars displayed in terminal
+ -a, --write_all Write all the scenes from a file
+ -w, --write_to_movie Render the scene as a movie file (this is on by default)
+ -s, --save_last_frame
+ Save the last frame only (no movie file is generated)
+ -g, --save_pngs Save each frame as a png
+ -i, --save_as_gif Save the video as gif
+ --disable_caching Disable caching (will generate partial-movie-files anyway)
+ --flush_cache Remove all cached partial-movie-files
+ --log_to_file Log terminal output to file
+ -c BACKGROUND_COLOR, --background_color BACKGROUND_COLOR
+ Specify background color
+ --background_opacity BACKGROUND_OPACITY
+ Specify background opacity
+ --media_dir MEDIA_DIR
+ Directory to store media (including video files)
+ --log_dir LOG_DIR Directory to store log files
+ --tex_template TEX_TEMPLATE
+ Specify a custom TeX template file
+ --dry_run Do a dry run (render scenes but generate no output files)
+ -t, --transparent Render a scene with an alpha channel
+ -q {k,p,h,m,l}, --quality {k,p,h,m,l}
+ Render at specific quality, short form of the --*_quality flags
+ --low_quality Render at low quality
+ --medium_quality Render at medium quality
+ --high_quality Render at high quality
+ --production_quality Render at default production quality
+ --fourk_quality Render at 4K quality
+ -l DEPRECATED: USE -ql or --quality l
+ -m DEPRECATED: USE -qm or --quality m
+ -e DEPRECATED: USE -qh or --quality h
+ -k DEPRECATED: USE -qk or --quality k
+ -r RESOLUTION, --resolution RESOLUTION
+ Resolution, passed as "height,width". Overrides any quality flags, if present
+ -n FROM_ANIMATION_NUMBER, --from_animation_number FROM_ANIMATION_NUMBER
+ Start rendering at the specified animation index, instead of the first animation. If you pass in two comma separated values, e.g. '3,6', it will end
+ the rendering at the second value
+ --use_js_renderer Render animations using the javascript frontend
+ --js_renderer_path JS_RENDERER_PATH
+ Path to the javascript frontend
+ --config_file CONFIG_FILE
+ Specify the configuration file
+ --custom_folders Use the folders defined in the [custom_folders] section of the config file to define the output folder structure
+ -v {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --verbosity {DEBUG,INFO,WARNING,ERROR,CRITICAL}
+ Verbosity level. Also changes the ffmpeg log level unless the latter is specified in the config
+ --progress_bar True/False
+ Display the progress bar
+
+ Made with <3 by the manim community devs
diff --git a/manim/__init__.py b/manim/__init__.py
index c1515d101..96d3eb321 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -2,7 +2,7 @@
# Importing the config module should be the first thing we do, since other
# modules depend on the global config dict for initialization.
-from .config import *
+from ._config import *
from .constants import *
diff --git a/manim/__main__.py b/manim/__main__.py
index ff4c657b2..d5aa10cf9 100644
--- a/manim/__main__.py
+++ b/manim/__main__.py
@@ -12,7 +12,7 @@ from manim.utils.module_ops import (
)
from manim.utils.file_ops import open_file as open_media_file
from manim.grpc.impl import frame_server_impl
-from manim.config.main_utils import *
+from manim._config.main_utils import parse_args
def open_file_if_needed(file_writer):
diff --git a/manim/config/__init__.py b/manim/_config/__init__.py
similarity index 66%
rename from manim/config/__init__.py
rename to manim/_config/__init__.py
index 491b14a89..7dbf32234 100644
--- a/manim/config/__init__.py
+++ b/manim/_config/__init__.py
@@ -1,7 +1,9 @@
+"""Set the global config and logger."""
+
import logging
from contextlib import contextmanager
-from .logger import make_logger
+from .logger_utils import make_logger
from .utils import make_config_parser, ManimConfig, ManimFrame
__all__ = [
@@ -22,38 +24,39 @@ logger, console = make_logger(parser["logger"], parser["CLI"]["verbosity"])
logging.getLogger("PIL").setLevel(logging.INFO)
logging.getLogger("matplotlib").setLevel(logging.INFO)
-config = ManimConfig(parser)
+config = ManimConfig().digest_parser(parser)
frame = ManimFrame(config)
# This has to go here because it needs access to this module's config
@contextmanager
def tempconfig(temp):
- """Context manager that temporarily modifies the global config dict.
+ """Context manager that temporarily modifies the global ``config`` object.
- The code block inside the ``with`` statement will use the modified config.
- After the code block, the config will be restored to its original value.
+ Inside the ``with`` statement, the modified config will be used. After
+ context manager exits, the config will be restored to its original state.
Parameters
----------
-
- temp : :class:`dict`
- A dictionary whose keys will be used to temporarily update the global
- config.
+ temp : Union[:class:`ManimConfig`, :class:`dict`]
+ Object whose keys will be used to temporarily update the global
+ ``config``.
Examples
--------
+
Use ``with tempconfig({...})`` to temporarily change the default values of
- certain objects.
+ certain config options.
- .. code_block:: python
+ .. code-block:: python
- c = Camera()
- c.frame_width == config['frame_width'] # -> True
- with tempconfig({'frame_width': 100}):
- c = Camera()
- c.frame_width == config['frame_width'] # -> False
- c.frame_width == 100 # -> True
+ >>> config['frame_height']
+ 8.0
+ >>> with tempconfig({'frame_height': 100.0}):
+ ... print(config['frame_height'])
+ 100.0
+ >>> config['frame_height']
+ 8.0
"""
global config
diff --git a/manim/config/cfg_subcmds.py b/manim/_config/cfg_subcmds.py
similarity index 99%
rename from manim/config/cfg_subcmds.py
rename to manim/_config/cfg_subcmds.py
index 9595e6b20..b1cdd3ddb 100644
--- a/manim/config/cfg_subcmds.py
+++ b/manim/_config/cfg_subcmds.py
@@ -11,7 +11,7 @@ import os
from ast import literal_eval
from manim import logger, console, config
-from manim.config.utils import config_file_paths, make_config_parser
+from manim._config.utils import config_file_paths, make_config_parser
from manim.utils.file_ops import guarantee_existence, open_file
__all__ = ["write", "show", "export"]
diff --git a/manim/config/default.cfg b/manim/_config/default.cfg
similarity index 100%
rename from manim/config/default.cfg
rename to manim/_config/default.cfg
diff --git a/manim/config/logger.py b/manim/_config/logger_utils.py
similarity index 58%
rename from manim/config/logger.py
rename to manim/_config/logger_utils.py
index 2b3c788e2..82d83132f 100644
--- a/manim/config/logger.py
+++ b/manim/_config/logger_utils.py
@@ -1,8 +1,12 @@
-"""
-logger.py
----------
+"""Utilities to create and set the logger.
+
+Manim's logger can be accessed as ``manim.logger``, or as
+``logging.getLogger("manim")``, once the library has been imported. Manim also
+exports a second object, ``console``, which should be used to print on screen
+messages that need not be logged.
-Functions to create and set the logger.
+Both ``logger`` and ``console`` use the ``rich`` library to produce rich text
+format.
"""
@@ -11,7 +15,6 @@ import logging
import json
import copy
-
from rich.console import Console
from rich.logging import RichHandler
from rich.theme import Theme
@@ -41,7 +44,32 @@ Loading the default color configuration.[/logging.level.error]
def make_logger(parser, verbosity):
- """Make the manim logger and the console."""
+ """Make the manim logger and console.
+
+ Parameters
+ ----------
+ parser : :class:`configparser.ConfigParser`
+ A parser containing any .cfg files in use.
+
+ verbosity : :class:`str`
+ The verbosity level of the logger.
+
+ Returns
+ -------
+ :class:`logging.Logger`, :class:`rich.Console`
+ The manim logger and console. Both use the theme returned by
+ :func:`parse_theme`
+
+ See Also
+ --------
+ :func:`~._config.utils.make_config_parser`, :func:`parse_theme`
+
+ Notes
+ -----
+ The ``parser`` is assumed to contain only the options related to
+ configuring the logger at the top level.
+
+ """
# Throughout the codebase, use Console.print() instead of print()
theme = parse_theme(parser)
console = Console(theme=theme)
@@ -60,22 +88,33 @@ def make_logger(parser, verbosity):
return logger, console
-def parse_theme(config_logger):
- theme = dict(
- zip(
- [key.replace("_", ".") for key in config_logger.keys()],
- list(config_logger.values()),
- )
- )
+def parse_theme(parser):
+ """Configure the rich style of logger and console output.
- theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"])
+ Parameters
+ ----------
+ parser : :class:`configparser.ConfigParser`
+ A parser containing any .cfg files in use.
+ Returns
+ -------
+ :class:`rich.Theme`
+ The rich theme to be used by the manim logger.
+
+ See Also
+ --------
+ :func:`make_logger`.
+
+ """
+ theme = {key.replace("_", "."): parser[key] for key in parser}
+
+ theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"])
theme["log.height"] = (
None if theme["log.height"] == "-1" else int(theme["log.height"])
)
theme["log.timestamps"] = False
try:
- customTheme = Theme(
+ custom_theme = Theme(
{
k: v
for k, v in theme.items()
@@ -84,12 +123,30 @@ def parse_theme(config_logger):
)
except (color.ColorParseError, errors.StyleSyntaxError):
printf(WRONG_COLOR_CONFIG_MSG)
- customTheme = None
+ custom_theme = None
- return customTheme
+ return custom_theme
def set_file_logger(config, verbosity):
+ """Add a file handler to manim logger.
+
+ The path to the file is built using ``config.log_dir``.
+
+ Parameters
+ ----------
+ config : :class:`ManimConfig`
+ The global config, used to determine the log file path.
+
+ verbosity : :class:`str`
+ The verbosity level of the logger.
+
+ Notes
+ -----
+ Calling this function changes the verbosity of all handlers assigned to
+ manim logger.
+
+ """
# Note: The log file name will be
# <name_of_animation_file>_<name_of_scene>.log, gotten from config. So it
# can differ from the real name of the scene. <name_of_scene> would only
@@ -110,13 +167,20 @@ def set_file_logger(config, verbosity):
logger = logging.getLogger("manim")
logger.addHandler(file_handler)
logger.info("Log file will be saved in %(logpath)s", {"logpath": log_file_path})
+
+ config.verbosity = verbosity
logger.setLevel(verbosity)
class JSONFormatter(logging.Formatter):
- """Subclass of `:class:`logging.Formatter`, to build our own format of the logs (JSON)."""
+ """A formatter that outputs logs in a custom JSON format.
+
+ This class is used internally for testing purposes.
+
+ """
def format(self, record):
+ """Format the record in a custom JSON format."""
record_c = copy.deepcopy(record)
if record_c.args:
for arg in record_c.args:
diff --git a/manim/config/main_utils.py b/manim/_config/main_utils.py
similarity index 95%
rename from manim/config/main_utils.py
rename to manim/_config/main_utils.py
index 5ae6ec176..1e3075c8f 100644
--- a/manim/config/main_utils.py
+++ b/manim/_config/main_utils.py
@@ -1,10 +1,4 @@
-"""
-main_utils.py
--------------
-
-Functions called from __main__.py to interact with the config.
-
-"""
+"""Utilities called from ``__main__.py`` to interact with the config."""
import os
import sys
@@ -15,10 +9,13 @@ import colour
from manim import constants, logger, config
from .utils import make_config_parser
-from .logger import JSONFormatter
+from .logger_utils import JSONFormatter
from ..utils.tex import TexTemplate, TexTemplateFromFile
+__all__ = ["parse_args"]
+
+
def _find_subcommand(args):
"""Return the subcommand that has been passed, if any.
@@ -84,6 +81,7 @@ def _init_cfg_subcmd(subparsers):
def _str2bool(s):
+ """Helper function that handles boolean CLI arguments."""
if s == "True":
return True
elif s == "False":
@@ -93,6 +91,19 @@ def _str2bool(s):
def parse_args(args):
+ """Parse CLI arguments.
+
+ Parameters
+ ----------
+ args : :class:`list`
+ A list of arguments; generally, this should be ``sys.argv``.
+
+ Returns
+ -------
+ :class:`argparse.Namespace`
+ An object returned by ``argparse.parse_args``.
+
+ """
if args[0] == "python" and args[1] == "-m":
args = args[2:]
@@ -144,6 +155,7 @@ def _parse_args_cfg_subcmd(args):
def _parse_args_no_subcmd(args):
+ """Parse arguments of the form 'manim <args>', when no command is present."""
parser = argparse.ArgumentParser(
description="Animation engine for explanatory math videos",
prog="manim",
diff --git a/manim/config/utils.py b/manim/_config/utils.py
similarity index 59%
rename from manim/config/utils.py
rename to manim/_config/utils.py
index 2dded4437..f7ba1c981 100644
--- a/manim/config/utils.py
+++ b/manim/_config/utils.py
@@ -1,8 +1,12 @@
-"""
-utils.py
---------
+"""Utilities to create and set the config.
+
+The main class exported by this module is :class:`ManimConfig`. This class
+contains all configuration options, including frame geometry (e.g. frame
+height/width, frame rate), output (e.g. directories, logging), styling
+(e.g. background color, transparency), and general behavior (e.g. writing a
+movie vs writing a single frame).
-Functions to create and set the config.
+See :doc:`tutorials/configuration` for an introduction to Manim's configuration system.
"""
@@ -19,10 +23,43 @@ import colour
from .. import constants
from ..utils.tex import TexTemplate, TexTemplateFromFile
-from .logger import set_file_logger
+from .logger_utils import set_file_logger
def config_file_paths():
+ """The paths where ``.cfg`` files will be searched for.
+
+ When manim is first imported, it processes any ``.cfg`` files it finds. This
+ function returns the locations in which these files are searched for. In
+ ascending order of precedence, these are: the library-wide config file, the
+ user-wide config file, and the folder-wide config file.
+
+ The library-wide config file determines manim's default behavior. The
+ user-wide config file is stored in the user's home folder, and determines
+ the behavior of manim whenever the user invokes it from anywhere in the
+ system. The folder-wide config file only affects scenes that are in the
+ same folder. The latter two files are optional.
+
+ These files, if they exist, are meant to loaded into a single
+ :class:`configparser.ConfigParser` object, and then processed by
+ :class:`ManimConfig`.
+
+ Returns
+ -------
+ List[:class:`Path`]
+ List of paths which may contain ``.cfg`` files, in ascending order of
+ precedence.
+
+ See Also
+ --------
+ :func:`make_config_parser`, :meth:`ManimConfig.digest_file`,
+ :meth:`ManimConfig.digest_parser`
+
+ Notes
+ -----
+ The location of the user-wide config file is OS-specific.
+
+ """
library_wide = Path.resolve(Path(__file__).parent / "default.cfg")
if sys.platform.startswith("win32"):
user_wide = Path.home() / "AppData" / "Roaming" / "Manim" / "manim.cfg"
@@ -33,20 +70,31 @@ def config_file_paths():
def make_config_parser(custom_file=None):
- """Make a ConfigParser object and load the .cfg files.
+ """Make a :class:`ConfigParser` object and load any ``.cfg`` files.
+
+ The user-wide file, if it exists, overrides the library-wide file. The
+ folder-wide file, if it exists, overrides the other two.
+
+ The folder-wide file can be ignored by passing ``custom_file``. However,
+ the user-wide and library-wide config files cannot be ignored.
Parameters
----------
- custom_file : str
-
+ custom_file : :class:`str`
Path to a custom config file. If used, the folder-wide file in the
relevant directory will be ignored, if it exists. If None, the
folder-wide file will be used, if it exists.
- Notes
- -----
- The folder-wide file can be ignored by passing custom_file. However, the
- user-wide and library-wide config files cannot be ignored.
+ Returns
+ -------
+ :class:`ConfigParser`
+ A parser containing the config options found in the .cfg files that
+ were found. It is guaranteed to contain at least the config options
+ found in the library-wide file.
+
+ See Also
+ --------
+ :func:`config_file_paths`
"""
library_wide, user_wide, folder_wide = config_file_paths()
@@ -64,7 +112,7 @@ def make_config_parser(custom_file=None):
return parser
-def determine_quality(args):
+def _determine_quality(args):
old_qualities = {
"k": "fourk_quality",
"e": "high_quality",
@@ -93,6 +141,108 @@ def determine_quality(args):
class ManimConfig(MutableMapping):
+ """Dict-like class storing all config options.
+
+ The global ``config`` object is an instance of this class, and acts as a
+ single source of truth for all of the library's customizable behavior.
+
+ The global ``config`` object is capable of digesting different types of
+ sources and converting them into a uniform interface. These sources are
+ (in ascending order of precedence): configuration files, command line
+ arguments, and programmatic changes. Regardless of how the user chooses to
+ set a config option, she can access its current value using
+ :class:`ManimConfig`'s attributes and properties.
+
+ Notes
+ -----
+ Each config option is implemented as a property of this class.
+
+ Each config option can be set via a config file, using the full name of the
+ property. If a config option has an associated CLI flag, then the flag is
+ equal to the full name of the property. Those that admit an alternative
+ flag or no flag at all are documented in the individual property's
+ docstring.
+
+ Examples
+ --------
+ Each config option allows for dict syntax and attribute syntax. For
+ example, the following two lines are equivalent,
+
+ .. code-block:: python
+
+ >>> from manim import config, WHITE
+ >>> config.background_color = WHITE
+ >>> config['background_color'] = WHITE
+
+ The former is preferred; the latter is provided mostly for backwards
+ compatibility.
+
+ The config options are designed to keep internal consistency. For example,
+ setting ``frame_y_radius`` will affect ``frame_height``:
+
+ .. code-block:: python
+
+ >>> config.frame_height
+ 8.0
+ >>> config.frame_y_radius = 5.0
+ >>> config.frame_height
+ 10.0
+
+ There are many ways of interacting with config options. Take for example
+ the config option ``background_color``. There are three ways to change it:
+ via a config file, via CLI flags, or programmatically.
+
+ To set the background color via a config file, save the following
+ ``manim.cfg`` file with the following contents.
+
+ .. code-block::
+
+ [CLI]
+ background_color = WHITE
+
+ In order to have this ``.cfg`` file apply to a manim scene, it needs to be
+ placed in the same directory as the script,
+
+ .. code-block:: bash
+
+ project/
+ ├─scene.py
+ └─manim.cfg
+
+ Now, when the user executes
+
+ .. code-block:: bash
+
+ manim scene.py
+
+ the background of the scene will be set to ``WHITE``. This applies regardless
+ of where the manim command is invoked from.
+
+ Command line arguments override ``.cfg`` files. In the previous example,
+ executing
+
+ .. code-block:: bash
+
+ manim scene.py -c BLUE
+
+ will set the background color to BLUE, regardless of the conents of
+ ``manim.cfg``.
+
+ Finally, any programmatic changes made within the scene script itself will
+ override the command line arguments. For example, if ``scene.py`` contains
+ the following
+
+ .. code-block:: python
+
+ from manim import *
+ config.background_color = RED
+ class MyScene(Scene):
+ # ...
+
+ the background color will be set to RED, regardless of the contents of
+ ``manim.cfg`` or the CLI arguments used when invoking manim.
+
+ """
_OPTS = {
"background_color",
@@ -140,11 +290,8 @@ class ManimConfig(MutableMapping):
"write_to_movie",
}
- def __init__(self, parser=None):
+ def __init__(self):
self._d = {k: None for k in self._OPTS}
- self._parser = parser
- if parser:
- self.digest_parser(parser)
# behave like a dict
def __iter__(self):
@@ -167,6 +314,33 @@ class ManimConfig(MutableMapping):
getattr(ManimConfig, key).fset(self, val) # fset is the property's setter
def update(self, obj):
+ """Digest the options found in another :class:`ManimConfig` or in a dict.
+
+ Similar to :meth:`dict.update`, replaces the values of this object with
+ those of ``obj``.
+
+ Parameters
+ ----------
+ obj : Union[:class:`ManimConfig`, :class:`dict`]
+ The object to copy values from.
+
+ Returns
+ -------
+ None
+
+ Raises
+ -----
+ :class:`AttributeError`
+ If ``obj`` is a dict but contains keys that do not belong to any
+ config options.
+
+ See Also
+ --------
+ :meth:`~ManimConfig.digest_file`, :meth:`~ManimConfig.digest_args`,
+ :meth:`~ManimConfig.digest_parser`
+
+ """
+
if isinstance(obj, ManimConfig):
self._d.update(obj._d)
@@ -189,30 +363,54 @@ class ManimConfig(MutableMapping):
# copy functions
def copy(self):
+ """Deepcopy the contents of this ManimConfig.
+
+ Returns
+ -------
+ :class:`ManimConfig`
+ A copy of this object containing no shared references.
+
+ See Also
+ --------
+ :func:`tempconfig`
+
+ Notes
+ -----
+ This is the main mechanism behind :func:`tempconfig`.
+
+ """
return copy.deepcopy(self)
def __copy__(self):
+ """See ManimConfig.copy()."""
return copy.deepcopy(self)
def __deepcopy__(self, memo):
+ """See ManimConfig.copy()."""
c = ManimConfig()
+ # Deepcopying the underlying dict is enough because all properties
+ # either read directly from it or compute their value on the fly from
+ # vaulues read directly from it.
c._d = copy.deepcopy(self._d, memo)
return c
# helper type-checking methods
def _set_from_list(self, key, val, values):
+ """Set ``key`` to ``val`` if ``val`` is contained in ``values``."""
if val in values:
self._d[key] = val
else:
raise ValueError(f"attempted to set {key} to {val}; must be in {values}")
def _set_boolean(self, key, val):
+ """Set ``key`` to ``val`` if ``val`` is Boolean."""
if val in [True, False]:
self._d[key] = val
else:
raise ValueError(f"{key} must be boolean")
def _set_str(self, key, val):
+ """Set ``key`` to ``val`` if ``val`` is a string."""
if isinstance(val, str):
self._d[key] = val
elif not val:
@@ -221,12 +419,14 @@ class ManimConfig(MutableMapping):
raise ValueError(f"{key} must be str or falsy value")
def _set_between(self, key, val, lo, hi):
+ """Set ``key`` to ``val`` if lo <= val <= hi."""
if lo <= val <= hi:
self._d[key] = val
else:
raise ValueError(f"{key} must be {lo} <= {key} <= {hi}")
def _set_pos_number(self, key, val, allow_inf):
+ """Set ``key`` to ``val`` if ``val`` is a positive integer."""
if isinstance(val, int) and val > -1:
self._d[key] = val
elif allow_inf and (val == -1 or val == float("inf")):
@@ -238,6 +438,55 @@ class ManimConfig(MutableMapping):
# builders
def digest_parser(self, parser):
+ """Process the config options present in a :class:`ConfigParser` object.
+
+ This method processes arbitrary parsers, not only those read from a
+ single file, whereas :meth:`~ManimConfig.digest_file` can only process one
+ file at a time.
+
+ Parameters
+ ----------
+ parser : :class:`ConfigParser`
+ An object reflecting the contents of one or many ``.cfg`` files. In
+ particular, it may reflect the contents of mulitple files that have
+ been parsed in a cascading fashion.
+
+ Returns
+ -------
+ self : :class:`ManimConfig`
+ This object, after processing the contents of ``parser``.
+
+ See Also
+ --------
+ :func:`make_config_parser`, :meth:`~.ManimConfig.digest_file`,
+ :meth:`~.ManimConfig.digest_args`,
+
+ Notes
+ -----
+ If there are multiple ``.cfg`` files to process, it is always more
+ efficient to parse them into a single :class:`ConfigParser` object
+ first, and then call this function once (instead of calling
+ :meth:`~.ManimConfig.digest_file` multiple times).
+
+ Examples
+ --------
+ To digest the config options set in two files, first create a
+ ConfigParser and parse both files and then digest the parser:
+
+ .. code-block:: python
+
+ parser = configparser.ConfigParser()
+ parser.read([file1, file2])
+ config = ManimConfig().digest_parser(parser)
+
+ In fact, the global ``config`` object is initialized like so:
+
+ .. code-block:: python
+
+ parser = make_config_parser()
+ config = ManimConfig().digest_parser(parser)
+
+ """
self._parser = parser
# boolean keys
@@ -312,6 +561,30 @@ class ManimConfig(MutableMapping):
return self
def digest_args(self, args):
+ """Process the config options present in CLI arguments.
+
+ Parameters
+ ----------
+ args : :class:`argparse.Namespace`
+ An object returned by :func:`.main_utils.parse_args()`.
+
+ Returns
+ -------
+ self : :class:`ManimConfig`
+ This object, after processing the contents of ``parser``.
+
+ See Also
+ --------
+ :func:`.main_utils.parse_args()`, :meth:`~.ManimConfig.digest_parser`,
+ :meth:`~.ManimConfig.digest_file`
+
+ Notes
+ -----
+ If ``args.config_file`` is a non-empty string, ``ManimConfig`` tries to digest the
+ contents of said file with :meth:`~ManimConfig.digest_file` before
+ digesting any other CLI arguments.
+
+ """
# if a config file has been passed, digest it first so that other CLI
# flags supersede it
if args.config_file:
@@ -377,7 +650,7 @@ class ManimConfig(MutableMapping):
self.from_animation_number = int(nflag)
# Handle the quality flags
- self.quality = determine_quality(args)
+ self.quality = _determine_quality(args)
# Handle the -r flag.
rflag = args.resolution
@@ -409,10 +682,37 @@ class ManimConfig(MutableMapping):
return self
- def digest_dict(self, _dict):
- pass
-
def digest_file(self, filename):
+ """Process the config options present in a ``.cfg`` file.
+
+ This method processes a single ``.cfg`` file, whereas
+ :meth:`~ManimConfig.digest_parser` can process arbitrary parsers, built
+ perhaps from multiple ``.cfg`` files.
+
+ Parameters
+ ----------
+ filename : :class:`str`
+ Path to the ``.cfg`` file.
+
+ Returns
+ -------
+ self : :class:`ManimConfig`
+ This object, after processing the contents of ``filename``.
+
+ See Also
+ --------
+ :meth:`~ManimConfig.digest_file`, :meth:`~ManimConfig.digest_args`,
+ :func:`make_config_parser`
+
+ Notes
+ -----
+ If there are multiple ``.cfg`` files to process, it is always more
+ efficient to parse them into a single :class:`ConfigParser` object
+ first and digesting them with one call to
+ :meth:`~ManimConfig.digest_parser`, instead of calling this method
+ multiple times.
+
+ """
if filename:
return self.digest_parser(make_config_parser(filename))
@@ -420,30 +720,30 @@ class ManimConfig(MutableMapping):
preview = property(
lambda self: self._d["preview"],
lambda self, val: self._set_boolean("preview", val),
- doc="Whether to play the movie once it is done rendering",
+ doc="Whether to play the rendered movie (-p).",
)
show_in_file_browser = property(
lambda self: self._d["show_in_file_browser"],
lambda self, val: self._set_boolean("show_in_file_browser", val),
- doc="Whether to show the rendered file in the file browser",
+ doc="Whether to show the output file in the file browser (-f).",
)
progress_bar = property(
lambda self: self._d["progress_bar"],
lambda self, val: self._set_boolean("progress_bar", val),
- doc="Whether to show progress bars while rendering animations",
+ doc="Whether to show progress bars while rendering animations.",
)
leave_progress_bars = property(
lambda self: self._d["leave_progress_bars"],
lambda self, val: self._set_boolean("leave_progress_bars", val),
- doc="Whether to leave the progress bar for each animations",
+ doc="Whether to leave the progress bar for each animation.",
)
@property
def log_to_file(self):
- """Whether to save logs to a file"""
+ """Whether to save logs to a file."""
return self._d["log_to_file"]
@log_to_file.setter
@@ -457,41 +757,42 @@ class ManimConfig(MutableMapping):
sound = property(
lambda self: self._d["sound"],
lambda self, val: self._set_boolean("sound", val),
- doc="Whether to play a sound to notify when a scene is rendered",
+ doc="Whether to play a sound to notify when a scene is rendered (no flag).",
)
write_to_movie = property(
lambda self: self._d["write_to_movie"],
lambda self, val: self._set_boolean("write_to_movie", val),
- doc="Whether to render the scene to a movie file",
+ doc="Whether to render the scene to a movie file (-w).",
)
save_last_frame = property(
lambda self: self._d["save_last_frame"],
lambda self, val: self._set_boolean("save_last_frame", val),
- doc="Whether to save the last frame of the scene as an image file",
+ doc="Whether to save the last frame of the scene as an image file (-s).",
)
write_all = property(
lambda self: self._d["write_all"],
lambda self, val: self._set_boolean("write_all", val),
- doc="Whether to render all scenes in the input file",
+ doc="Whether to render all scenes in the input file (-a).",
)
save_pngs = property(
lambda self: self._d["save_pngs"],
lambda self, val: self._set_boolean("save_pngs", val),
- doc="Whether to save all frames in the scene as images files",
+ doc="Whether to save all frames in the scene as images files (-g).",
)
save_as_gif = property(
lambda self: self._d["save_as_gif"],
lambda self, val: self._set_boolean("save_as_gif", val),
- doc="Whether to save the rendered scene in .gif format.",
+ doc="Whether to save the rendered scene in .gif format (-i).",
)
@property
def verbosity(self):
+ """Logger verbosity; "DEBUG", "INFO", "WARNING", "ERROR", or "CRITICAL" (-v)."""
return self._d["verbosity"]
@verbosity.setter
@@ -509,36 +810,36 @@ class ManimConfig(MutableMapping):
lambda self, val: self._set_from_list(
"ffmpeg_loglevel", val, ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
),
- doc="Verbosity level of ffmpeg.",
+ doc="Verbosity level of ffmpeg (no flag).",
)
pixel_width = property(
lambda self: self._d["pixel_width"],
lambda self, val: self._set_pos_number("pixel_width", val, False),
- doc="Frame width in pixels",
+ doc="Frame width in pixels (--resolution, -r).",
)
pixel_height = property(
lambda self: self._d["pixel_height"],
lambda self, val: self._set_pos_number("pixel_height", val, False),
- doc="Frame height in pixels",
+ doc="Frame height in pixels (--resolution, -r).",
)
aspect_ratio = property(
lambda self: self._d["pixel_width"] / self._d["pixel_height"],
- doc="Aspect ratio (width / height) in pixels",
+ doc="Aspect ratio (width / height) in pixels (--resolution, -r).",
)
frame_height = property(
lambda self: self._d["frame_height"],
lambda self, val: self._d.__setitem__("frame_height", val),
- doc="Frame height in logical units",
+ doc="Frame height in logical units (no flag).",
)
frame_width = property(
lambda self: self._d["frame_width"],
lambda self, val: self._d.__setitem__("frame_width", val),
- doc="Frame width in logical units",
+ doc="Frame width in logical units (no flag).",
)
frame_y_radius = property(
@@ -547,7 +848,7 @@ class ManimConfig(MutableMapping):
self._d.__setitem__("frame_y_radius", val)
or self._d.__setitem__("frame_height", 2 * val)
),
- doc="Half the frame height",
+ doc="Half the frame height (no flag).",
)
frame_x_radius = property(
@@ -556,87 +857,81 @@ class ManimConfig(MutableMapping):
self._d.__setitem__("frame_x_radius", val)
or self._d.__setitem__("frame_width", 2 * val)
),
- doc="Half the frame width",
+ doc="Half the frame width (no flag).",
)
top = property(
lambda self: self.frame_y_radius * constants.UP,
- doc="One unit step in the positive vertical direction",
+ doc="Coordinate at the center top of the frame.",
)
bottom = property(
lambda self: self.frame_y_radius * constants.DOWN,
- doc="One unit step in the negative vertical direction",
+ doc="Coordinate at the center bottom of the frame.",
)
left_side = property(
lambda self: self.frame_x_radius * constants.LEFT,
- doc="One unit step in the negative horizontal direction",
+ doc="Coordinate at the middle left of the frame.",
)
right_side = property(
lambda self: self.frame_x_radius * constants.RIGHT,
- doc="One unit step in the positive horizontal direction",
+ doc="Coordinate at the middle right of the frame.",
)
frame_rate = property(
lambda self: self._d["frame_rate"],
lambda self, val: self._d.__setitem__("frame_rate", val),
- doc="Frame rate in fps (rames per second)",
+ doc="Frame rate in frames per second (-q).",
)
background_color = property(
lambda self: self._d["background_color"],
lambda self, val: self._d.__setitem__("background_color", colour.Color(val)),
- doc="Background color of the scene.",
+ doc="Background color of the scene (-c).",
)
from_animation_number = property(
lambda self: self._d["from_animation_number"],
lambda self, val: self._d.__setitem__("from_animation_number", val),
- doc="Set to a number greater than 1 to skip animations.",
+ doc="Start rendering animations at this number (-n).",
)
upto_animation_number = property(
lambda self: self._d["upto_animation_number"],
lambda self, val: self._set_pos_number("upto_animation_number", val, True),
- doc=(
- "Set to less than the number of animations to skip "
- "animations. Use -1 to avoid skipping."
- ),
+ doc="Stop rendering animations at this nmber. Use -1 to avoid skipping (-n).",
)
skip_animations = property(
lambda self: self._d["skip_animations"],
lambda self, val: self._set_boolean("skip_animations", val),
- doc=(
- "Set to less than the number of animations to skip "
- "animations. Use -1 to avoid skipping."
- ),
+ doc="Whether to skip the next animation. Internal use only.",
)
max_files_cached = property(
lambda self: self._d["max_files_cached"],
lambda self, val: self._set_pos_number("max_files_cached", val, True),
- doc="Maximum number of files cached. Use -1 for infinity.",
+ doc="Maximum number of files cached. Use -1 for infinity (no flag).",
)
flush_cache = property(
lambda self: self._d["flush_cache"],
lambda self, val: self._set_boolean("flush_cache", val),
- doc="whether to delete all the cached partial movie files.",
+ doc="Whether to delete all the cached partial movie files.",
)
disable_caching = property(
lambda self: self._d["disable_caching"],
lambda self, val: self._set_boolean("disable_caching", val),
- doc="whether to use scene caching.",
+ doc="Whether to use scene caching.",
)
png_mode = property(
lambda self: self._d["png_mode"],
lambda self, val: self._set_from_list("png_mode", val, ["RGB", "RGBA"]),
- doc="Either RGA (no transparency) or RGBA (with transparency).",
+ doc="Either RGA (no transparency) or RGBA (with transparency) (no flag).",
)
movie_file_extension = property(
@@ -644,7 +939,7 @@ class ManimConfig(MutableMapping):
lambda self, val: self._set_from_list(
"movie_file_extension", val, [".mp4", ".mov"]
),
- doc="Either .mp4 or .mov.",
+ doc="Either .mp4 or .mov (no flag).",
)
background_opacity = property(
@@ -659,12 +954,12 @@ class ManimConfig(MutableMapping):
self._d.__setitem__("pixel_width", tup[0])
or self._d.__setitem__("pixel_height", tup[1])
),
- doc="",
+ doc="Tuple with (pixel width, pixel height) (no flag).",
)
@property
def quality(self):
- """Video quality."""
+ """Video quality (-q)."""
keys = ["pixel_width", "pixel_height", "frame_rate"]
q = {k: self[k] for k in keys}
for qual in constants.QUALITIES:
@@ -683,7 +978,7 @@ class ManimConfig(MutableMapping):
@property
def transparent(self):
- """Whether the background opacity is 0.0."""
+ """Whether the background opacity is 0.0 (-t)."""
return self._d["background_opacity"] == 0.0
@transparent.setter
@@ -726,6 +1021,7 @@ class ManimConfig(MutableMapping):
@property
def use_js_renderer(self):
+ """Whether to use JS renderer or not (default)."""
self._d["use_js_renderer"]
@use_js_renderer.setter
@@ -743,10 +1039,119 @@ class ManimConfig(MutableMapping):
media_dir = property(
lambda self: self._d["media_dir"],
lambda self, val: self._set_dir("media_dir", val),
- doc="Main output directory, relative to execution directory.",
+ doc="Main output directory. See :meth:`ManimConfig.get_dir`.",
)
def get_dir(self, key, **kwargs):
+ """Resolve a config option that stores a directory.
+
+ Config options that store directories may depend on one another. This
+ method is used to provide the actual directory to the end user.
+
+ Parameters
+ ----------
+ key : :class:`str`
+ The config option to be resolved. Must be an option ending in
+ ``'_dir'``, for example ``'media_dir'`` or ``'video_dir'``.
+
+ kwargs : :class:`str`
+ Any strings to be used when resolving the directory.
+
+ Returns
+ -------
+ :class:`pathlib.Path`
+ Path to the requested directory. If the path resolves to the empty
+ string, return ``None`` instead.
+
+ Raises
+ ------
+ :class:`KeyError`
+ When ``key`` is not a config option that stores a directory and
+ thus :meth:`~ManimConfig.get_dir` is not appropriate; or when
+ ``key`` is appropriate but there is not enough information to
+ resolve the directory.
+
+ Notes
+ -----
+ Standard :meth:`str.format` syntax is used to resolve the paths so the
+ paths may contain arbitrary placeholders using f-string notation.
+ However, these will require ``kwargs`` to contain the required values.
+
+ Examples
+ --------
+
+ The value of ``config.tex_dir`` is ``'{media_dir}/Tex'`` by default,
+ i.e. it is a subfolder of wherever ``config.media_dir`` is located. In
+ order to get the *actual* directory, use :meth:`~ManimConfig.get_dir`.
+
+ .. code-block:: python
+
+ >>> from manim import config
+ >>> config.tex_dir
+ '{media_dir}/Tex'
+ >>> config.media_dir
+ './media'
+ >>> config.get_dir("tex_dir").as_posix()
+ 'media/Tex'
+
+ Resolving directories is done in a lazy way, at the last possible
+ moment, to reflect any changes in other config options:
+
+ .. code-block:: python
+
+ >>> config.media_dir = 'my_media_dir'
+ >>> config.get_dir("tex_dir").as_posix()
+ 'my_media_dir/Tex'
+
+ Some directories depend on information that is not available to
+ :class:`ManimConfig`. For example, the default value of `video_dir`
+ includes the name of the input file and the video quality
+ (e.g. 480p15). This informamtion has to be supplied via ``kwargs``:
+
+ .. code-block:: python
+
+ >>> config.video_dir
+ '{media_dir}/videos/{module_name}/{quality}'
+ >>> config.get_dir("video_dir")
+ Traceback (most recent call last):
+ KeyError: 'video_dir {media_dir}/videos/{module_name}/{quality} requires the following keyword arguments: module_name'
+ >>> config.get_dir("video_dir", module_name="myfile").as_posix()
+ 'my_media_dir/videos/myfile/1080p60'
+
+ Note the quality does not need to be passed as keyword argument since
+ :class:`ManimConfig` does store information about quality.
+
+ Directories may be recursively defined. For example, the config option
+ ``partial_movie_dir`` depends on ``video_dir``, which in turn depends
+ on ``media_dir``:
+
+ .. code-block:: python
+
+ >>> config.partial_movie_dir
+ '{video_dir}/partial_movie_files/{scene_name}'
+ >>> config.get_dir("partial_movie_dir")
+ Traceback (most recent call last):
+ KeyError: 'partial_movie_dir {video_dir}/partial_movie_files/{scene_name} requires the following keyword arguments: scene_name'
+ >>> config.get_dir("partial_movie_dir", module_name="myfile", scene_name="myscene").as_posix()
+ 'my_media_dir/videos/myfile/1080p60/partial_movie_files/myscene'
+
+ Standard f-string syntax is used. Arbitrary names can be used when
+ defining directories, as long as the corresponding values are passed to
+ :meth:`ManimConfig.get_dir` via ``kwargs``.
+
+ .. code-block:: python
+
+ >>> config.media_dir = "{dir1}/{dir2}"
+ >>> config.get_dir("media_dir")
+ Traceback (most recent call last):
+ KeyError: 'media_dir {dir1}/{dir2} requires the following keyword arguments: dir1'
+ >>> config.get_dir("media_dir", dir1='foo', dir2='bar').as_posix()
+ 'foo/bar'
+ >>> config.media_dir = "./media"
+ >>> config.get_dir("media_dir").as_posix()
+ 'media'
+
+ """
dirs = [
"media_dir",
"video_dir",
@@ -793,43 +1198,43 @@ class ManimConfig(MutableMapping):
log_dir = property(
lambda self: self._d["log_dir"],
lambda self, val: self._set_dir("log_dir", val),
- doc="Directory to place logs",
+ doc="Directory to place logs. See :meth:`ManimConfig.get_dir`.",
)
video_dir = property(
lambda self: self._d["video_dir"],
lambda self, val: self._set_dir("video_dir", val),
- doc="Directory to place videos",
+ doc="Directory to place videos (no flag). See :meth:`ManimConfig.get_dir`.",
)
images_dir = property(
lambda self: self._d["images_dir"],
lambda self, val: self._set_dir("images_dir", val),
- doc="Directory to place images",
+ doc="Directory to place images (no flag). See :meth:`ManimConfig.get_dir`.",
)
text_dir = property(
lambda self: self._d["text_dir"],
lambda self, val: self._set_dir("text_dir", val),
- doc="Directory to place text",
+ doc="Directory to place text (no flag). See :meth:`ManimConfig.get_dir`.",
)
tex_dir = property(
lambda self: self._d["tex_dir"],
lambda self, val: self._set_dir("tex_dir", val),
- doc="Directory to place tex",
+ doc="Directory to place tex (no flag). See :meth:`ManimConfig.get_dir`.",
)
partial_movie_dir = property(
lambda self: self._d["partial_movie_dir"],
lambda self, val: self._set_dir("partial_movie_dir", val),
- doc="Directory to place partial movie files",
+ doc="Directory to place partial movie files (no flag). See :meth:`ManimConfig.get_dir`.",
)
custom_folders = property(
lambda self: self._d["custom_folders"],
lambda self, val: self._set_boolean("custom_folders", val),
- doc="Whether to use custom folders.",
+ doc="Whether to use custom folder output.",
)
input_file = property(
@@ -841,7 +1246,7 @@ class ManimConfig(MutableMapping):
output_file = property(
lambda self: self._d["output_file"],
lambda self, val: self._set_dir("output_file", val),
- doc="Output file name.",
+ doc="Output file name (-o).",
)
scene_names = property(
@@ -852,6 +1257,7 @@ class ManimConfig(MutableMapping):
@property
def tex_template(self):
+ """Template used when rendering Tex. See :class:`.TexTemplate`."""
if not hasattr(self, "_tex_template") or not self._tex_template:
fn = self._d["tex_template_file"]
if fn:
@@ -867,6 +1273,7 @@ class ManimConfig(MutableMapping):
@property
def tex_template_file(self):
+ """File to read Tex template from (no flag). See :class:`.TexTemplateFromFile`."""
return self._d["tex_template_file"]
@tex_template_file.setter
diff --git a/manim/grpc/impl/frame_server_impl.py b/manim/grpc/impl/frame_server_impl.py
index 5960e7430..851d7ec80 100644
--- a/manim/grpc/impl/frame_server_impl.py
+++ b/manim/grpc/impl/frame_server_impl.py
@@ -1,4 +1,4 @@
-from ...config import config
+from ... import config
from ...scene import scene
from ..gen import frameserver_pb2
from ..gen import frameserver_pb2_grpc
diff --git a/manim/scene/js_scene.py b/manim/scene/js_scene.py
index 45bb46681..8acd9df0e 100644
--- a/manim/scene/js_scene.py
+++ b/manim/scene/js_scene.py
@@ -1,7 +1,7 @@
from . import scene
from ..camera.camera import Camera
from ..camera.js_camera import JsCamera
-from ..config import config
+from .. import config
from ..grpc.gen import renderserver_pb2
from ..grpc.gen import renderserver_pb2_grpc
from ..grpc.impl.frame_server_impl import FrameServer
diff --git a/tests/control_data/logs_data/BasicSceneLoggingTest.txt b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
index c30063bd1..ff9db9c0a 100644
--- a/tests/control_data/logs_data/BasicSceneLoggingTest.txt
+++ b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
@@ -1,4 +1,4 @@
-{"levelname": "INFO", "module": "logger", "message": "Log file will be saved in <>"}
+{"levelname": "INFO", "module": "logger_utils", "message": "Log file will be saved in <>"}
{"levelname": "DEBUG", "module": "hashing", "message": "Hashing ..."}
{"levelname": "DEBUG", "module": "hashing", "message": "Hashing done in <> s."}
{"levelname": "DEBUG", "module": "hashing", "message": "Hash generated : <>"}
diff --git a/tests/test_quality_flags.py b/tests/test_quality_flags.py
index 72752538c..616eeef9e 100644
--- a/tests/test_quality_flags.py
+++ b/tests/test_quality_flags.py
@@ -1,6 +1,6 @@
from manim import constants
-from manim.config.main_utils import parse_args
-from manim.config.utils import determine_quality
+from manim._config.main_utils import parse_args
+from manim._config.utils import _determine_quality
def test_quality_flags():
@@ -8,7 +8,7 @@ def test_quality_flags():
parsed = parse_args("manim dummy_filename".split())
assert parsed.quality == constants.DEFAULT_QUALITY_SHORT
- assert determine_quality(parsed) == constants.DEFAULT_QUALITY
+ assert _determine_quality(parsed) == constants.DEFAULT_QUALITY
for quality in constants.QUALITIES.keys():
flag = constants.QUALITIES[quality]["flag"]
@@ -17,31 +17,31 @@ def test_quality_flags():
parsed = parse_args(arguments)
assert parsed.quality == flag
- assert quality == determine_quality(parsed)
+ assert quality == _determine_quality(parsed)
# Assert that quality is properly set when using -q *
arguments = f"manim -q {flag} dummy_filename".split()
parsed = parse_args(arguments)
assert parsed.quality == flag
- assert quality == determine_quality(parsed)
+ assert quality == _determine_quality(parsed)
# Assert that quality is properly set when using --quality *
arguments = f"manim --quality {flag} dummy_filename".split()
parsed = parse_args(arguments)
assert parsed.quality == flag
- assert quality == determine_quality(parsed)
+ assert quality == _determine_quality(parsed)
# Assert that quality is properly set when using -*_quality
arguments = f"manim --{quality} dummy_filename".split()
parsed = parse_args(arguments)
assert getattr(parsed, quality)
- assert quality == determine_quality(parsed)
+ assert quality == _determine_quality(parsed)
# Assert that *_quality is False when not specifying it
parsed = parse_args("manim dummy_filename".split())
assert not getattr(parsed, quality)
- assert determine_quality(parsed) == constants.DEFAULT_QUALITY
+ assert _determine_quality(parsed) == constants.DEFAULT_QUALITY