Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

feat: add a 'seed' option for reproducible outputs (#4532)

Arnaud2317b0ee8b07
diff --git a/manim/_config/utils.py b/manim/_config/utils.py
index a3da85558..1db9d6b29 100644
--- a/manim/_config/utils.py
+++ b/manim/_config/utils.py
@@ -299,6 +299,7 @@ class ManimConfig(MutableMapping):
"save_last_frame",
"save_pngs",
"scene_names",
+ "seed",
"show_in_file_browser",
"tex_dir",
"tex_template",
@@ -606,6 +607,7 @@ class ManimConfig(MutableMapping):
# the next two must be set BEFORE digesting frame_width and frame_height
"pixel_height",
"pixel_width",
+ "seed",
"window_monitor",
"zero_pad",
]:
@@ -772,6 +774,7 @@ class ManimConfig(MutableMapping):
"dry_run",
"no_latex_cleanup",
"preview_command",
+ "seed",
]:
if hasattr(args, key):
attr = getattr(args, key)
@@ -1803,6 +1806,17 @@ class ManimConfig(MutableMapping):
def plugins(self, value: list[str]):
self._d["plugins"] = value
+ @property
+ def seed(self) -> int | None:
+ """Random seed for reproducibility. None means no seed is set."""
+ return self._d["seed"]
+
+ @seed.setter
+ def seed(self, value: int | None) -> None:
+ if value is None:
+ return
+ self._set_pos_number("seed", value, False)
+
# TODO: to be used in the future - see PR #620
# https://github.com/ManimCommunity/manim/pull/620
diff --git a/manim/cli/render/global_options.py b/manim/cli/render/global_options.py
index 209af5261..fc299d204 100644
--- a/manim/cli/render/global_options.py
+++ b/manim/cli/render/global_options.py
@@ -144,4 +144,10 @@ global_options = option_group(
help="The command used to preview the output file (for example vlc for video files)",
default=None,
),
+ option(
+ "--seed",
+ type=int,
+ help="Set the random seed to allow reproducibility.",
+ default=None,
+ ),
)
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index ab250d7c9..96d5fd9ab 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -177,7 +177,7 @@ class Scene:
) -> None:
self.camera_class = camera_class
self.always_update_mobjects = always_update_mobjects
- self.random_seed = random_seed
+ self.random_seed = random_seed if random_seed is not None else config.seed
self.skip_animations = skip_animations
self.animations: list[Animation] | None = None
@@ -219,9 +219,9 @@ class Scene:
self.mobjects: list[Mobject] = []
# TODO, remove need for foreground mobjects
self.foreground_mobjects: list[Mobject] = []
- if self.random_seed is not None:
- random.seed(self.random_seed)
- np.random.default_rng(self.random_seed)
+
+ random.seed(self.random_seed)
+ np.random.seed(self.random_seed) # noqa: NPY002 (only way to set seed globally)
@property
def camera(self) -> Camera | OpenGLCamera:
diff --git a/manim/utils/color/core.py b/manim/utils/color/core.py
index d8f5a497c..afcfccb5d 100644
--- a/manim/utils/color/core.py
+++ b/manim/utils/color/core.py
@@ -1559,10 +1559,9 @@ class RandomColorGenerator:
seed: int | None = None,
sample_colors: list[ManimColor] | None = None,
) -> None:
- self.choice = random.choice if seed is None else random.Random(seed).choice
-
from manim.utils.color.manim_colors import _all_manim_colors
+ self.choice = random.choice if seed is None else random.Random(seed).choice
self.colors = _all_manim_colors if sample_colors is None else sample_colors
def next(self) -> ManimColor:
diff --git a/manim/utils/commands.py b/manim/utils/commands.py
index b8154ca8b..cc4f27a7a 100644
--- a/manim/utils/commands.py
+++ b/manim/utils/commands.py
@@ -18,7 +18,9 @@ __all__ = [
def capture(
- command: str, cwd: StrOrBytesPath | None = None, command_input: str | None = None
+ command: str | list[str],
+ cwd: StrOrBytesPath | None = None,
+ command_input: str | None = None,
) -> tuple[str, str, int]:
p = run(
command,
diff --git a/tests/module/scene/test_scene.py b/tests/module/scene/test_scene.py
index 70ea9eaf2..c64fbd46a 100644
--- a/tests/module/scene/test_scene.py
+++ b/tests/module/scene/test_scene.py
@@ -4,7 +4,7 @@ import datetime
import pytest
-from manim import Circle, FadeIn, Group, Mobject, Scene, Square
+from manim import Circle, Dot, FadeIn, Group, Mobject, Scene, Square
from manim.animation.animation import Wait
@@ -101,3 +101,48 @@ def test_replace(dry_run):
scene.replace(second, beta)
assert_names(scene.mobjects, ["alpha", "group", "fourth"])
assert_names(scene.mobjects[1], ["beta", "third"])
+
+
+def test_reproducible_scene(dry_run):
+ import numpy as np
+
+ scene = Scene(random_seed=42)
+ dots1 = []
+ for _ in range(10):
+ dot = Dot(np.random.uniform(-3, 3, size=3)) # noqa: NPY002
+ dots1.append(dot)
+ scene.add(*dots1)
+
+ scene2 = Scene(random_seed=42)
+ dots2 = []
+ for _ in range(5):
+ dot = Dot(np.random.uniform(-3, 3, size=3)) # noqa: NPY002
+ dots2.append(dot)
+ scene2.add(*dots2)
+
+ for d1, d2 in zip(dots1, dots2, strict=False):
+ np.testing.assert_allclose(d1.get_center(), d2.get_center())
+
+
+def test_random_color_reproducibility_with_seed(dry_run):
+ from manim import random_color, tempconfig
+
+ with tempconfig({"seed": 123}):
+ # First run: create scene (which seeds global random state) and generate colors
+ scene1 = Scene()
+ colors_first_run = [random_color() for _ in range(5)]
+
+ # Interrupt with a scene that has an explicit different seed
+ scene_explicit = Scene(random_seed=999)
+ colors_interrupted = [random_color() for _ in range(3)]
+
+ # Second run: create a new scene without explicit seed (should use config.seed)
+ scene2 = Scene()
+ colors_second_run = [random_color() for _ in range(5)]
+
+ # The colors from the first and second run should match
+ # because both scenes were seeded with config.seed=123
+ assert colors_first_run == colors_second_run
+
+ # The interrupted colors should be different (seeded with 999)
+ assert colors_interrupted != colors_first_run[:3]
diff --git a/tests/test_scene_rendering/simple_scenes.py b/tests/test_scene_rendering/simple_scenes.py
index 7f626ffbe..ec190bbf0 100644
--- a/tests/test_scene_rendering/simple_scenes.py
+++ b/tests/test_scene_rendering/simple_scenes.py
@@ -165,3 +165,15 @@ class ElaborateSceneWithSections(Scene):
self.next_section("fade out")
self.play(FadeOut(square))
self.wait()
+
+
+class SceneWithRandomness(Scene):
+ def construct(self):
+ dots = VGroup()
+ for _ in range(10):
+ dot = Dot(
+ point=np.random.uniform(-3, 3, size=3), # noqa: NPY002
+ )
+ dots.add(dot)
+ self.add(dots)
+ self.wait()
diff --git a/tests/test_scene_rendering/test_cli_flags.py b/tests/test_scene_rendering/test_cli_flags.py
index 498f1ce4a..282dd1b50 100644
--- a/tests/test_scene_rendering/test_cli_flags.py
+++ b/tests/test_scene_rendering/test_cli_flags.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import sys
+from pathlib import Path
import numpy as np
import pytest
@@ -719,6 +720,49 @@ def test_mov_can_be_set_as_output_format(tmp_path, manim_cfg_file, simple_scenes
)
+def test_reproducible_animation(tmp_path: Path, manim_cfg_file, simple_scenes_path):
+ scene_name = "SceneWithRandomness"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "-ql",
+ "--media_dir",
+ str(tmp_path),
+ "--seed",
+ "42",
+ str(simple_scenes_path),
+ scene_name,
+ ]
+ out, err, exit_code = capture(command)
+ assert exit_code == 0, err
+
+ first_path = tmp_path / "videos" / "simple_scenes" / "480p15" / f"{scene_name}.mp4"
+
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "-ql",
+ "--media_dir",
+ str(tmp_path),
+ "--seed",
+ "42",
+ str(simple_scenes_path),
+ scene_name,
+ ]
+ out, err, exit_code = capture(command)
+ assert exit_code == 0, err
+
+ second_path = first_path.with_name(scene_name).with_suffix(".mp4")
+
+ with open(first_path, "rb") as f1, open(second_path, "rb") as f2:
+ first_data = f1.read()
+ second_data = f2.read()
+ assert first_data == second_data, "Videos with the same seed differ."
+
+
@pytest.mark.slow
@video_comparison(
"InputFileViaCfg.json",