Files
Gymnasium/tests/wrappers/test_record_video.py

186 lines
5.8 KiB
Python
Raw Permalink Normal View History

"""Test suite for RecordVideo wrapper."""
2024-06-10 17:07:47 +01:00
import os
import shutil
import numpy as np
import pytest
import gymnasium as gym
from gymnasium.wrappers import RecordVideo, RenderCollection
def test_video_folder_and_filenames(
video_folder="custom_video_folder", name_prefix="video-prefix"
):
env = gym.make("CartPole-v1", render_mode="rgb_array")
env = RecordVideo(
env,
video_folder=video_folder,
name_prefix=name_prefix,
episode_trigger=lambda x: x in [1, 4],
step_trigger=lambda x: x in [0, 25],
)
env.reset(seed=123)
env.action_space.seed(123)
for _ in range(100):
2021-08-31 16:59:21 -04:00
action = env.action_space.sample()
_, _, terminated, truncated, _ = env.step(action)
if terminated or truncated:
2021-08-31 16:59:21 -04:00
env.reset()
env.close()
assert os.path.isdir(video_folder)
mp4_files = {file for file in os.listdir(video_folder) if file.endswith(".mp4")}
shutil.rmtree(video_folder)
assert mp4_files == {
"video-prefix-step-0.mp4", # step triggers
"video-prefix-step-25.mp4",
"video-prefix-episode-1.mp4", # episode triggers
"video-prefix-episode-4.mp4",
}
@pytest.mark.parametrize("episodic_trigger", [None, lambda x: x in [0, 3, 5, 10, 12]])
def test_episodic_trigger(episodic_trigger):
"""Test RecordVideo using the default episode trigger."""
env = gym.make("CartPole-v1", render_mode="rgb_array")
env = RecordVideo(env, "videos", episode_trigger=episodic_trigger)
2021-08-31 16:59:21 -04:00
env.reset()
episode_count = 0
for _ in range(199):
action = env.action_space.sample()
_, _, terminated, truncated, _ = env.step(action)
if terminated or truncated:
env.reset()
episode_count += 1
env.close()
assert os.path.isdir("videos")
mp4_files = [file for file in os.listdir("videos") if file.endswith(".mp4")]
assert env.episode_trigger is not None
assert len(mp4_files) == sum(
env.episode_trigger(i) for i in range(episode_count + 1)
)
shutil.rmtree("videos")
def test_step_trigger():
"""Test RecordVideo defining step trigger function."""
env = gym.make("CartPole-v1", render_mode="rgb_array")
env = RecordVideo(env, "videos", step_trigger=lambda x: x % 100 == 0)
env.reset()
for _ in range(199):
action = env.action_space.sample()
_, _, terminated, truncated, _ = env.step(action)
if terminated or truncated:
env.reset()
env.close()
assert os.path.isdir("videos")
mp4_files = [file for file in os.listdir("videos") if file.endswith(".mp4")]
shutil.rmtree("videos")
assert len(mp4_files) == 2
def test_both_episodic_and_step_trigger():
"""Test RecordVideo defining both step and episode trigger functions."""
env = gym.make("CartPole-v1", render_mode="rgb_array")
env = RecordVideo(
env,
"videos",
step_trigger=lambda x: x == 100,
episode_trigger=lambda x: x == 0 or x == 3,
Render API (#2671) * add pygame GUI for frozen_lake.py env * add new line at EOF * pre-commit reformat * improve graphics * new images and dynamic window size * darker tile borders and fix ICC profile * pre-commit hook * adjust elf and stool size * Update frozen_lake.py * reformat * fix #2600 * #2600 * add rgb_array support * reformat * test render api change on FrozenLake * add render support for reset on frozenlake * add clock on pygame render * new render api for blackjack * new render api for cliffwalking * new render api for Env class * update reset method, lunar and Env * fix wrapper * fix reset lunar * new render api for box2d envs * new render api for mujoco envs * fix bug * new render api for classic control envs * fix tests * add render_mode None for CartPole * new render api for test fake envs * pre-commit hook * fix FrozenLake * fix FrozenLake * more render_mode to super - frozenlake * remove kwargs from frozen_lake new * pre-commit hook * add deprecated render method * add backwards compatibility * fix test * add _render * move pygame.init() (avoid pygame dependency on init) * fix pygame dependencies * remove collect_render() maintain multi-behaviours .render() * add type hints * fix renderer * don't call .render() with None * improve docstring * add single_rgb_array to all envs * remove None from metadata["render_modes"] * add type hints to test_env_checkers * fix lint * add comments to renderer * add comments to single_depth_array and single_state_pixels * reformat * add deprecation warnings and env.render_mode declaration * fix lint * reformat * fix tests * add docs * fix car racing determinism * remove warning test envs, customizable modes on renderer * remove commments and add todo for env_checker * fix car racing * replace render mode check with assert * update new mujoco * reformat * reformat * change metaclass definition * fix tests * implement mark suggestions (test, docs, sets) * check_render Co-authored-by: J K Terry <jkterry0@gmail.com>
2022-06-08 00:20:56 +02:00
)
# episode reset time steps: 0, 18, 44, 55, 80, 103, 117, 143, 173, 191
# steps recorded: 0-18, 55-80, 100-103
env.reset(seed=123)
env.action_space.seed(123)
for i in range(199):
action = env.action_space.sample()
_, _, terminated, truncated, _ = env.step(action)
if terminated or truncated:
env.reset()
env.close()
assert os.path.isdir("videos")
mp4_files = [file for file in os.listdir("videos") if file.endswith(".mp4")]
shutil.rmtree("videos")
assert len(mp4_files) == 3
New `info` API for vectorized environments #2657 (#2773) * WIP refactor info API sync vector. * Add missing untracked file. * Add info strategy to reset_wait. * Add interface and docstring. * info with strategy pattern on async vector env. * Add default to async vecenv. * episode statistics for asyncvecnev. * Add tests info strategy format. * Add info strategy to reset_wait. * refactor and cleanup. * Code cleanup. Add tests. * Add tests for video recording with new info format. * fix test case. * fix camelcase. * rename enum. * update tests, docstrings, cleanup. * Changes brax strategy to numpy. add_strategy method in StrategyFactory. Add tests. * fix docstring and logging format. * Set Brax info format as default. Remove classic info format. Update tests. * breaking the wrong loop. * WIP: wrapper. * Add wrapper for brax to classic info. * WIP: wrapper with nested RecordEpisodeStatistic. * Add tests. Refactor docstrings. Cleanup. * cleanup. * patch conflicts. * rebase and conflicts. * new pre-commit conventions. * docstring. * renaming. * incorporate info_processor in vecEnv. * renaming. Create info dict only if needed. * remove all brax references. update docstring. Update duplicate test. * reviews. * pre-commit. * reviews. * docstring. * cleanup blank lines. * add support for numpy dtypes. * docstring fix. * formatting. * naming. * assert correct info from wrappers chaining. Test correct wrappers chaining. naming. * simplify episode_statistics. * change args orer. * update tests. * wip: refactor episode_statistics. * Add test for add_vecore_episode_statistics.
2022-05-24 16:36:35 +02:00
def test_video_length(video_length: int = 10):
"""Test if argument video_length of RecordVideo works properly."""
env = gym.make("CartPole-v1", render_mode="rgb_array")
env = RecordVideo(
env, "videos", step_trigger=lambda x: x == 0, video_length=video_length
)
env.reset(seed=123)
env.action_space.seed(123)
for _ in range(video_length):
_, _, term, trunc, _ = env.step(env.action_space.sample())
if term or trunc:
break
# check that the environment is still recording then take a step to take the number of steps > video length
assert env.recording
env.step(env.action_space.sample())
assert not env.recording
env.close()
# check that only one video is recorded
assert os.path.isdir("videos")
mp4_files = [file for file in os.listdir("videos") if file.endswith(".mp4")]
assert len(mp4_files) == 1
shutil.rmtree("videos")
def test_with_rgb_array_list(n_steps: int = 10):
"""Test if `env.render` works with RenderCollection and RecordVideo."""
# fyi, can't work as a `pytest.mark.parameterize`
env = RecordVideo(
RenderCollection(gym.make("CartPole-v1", render_mode="rgb_array")), "videos"
)
env.reset(seed=123)
env.action_space.seed(123)
for _ in range(n_steps):
env.step(env.action_space.sample())
render_out = env.render()
assert isinstance(render_out, list)
assert len(render_out) == n_steps + 1
assert all(isinstance(render, np.ndarray) for render in render_out)
assert all(render.ndim == 3 for render in render_out)
render_out = env.render()
assert isinstance(render_out, list)
assert len(render_out) == 0
env.close()
shutil.rmtree("videos")
# Test in reverse order
env = RenderCollection(
RecordVideo(gym.make("CartPole-v1", render_mode="rgb_array"), "videos")
)
env.reset(seed=123)
env.action_space.seed(123)
for _ in range(n_steps):
env.step(env.action_space.sample())
render_out = env.render()
assert isinstance(render_out, list)
assert len(render_out) == n_steps + 1
assert all(isinstance(render, np.ndarray) for render in render_out)
assert all(render.ndim == 3 for render in render_out)
render_out = env.render()
assert isinstance(render_out, list)
assert len(render_out) == 0
env.close()
shutil.rmtree("videos")