数学视频动画引擎Python库 -- Manim 的配置 Configuration

文中内容仅限技术学习与代码实践参考,市场存在不确定性,技术分析需谨慎验证,不构成任何投资建议。

Mathematical Animation Engine

配置

Manim 提供了一个广泛的配置系统,使其能够适应许多不同的使用场景。有许多配置选项可以在场景渲染过程中的不同时间进行配置。每个选项都可以通过 ManimConfig 类以编程方式配置,通过命令行参数在命令调用时配置,或者通过配置文件在首次导入库时配置。

最常见、最简单且推荐的配置 Manim 的方式是通过命令行界面(CLI),其描述直接如下。

命令行参数

在 CLI 中最常使用的命令是 render 命令,该命令用于将场景渲染到输出文件中。它与以下参数一起使用:

/home/docs/checkouts/readthedocs.org/user_builds/manimce/envs/stable/lib/python3.13/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
  warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
Manim Community v0.19.0

Usage: manim render [OPTIONS] FILE [SCENE_NAMES]...

  Render SCENE(S) from the input FILE.

  FILE is the file path of the script or a config file.
...

然而,由于 Manim 默认在未指定任何命令时调用 render 命令,因此以下形式更为常见,可以代替使用:

manim [OPTIONS] FILE [SCENES]

使用上述形式的一个示例是:

manim -qm file.py SceneOne

这要求 Manim 在文件 file.py 中查找名为 SceneOne 的 Scene 类,并以中等质量(由 -qm 标志指定)渲染它。

另一个常用的标志是 -p(“预览”),这使得 manim 在渲染完成后打开渲染的视频。

注意:-p 标志不会改变全局 config 字典的任何属性。-p 标志只是一个命令行便利功能。

高级示例

要以高清晰度渲染场景,但只输出场景的最后一帧而不是整个视频,可以执行

manim -sqh <file.py> SceneName

以下示例指定了输出文件名(使用 -o 标志),仅渲染前十个动画(-n 标志),背景为白色(-c 标志),并将动画保存为 .gif 文件而不是 .mp4 文件(--format=gif 标志)。它使用默认质量,并且在渲染完成后不会尝试打开文件。

manim -o myscene --format=gif -n 0,10 -c WHITE <file.py> SceneName

所有 CLI 标志的列表

$ manim --help
/home/docs/checkouts/readthedocs.org/user_builds/manimce/envs/stable/lib/python3.13/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
  warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
Usage: manim [OPTIONS] COMMAND [ARGS]...

  Animation engine for explanatory math videos.

Options:
  --version                      Show version and exit.
  --show-splash / --hide-splash  Print splash message with version information.
  --help                         Show this message and exit.

Commands:
  cfg          Manages Manim configuration files.
  checkhealth  This subcommand checks whether Manim is installed correctly...
  init         Create a new project or insert a new scene.
  plugins      Manages Manim plugins.
  render       Render SCENE(S) from the input FILE.

See 'manim <command>' to read about a specific subcommand.

Note: the subcommand 'manim render' is called if no other subcommand is
specified. Run 'manim render --help' if you would like to know what the '-ql' or
'-p' flags do, for example.

Made with <3 by Manim Community developers.
$ manim render --help
/home/docs/checkouts/readthedocs.org/user_builds/manimce/envs/stable/lib/python3.13/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
  warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
Manim Community v0.19.0

Usage: manim render [OPTIONS] FILE [SCENE_NAMES]...

  Render SCENE(S) from the input FILE.

  FILE is the file path of the script or a config file.

  SCENES is an optional list of scenes in the file.

Global options:
  -c, --config_file TEXT         Specify the configuration file to use for
                                 render settings.
  --custom_folders               Use the folders defined in the [custom_folders]
                                 section of the config file to define the output
                                 folder structure.
  --disable_caching              Disable the use of the cache (still generates
                                 cache files).
  --flush_cache                  Remove cached partial movie files.
  --tex_template TEXT            Specify a custom TeX template file.
  -v, --verbosity [DEBUG|INFO|WARNING|ERROR|CRITICAL]
                                 Verbosity of CLI output. Changes ffmpeg log
                                 level unless 5+.
  --notify_outdated_version / --silent
                                 Display warnings for outdated installation.
  --enable_gui                   Enable GUI interaction.
  --gui_location TEXT            Starting location for the GUI.
  --fullscreen                   Expand the window to its maximum possible size.
  --enable_wireframe             Enable wireframe debugging mode in opengl.
  --force_window                 Force window to open when using the opengl
                                 renderer, intended for debugging as it may
                                 impact performance
  --dry_run                      Renders animations without outputting image or
                                 video files and disables the window
  --no_latex_cleanup             Prevents deletion of .aux, .dvi, and .log files
                                 produced by Tex and MathTex.
  --preview_command TEXT         The command used to preview the output file
                                 (for example vlc for video files)

