LCOV - code coverage report
Current view: top level - scripts - render_compare.py (source / functions) Coverage Total Hit
Test: EnvPool coverage report Lines: 59.0 % 300 177
Test Date: 2026-11-08 03:08:01 Functions: 50.0 % 18 9
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 38.3 % 60 23

             Branch data     Line data    Source code
       1                 :             : #!/usr/bin/env python3
       2                 :             : 
       3                 :             : # Copyright 2026 Garena Online Private Limited
       4                 :             : #
       5                 :             : # Licensed under the Apache License, Version 2.0 (the "License");
       6                 :             : # you may not use this file except in compliance with the License.
       7                 :             : # You may obtain a copy of the License at
       8                 :             : #
       9                 :             : #      http://www.apache.org/licenses/LICENSE-2.0
      10                 :             : #
      11                 :             : # Unless required by applicable law or agreed to in writing, software
      12                 :             : # distributed under the License is distributed on an "AS IS" BASIS,
      13                 :             : # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      14                 :             : # See the License for the specific language governing permissions and
      15                 :             : # limitations under the License.
      16                 :             : """Generate render comparison and sample images for docs."""
      17                 :             : 
      18                 :           1 : from __future__ import annotations
      19                 :             : 
      20                 :           1 : import argparse
      21                 :           1 : import math
      22                 :           1 : import os
      23                 :           1 : from collections.abc import Callable
      24                 :           1 : from dataclasses import dataclass
      25                 :           1 : from pathlib import Path
      26                 :           1 : from typing import Any
      27                 :             : 
      28                 :           1 : import numpy as np
      29                 :           1 : from PIL import Image, ImageDraw, ImageFont
      30                 :             : 
      31                 :           1 : from envpool.mujoco.render_oracle import configure_linux_mujoco_gl
      32                 :           1 : from envpool.python.glfw_context import preload_windows_gl_dlls
      33                 :             : 
      34                 :           1 : preload_windows_gl_dlls(strict=True)
      35                 :           1 : configure_linux_mujoco_gl()
      36                 :             : 
      37                 :             : 
      38                 :           1 : @dataclass(frozen=True)
      39                 :           1 : class RenderCompareConfig:
      40                 :             :     """Shared image generation and comparison settings."""
      41                 :             : 
      42                 :           1 :     family: str
      43                 :           1 :     tile_width: int
      44                 :           1 :     tile_height: int
      45                 :           1 :     source_width: int
      46                 :           1 :     source_height: int
      47                 :           1 :     columns: int
      48                 :           1 :     seed: int
      49                 :           1 :     camera_id: int
      50                 :           1 :     max_mean_abs_diff: float
      51                 :           1 :     max_mismatch_ratio: float
      52                 :           1 :     max_ignored_abs_diff: int
      53                 :           1 :     require_bitwise: bool
      54                 :           1 :     flip_vertical: bool
      55                 :             : 
      56                 :             : 
      57                 :           1 : RenderPairFn = Callable[
      58                 :             :     [str, RenderCompareConfig], tuple[np.ndarray, np.ndarray | None]
      59                 :             : ]
      60                 :             : 
      61                 :             : 
      62                 :           1 : @dataclass(frozen=True)
      63                 :           1 : class RenderItem:
      64                 :             :     """One family-specific render key and its display label."""
      65                 :             : 
      66                 :           1 :     key: str
      67                 :           1 :     label: str
      68                 :             : 
      69                 :             : 
      70                 :           1 : @dataclass(frozen=True)
      71                 :           1 : class RenderFamily:
      72                 :             :     """Family-specific render integration."""
      73                 :             : 
      74                 :           1 :     items: tuple[RenderItem, ...]
      75                 :           1 :     default_output: Path
      76                 :           1 :     render_pair: RenderPairFn
      77                 :           1 :     left_title: str = "EnvPool"
      78                 :           1 :     right_title: str | None = "Official"
      79                 :           1 :     default_flip_vertical: bool = False
      80                 :           1 :     compare_frames: bool = True
      81                 :             : 
      82                 :             : 
      83                 :           1 : _PAIR_GAP = 4
      84                 :           1 : _CELL_GAP = 12
      85                 :           1 : _HEADER_HEIGHT = 28
      86                 :           1 : _MARGIN = 16
      87                 :             : 
      88                 :             : 
      89                 :           1 : def _make_craftax_family() -> RenderFamily:
      90                 :             :     """Build the Craftax comparison adapter using actual gameplay frames."""
      91                 :           0 :     import envpool.craftax.registration  # noqa: F401
      92                 :           0 :     from envpool.craftax.oracle import (
      93                 :             :         assert_pixels,
      94                 :             :         encode,
      95                 :             :         jax,
      96                 :             :         make_oracle,
      97                 :             :         renderer,
      98                 :             :         rollout_action,
      99                 :             :         state_layout,
     100                 :             :         sync_world,
     101                 :             :     )
     102                 :           0 :     from envpool.registration import make_gymnasium
     103                 :             : 
     104                 :           0 :     scenes = {
     105                 :             :         "Classic": (True, 0, 96),
     106                 :             :         "Craftax": (False, 0, 96),
     107                 :             :         "Cave": (False, 2, 48),
     108                 :             :     }
     109                 :             : 
     110                 :           0 :     def render_pair(
     111                 :             :         scene: str, cfg: RenderCompareConfig
     112                 :             :     ) -> tuple[np.ndarray, np.ndarray]:
     113                 :           0 :         classic, level, length = scenes[scene]
     114                 :           0 :         task = "Craftax-" + ("Classic-" if classic else "") + "Symbolic-v1"
     115                 :           0 :         oracle, params = make_oracle(task)
     116                 :           0 :         params = params.replace(mob_despawn_distance=1)
     117                 :           0 :         key = jax.random.PRNGKey(cfg.seed + 1000)
     118                 :           0 :         _, state = oracle.reset(key, params)
     119                 :           0 :         layout = state_layout(state, classic)
     120                 :           0 :         kwargs: dict[str, Any] = {}
     121         [ #  # ]:           0 :         if level:
     122                 :           0 :             state = state.replace(
     123                 :             :                 player_level=jax.numpy.asarray(level, dtype=jax.numpy.int32),
     124                 :             :                 player_position=state.up_ladders[level],
     125                 :             :             )
     126                 :           0 :             kwargs["initial_state"] = encode(state, layout).tolist()
     127                 :           0 :         pool = make_gymnasium(
     128                 :             :             task,
     129                 :             :             num_envs=1,
     130                 :             :             seed=cfg.seed,
     131                 :             :             render_mode="rgb_array",
     132                 :             :             mob_despawn_distance=1,
     133                 :             :             debug_state=True,
     134                 :             :             **kwargs,
     135                 :             :         )
     136                 :           0 :         step = jax.jit(oracle.step_env)
     137                 :           0 :         rng = np.random.default_rng(40)
     138                 :           0 :         try:
     139                 :           0 :             _, info = pool.reset()
     140         [ #  # ]:           0 :             if not level:
     141                 :           0 :                 state = sync_world(
     142                 :             :                     state, info["state"][0], layout, classic, params
     143                 :             :                 )
     144         [ #  # ]:           0 :             for _ in range(length):
     145                 :           0 :                 key, draw = jax.random.split(key)
     146                 :           0 :                 action = rollout_action(
     147                 :             :                     state, int(rng.integers(17 if classic else 43)), classic
     148                 :             :                 )
     149                 :           0 :                 _, state, _, _, _ = step(draw, state, action, params)
     150                 :           0 :                 pool.step(np.array([action], np.int32))
     151                 :           0 :             actual = np.asarray(pool.render())[0]
     152                 :           0 :             expected = np.asarray(renderer(classic)(state))
     153                 :           0 :             assert_pixels(actual, expected, scene)
     154                 :           0 :             return actual, expected.astype(np.uint8)
     155                 :             :         finally:
     156                 :           0 :             pool.close()
     157                 :             : 
     158                 :           0 :     return RenderFamily(
     159                 :             :         items=tuple(
     160                 :             :             RenderItem(key=scene, label=f"{scene} / {length} actions")
     161                 :             :             for scene, (_, _, length) in scenes.items()
     162                 :             :         ),
     163                 :             :         default_output=Path(
     164                 :             :             "docs/_static/render_samples/craftax_official_compare.png"
     165                 :             :         ),
     166                 :             :         render_pair=render_pair,
     167                 :             :         right_title="Official Craftax 1.6.1",
     168                 :             :     )
     169                 :             : 
     170                 :             : 
     171                 :           1 : def _make_metaworld_family() -> RenderFamily:
     172                 :             :     """Build the MetaWorld render comparison adapter."""
     173                 :           0 :     import mujoco
     174                 :           0 :     from metaworld.env_dict import ALL_V3_ENVIRONMENTS
     175                 :             : 
     176                 :           0 :     import envpool.mujoco.metaworld.registration as metaworld_registration
     177                 :           0 :     from envpool.registration import make_gymnasium
     178                 :             : 
     179                 :           0 :     def make_oracle(task_name: str, cfg: RenderCompareConfig) -> Any:
     180                 :           0 :         env = ALL_V3_ENVIRONMENTS[task_name](
     181                 :             :             render_mode="rgb_array",
     182                 :             :             camera_id=cfg.camera_id,
     183                 :             :         )
     184                 :           0 :         env._set_task_called = True
     185                 :           0 :         env._partially_observable = True
     186                 :           0 :         env.mujoco_renderer.width = cfg.source_width
     187                 :           0 :         env.mujoco_renderer.height = cfg.source_height
     188                 :           0 :         return env
     189                 :             : 
     190                 :           0 :     def sync_reset_state(oracle: Any, info: dict[str, Any]) -> None:
     191                 :           0 :         required_keys = (
     192                 :             :             "rand_vec0",
     193                 :             :             "qpos0",
     194                 :             :             "qvel0",
     195                 :             :             "mocap_pos0",
     196                 :             :             "mocap_quat0",
     197                 :             :             "qacc0",
     198                 :             :             "qacc_warmstart0",
     199                 :             :             "init_tcp0",
     200                 :             :             "init_left_pad0",
     201                 :             :             "init_right_pad0",
     202                 :             :         )
     203                 :           0 :         missing = [key for key in required_keys if key not in info]
     204         [ #  # ]:           0 :         if missing:
     205                 :           0 :             raise RuntimeError(
     206                 :             :                 "MetaWorld render comparison must be generated with "
     207                 :             :                 "`bazel run --config=debug //scripts:render_compare -- "
     208                 :             :                 "--family=metaworld` so EnvPool exposes reset-sync info. "
     209                 :             :                 f"Missing keys: {missing}"
     210                 :             :             )
     211                 :             : 
     212                 :           0 :         rand_vec = np.asarray(info["rand_vec0"][0], dtype=np.float64)
     213                 :           0 :         random_dim = int(oracle._random_reset_space.low.size)
     214                 :           0 :         oracle._freeze_rand_vec = True
     215                 :           0 :         oracle._last_rand_vec = rand_vec[:random_dim].copy()
     216                 :           0 :         oracle.reset()
     217                 :             : 
     218                 :           0 :         qpos = np.asarray(info["qpos0"][0], dtype=np.float64)[
     219                 :             :             : oracle.data.qpos.size
     220                 :             :         ]
     221                 :           0 :         qvel = np.asarray(info["qvel0"][0], dtype=np.float64)[
     222                 :             :             : oracle.data.qvel.size
     223                 :             :         ]
     224                 :           0 :         oracle.set_state(qpos, qvel)
     225                 :           0 :         oracle.data.mocap_pos[0] = np.asarray(
     226                 :             :             info["mocap_pos0"][0], dtype=np.float64
     227                 :             :         )
     228                 :           0 :         oracle.data.mocap_quat[0] = np.asarray(
     229                 :             :             info["mocap_quat0"][0], dtype=np.float64
     230                 :             :         )
     231                 :           0 :         oracle.data.qacc[:] = np.asarray(info["qacc0"][0], dtype=np.float64)[
     232                 :             :             : oracle.data.qacc.size
     233                 :             :         ]
     234                 :           0 :         oracle.data.qacc_warmstart[:] = np.asarray(
     235                 :             :             info["qacc_warmstart0"][0], dtype=np.float64
     236                 :             :         )[: oracle.data.qacc_warmstart.size]
     237                 :           0 :         mujoco.mj_forward(oracle.model, oracle.data)
     238                 :           0 :         oracle.init_tcp = np.asarray(
     239                 :             :             info["init_tcp0"][0], dtype=np.float64
     240                 :             :         ).copy()
     241                 :           0 :         oracle.init_left_pad = np.asarray(
     242                 :             :             info["init_left_pad0"][0], dtype=np.float64
     243                 :             :         ).copy()
     244                 :           0 :         oracle.init_right_pad = np.asarray(
     245                 :             :             info["init_right_pad0"][0], dtype=np.float64
     246                 :             :         ).copy()
     247         [ #  # ]:           0 :         if hasattr(oracle, "_handle_init_pos"):
     248                 :           0 :             oracle._handle_init_pos = oracle._get_pos_objects().copy()
     249                 :             : 
     250                 :           0 :         curr_obs = oracle._get_curr_obs_combined_no_goal()
     251                 :           0 :         oracle._prev_obs = curr_obs.copy()
     252                 :           0 :         obs = oracle._get_obs().astype(np.float64)
     253                 :           0 :         oracle._last_stable_obs = obs.copy()
     254                 :             : 
     255                 :           0 :     def render_pair(
     256                 :             :         task_name: str,
     257                 :             :         cfg: RenderCompareConfig,
     258                 :             :     ) -> tuple[np.ndarray, np.ndarray]:
     259                 :           0 :         task_id = metaworld_registration.metaworld_task_id(task_name)
     260                 :           0 :         env = make_gymnasium(
     261                 :             :             task_id,
     262                 :             :             num_envs=1,
     263                 :             :             seed=cfg.seed,
     264                 :             :             render_mode="rgb_array",
     265                 :             :             render_width=cfg.source_width,
     266                 :             :             render_height=cfg.source_height,
     267                 :             :             render_camera_id=cfg.camera_id,
     268                 :             :         )
     269                 :           0 :         oracle = make_oracle(task_name, cfg)
     270                 :           0 :         try:
     271                 :           0 :             _, info = env.reset()
     272                 :           0 :             sync_reset_state(oracle, info)
     273                 :           0 :             envpool_frame = env.render()
     274         [ #  # ]:           0 :             if envpool_frame is None:
     275                 :           0 :                 raise RuntimeError(f"{task_id} returned no EnvPool frame")
     276                 :           0 :             return envpool_frame[0], oracle.render()
     277                 :             :         finally:
     278                 :           0 :             env.close()
     279                 :           0 :             oracle.close()
     280                 :             : 
     281                 :           0 :     return RenderFamily(
     282                 :             :         items=tuple(
     283                 :             :             RenderItem(
     284                 :             :                 key=task_name,
     285                 :             :                 label=metaworld_registration.metaworld_public_task_name(
     286                 :             :                     task_name
     287                 :             :                 ),
     288                 :             :             )
     289                 :             :             for task_name in metaworld_registration.metaworld_v3_envs
     290                 :             :         ),
     291                 :             :         default_output=Path(
     292                 :             :             "docs/_static/render_samples/metaworld_official_compare.png"
     293                 :             :         ),
     294                 :             :         render_pair=render_pair,
     295                 :             :         default_flip_vertical=True,
     296                 :             :     )
     297                 :             : 
     298                 :             : 
     299                 :           1 : def _make_jumanji_family() -> RenderFamily:
     300                 :             :     """Use the same reset synchronization as independent alignment tests."""
     301                 :           0 :     import envpool.jumanji.registration as jumanji_registration
     302                 :           0 :     from envpool.jumanji import oracle
     303                 :           0 :     from envpool.registration import make_gymnasium
     304                 :             : 
     305                 :           0 :     def render_pair(
     306                 :             :         task_id: str, cfg: RenderCompareConfig
     307                 :             :     ) -> tuple[np.ndarray, np.ndarray]:
     308                 :           0 :         official_env = oracle._make_official_env(task_id)
     309                 :           0 :         env = None
     310                 :           0 :         try:
     311                 :           0 :             state, timestep = official_env.reset(
     312                 :             :                 oracle.jax.random.PRNGKey(cfg.seed)
     313                 :             :             )
     314                 :           0 :             kwargs = oracle._envpool_kwargs_from_official_state(
     315                 :             :                 task_id, state, timestep.observation
     316                 :             :             )
     317         [ #  # ]:           0 :             if task_id == "Sokoban-v0":
     318                 :           0 :                 kwargs.update(
     319                 :             :                     base_path="/tmp/envpool-missing-boxoban",
     320                 :             :                     sokoban_level_index=0,
     321                 :             :                 )
     322                 :           0 :             env = make_gymnasium(
     323                 :             :                 task_id,
     324                 :             :                 num_envs=1,
     325                 :             :                 seed=cfg.seed,
     326                 :             :                 render_mode="rgb_array",
     327                 :             :                 render_width=cfg.source_width,
     328                 :             :                 render_height=cfg.source_height,
     329                 :             :                 **kwargs,
     330                 :             :             )
     331                 :           0 :             env.reset()
     332                 :           0 :             frames = env.render()
     333                 :           0 :             assert frames is not None
     334                 :           0 :             return frames[0], oracle._official_render(
     335                 :             :                 official_env, state, cfg.source_width, cfg.source_height
     336                 :             :             )
     337                 :             :         finally:
     338         [ #  # ]:           0 :             if env is not None:
     339                 :           0 :                 env.close()
     340                 :           0 :             official_env.close()
     341                 :             : 
     342                 :           0 :     return RenderFamily(
     343                 :             :         items=tuple(
     344                 :             :             RenderItem(key=task_id, label=task_id)
     345                 :             :             for task_id in jumanji_registration.jumanji_env_ids
     346                 :             :         ),
     347                 :             :         default_output=Path(
     348                 :             :             "docs/_static/render_samples/jumanji_official_compare.png"
     349                 :             :         ),
     350                 :             :         render_pair=render_pair,
     351                 :             :         left_title="EnvPool",
     352                 :             :         right_title="Official",
     353                 :             :         # Native task graphics intentionally use a different layout and style.
     354                 :             :         compare_frames=False,
     355                 :             :     )
     356                 :             : 
     357                 :             : 
     358                 :           1 : def _make_mujoco_playground_family() -> RenderFamily:
     359                 :             :     """Build the MuJoCo Playground official render comparison adapter."""
     360                 :           1 :     from jax import config as jax_config
     361                 :             : 
     362                 :           1 :     jax_config.update("jax_enable_x64", True)
     363                 :             : 
     364                 :           1 :     import mujoco
     365                 :             : 
     366                 :           1 :     import envpool.mujoco.playground.registration as playground_registration
     367                 :           1 :     from envpool.mujoco.playground.oracle import (
     368                 :             :         FrameRenderer,
     369                 :             :         make_oracle,
     370                 :             :         native_config,
     371                 :             :     )
     372                 :           1 :     from envpool.mujoco.render_oracle import configure_macos_mujoco_renderer
     373                 :           1 :     from envpool.registration import make_gymnasium
     374                 :             : 
     375                 :           1 :     configure_macos_mujoco_renderer()
     376                 :             : 
     377                 :           1 :     def make_render_data(model: Any, info: dict[str, Any]) -> Any:
     378                 :           1 :         data = mujoco.MjData(model)
     379                 :           1 :         data.qpos[:] = info["qpos"][0, : model.nq]
     380                 :           1 :         data.qvel[:] = info["qvel"][0, : model.nv]
     381         [ +  - ]:           1 :         if "ctrl" in info:
     382                 :           1 :             data.ctrl[:] = info["ctrl"][0, : model.nu]
     383         [ +  + ]:           1 :         if "mocap_pos" in info:
     384                 :           1 :             data.mocap_pos[:] = info["mocap_pos"][
     385                 :             :                 0, : model.nmocap * 3
     386                 :             :             ].reshape(model.nmocap, 3)
     387         [ +  + ]:           1 :         if "mocap_quat" in info:
     388                 :           1 :             data.mocap_quat[:] = info["mocap_quat"][
     389                 :             :                 0, : model.nmocap * 4
     390                 :             :             ].reshape(model.nmocap, 4)
     391         [ +  - ]:           1 :         if "qacc_warmstart" in info:
     392                 :           1 :             data.qacc_warmstart[:] = info["qacc_warmstart"][0, : model.nv]
     393                 :           1 :         mujoco.mj_forward(model, data)
     394         [ +  - ]:           1 :         if "qacc" in info:
     395                 :           1 :             data.qacc[:] = info["qacc"][0, : model.nv]
     396         [ +  - ]:           1 :         if "qacc_warmstart" in info:
     397                 :           1 :             data.qacc_warmstart[:] = info["qacc_warmstart"][0, : model.nv]
     398         [ +  - ]:           1 :         if "sensordata" in info:
     399                 :           1 :             data.sensordata[:] = info["sensordata"][0, : data.sensordata.size]
     400                 :           1 :         return data
     401                 :             : 
     402                 :           1 :     def render_pair(
     403                 :             :         task_id: str,
     404                 :             :         cfg: RenderCompareConfig,
     405                 :             :     ) -> tuple[np.ndarray, np.ndarray]:
     406                 :           1 :         oracle = make_oracle(task_id)
     407                 :           1 :         env = make_gymnasium(
     408                 :             :             task_id,
     409                 :             :             num_envs=1,
     410                 :             :             seed=cfg.seed,
     411                 :             :             render_mode="rgb_array",
     412                 :             :             render_width=cfg.source_width,
     413                 :             :             render_height=cfg.source_height,
     414                 :             :             **native_config(task_id),
     415                 :             :         )
     416                 :           1 :         try:
     417                 :           1 :             _, info = env.reset()
     418                 :           1 :             render_model = oracle.mj_model
     419                 :           1 :             render_data = make_render_data(render_model, info)
     420                 :           1 :             renderer = FrameRenderer(
     421                 :             :                 oracle,
     422                 :             :                 task_id,
     423                 :             :                 width=cfg.source_width,
     424                 :             :                 height=cfg.source_height,
     425                 :             :             )
     426                 :           1 :             try:
     427                 :           1 :                 official_frame = renderer.render(render_data)
     428                 :             :             finally:
     429                 :           1 :                 renderer.close()
     430                 :           1 :             envpool_frame = env.render(env_ids=[0])
     431         [ -  + ]:           1 :             if envpool_frame is None:
     432                 :           0 :                 raise RuntimeError(f"{task_id} returned no EnvPool frame")
     433                 :           1 :             return np.asarray(envpool_frame[0]), official_frame
     434                 :             :         finally:
     435                 :           1 :             env.close()
     436                 :             : 
     437                 :           1 :     return RenderFamily(
     438                 :             :         items=tuple(
     439                 :             :             RenderItem(
     440                 :             :                 key=f"{task_name}-v1",
     441                 :             :                 label=task_name
     442                 :             :                 .replace("BerkeleyHumanoid", "Berkeley ")
     443                 :             :                 .replace("G1", "G1 ")
     444                 :             :                 .replace("Go1", "Go1 ")
     445                 :             :                 .replace("Op3", "OP3"),
     446                 :             :             )
     447                 :             :             for task_name in playground_registration.PLAYGROUND_ENVS
     448                 :             :         ),
     449                 :             :         default_output=Path(
     450                 :             :             "docs/_static/render_samples/mujoco_playground_official_compare.png"
     451                 :             :         ),
     452                 :             :         render_pair=render_pair,
     453                 :             :     )
     454                 :             : 
     455                 :             : 
     456                 :           1 : _FAMILY_BUILDERS: dict[str, Callable[[], RenderFamily]] = {
     457                 :             :     "craftax": _make_craftax_family,
     458                 :             :     "jumanji": _make_jumanji_family,
     459                 :             :     "metaworld": _make_metaworld_family,
     460                 :             :     "mujoco_playground": _make_mujoco_playground_family,
     461                 :             : }
     462                 :             : 
     463                 :             : 
     464                 :           1 : def _make_display_image(
     465                 :             :     frame: np.ndarray, cfg: RenderCompareConfig
     466                 :             : ) -> Image.Image:
     467                 :           1 :     image = Image.fromarray(np.asarray(frame, dtype=np.uint8))
     468         [ -  + ]:           1 :     if image.mode != "RGB":
     469                 :           0 :         image = image.convert("RGB")
     470         [ -  + ]:           1 :     if cfg.flip_vertical:
     471                 :           0 :         image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
     472                 :           1 :     size = (cfg.tile_width, cfg.tile_height)
     473         [ -  + ]:           1 :     if image.size == size:
     474                 :           0 :         return image
     475                 :           1 :     return image.resize(size, Image.Resampling.LANCZOS)
     476                 :             : 
     477                 :             : 
     478                 :           1 : def _render_mismatch_message(
     479                 :             :     label: str,
     480                 :             :     diff: np.ndarray,
     481                 :             :     mismatch_ratio: float,
     482                 :             :     max_ignored_abs_diff: int,
     483                 :             : ) -> str:
     484                 :           0 :     return (
     485                 :             :         f"{label} render mismatch: "
     486                 :             :         f"mean_abs_diff={float(diff.mean()):.6f}, "
     487                 :             :         f"max_abs_diff={int(diff.max())}, "
     488                 :             :         f"mismatch_ratio={mismatch_ratio:.6%}, "
     489                 :             :         f"ignored_abs_diff={max_ignored_abs_diff}"
     490                 :             :     )
     491                 :             : 
     492                 :             : 
     493                 :           1 : def _assert_frames_match(
     494                 :             :     label: str,
     495                 :             :     envpool_frame: np.ndarray,
     496                 :             :     official_frame: np.ndarray,
     497                 :             :     cfg: RenderCompareConfig,
     498                 :             : ) -> None:
     499         [ -  + ]:           1 :     if envpool_frame.shape != official_frame.shape:
     500                 :           0 :         raise RuntimeError(
     501                 :             :             f"{label} render shape mismatch: "
     502                 :             :             f"{envpool_frame.shape} != {official_frame.shape}"
     503                 :             :         )
     504         [ +  - ]:           1 :     if np.array_equal(envpool_frame, official_frame):
     505                 :           1 :         return
     506                 :             : 
     507                 :           0 :     diff = np.abs(
     508                 :             :         envpool_frame.astype(np.int16) - official_frame.astype(np.int16)
     509                 :             :     )
     510                 :           0 :     mismatch_ratio = float(np.count_nonzero(diff)) / float(diff.size)
     511         [ #  # ]:           0 :     if cfg.require_bitwise:
     512                 :           0 :         raise RuntimeError(
     513                 :             :             _render_mismatch_message(label, diff, mismatch_ratio, 0)
     514                 :             :         )
     515                 :             : 
     516                 :           0 :     mean_abs_diff = float(diff.mean())
     517                 :           0 :     significant = diff > cfg.max_ignored_abs_diff
     518                 :           0 :     mismatch_ratio = float(np.count_nonzero(significant)) / float(diff.size)
     519         [ #  # ]:           0 :     if (
     520                 :             :         mean_abs_diff > cfg.max_mean_abs_diff
     521                 :             :         or mismatch_ratio > cfg.max_mismatch_ratio
     522                 :             :     ):
     523                 :           0 :         raise RuntimeError(
     524                 :             :             _render_mismatch_message(
     525                 :             :                 label, diff, mismatch_ratio, cfg.max_ignored_abs_diff
     526                 :             :             )
     527                 :             :         )
     528                 :             : 
     529                 :             : 
     530                 :           1 : def _draw_panel(
     531                 :             :     canvas: Image.Image,
     532                 :             :     family: RenderFamily,
     533                 :             :     label: str,
     534                 :             :     envpool_image: Image.Image,
     535                 :             :     official_image: Image.Image | None,
     536                 :             :     index: int,
     537                 :             :     cfg: RenderCompareConfig,
     538                 :             :     font: Any,
     539                 :             : ) -> None:
     540                 :           1 :     draw = ImageDraw.Draw(canvas)
     541                 :           1 :     has_official = official_image is not None
     542                 :           1 :     cell_width = cfg.tile_width * (2 if has_official else 1)
     543         [ +  - ]:           1 :     if has_official:
     544                 :           1 :         cell_width += _PAIR_GAP
     545                 :           1 :     cell_height = _HEADER_HEIGHT + cfg.tile_height
     546                 :           1 :     col = index % cfg.columns
     547                 :           1 :     row = index // cfg.columns
     548                 :           1 :     left = _MARGIN + col * (cell_width + _CELL_GAP)
     549                 :           1 :     top = _MARGIN + row * (cell_height + _CELL_GAP)
     550                 :           1 :     frame_top = top + _HEADER_HEIGHT
     551                 :             : 
     552                 :           1 :     draw.text((left, top), label, fill=(30, 30, 30), font=font)
     553                 :           1 :     draw.text((left, top + 14), family.left_title, fill=(80, 80, 80), font=font)
     554                 :           1 :     canvas.paste(envpool_image, (left, frame_top))
     555                 :           1 :     draw.rectangle(
     556                 :             :         [
     557                 :             :             left,
     558                 :             :             frame_top,
     559                 :             :             left + cfg.tile_width - 1,
     560                 :             :             frame_top + cfg.tile_height - 1,
     561                 :             :         ],
     562                 :             :         outline=(205, 205, 205),
     563                 :             :     )
     564         [ +  - ]:           1 :     if has_official:
     565                 :           1 :         official_left = left + cfg.tile_width + _PAIR_GAP
     566                 :           1 :         assert family.right_title is not None
     567                 :           1 :         draw.text(
     568                 :             :             (official_left, top + 14),
     569                 :             :             family.right_title,
     570                 :             :             fill=(80, 80, 80),
     571                 :             :             font=font,
     572                 :             :         )
     573                 :           1 :         canvas.paste(official_image, (official_left, frame_top))
     574                 :           1 :         draw.rectangle(
     575                 :             :             [
     576                 :             :                 official_left,
     577                 :             :                 frame_top,
     578                 :             :                 official_left + cfg.tile_width - 1,
     579                 :             :                 frame_top + cfg.tile_height - 1,
     580                 :             :             ],
     581                 :             :             outline=(205, 205, 205),
     582                 :             :         )
     583                 :             : 
     584                 :             : 
     585                 :           1 : def generate(
     586                 :             :     output: Path, family: RenderFamily, cfg: RenderCompareConfig
     587                 :             : ) -> None:
     588                 :             :     """Generate and write one docs render image."""
     589                 :           1 :     rows = math.ceil(len(family.items) / cfg.columns)
     590                 :           1 :     has_official = family.right_title is not None
     591                 :           1 :     cell_width = cfg.tile_width * (2 if has_official else 1)
     592         [ +  - ]:           1 :     if has_official:
     593                 :           1 :         cell_width += _PAIR_GAP
     594                 :           1 :     cell_height = _HEADER_HEIGHT + cfg.tile_height
     595                 :           1 :     width = _MARGIN * 2 + cfg.columns * cell_width
     596                 :           1 :     width += (cfg.columns - 1) * _CELL_GAP
     597                 :           1 :     height = _MARGIN * 2 + rows * cell_height + (rows - 1) * _CELL_GAP
     598                 :           1 :     canvas = Image.new("RGB", (width, height), (255, 255, 255))
     599                 :           1 :     font = ImageFont.load_default()
     600                 :             : 
     601         [ +  + ]:           1 :     for index, item in enumerate(family.items):
     602                 :           1 :         envpool_frame, official_frame = family.render_pair(item.key, cfg)
     603         [ +  - ]:           1 :         if official_frame is not None and family.compare_frames:
     604                 :           1 :             _assert_frames_match(item.label, envpool_frame, official_frame, cfg)
     605                 :           1 :         envpool_image = _make_display_image(envpool_frame, cfg)
     606                 :           1 :         official_image = (
     607                 :             :             None
     608                 :             :             if official_frame is None
     609                 :             :             else _make_display_image(official_frame, cfg)
     610                 :             :         )
     611                 :           1 :         _draw_panel(
     612                 :             :             canvas,
     613                 :             :             family,
     614                 :             :             item.label,
     615                 :             :             envpool_image,
     616                 :             :             official_image,
     617                 :             :             index,
     618                 :             :             cfg,
     619                 :             :             font,
     620                 :             :         )
     621                 :             : 
     622                 :           1 :     output.parent.mkdir(parents=True, exist_ok=True)
     623                 :           1 :     canvas.save(output)
     624                 :             : 
     625                 :             : 
     626                 :           1 : def _parse_args() -> argparse.Namespace:
     627                 :           1 :     parser = argparse.ArgumentParser()
     628                 :           1 :     parser.add_argument(
     629                 :             :         "--family",
     630                 :             :         choices=sorted(_FAMILY_BUILDERS),
     631                 :             :         default="metaworld",
     632                 :             :     )
     633                 :           1 :     parser.add_argument("--output", type=Path)
     634                 :           1 :     parser.add_argument("--tile-width", type=int, default=96)
     635                 :           1 :     parser.add_argument("--tile-height", type=int, default=72)
     636                 :           1 :     parser.add_argument(
     637                 :             :         "--source-width",
     638                 :             :         type=int,
     639                 :             :         default=480,
     640                 :             :         help="Source render width before docs thumbnail downsampling.",
     641                 :             :     )
     642                 :           1 :     parser.add_argument(
     643                 :             :         "--source-height",
     644                 :             :         type=int,
     645                 :             :         default=480,
     646                 :             :         help="Source render height before docs thumbnail downsampling.",
     647                 :             :     )
     648                 :           1 :     parser.add_argument("--columns", type=int, default=5)
     649                 :           1 :     parser.add_argument("--seed", type=int, default=7)
     650                 :           1 :     parser.add_argument(
     651                 :             :         "--camera-id",
     652                 :             :         type=int,
     653                 :             :         default=1,
     654                 :             :         help="Renderer camera id for families that support camera selection.",
     655                 :             :     )
     656                 :           1 :     parser.add_argument("--max-mean-abs-diff", type=float, default=0.25)
     657                 :           1 :     parser.add_argument("--max-mismatch-ratio", type=float, default=0.005)
     658                 :           1 :     parser.add_argument(
     659                 :             :         "--max-ignored-abs-diff",
     660                 :             :         type=int,
     661                 :             :         default=0,
     662                 :             :         help=(
     663                 :             :             "RGB channel deltas up to this value are ignored when computing "
     664                 :             :             "mismatch ratio. Mean absolute diff still uses raw deltas."
     665                 :             :         ),
     666                 :             :     )
     667                 :           1 :     parser.add_argument("--require-bitwise", action="store_true")
     668                 :           1 :     parser.add_argument(
     669                 :             :         "--flip-vertical",
     670                 :             :         action="store_true",
     671                 :             :         default=None,
     672                 :             :         help="Flip both EnvPool and oracle frames vertically in the output.",
     673                 :             :     )
     674                 :           1 :     parser.add_argument(
     675                 :             :         "--no-flip-vertical",
     676                 :             :         action="store_false",
     677                 :             :         dest="flip_vertical",
     678                 :             :         help="Do not vertically flip output frames.",
     679                 :             :     )
     680                 :           1 :     return parser.parse_args()
     681                 :             : 
     682                 :             : 
     683                 :           1 : def main() -> None:
     684                 :             :     """Parse command-line arguments and generate the comparison image."""
     685                 :           1 :     args = _parse_args()
     686                 :           1 :     family = _FAMILY_BUILDERS[args.family]()
     687                 :           1 :     cfg = RenderCompareConfig(
     688                 :             :         family=args.family,
     689                 :             :         tile_width=args.tile_width,
     690                 :             :         tile_height=args.tile_height,
     691                 :             :         source_width=args.source_width,
     692                 :             :         source_height=args.source_height,
     693                 :             :         columns=args.columns,
     694                 :             :         seed=args.seed,
     695                 :             :         camera_id=args.camera_id,
     696                 :             :         max_mean_abs_diff=args.max_mean_abs_diff,
     697                 :             :         max_mismatch_ratio=args.max_mismatch_ratio,
     698                 :             :         max_ignored_abs_diff=args.max_ignored_abs_diff,
     699                 :             :         require_bitwise=args.require_bitwise,
     700                 :             :         flip_vertical=(
     701                 :             :             family.default_flip_vertical
     702                 :             :             if args.flip_vertical is None
     703                 :             :             else args.flip_vertical
     704                 :             :         ),
     705                 :             :     )
     706                 :             : 
     707                 :           1 :     output = args.output or family.default_output
     708         [ -  + ]:           1 :     if not output.is_absolute():
     709                 :           0 :         output = Path(
     710                 :             :             os.environ.get("BUILD_WORKSPACE_DIRECTORY", ".")
     711                 :             :         ).joinpath(output)
     712                 :           1 :     generate(output, family, cfg)
     713                 :             : 
     714                 :             : 
     715         [ -  + ]:           1 : if __name__ == "__main__":
     716                 :           0 :     main()
        

Generated by: LCOV version 2.0-1