| |
| |
|
|
| """Environment runtime utilities. |
| |
| This module provides functions for creating and managing environment instances |
| at runtime, including environment creation, episode management, and |
| termination checking. |
| """ |
|
|
| import json |
| import logging |
| import os |
|
|
| import carb |
| import gymnasium as gym |
| import numpy as np |
| import omni.usd |
| from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg, ManagerBasedRLEnv |
|
|
| import robolab.constants |
| from robolab.constants import get_output_dir |
| from robolab.core.environments.config import parse_env_cfg |
| from robolab.core.environments.env import RobolabEnv |
| from robolab.core.events.utils import merge_events_cfg |
| from robolab.core.task.task import resolve_instruction |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| def check_scene_valid(env: ManagerBasedEnv) -> bool: |
| """ |
| Checks the scene has all the required fields for RoboLab. |
| """ |
| if 'robot' not in env.scene.articulations.keys(): |
| raise ValueError("Scene entity 'robot' not found; Available articulations: " + str(list(env.scene.articulations.keys()))) |
|
|
| return True |
|
|
|
|
| def create_env(scene: str | ManagerBasedEnvCfg, |
| device="cuda:0", |
| seed=0, |
| num_envs=1, |
| env_spacing=None, |
| eye=None, |
| lookat=None, |
| use_fabric=True, |
| events=None, |
| instruction_type="default", |
| policy=None, |
| ): |
| """ |
| Creates and initializes a gym environment for the specified scene. Supported types: str, ManagerBasedEnvCfg. |
| Example use: |
| env_cfg = BananaEnvCfg() |
| env = create_env(scene=env_cfg, device="cuda:0", num_envs=1, use_fabric=True) |
| |
| env=create_env(scene="BananaEnv", device="cuda:0", num_envs=1, use_fabric=True) |
| |
| # With a variation event (example: camera pose variation) |
| from robolab.core.events.reset_camera import reset_camera_pose_uniform |
| from isaaclab.managers import EventTermCfg as EventTerm |
| env, env_cfg = create_env( |
| scene="BananaEnv", |
| events={ |
| "reset_camera": EventTerm( |
| func=reset_camera_pose_uniform, |
| mode="reset", |
| params={ |
| "camera_names": ["over_shoulder_left_camera"], |
| "pose_range": {"x": (-0.05, 0.05), "y": (-0.05, 0.05)}, |
| } |
| ) |
| } |
| ) |
| |
| # Or using the configclass helper |
| from robolab.core.events.reset_camera import RandomizeCameraPoseUniform |
| events = RandomizeCameraPoseUniform.from_params( |
| cameras=["over_shoulder_left_camera"], |
| pose_range={"x": (-0.05, 0.05), "y": (-0.05, 0.05)} |
| ) |
| env, env_cfg = create_env(scene="BananaEnv", events=events) |
| |
| Args: |
| scene (str, ManagerBasedEnvCfg): The scene name, or environment configuration |
| device: The device to run the environment on (e.g., 'cuda', 'cpu') |
| num_envs (int, optional): Number of environments to spawn. Defaults to 1. |
| use_fabric (bool, optional): Whether to use fabric for physics simulation. Defaults to True. |
| events: Event configuration to add to the environment. Can be: |
| - A dict of {event_name: EventTerm} (automatically converted to configclass) |
| - A configclass instance with EventTerm attributes |
| instruction_type: Which instruction variant to use when the task defines |
| instruction as a dict (e.g., "default", "vague", "specific"). Ignored |
| when instruction is a plain string. Defaults to "default". |
| policy: Policy backend name (e.g., "pi0", "gr00t"). Stored on env_cfg |
| so downstream code (e.g., run_episode) can read it. |
| |
| Raises: |
| ValueError: If the scene type is not supported or environment creation fails |
| |
| Returns: |
| tuple: (env, env_cfg) - The created environment instance and its configuration |
| """ |
| env = None |
|
|
| if isinstance(scene, str): |
| |
| omni.usd.get_context().new_stage() |
| |
| carb.settings.get_settings().set_bool("/isaaclab/render/rtx_sensors", False) |
|
|
| try: |
| |
| env_cfg = parse_env_cfg( |
| scene, |
| device=device, |
| seed=seed, |
| num_envs=num_envs, |
| env_spacing=env_spacing, |
| use_fabric=use_fabric, |
| eye=eye, |
| lookat=lookat, |
| ) |
|
|
| env_cfg._instruction_variants = env_cfg.instruction |
| env_cfg.instruction = resolve_instruction(env_cfg.instruction, instruction_type) |
|
|
| |
| |
| if events is not None: |
| env_cfg.events = merge_events_cfg(env_cfg.events, events) |
| if robolab.constants.VERBOSE: |
| print(f"Merged events into environment configuration: {env_cfg.events}") |
|
|
| |
| env = gym.make(scene, cfg=env_cfg).unwrapped |
| except Exception: |
| |
| |
| |
| if env is not None and hasattr(env, "_is_closed") and not env._is_closed: |
| try: |
| env.close() |
| except Exception: |
| logger.exception("env.close() failed during error cleanup") |
| raise |
|
|
| elif isinstance(scene, ManagerBasedEnvCfg): |
| |
| omni.usd.get_context().new_stage() |
| |
| carb.settings.get_settings().set_bool("/isaaclab/render/rtx_sensors", False) |
| env_cfg = scene |
|
|
| env_cfg._instruction_variants = env_cfg.instruction |
| env_cfg.instruction = resolve_instruction(env_cfg.instruction, instruction_type) |
|
|
| |
| |
| if events is not None: |
| env_cfg.events = merge_events_cfg(env_cfg.events, events) |
| if robolab.constants.VERBOSE: |
| print(f"Merged events into environment configuration: {env_cfg.events}") |
|
|
| env = RobolabEnv(env_cfg) |
| else: |
| raise ValueError(f"Unsupported scene type: {type(scene)}") |
|
|
| if env is None: |
| raise ValueError(f"Failed to create environment for scene {scene}") |
|
|
| check_scene_valid(env) |
|
|
| |
| env.sim._app_control_on_stop_handle = None |
|
|
| env.output_dir = get_output_dir() |
| os.makedirs(env.output_dir, exist_ok=True) |
|
|
| if policy is not None: |
| env_cfg.policy = policy |
|
|
| from robolab.core.utils.print_utils import print_env_info |
| env_name = scene if isinstance(scene, str) else env_cfg.__class__.__name__ |
| print_env_info( |
| env_name=env_name, |
| instruction=env_cfg.instruction, |
| instruction_type=instruction_type, |
| seed=env_cfg.seed, |
| policy=policy or "", |
| scene_name=env_cfg.scene.__class__.__name__, |
| attributes=getattr(env_cfg, '_task_attributes', None), |
| ) |
|
|
| |
| with open(os.path.join(env.output_dir, "env_cfg.json"), "w") as f: |
| json.dump(env_cfg.to_dict(), f, default=str) |
| if robolab.constants.VERBOSE: |
| print(f"Saved env_cfg to {os.path.join(env.output_dir, 'env_cfg.json')}") |
|
|
| return env, env_cfg |
|
|
|
|
| def end_episode(env: ManagerBasedRLEnv): |
| from robolab.core.logging.recorder_manager import RobolabRecorderManager |
| |
| if env.recorder_manager is not None: |
| if isinstance(env.recorder_manager, RobolabRecorderManager)and env.recorder_manager.initialized: |
| if robolab.constants.VERBOSE: |
| print("Exporting data....") |
| env.recorder_manager.export_episodes() |
| if robolab.constants.VERBOSE: |
| print("Episodes exported. ") |
| env.recorder_manager.clear() |
|
|
|
|
| def check_terminated(env: ManagerBasedRLEnv, term, trunc) -> np.ndarray: |
| """ |
| Check termination status for each environment. |
| |
| Usage: |
| succ_vec = check_terminated(env, term, trunc) |
| if any(succ_vec, None): |
| # still running |
| continue |
| else: |
| return succ_vec |
| |
| Args: |
| env: The environment instance |
| term: Termination tensor of shape [N] |
| trunc: Truncation tensor of shape [N] |
| |
| Returns: |
| Numpy array of shape [N] stored on CPU where: |
| - True: episode terminated (term=True) |
| - False: episode truncated (trunc=True and term=False) |
| - None: episode still running (both term=False and trunc=False) |
| """ |
| import torch |
|
|
| |
| term_bool = term.bool().cpu() |
| trunc_bool = trunc.bool().cpu() |
|
|
| |
| result = torch.zeros_like(term, dtype=torch.bool).cpu().numpy().astype(object) |
|
|
| |
| result[term_bool.numpy()] = True |
|
|
| |
| result[(trunc_bool & ~term_bool).numpy()] = False |
|
|
| |
| still_running = ~(term_bool | trunc_bool) |
| result[still_running.numpy()] = None |
|
|
| return result |
|
|