Output options:
  -o, --output_file TEXT         Specify the filename(s) of the rendered
                                 scene(s).
  -0, --zero_pad INTEGER RANGE   Zero padding for PNG file names.  [0<=x<=9]
  --write_to_movie               Write the video rendered with opengl to a file.
  --media_dir PATH               Path to store rendered videos and latex.
  --log_dir PATH                 Path to store render logs.
  --log_to_file                  Log terminal output to file.

Render Options:
  -n, --from_animation_number TEXT
                                 Start rendering from n_0 until n_1. If n_1 is
                                 left unspecified, renders all scenes after n_0.
  -a, --write_all                Render all scenes in the input file.
  --format [png|gif|mp4|webm|mov]
  -s, --save_last_frame          Render and save only the last frame of a scene
                                 as a PNG image.
  -q, --quality [l|m|h|p|k]      Render quality at the follow resolution
                                 framerates, respectively: 854x480 15FPS,
                                 1280x720 30FPS, 1920x1080 60FPS, 2560x1440
                                 60FPS, 3840x2160 60FPS
  -r, --resolution TEXT          Resolution in "W,H" for when 16:9 aspect ratio
                                 isn't possible.
  --fps, --frame_rate FLOAT      Render at this frame rate.
  --renderer [cairo|opengl]      Select a renderer for your Scene.
  -g, --save_pngs                Save each frame as png (Deprecated).
  -i, --save_as_gif              Save as a gif (Deprecated).
  --save_sections                Save section videos in addition to movie file.
  -t, --transparent              Render scenes with alpha channel.
  --use_projection_fill_shaders  Use shaders for OpenGLVMobject fill which are
                                 compatible with transformation matrices.
  --use_projection_stroke_shaders
                                 Use shaders for OpenGLVMobject stroke which are
                                 compatible with transformation matrices.

Ease of access options:
  --progress_bar [display|leave|none]
                                 Display progress bars and/or keep them
                                 displayed.
  -p, --preview                  Preview the Scene's animation. OpenGL does a
                                 live preview in a popup window. Cairo opens the
                                 rendered video file in the system default media
                                 player.
  -f, --show_in_file_browser     Show the output file in the file browser.
  --jupyter                      Using jupyter notebook magic.

Other options:
  --help                         Show this message and exit.

Made with <3 by Manim Community developers.
$ manim cfg --help
/home/docs/checkouts/readthedocs.org/user_builds/manimce/envs/stable/lib/python3.13/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
  warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
Manim Community v0.19.0

Usage: manim cfg [OPTIONS] COMMAND [ARGS]...

  Manages Manim configuration files.

Options:
  --help  Show this message and exit.

Commands:
  export
  show
  write

Made with <3 by Manim Community developers.
$ manim plugins --help
/home/docs/checkouts/readthedocs.org/user_builds/manimce/envs/stable/lib/python3.13/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
  warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
Manim Community v0.19.0

Usage: manim plugins [OPTIONS]

  Manages Manim plugins.

Options:
  -l, --list  List available plugins.
  --help      Show this message and exit.

Made with <3 by Manim Community developers.

ManimConfig 类

配置 Manim 最直接的方式是通过全局 config 对象,它是 ManimConfig 的一个实例。此类的每个属性都是一个配置选项,可以通过标准属性语法或类似字典的语法访问:

>>> from manim import *
>>> config.background_color = WHITE
>>> config["background_color"] = WHITE

注意:前者是首选;后者是为了向后兼容而提供的。

大多数类,包括 CameraMobjectAnimation,都会从全局 config 中读取一些默认配置。

>>> Camera({}).background_color
<Color white>
>>> config.background_color = RED  # 0xfc6255
>>> Camera({}).background_color
<Color #fc6255>

ManimConfig 被设计为保持内部一致性。例如,设置 frame_y_radius 将会影响 frame_height

>>> config.frame_height
8.0
>>> config.frame_y_radius = 5.0
>>> config.frame_height
10.0

全局 config 对象旨在成为所有配置选项的单一事实来源。所有其他设置配置选项的方式最终都会改变全局 config 对象的值。

以下示例说明了在文档中示例渲染所选择的视频分辨率,并附有参考框架。

示例:ShowScreenResolution

img

from manim import *

class ShowScreenResolution(Scene):
    def construct(self):
        pixel_height = config["pixel_height"]  #  1080 is default
        pixel_width = config["pixel_width"]  # 1920 is default
        frame_width = config["frame_width"]
        frame_height = config["frame_height"]
        self.add(Dot())
        d1 = Line(frame_width * LEFT / 2, frame_width * RIGHT / 2).to_edge(DOWN)
        self.add(d1)
        self.add(Text(str(pixel_width)).next_to(d1, UP))
        d2 = Line(frame_height * UP / 2, frame_height * DOWN / 2).to_edge(LEFT)
        self.add(d2)
        self.add(Text(str(pixel_height)).next_to(d2, RIGHT))
class ShowScreenResolution(Scene):
    def construct(self):
        pixel_height = config["pixel_height"]  #  1080 is default
        pixel_width = config["pixel_width"]  # 1920 is default
        frame_width = config["frame_width"]
        frame_height = config["frame_height"]
        self.add(Dot())
        d1 = Line(frame_width * LEFT / 2, frame_width * RIGHT / 2).to_edge(DOWN)
        self.add(d1)
        self.add(Text(str(pixel_width)).next_to(d1, UP))
        d2 = Line(frame_height * UP / 2, frame_height * DOWN / 2).to_edge(LEFT)
        self.add(d2)
        self.add(Text(str(pixel_height)).next_to(d2, RIGHT))

配置文件

正如上一个示例所示,从命令行执行 Manim 可能会同时使用许多标志。如果必须在短时间内多次执行相同的脚本,例如在对场景脚本进行小的增量调整时,这可能会成为一个麻烦。因此,Manim 也可以通过配置文件进行配置。配置文件是一个以 .cfg 后缀结尾的文件。

要使用本地配置文件渲染场景,必须在场景代码所在的目录中创建一个名为 manim.cfg 的文件。

警告:配置文件必须命名为 manim.cfg。目前,Manim 不支持任何其他名称的配置文件。

配置文件必须以 [CLI] 部分标题开头。此标题下的配置选项与 CLI 标志同名,并且具有相同的作用。例如,以下配置文件。

[CLI]
# my config file
output_file = myscene
save_as_gif = True
background_color = WHITE

配置文件使用标准 Python 库 configparser 进行解析。特别是,它们会忽略以井号符号 # 开头的任何行。

现在,执行以下命令

manim -o myscene -i -c WHITE <file.py> SceneName

等同于在 manim.cfg 位于 <file.py> 同一目录的情况下执行以下命令,

manim <file.py> SceneName

提示:配置文件中允许的配置选项名称与相应命令行标志的长名称完全相同。例如,-c--background_color 标志可以互换,但配置文件只接受 background_color 作为一个有效的选项。

由于配置文件旨在替代 CLI 标志,因此所有 CLI 标志都可以通过配置文件设置。此外,任何配置选项都可以通过配置文件设置,无论它是否有一个相关的 CLI 标志。参见本文档底部的所有 CLI 标志和配置选项列表。

Manim 会在被渲染文件所在的目录中查找 manim.cfg 配置文件,而不是在执行目录中。例如,

manim -o myscene -i -c WHITE <path/to/file.py> SceneName

将使用在 <path/to/file.py> 中找到的配置文件(如果有的话)。它不会使用当前工作目录中找到的配置文件,即使它存在。这样,用户可以为不同的场景或项目保留不同的配置文件,并从系统中的任何地方使用正确的配置执行它们。

这里描述的文件称为文件夹范围配置文件,因为它会影响同一文件夹中的所有场景脚本。

用户配置文件

如上一节所述,manim.cfg 配置文件只影响其同一文件夹中的场景脚本。然而,用户还可以创建一个特殊的配置文件,该文件将适用于该用户渲染的所有场景。这被称为用户范围配置文件,无论从哪里执行 Manim,也无论场景脚本存储在哪里,它都将适用。

用户范围配置文件位于一个特殊的文件夹中,具体取决于操作系统。

  • Windows:UserDirectory/AppData/Roaming/Manim/manim.cfg

  • MacOS:UserDirectory/.config/manim/manim.cfg

  • Linux:UserDirectory/.config/manim/manim.cfg

这里,UserDirectory 是用户的主文件夹。

注意:一个用户可以有许多文件夹范围配置文件,每个文件夹一个,但只能有一个用户范围配置文件。同一计算机上的不同用户可以各自拥有自己的用户范围配置文件。

警告:不要将场景脚本存储在用户范围配置文件所在的同一文件夹中。在这种情况下,行为是未定义的。

无论从系统中的任何地方使用 Manim,Manim 都会查找用户范围配置文件并读取其配置。

级联配置文件

如果执行 Manim 时,它同时找到了文件夹范围配置文件和用户范围配置文件,Manim 将读取两个文件,但如果它们不兼容,文件夹范围文件将优先

例如,取以下用户范围配置文件

# user-wide
[CLI]
output_file = myscene
save_as_gif = True
background_color = WHITE

以及以下文件夹范围文件

# folder-wide
[CLI]
save_as_gif = False

那么,执行 manim <file.py> SceneName 将等同于不使用任何配置文件并执行

manim -o myscene -c WHITE <file.py> SceneName

任何命令行标志都优先于任何配置文件。例如,使用上述两个配置文件并执行 manim -c RED <file.py> SceneName 等同于不使用任何配置文件并执行

manim -o myscene -c RED <file.py> SceneName

还有一个库范围配置文件,它决定了 Manim 的默认行为,并适用于库的每个用户。它具有最低的优先级,因此用户范围和任何文件夹范围文件中的任何配置选项都将覆盖库范围文件。这被称为级联配置文件系统。

警告:用户不应尝试修改库范围文件。贡献者在修改它之前应从核心开发团队获得明确的确认。

操作顺序

由于配置 Manim 的方式多种多样,因此很难知道每个配置选项在何时被设置。实际上,这取决于 Manim 的使用方式。

如果从模块导入 Manim,则配置系统将遵循以下步骤:

  1. 加载库级别的配置文件。
  2. 如果存在,加载用户级别和文件夹级别的文件。
  3. 将前两步中找到的所有文件解析到一个名为 parser 的单个 ConfigParser 对象中。这就是级联发生的地方。
  4. 实例化 logging.Logger 以创建 Manim 的全局日志记录器对象。它使用 parser 中的“logger”部分进行配置,即 parser['logger']
  5. 实例化 ManimConfig 以创建全局配置对象。
  6. 将第 3 步中的 parser 通过 ManimConfig.digest_parser()传递给第 5 步中的配置。
  7. 日志记录器和配置都暴露给用户。

如果从命令行调用 Manim,则会执行上述所有步骤,并补充以下步骤:

  1. 解析命令行界面标志并通过 digest_args() 传递给配置。
  2. 如果使用了 --config_file 标志,则会使用库级别文件、用户级别文件(如果存在)以及通过 --config_file 传递的文件的内容创建一个新的 ConfigParser 对象。在这种情况下,如果存在文件夹级别的文件,则会被忽略。
  3. 将新的 parser 传递给配置。
  4. 处理其余的命令行界面标志。

总结来说,配置选项的优先级顺序(从低到高)是:

  1. 库级别的配置文件,
  2. 用户级别的配置文件(如果存在),
  3. 文件夹级别的配置文件(如果存在)或自定义配置文件(如果通过 --config_file 传递),
  4. 其他命令行界面标志,以及
  5. 在配置系统设置后进行的任何程序性更改。

所有配置选项的列表

['aspect_ratio', 'assets_dir', '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', `fullscreen`, 'images_dir', 'input_file', 'left_side',
'log_dir', 'log_to_file', 'max_files_cached', 'media_dir', 'media_width',
'movie_file_extension', 'notify_outdated_version', 'output_file', 'partial_movie_dir',
'pixel_height', 'pixel_width', 'plugins', 'preview',
'progress_bar', 'quality', 'right_side', 'save_as_gif', 'save_last_frame',
'save_pngs', 'scene_names', 'show_in_file_browser', 'sound', 'tex_dir',
'tex_template', 'tex_template_file', 'text_dir', 'top', 'transparent',
'upto_animation_number', 'use_opengl_renderer', 'verbosity', 'video_dir',
'window_position', 'window_monitor', 'window_size', 'write_all', 'write_to_movie',
'enable_wireframe', 'force_window']

访问命令行选项

输入 manimmanim --help 将打开主帮助页面。

Usage: manim [OPTIONS] COMMAND [ARGS]...

  Animation engine for explanatory math videos.

Options:
  --version  Show version and exit.
  --help     Show this message and exit.

Commands:
  cfg      Manages Manim configuration files.
  init     Sets up a new project in current working directory with default
           settings.

           It copies files from templates directory and pastes them in the
           current working dir.
  new      Create a new project or insert a new scene.
  plugins  Manages Manim plugins.
  render   Render SCENE(S) from the input FILE.

See 'manim <command>' to read about a specific subcommand.

Made with <3 by Manim Community developers.

每个子命令都有自己的帮助页面,可以通过类似的方式访问。

manim render
manim render --help

风险提示与免责声明
本文内容基于公开信息研究整理,不构成任何形式的投资建议。历史表现不应作为未来收益保证,市场存在不可预见的波动风险。投资者需结合自身财务状况及风险承受能力独立决策,并自行承担交易结果。作者及发布方不对任何依据本文操作导致的损失承担法律责任。市场有风险,投资须谨慎。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

船长Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值