file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
isaac-sim/IsaacLab/source/standalone/workflows/robomimic/train.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # MIT License # # Copyright (c) 2021 Stanford Vision and Learning Lab # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ The main entry point for training policies from pre-collected data. Args: algo: name of the algorithm to run. task: name of the environment. name: if provided, override the experiment name defined in the config dataset: if provided, override the dataset path defined in the config This file has been modified from the original version in the following ways: * Added import of AppLauncher from omni.isaac.lab.app to resolve the configuration to load for training. """ """Launch Isaac Sim Simulator first.""" from omni.isaac.lab.app import AppLauncher # launch omniverse app app_launcher = AppLauncher(headless=True) simulation_app = app_launcher.app """Rest everything follows.""" import argparse import gymnasium as gym import json import numpy as np import os import sys import time import torch import traceback from collections import OrderedDict from torch.utils.data import DataLoader import psutil import robomimic.utils.env_utils as EnvUtils import robomimic.utils.file_utils as FileUtils import robomimic.utils.obs_utils as ObsUtils import robomimic.utils.torch_utils as TorchUtils import robomimic.utils.train_utils as TrainUtils from robomimic.algo import RolloutPolicy, algo_factory from robomimic.config import config_factory from robomimic.utils.log_utils import DataLogger, PrintLogger # Needed so that environment is registered import omni.isaac.lab_tasks # noqa: F401 def train(config, device): """Train a model using the algorithm.""" # first set seeds np.random.seed(config.train.seed) torch.manual_seed(config.train.seed) print("\n============= New Training Run with Config =============") print(config) print("") log_dir, ckpt_dir, video_dir = TrainUtils.get_exp_dir(config) print(f">>> Saving logs into directory: {log_dir}") print(f">>> Saving checkpoints into directory: {ckpt_dir}") print(f">>> Saving videos into directory: {video_dir}") if config.experiment.logging.terminal_output_to_txt: # log stdout and stderr to a text file logger = PrintLogger(os.path.join(log_dir, "log.txt")) sys.stdout = logger sys.stderr = logger # read config to set up metadata for observation modalities (e.g. detecting rgb observations) ObsUtils.initialize_obs_utils_with_config(config) # make sure the dataset exists dataset_path = os.path.expanduser(config.train.data) if not os.path.exists(dataset_path): raise FileNotFoundError(f"Dataset at provided path {dataset_path} not found!") # load basic metadata from training file print("\n============= Loaded Environment Metadata =============") env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=config.train.data) shape_meta = FileUtils.get_shape_metadata_from_dataset( dataset_path=config.train.data, all_obs_keys=config.all_obs_keys, verbose=True ) if config.experiment.env is not None: env_meta["env_name"] = config.experiment.env print("=" * 30 + "\n" + "Replacing Env to {}\n".format(env_meta["env_name"]) + "=" * 30) # create environment envs = OrderedDict() if config.experiment.rollout.enabled: # create environments for validation runs env_names = [env_meta["env_name"]] if config.experiment.additional_envs is not None: for name in config.experiment.additional_envs: env_names.append(name) for env_name in env_names: env = EnvUtils.create_env_from_metadata( env_meta=env_meta, env_name=env_name, render=False, render_offscreen=config.experiment.render_video, use_image_obs=shape_meta["use_images"], ) envs[env.name] = env print(envs[env.name]) print("") # setup for a new training run data_logger = DataLogger(log_dir, config=config, log_tb=config.experiment.logging.log_tb) model = algo_factory( algo_name=config.algo_name, config=config, obs_key_shapes=shape_meta["all_shapes"], ac_dim=shape_meta["ac_dim"], device=device, ) # save the config as a json file with open(os.path.join(log_dir, "..", "config.json"), "w") as outfile: json.dump(config, outfile, indent=4) print("\n============= Model Summary =============") print(model) # print model summary print("") # load training data trainset, validset = TrainUtils.load_data_for_training(config, obs_keys=shape_meta["all_obs_keys"]) train_sampler = trainset.get_dataset_sampler() print("\n============= Training Dataset =============") print(trainset) print("") # maybe retrieve statistics for normalizing observations obs_normalization_stats = None if config.train.hdf5_normalize_obs: obs_normalization_stats = trainset.get_obs_normalization_stats() # initialize data loaders train_loader = DataLoader( dataset=trainset, sampler=train_sampler, batch_size=config.train.batch_size, shuffle=(train_sampler is None), num_workers=config.train.num_data_workers, drop_last=True, ) if config.experiment.validate: # cap num workers for validation dataset at 1 num_workers = min(config.train.num_data_workers, 1) valid_sampler = validset.get_dataset_sampler() valid_loader = DataLoader( dataset=validset, sampler=valid_sampler, batch_size=config.train.batch_size, shuffle=(valid_sampler is None), num_workers=num_workers, drop_last=True, ) else: valid_loader = None # main training loop best_valid_loss = None best_return = {k: -np.inf for k in envs} if config.experiment.rollout.enabled else None best_success_rate = {k: -1.0 for k in envs} if config.experiment.rollout.enabled else None last_ckpt_time = time.time() # number of learning steps per epoch (defaults to a full dataset pass) train_num_steps = config.experiment.epoch_every_n_steps valid_num_steps = config.experiment.validation_epoch_every_n_steps for epoch in range(1, config.train.num_epochs + 1): # epoch numbers start at 1 step_log = TrainUtils.run_epoch(model=model, data_loader=train_loader, epoch=epoch, num_steps=train_num_steps) model.on_epoch_end(epoch) # setup checkpoint path epoch_ckpt_name = f"model_epoch_{epoch}" # check for recurring checkpoint saving conditions should_save_ckpt = False if config.experiment.save.enabled: time_check = (config.experiment.save.every_n_seconds is not None) and ( time.time() - last_ckpt_time > config.experiment.save.every_n_seconds ) epoch_check = ( (config.experiment.save.every_n_epochs is not None) and (epoch > 0) and (epoch % config.experiment.save.every_n_epochs == 0) ) epoch_list_check = epoch in config.experiment.save.epochs should_save_ckpt = time_check or epoch_check or epoch_list_check ckpt_reason = None if should_save_ckpt: last_ckpt_time = time.time() ckpt_reason = "time" print(f"Train Epoch {epoch}") print(json.dumps(step_log, sort_keys=True, indent=4)) for k, v in step_log.items(): if k.startswith("Time_"): data_logger.record(f"Timing_Stats/Train_{k[5:]}", v, epoch) else: data_logger.record(f"Train/{k}", v, epoch) # Evaluate the model on validation set if config.experiment.validate: with torch.no_grad(): step_log = TrainUtils.run_epoch( model=model, data_loader=valid_loader, epoch=epoch, validate=True, num_steps=valid_num_steps ) for k, v in step_log.items(): if k.startswith("Time_"): data_logger.record(f"Timing_Stats/Valid_{k[5:]}", v, epoch) else: data_logger.record(f"Valid/{k}", v, epoch) print(f"Validation Epoch {epoch}") print(json.dumps(step_log, sort_keys=True, indent=4)) # save checkpoint if achieve new best validation loss valid_check = "Loss" in step_log if valid_check and (best_valid_loss is None or (step_log["Loss"] <= best_valid_loss)): best_valid_loss = step_log["Loss"] if config.experiment.save.enabled and config.experiment.save.on_best_validation: epoch_ckpt_name += f"_best_validation_{best_valid_loss}" should_save_ckpt = True ckpt_reason = "valid" if ckpt_reason is None else ckpt_reason # Evaluate the model by by running rollouts # do rollouts at fixed rate or if it's time to save a new ckpt video_paths = None rollout_check = (epoch % config.experiment.rollout.rate == 0) or (should_save_ckpt and ckpt_reason == "time") if config.experiment.rollout.enabled and (epoch > config.experiment.rollout.warmstart) and rollout_check: # wrap model as a RolloutPolicy to prepare for rollouts rollout_model = RolloutPolicy(model, obs_normalization_stats=obs_normalization_stats) num_episodes = config.experiment.rollout.n all_rollout_logs, video_paths = TrainUtils.rollout_with_stats( policy=rollout_model, envs=envs, horizon=config.experiment.rollout.horizon, use_goals=config.use_goals, num_episodes=num_episodes, render=False, video_dir=video_dir if config.experiment.render_video else None, epoch=epoch, video_skip=config.experiment.get("video_skip", 5), terminate_on_success=config.experiment.rollout.terminate_on_success, ) # summarize results from rollouts to tensorboard and terminal for env_name in all_rollout_logs: rollout_logs = all_rollout_logs[env_name] for k, v in rollout_logs.items(): if k.startswith("Time_"): data_logger.record(f"Timing_Stats/Rollout_{env_name}_{k[5:]}", v, epoch) else: data_logger.record(f"Rollout/{k}/{env_name}", v, epoch, log_stats=True) print("\nEpoch {} Rollouts took {}s (avg) with results:".format(epoch, rollout_logs["time"])) print(f"Env: {env_name}") print(json.dumps(rollout_logs, sort_keys=True, indent=4)) # checkpoint and video saving logic updated_stats = TrainUtils.should_save_from_rollout_logs( all_rollout_logs=all_rollout_logs, best_return=best_return, best_success_rate=best_success_rate, epoch_ckpt_name=epoch_ckpt_name, save_on_best_rollout_return=config.experiment.save.on_best_rollout_return, save_on_best_rollout_success_rate=config.experiment.save.on_best_rollout_success_rate, ) best_return = updated_stats["best_return"] best_success_rate = updated_stats["best_success_rate"] epoch_ckpt_name = updated_stats["epoch_ckpt_name"] should_save_ckpt = ( config.experiment.save.enabled and updated_stats["should_save_ckpt"] ) or should_save_ckpt if updated_stats["ckpt_reason"] is not None: ckpt_reason = updated_stats["ckpt_reason"] # Only keep saved videos if the ckpt should be saved (but not because of validation score) should_save_video = (should_save_ckpt and (ckpt_reason != "valid")) or config.experiment.keep_all_videos if video_paths is not None and not should_save_video: for env_name in video_paths: os.remove(video_paths[env_name]) # Save model checkpoints based on conditions (success rate, validation loss, etc) if should_save_ckpt: TrainUtils.save_model( model=model, config=config, env_meta=env_meta, shape_meta=shape_meta, ckpt_path=os.path.join(ckpt_dir, epoch_ckpt_name + ".pth"), obs_normalization_stats=obs_normalization_stats, ) # Finally, log memory usage in MB process = psutil.Process(os.getpid()) mem_usage = int(process.memory_info().rss / 1000000) data_logger.record("System/RAM Usage (MB)", mem_usage, epoch) print(f"\nEpoch {epoch} Memory Usage: {mem_usage} MB\n") # terminate logging data_logger.close() def main(args): """Train a model on a task using a specified algorithm.""" # load config if args.task is not None: # obtain the configuration entry point cfg_entry_point_key = f"robomimic_{args.algo}_cfg_entry_point" print(f"Loading configuration for task: {args.task}") cfg_entry_point_file = gym.spec(args.task).kwargs.pop(cfg_entry_point_key) # check if entry point exists if cfg_entry_point_file is None: raise ValueError( f"Could not find configuration for the environment: '{args.task}'." f" Please check that the gym registry has the entry point: '{cfg_entry_point_key}'." ) # load config from json file with open(cfg_entry_point_file) as f: ext_cfg = json.load(f) config = config_factory(ext_cfg["algo_name"]) # update config with external json - this will throw errors if # the external config has keys not present in the base algo config with config.values_unlocked(): config.update(ext_cfg) else: raise ValueError("Please provide a task name through CLI arguments.") if args.dataset is not None: config.train.data = args.dataset if args.name is not None: config.experiment.name = args.name # change location of experiment directory config.train.output_dir = os.path.abspath(os.path.join("./logs/robomimic", args.task)) # get torch device device = TorchUtils.get_torch_device(try_to_use_cuda=config.train.cuda) config.lock() # catch error during training and print it res_str = "finished run successfully!" try: train(config, device=device) except Exception as e: res_str = f"run failed with error:\n{e}\n\n{traceback.format_exc()}" print(res_str) if __name__ == "__main__": parser = argparse.ArgumentParser() # Experiment Name (for tensorboard, saving models, etc.) parser.add_argument( "--name", type=str, default=None, help="(optional) if provided, override the experiment name defined in the config", ) # Dataset path, to override the one in the config parser.add_argument( "--dataset", type=str, default=None, help="(optional) if provided, override the dataset path defined in the config", ) parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--algo", type=str, default=None, help="Name of the algorithm.") args = parser.parse_args() # run training main(args) # close sim app simulation_app.close()
16,861
Python
39.243437
118
0.633533
isaac-sim/IsaacLab/source/standalone/workflows/robomimic/tools/episode_merging.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Tool to merge multiple episodes with single trajectory into one episode with multiple trajectories.""" import argparse import h5py import json import os if __name__ == "__main__": # parse arguments parser = argparse.ArgumentParser(description="Merge multiple episodes with single trajectory into one episode.") parser.add_argument( "--dir", type=str, default=None, help="Path to directory that contains all single episode hdf5 files" ) parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--out", type=str, default="merged_dataset.hdf5", help="output hdf5 file") args_cli = parser.parse_args() # read arguments parent_dir = args_cli.dir merged_dataset_name = args_cli.out task_name = args_cli.task # check valid task name if task_name is None: raise ValueError("Please specify a valid task name.") # get hdf5 entries from specified directory entries = [i for i in os.listdir(parent_dir) if i.endswith(".hdf5")] # create new hdf5 file for merging episodes fp = h5py.File(parent_dir + merged_dataset_name, "a") # initiate data group f_grp = fp.create_group("data") f_grp.attrs["num_samples"] = 0 # merge all episodes for count, entry in enumerate(entries): fc = h5py.File(parent_dir + entry, "r") # find total number of samples in all demos f_grp.attrs["num_samples"] = f_grp.attrs["num_samples"] + fc["data"]["demo_0"].attrs["num_samples"] fc.copy("data/demo_0", fp["data"], "demo_" + str(count)) # This is needed to run env in robomimic fp["data"].attrs["env_args"] = json.dumps({"env_name": task_name, "type": 2, "env_kwargs": {}}) fp.close() print("merged")
1,902
Python
32.982142
116
0.659832
isaac-sim/IsaacLab/source/standalone/workflows/robomimic/tools/inspect_demonstrations.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Tool to check structure of hdf5 files.""" import argparse import h5py def check_group(f, num: int): """Print the data from different keys in stored dictionary.""" # print name of the group first for subs in f: if isinstance(subs, str): print("\t" * num, subs, ":", type(f[subs])) check_group(f[subs], num + 1) # print attributes of the group print("\t" * num, "attributes", ":") for attr in f.attrs: print("\t" * (num + 1), attr, ":", type(f.attrs[attr]), ":", f.attrs[attr]) if __name__ == "__main__": # parse arguments parser = argparse.ArgumentParser(description="Check structure of hdf5 file.") parser.add_argument("file", type=str, default=None, help="The path to HDF5 file to analyze.") args_cli = parser.parse_args() # open specified file with h5py.File(args_cli.file, "r") as f: # print name of the file first print(f) # print contents of file check_group(f["data"], 1)
1,134
Python
29.675675
97
0.611111
isaac-sim/IsaacLab/source/standalone/workflows/robomimic/tools/split_train_val.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # MIT License # # Copyright (c) 2021 Stanford Vision and Learning Lab # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # """ Script for splitting a dataset hdf5 file into training and validation trajectories. Args: dataset: path to hdf5 dataset filter_key: if provided, split the subset of trajectories in the file that correspond to this filter key into a training and validation set of trajectories, instead of splitting the full set of trajectories ratio: validation ratio, in (0, 1). Defaults to 0.1, which is 10%. Example usage: python split_train_val.py --dataset /path/to/demo.hdf5 --ratio 0.1 """ import argparse import h5py import numpy as np from robomimic.utils.file_utils import create_hdf5_filter_key def split_train_val_from_hdf5(hdf5_path: str, val_ratio=0.1, filter_key=None): """ Splits data into training set and validation set from HDF5 file. Args: hdf5_path: path to the hdf5 file to load the transitions from val_ratio: ratio of validation demonstrations to all demonstrations filter_key: if provided, split the subset of demonstration keys stored under mask/@filter_key instead of the full set of demonstrations """ # retrieve number of demos f = h5py.File(hdf5_path, "r") if filter_key is not None: print(f"Using filter key: {filter_key}") demos = sorted(elem.decode("utf-8") for elem in np.array(f[f"mask/{filter_key}"])) else: demos = sorted(list(f["data"].keys())) num_demos = len(demos) f.close() # get random split num_demos = len(demos) num_val = int(val_ratio * num_demos) mask = np.zeros(num_demos) mask[:num_val] = 1.0 np.random.shuffle(mask) mask = mask.astype(int) train_inds = (1 - mask).nonzero()[0] valid_inds = mask.nonzero()[0] train_keys = [demos[i] for i in train_inds] valid_keys = [demos[i] for i in valid_inds] print(f"{num_val} validation demonstrations out of {num_demos} total demonstrations.") # pass mask to generate split name_1 = "train" name_2 = "valid" if filter_key is not None: name_1 = f"{filter_key}_{name_1}" name_2 = f"{filter_key}_{name_2}" train_lengths = create_hdf5_filter_key(hdf5_path=hdf5_path, demo_keys=train_keys, key_name=name_1) valid_lengths = create_hdf5_filter_key(hdf5_path=hdf5_path, demo_keys=valid_keys, key_name=name_2) print(f"Total number of train samples: {np.sum(train_lengths)}") print(f"Average number of train samples {np.mean(train_lengths)}") print(f"Total number of valid samples: {np.sum(valid_lengths)}") print(f"Average number of valid samples {np.mean(valid_lengths)}") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("dataset", type=str, help="path to hdf5 dataset") parser.add_argument( "--filter_key", type=str, default=None, help=( "If provided, split the subset of trajectories in the file that correspond to this filter key" " into a training and validation set of trajectories, instead of splitting the full set of" " trajectories." ), ) parser.add_argument("--ratio", type=float, default=0.1, help="validation ratio, in (0, 1)") args = parser.parse_args() # seed to make sure results are consistent np.random.seed(0) split_train_val_from_hdf5(args.dataset, val_ratio=args.ratio, filter_key=args.filter_key)
4,653
Python
36.532258
106
0.689877
isaac-sim/IsaacLab/source/standalone/workflows/sb3/play.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to play a checkpoint if an RL agent from Stable-Baselines3.""" """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.lab.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from Stable-Baselines3.") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument( "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." ) parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") parser.add_argument( "--use_last_checkpoint", action="store_true", help="When no checkpoint provided, use the last saved model. Otherwise use the best saved model.", ) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import numpy as np import os import torch from stable_baselines3 import PPO from stable_baselines3.common.vec_env import VecNormalize import omni.isaac.lab_tasks # noqa: F401 from omni.isaac.lab_tasks.utils.parse_cfg import get_checkpoint_path, load_cfg_from_registry, parse_env_cfg from omni.isaac.lab_tasks.utils.wrappers.sb3 import Sb3VecEnvWrapper, process_sb3_cfg def main(): """Play with stable-baselines agent.""" # parse configuration env_cfg = parse_env_cfg( args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs, use_fabric=not args_cli.disable_fabric ) agent_cfg = load_cfg_from_registry(args_cli.task, "sb3_cfg_entry_point") # post-process agent configuration agent_cfg = process_sb3_cfg(agent_cfg) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg) # wrap around environment for stable baselines env = Sb3VecEnvWrapper(env) # normalize environment (if needed) if "normalize_input" in agent_cfg: env = VecNormalize( env, training=True, norm_obs="normalize_input" in agent_cfg and agent_cfg.pop("normalize_input"), norm_reward="normalize_value" in agent_cfg and agent_cfg.pop("normalize_value"), clip_obs="clip_obs" in agent_cfg and agent_cfg.pop("clip_obs"), gamma=agent_cfg["gamma"], clip_reward=np.inf, ) # directory for logging into log_root_path = os.path.join("logs", "sb3", args_cli.task) log_root_path = os.path.abspath(log_root_path) # check checkpoint is valid if args_cli.checkpoint is None: if args_cli.use_last_checkpoint: checkpoint = "model_.*.zip" else: checkpoint = "model.zip" checkpoint_path = get_checkpoint_path(log_root_path, ".*", checkpoint) else: checkpoint_path = args_cli.checkpoint # create agent from stable baselines print(f"Loading checkpoint from: {checkpoint_path}") agent = PPO.load(checkpoint_path, env, print_system_info=True) # reset environment obs = env.reset() # simulate environment while simulation_app.is_running(): # run everything in inference mode with torch.inference_mode(): # agent stepping actions, _ = agent.predict(obs, deterministic=True) # env stepping obs, _, _, _ = env.step(actions) # close the simulator env.close() if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()
3,973
Python
33.556521
115
0.679839
isaac-sim/IsaacLab/source/standalone/workflows/sb3/train.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to train RL agent with Stable Baselines3. Since Stable-Baselines3 does not support buffers living on GPU directly, we recommend using smaller number of environments. Otherwise, there will be significant overhead in GPU->CPU transfer. """ """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.lab.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with Stable-Baselines3.") parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument( "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." ) parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import numpy as np import os from datetime import datetime from stable_baselines3 import PPO from stable_baselines3.common.callbacks import CheckpointCallback from stable_baselines3.common.logger import configure from stable_baselines3.common.vec_env import VecNormalize from omni.isaac.lab.utils.dict import print_dict from omni.isaac.lab.utils.io import dump_pickle, dump_yaml import omni.isaac.lab_tasks # noqa: F401 from omni.isaac.lab_tasks.utils import load_cfg_from_registry, parse_env_cfg from omni.isaac.lab_tasks.utils.wrappers.sb3 import Sb3VecEnvWrapper, process_sb3_cfg def main(): """Train with stable-baselines agent.""" # parse configuration env_cfg = parse_env_cfg( args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs, use_fabric=not args_cli.disable_fabric ) agent_cfg = load_cfg_from_registry(args_cli.task, "sb3_cfg_entry_point") # override configuration with command line arguments if args_cli.seed is not None: agent_cfg["seed"] = args_cli.seed # max iterations for training if args_cli.max_iterations: agent_cfg["n_timesteps"] = args_cli.max_iterations * agent_cfg["n_steps"] * env_cfg.scene.num_envs # directory for logging into log_dir = os.path.join("logs", "sb3", args_cli.task, datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) # dump the configuration into log-directory dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg) dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg) # post-process agent configuration agent_cfg = process_sb3_cfg(agent_cfg) # read configurations about the agent-training policy_arch = agent_cfg.pop("policy") n_timesteps = agent_cfg.pop("n_timesteps") # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) # wrap for video recording if args_cli.video: video_kwargs = { "video_folder": os.path.join(log_dir, "videos"), "step_trigger": lambda step: step % args_cli.video_interval == 0, "video_length": args_cli.video_length, "disable_logger": True, } print("[INFO] Recording videos during training.") print_dict(video_kwargs, nesting=4) env = gym.wrappers.RecordVideo(env, **video_kwargs) # wrap around environment for stable baselines env = Sb3VecEnvWrapper(env) # set the seed env.seed(seed=agent_cfg["seed"]) if "normalize_input" in agent_cfg: env = VecNormalize( env, training=True, norm_obs="normalize_input" in agent_cfg and agent_cfg.pop("normalize_input"), norm_reward="normalize_value" in agent_cfg and agent_cfg.pop("normalize_value"), clip_obs="clip_obs" in agent_cfg and agent_cfg.pop("clip_obs"), gamma=agent_cfg["gamma"], clip_reward=np.inf, ) # create agent from stable baselines agent = PPO(policy_arch, env, verbose=1, **agent_cfg) # configure the logger new_logger = configure(log_dir, ["stdout", "tensorboard"]) agent.set_logger(new_logger) # callbacks for agent checkpoint_callback = CheckpointCallback(save_freq=1000, save_path=log_dir, name_prefix="model", verbose=2) # train the agent agent.learn(total_timesteps=n_timesteps, callback=checkpoint_callback) # save the final model agent.save(os.path.join(log_dir, "model")) # close the simulator env.close() if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()
5,594
Python
38.401408
117
0.695745
isaac-sim/IsaacLab/source/standalone/workflows/rl_games/play.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to play a checkpoint if an RL agent from RL-Games.""" """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.lab.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from RL-Games.") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument( "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." ) parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") parser.add_argument( "--use_last_checkpoint", action="store_true", help="When no checkpoint provided, use the last saved model. Otherwise use the best saved model.", ) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import math import os import torch from rl_games.common import env_configurations, vecenv from rl_games.common.player import BasePlayer from rl_games.torch_runner import Runner from omni.isaac.lab.utils.assets import retrieve_file_path import omni.isaac.lab_tasks # noqa: F401 from omni.isaac.lab_tasks.utils import get_checkpoint_path, load_cfg_from_registry, parse_env_cfg from omni.isaac.lab_tasks.utils.wrappers.rl_games import RlGamesGpuEnv, RlGamesVecEnvWrapper def main(): """Play with RL-Games agent.""" # parse env configuration env_cfg = parse_env_cfg( args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs, use_fabric=not args_cli.disable_fabric ) agent_cfg = load_cfg_from_registry(args_cli.task, "rl_games_cfg_entry_point") # wrap around environment for rl-games rl_device = agent_cfg["params"]["config"]["device"] clip_obs = agent_cfg["params"]["env"].get("clip_observations", math.inf) clip_actions = agent_cfg["params"]["env"].get("clip_actions", math.inf) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg) # wrap around environment for rl-games env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions) # register the environment to rl-games registry # note: in agents configuration: environment name must be "rlgpu" vecenv.register( "IsaacRlgWrapper", lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs) ) env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env}) # specify directory for logging experiments log_root_path = os.path.join("logs", "rl_games", agent_cfg["params"]["config"]["name"]) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Loading experiment from directory: {log_root_path}") # find checkpoint if args_cli.checkpoint is None: # specify directory for logging runs run_dir = agent_cfg["params"]["config"].get("full_experiment_name", ".*") # specify name of checkpoint if args_cli.use_last_checkpoint: checkpoint_file = ".*" else: # this loads the best checkpoint checkpoint_file = f"{agent_cfg['params']['config']['name']}.pth" # get path to previous checkpoint resume_path = get_checkpoint_path(log_root_path, run_dir, checkpoint_file, other_dirs=["nn"]) else: resume_path = retrieve_file_path(args_cli.checkpoint) # load previously trained model agent_cfg["params"]["load_checkpoint"] = True agent_cfg["params"]["load_path"] = resume_path print(f"[INFO]: Loading model checkpoint from: {agent_cfg['params']['load_path']}") # set number of actors into agent config agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs # create runner from rl-games runner = Runner() runner.load(agent_cfg) # obtain the agent from the runner agent: BasePlayer = runner.create_player() agent.restore(resume_path) agent.reset() # reset environment obs = env.reset() if isinstance(obs, dict): obs = obs["obs"] # required: enables the flag for batched observations _ = agent.get_batch_size(obs, 1) # initialize RNN states if used if agent.is_rnn: agent.init_rnn() # simulate environment # note: We simplified the logic in rl-games player.py (:func:`BasePlayer.run()`) function in an # attempt to have complete control over environment stepping. However, this removes other # operations such as masking that is used for multi-agent learning by RL-Games. while simulation_app.is_running(): # run everything in inference mode with torch.inference_mode(): # convert obs to agent format obs = agent.obs_to_torch(obs) # agent stepping actions = agent.get_action(obs, is_deterministic=True) # env stepping obs, _, dones, _ = env.step(actions) # perform operations for terminated episodes if len(dones) > 0: # reset rnn state for terminated episodes if agent.is_rnn and agent.states is not None: for s in agent.states: s[:, dones, :] = 0.0 # close the simulator env.close() if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()
5,880
Python
37.437908
117
0.672449
isaac-sim/IsaacLab/source/standalone/workflows/rl_games/train.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to train RL agent with RL-Games.""" """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.lab.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RL-Games.") parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument( "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." ) parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") parser.add_argument( "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." ) parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import math import os from datetime import datetime from rl_games.common import env_configurations, vecenv from rl_games.common.algo_observer import IsaacAlgoObserver from rl_games.torch_runner import Runner from omni.isaac.lab.utils.dict import print_dict from omni.isaac.lab.utils.io import dump_pickle, dump_yaml import omni.isaac.lab_tasks # noqa: F401 from omni.isaac.lab_tasks.utils import load_cfg_from_registry, parse_env_cfg from omni.isaac.lab_tasks.utils.wrappers.rl_games import RlGamesGpuEnv, RlGamesVecEnvWrapper def main(): """Train with RL-Games agent.""" # parse seed from command line args_cli_seed = args_cli.seed # parse configuration env_cfg = parse_env_cfg( args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs, use_fabric=not args_cli.disable_fabric ) agent_cfg = load_cfg_from_registry(args_cli.task, "rl_games_cfg_entry_point") # override from command line if args_cli_seed is not None: agent_cfg["params"]["seed"] = args_cli_seed # specify directory for logging experiments log_root_path = os.path.join("logs", "rl_games", agent_cfg["params"]["config"]["name"]) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Logging experiment in directory: {log_root_path}") # specify directory for logging runs log_dir = agent_cfg["params"]["config"].get("full_experiment_name", datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) # set directory into agent config # logging directory path: <train_dir>/<full_experiment_name> agent_cfg["params"]["config"]["train_dir"] = log_root_path agent_cfg["params"]["config"]["full_experiment_name"] = log_dir # multi-gpu training config if args_cli.distributed: agent_cfg["params"]["seed"] += app_launcher.global_rank agent_cfg["params"]["config"]["device"] = f"cuda:{app_launcher.local_rank}" agent_cfg["params"]["config"]["device_name"] = f"cuda:{app_launcher.local_rank}" agent_cfg["params"]["config"]["multi_gpu"] = True # update env config device env_cfg.sim.device = f"cuda:{app_launcher.local_rank}" # max iterations if args_cli.max_iterations: agent_cfg["params"]["config"]["max_epochs"] = args_cli.max_iterations # dump the configuration into log-directory dump_yaml(os.path.join(log_root_path, log_dir, "params", "env.yaml"), env_cfg) dump_yaml(os.path.join(log_root_path, log_dir, "params", "agent.yaml"), agent_cfg) dump_pickle(os.path.join(log_root_path, log_dir, "params", "env.pkl"), env_cfg) dump_pickle(os.path.join(log_root_path, log_dir, "params", "agent.pkl"), agent_cfg) # read configurations about the agent-training rl_device = agent_cfg["params"]["config"]["device"] clip_obs = agent_cfg["params"]["env"].get("clip_observations", math.inf) clip_actions = agent_cfg["params"]["env"].get("clip_actions", math.inf) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) # wrap for video recording if args_cli.video: video_kwargs = { "video_folder": os.path.join(log_root_path, log_dir, "videos"), "step_trigger": lambda step: step % args_cli.video_interval == 0, "video_length": args_cli.video_length, "disable_logger": True, } print("[INFO] Recording videos during training.") print_dict(video_kwargs, nesting=4) env = gym.wrappers.RecordVideo(env, **video_kwargs) # wrap around environment for rl-games env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions) # register the environment to rl-games registry # note: in agents configuration: environment name must be "rlgpu" vecenv.register( "IsaacRlgWrapper", lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs) ) env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env}) # set number of actors into agent config agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs # create runner from rl-games runner = Runner(IsaacAlgoObserver()) runner.load(agent_cfg) # set seed of the env env.seed(agent_cfg["params"]["seed"]) # reset the agent and env runner.reset() # train the agent runner.run({"train": True, "play": False, "sigma": None}) # close the simulator env.close() if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()
6,349
Python
40.503268
117
0.68625
isaac-sim/IsaacLab/docker/x11.yaml
services: isaac-lab-base: environment: - DISPLAY - TERM - QT_X11_NO_MITSHM=1 - XAUTHORITY=${__ISAACLAB_TMP_XAUTH} volumes: - type: bind source: ${__ISAACLAB_TMP_XAUTH} target: ${__ISAACLAB_TMP_XAUTH} - type: bind source: /tmp/.X11-unix target: /tmp/.X11-unix - type: bind source: /etc/localtime target: /etc/localtime read_only: true isaac-lab-ros2: environment: - DISPLAY - TERM - QT_X11_NO_MITSHM=1 - XAUTHORITY=${__ISAACLAB_TMP_XAUTH} volumes: - type: bind source: ${__ISAACLAB_TMP_XAUTH} target: ${__ISAACLAB_TMP_XAUTH} - type: bind source: /tmp/.X11-unix target: /tmp/.X11-unix - type: bind source: /etc/localtime target: /etc/localtime read_only: true
835
YAML
21.594594
42
0.558084
isaac-sim/IsaacLab/docker/docker-compose.yaml
# Here we set the parts that would # be re-used between services to an # extension field # https://docs.docker.com/compose/compose-file/compose-file-v3/#extension-fields x-default-isaac-lab-volumes: &default-isaac-lab-volumes # These volumes follow from this page # https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_faq.html#save-isaac-sim-configs-on-local-disk - type: volume source: isaac-cache-kit target: ${DOCKER_ISAACSIM_ROOT_PATH}/kit/cache - type: volume source: isaac-cache-ov target: ${DOCKER_USER_HOME}/.cache/ov - type: volume source: isaac-cache-pip target: ${DOCKER_USER_HOME}/.cache/pip - type: volume source: isaac-cache-gl target: ${DOCKER_USER_HOME}/.cache/nvidia/GLCache - type: volume source: isaac-cache-compute target: ${DOCKER_USER_HOME}/.nv/ComputeCache - type: volume source: isaac-logs target: ${DOCKER_USER_HOME}/.nvidia-omniverse/logs - type: volume source: isaac-carb-logs target: ${DOCKER_ISAACSIM_ROOT_PATH}/kit/logs/Kit/Isaac-Sim - type: volume source: isaac-data target: ${DOCKER_USER_HOME}/.local/share/ov/data - type: volume source: isaac-docs target: ${DOCKER_USER_HOME}/Documents # This overlay allows changes on the local files to # be reflected within the container immediately - type: bind source: ../source target: /workspace/isaaclab/source - type: bind source: ../docs target: /workspace/isaaclab/docs # The effect of these volumes is twofold: # 1. Prevent root-owned files from flooding the _build and logs dir # on the host machine # 2. Preserve the artifacts in persistent volumes for later copying # to the host machine - type: volume source: isaac-lab-docs target: /workspace/isaaclab/docs/_build - type: volume source: isaac-lab-logs target: /workspace/isaaclab/logs - type: volume source: isaac-lab-data target: /workspace/isaaclab/data_storage x-default-isaac-lab-environment: &default-isaac-lab-environment - ISAACSIM_PATH=${DOCKER_ISAACLAB_PATH}/_isaac_sim - OMNI_KIT_ALLOW_ROOT=1 x-default-isaac-lab-deploy: &default-isaac-lab-deploy resources: reservations: devices: - driver: nvidia count: all capabilities: [ gpu ] services: # This service is the base Isaac Lab image isaac-lab-base: profiles: [ "base" ] env_file: .env.base build: context: ../ dockerfile: docker/Dockerfile.base args: - ISAACSIM_VERSION_ARG=${ISAACSIM_VERSION} - ISAACSIM_ROOT_PATH_ARG=${DOCKER_ISAACSIM_ROOT_PATH} - ISAACLAB_PATH_ARG=${DOCKER_ISAACLAB_PATH} - DOCKER_USER_HOME_ARG=${DOCKER_USER_HOME} image: isaac-lab-base container_name: isaac-lab-base environment: *default-isaac-lab-environment volumes: *default-isaac-lab-volumes network_mode: host deploy: *default-isaac-lab-deploy # This is the entrypoint for the container entrypoint: bash stdin_open: true tty: true # This service adds a ROS2 Humble # installation on top of the base image isaac-lab-ros2: profiles: [ "ros2" ] env_file: - .env.base - .env.ros2 build: context: ../ dockerfile: docker/Dockerfile.ros2 args: # ROS2_APT_PACKAGE will default to NONE. This is to # avoid a warning message when building only the base profile # with the .env.base file - ROS2_APT_PACKAGE=${ROS2_APT_PACKAGE:-NONE} image: isaac-lab-ros2 container_name: isaac-lab-ros2 environment: *default-isaac-lab-environment volumes: *default-isaac-lab-volumes network_mode: host deploy: *default-isaac-lab-deploy # This is the entrypoint for the container entrypoint: bash stdin_open: true tty: true volumes: # isaac-sim isaac-cache-kit: isaac-cache-ov: isaac-cache-pip: isaac-cache-gl: isaac-cache-compute: isaac-logs: isaac-carb-logs: isaac-data: isaac-docs: # isaac-lab isaac-lab-docs: isaac-lab-logs: isaac-lab-data:
4,084
YAML
29.259259
117
0.673849
isaac-sim/IsaacLab/docs/README.md
# Building Documentation We use [Sphinx](https://www.sphinx-doc.org/en/master/) with the [Book Theme](https://sphinx-book-theme.readthedocs.io/en/stable/) for maintaining the documentation. > **Note:** To build the documentation, we recommend creating a virtual environment to avoid any conflicts with system installed dependencies. Execute the following instructions to build the documentation (assumed from the top of the repository): 1. Install the dependencies for [Sphinx](https://www.sphinx-doc.org/en/master/): ```bash # enter the location where this readme exists cd docs # install dependencies pip install -r requirements.txt ``` 2. Generate the documentation file via: ```bash # make the html version make html ``` 3. The documentation is now available at `docs/_build/html/index.html`: ```bash # open on default browser xdg-open _build/html/index.html ```
932
Markdown
29.096773
164
0.714592
isaac-sim/IsaacLab/docs/index.rst
Overview ======== .. figure:: source/_static/isaaclab.jpg :width: 100% :alt: H1 Humanoid example using Isaac Lab **Isaac Lab** is a unified and modular framework for robot learning that aims to simplify common workflows in robotics research (such as RL, learning from demonstrations, and motion planning). It is built upon `NVIDIA Isaac Sim`_ to leverage the latest simulation capabilities for photo-realistic scenes, and fast and efficient simulation. The core objectives of the framework are: - **Modularity**: Easily customize and add new environments, robots, and sensors. - **Agility**: Adapt to the changing needs of the community. - **Openness**: Remain open-sourced to allow the community to contribute and extend the framework. - **Battery-included**: Include a number of environments, sensors, and tasks that are ready to use. Key features available in Isaac Lab include fast and accurate physics simulation provided by PhysX, tiled rendering APIs for vectorized rendering, domain randomization for improving robustness and adaptability, and support for running in the cloud. For more information about the framework, please refer to the `paper <https://arxiv.org/abs/2301.04195>`_ :cite:`mittal2023orbit`. For clarifications on NVIDIA Isaac ecosystem, please check out the :doc:`/source/setup/faq` section. .. figure:: source/_static/tasks.jpg :width: 100% :alt: Example tasks created using Isaac Lab License ======= NVIDIA Isaac Sim is provided under the NVIDIA End User License Agreement. However, the Isaac Lab framework is open-sourced under the BSD-3-Clause license. Please refer to :ref:`license` for more details. Table of Contents ================= .. toctree:: :maxdepth: 2 :caption: Getting Started source/setup/installation/index source/setup/developer source/setup/sample source/setup/template source/setup/faq .. toctree:: :maxdepth: 2 :caption: Features source/features/workflows source/features/multi_gpu source/features/tiled_rendering source/features/environments source/features/actuators .. source/features/motion_generators .. toctree:: :maxdepth: 1 :caption: Resources :titlesonly: source/migration/index source/tutorials/index source/how-to/index source/deployment/index .. toctree:: :maxdepth: 1 :caption: Source API source/api/index .. toctree:: :maxdepth: 1 :caption: References source/refs/migration source/refs/contributing source/refs/troubleshooting source/refs/issues source/refs/changelog source/refs/license source/refs/bibliography .. toctree:: :hidden: :caption: Project Links GitHub <https://github.com/isaac-sim/IsaacLab> Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _NVIDIA Isaac Sim: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html
2,907
reStructuredText
26.695238
110
0.734434
isaac-sim/IsaacLab/docs/conf.py
# Copyright (c) 2022-2024, The Isaac Lab Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath("../source/extensions/omni.isaac.lab")) sys.path.insert(0, os.path.abspath("../source/extensions/omni.isaac.lab/omni/isaac/lab")) sys.path.insert(0, os.path.abspath("../source/extensions/omni.isaac.lab_tasks")) sys.path.insert(0, os.path.abspath("../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks")) # -- Project information ----------------------------------------------------- project = "Isaac Lab" copyright = "2022-2024, The Isaac Lab Project Developers." author = "The Isaac Lab Project Developers." version = "0.3.0" # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "autodocsumm", "myst_parser", "sphinx.ext.napoleon", "sphinxemoji.sphinxemoji", "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.githubpages", "sphinx.ext.intersphinx", "sphinx.ext.mathjax", "sphinx.ext.todo", "sphinx.ext.viewcode", "sphinxcontrib.bibtex", "sphinx_copybutton", "sphinx_design", "sphinx_tabs.tabs", ] # mathjax hacks mathjax3_config = { "tex": { "inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], }, } # panels hacks panels_add_bootstrap_css = False panels_add_fontawesome_css = True # supported file extensions for source files source_suffix = { ".rst": "restructuredtext", ".md": "markdown", } # make sure we don't have any unknown references # TODO: Enable this by default once we have fixed all the warnings # nitpicky = True # put type hints inside the signature instead of the description (easier to maintain) autodoc_typehints = "signature" # autodoc_typehints_format = "fully-qualified" # document class *and* __init__ methods autoclass_content = "class" # # separate class docstring from __init__ docstring autodoc_class_signature = "separated" # sort members by source order autodoc_member_order = "bysource" # inherit docstrings from base classes autodoc_inherit_docstrings = True # BibTeX configuration bibtex_bibfiles = ["source/_static/refs.bib"] # generate autosummary even if no references autosummary_generate = True autosummary_generate_overwrite = False # default autodoc settings autodoc_default_options = { "autosummary": True, } # generate links to the documentation of objects in external projects intersphinx_mapping = { "python": ("https://docs.python.org/3", None), "numpy": ("https://numpy.org/doc/stable/", None), "torch": ("https://pytorch.org/docs/stable/", None), "isaac": ("https://docs.omniverse.nvidia.com/py/isaacsim", None), "gymnasium": ("https://gymnasium.farama.org/", None), "warp": ("https://nvidia.github.io/warp/", None), } # Add any paths that contain templates here, relative to this directory. templates_path = [] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "README.md", "licenses/*"] # Mock out modules that are not available on RTD autodoc_mock_imports = [ "torch", "numpy", "matplotlib", "scipy", "carb", "warp", "pxr", "omni.kit", "omni.usd", "omni.client", "omni.physx", "omni.physics", "pxr.PhysxSchema", "pxr.PhysicsSchemaTools", "omni.replicator", "omni.isaac.core", "omni.isaac.kit", "omni.isaac.cloner", "omni.isaac.urdf", "omni.isaac.version", "omni.isaac.motion_generation", "omni.isaac.ui", "omni.syntheticdata", "omni.timeline", "omni.ui", "gym", "skrl", "stable_baselines3", "rsl_rl", "rl_games", "ray", "h5py", "hid", "prettytable", "tqdm", "tensordict", "trimesh", "toml", ] # List of zero or more Sphinx-specific warning categories to be squelched (i.e., # suppressed, ignored). suppress_warnings = [ # Generally speaking, we do want Sphinx to inform # us about cross-referencing failures. Remove this entirely after Sphinx # resolves this open issue: # https://github.com/sphinx-doc/sphinx/issues/4961 # Squelch mostly ignorable warnings resembling: # WARNING: more than one target found for cross-reference 'TypeHint': # beartype.door._doorcls.TypeHint, beartype.door.TypeHint # # Sphinx currently emits *MANY* of these warnings against our # documentation. All of these warnings appear to be ignorable. Although we # could explicitly squelch *SOME* of these warnings by canonicalizing # relative to absolute references in docstrings, Sphinx emits still others # of these warnings when parsing PEP-compliant type hints via static # analysis. Since those hints are actual hints that *CANNOT* by definition # by canonicalized, our only recourse is to squelch warnings altogether. "ref.python", ] # -- Internationalization ---------------------------------------------------- # specifying the natural language populates some key tags language = "en" # -- Options for HTML output ------------------------------------------------- import sphinx_book_theme html_title = "Isaac Lab documentation" html_theme_path = [sphinx_book_theme.get_html_theme_path()] html_theme = "sphinx_book_theme" html_favicon = "source/_static/favicon.ico" html_show_copyright = True html_show_sphinx = False html_last_updated_fmt = "" # to reveal the build date in the pages meta # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["source/_static/css"] html_css_files = ["custom.css"] html_theme_options = { "collapse_navigation": True, "repository_url": "https://github.com/isaac-sim/IsaacLab", "announcement": "We have now released v0.3.0! Please use the latest version for the best experience.", "use_repository_button": True, "use_issues_button": True, "use_edit_page_button": True, "show_toc_level": 1, "use_sidenotes": True, "logo": { "text": "Isaac Lab documentation", "image_light": "source/_static/NVIDIA-logo-white.png", "image_dark": "source/_static/NVIDIA-logo-black.png", }, "icon_links": [ { "name": "GitHub", "url": "https://github.com/isaac-sim/IsaacLab", "icon": "fa-brands fa-square-github", "type": "fontawesome", }, { "name": "Isaac Sim", "url": "https://developer.nvidia.com/isaac-sim", "icon": "https://img.shields.io/badge/IsaacSim-4.0-silver.svg", "type": "url", }, { "name": "Stars", "url": "https://img.shields.io/github/stars/isaac-sim/IsaacLab?color=fedcba", "icon": "https://img.shields.io/github/stars/isaac-sim/IsaacLab?color=fedcba", "type": "url", }, ], "icon_links_label": "Quick Links", } html_sidebars = {"**": ["navbar-logo.html", "icon-links.html", "search-field.html", "sbt-sidebar-nav.html"]} # -- Advanced configuration ------------------------------------------------- def skip_member(app, what, name, obj, skip, options): # List the names of the functions you want to skip here exclusions = ["from_dict", "to_dict", "replace", "copy", "__post_init__"] if name in exclusions: return True return None def setup(app): app.connect("autodoc-skip-member", skip_member)
8,475
Python
31.980545
108
0.643422
isaac-sim/IsaacLab/docs/source/how-to/save_camera_output.rst
.. _how-to-save-images-and-3d-reprojection: Saving rendered images and 3D re-projection =========================================== .. currentmodule:: omni.isaac.lab This guide accompanied with the ``run_usd_camera.py`` script in the ``IsaacLab/source/standalone/tutorials/04_sensors`` directory. .. dropdown:: Code for run_usd_camera.py :icon: code .. literalinclude:: ../../../source/standalone/tutorials/04_sensors/run_usd_camera.py :language: python :emphasize-lines: 171-179, 229-247, 251-264 :linenos: Saving using Replicator Basic Writer ------------------------------------ To save camera outputs, we use the basic write class from Omniverse Replicator. This class allows us to save the images in a numpy format. For more information on the basic writer, please check the `documentation <https://docs.omniverse.nvidia.com/extensions/latest/ext_replicator/writer_examples.html>`_. .. literalinclude:: ../../../source/standalone/tutorials/04_sensors/run_usd_camera.py :language: python :start-at: rep_writer = rep.BasicWriter( :end-before: # Camera positions, targets, orientations While stepping the simulator, the images can be saved to the defined folder. Since the BasicWriter only supports saving data using NumPy format, we first need to convert the PyTorch sensors to NumPy arrays before packing them in a dictionary. .. literalinclude:: ../../../source/standalone/tutorials/04_sensors/run_usd_camera.py :language: python :start-at: # Save images from camera at camera_index :end-at: single_cam_info = camera.data.info[camera_index] After this step, we can save the images using the BasicWriter. .. literalinclude:: ../../../source/standalone/tutorials/04_sensors/run_usd_camera.py :language: python :start-at: # Pack data back into replicator format to save them using its writer :end-at: rep_writer.write(rep_output) Projection into 3D Space ------------------------ We include utilities to project the depth image into 3D Space. The re-projection operations are done using PyTorch operations which allows faster computation. .. code-block:: python from omni.isaac.lab.utils.math import transform_points, unproject_depth # Pointcloud in world frame points_3d_cam = unproject_depth( camera.data.output["distance_to_image_plane"], camera.data.intrinsic_matrices ) points_3d_world = transform_points(points_3d_cam, camera.data.pos_w, camera.data.quat_w_ros) Alternately, we can use the :meth:`omni.isaac.lab.sensors.camera.utils.create_pointcloud_from_depth` function to create a point cloud from the depth image and transform it to the world frame. .. literalinclude:: ../../../source/standalone/tutorials/04_sensors/run_usd_camera.py :language: python :start-at: # Derive pointcloud from camera at camera_index :end-before: # In the first few steps, things are still being instanced and Camera.data The resulting point cloud can be visualized using the :mod:`omni.isaac.debug_draw` extension from Isaac Sim. This makes it easy to visualize the point cloud in the 3D space. .. literalinclude:: ../../../source/standalone/tutorials/04_sensors/run_usd_camera.py :language: python :start-at: # In the first few steps, things are still being instanced and Camera.data :end-at: pc_markers.visualize(translations=pointcloud) Executing the script -------------------- To run the accompanying script, execute the following command: .. code-block:: bash # Usage with saving and drawing ./isaaclab.sh -p source/standalone/tutorials/04_sensors/run_usd_camera.py --save --draw # Usage with saving only in headless mode ./isaaclab.sh -p source/standalone/tutorials/04_sensors/run_usd_camera.py --save --headless --enable_cameras The simulation should start, and you can observe different objects falling down. An output folder will be created in the ``IsaacLab/source/standalone/tutorials/04_sensors`` directory, where the images will be saved. Additionally, you should see the point cloud in the 3D space drawn on the viewport. To stop the simulation, close the window, press the ``STOP`` button in the UI, or use ``Ctrl+C`` in the terminal.
4,179
reStructuredText
39.582524
119
0.728643
isaac-sim/IsaacLab/docs/source/how-to/wrap_rl_env.rst
.. _how-to-env-wrappers: Wrapping environments ===================== .. currentmodule:: omni.isaac.lab Environment wrappers are a way to modify the behavior of an environment without modifying the environment itself. This can be used to apply functions to modify observations or rewards, record videos, enforce time limits, etc. A detailed description of the API is available in the :class:`gymnasium.Wrapper` class. At present, all RL environments inheriting from the :class:`~envs.ManagerBasedRLEnv` class are compatible with :class:`gymnasium.Wrapper`, since the base class implements the :class:`gymnasium.Env` interface. In order to wrap an environment, you need to first initialize the base environment. After that, you can wrap it with as many wrappers as you want by calling ``env = wrapper(env, *args, **kwargs)`` repeatedly. For example, here is how you would wrap an environment to enforce that reset is called before step or render: .. code-block:: python """Launch Isaac Sim Simulator first.""" from omni.isaac.lab.app import AppLauncher # launch omniverse app in headless mode app_launcher = AppLauncher(headless=True) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import omni.isaac.lab_tasks # noqa: F401 from omni.isaac.lab_tasks.utils import load_cfg_from_registry # create base environment cfg = load_cfg_from_registry("Isaac-Reach-Franka-v0", "env_cfg_entry_point") env = gym.make("Isaac-Reach-Franka-v0", cfg=cfg) # wrap environment to enforce that reset is called before step env = gym.wrappers.OrderEnforcing(env) Wrapper for recording videos ---------------------------- The :class:`gymnasium.wrappers.RecordVideo` wrapper can be used to record videos of the environment. The wrapper takes a ``video_dir`` argument, which specifies where to save the videos. The videos are saved in `mp4 <https://en.wikipedia.org/wiki/MP4_file_format>`__ format at specified intervals for specified number of environment steps or episodes. To use the wrapper, you need to first install ``ffmpeg``. On Ubuntu, you can install it by running: .. code-block:: bash sudo apt-get install ffmpeg .. attention:: By default, when running an environment in headless mode, the Omniverse viewport is disabled. This is done to improve performance by avoiding unnecessary rendering. We notice the following performance in different rendering modes with the ``Isaac-Reach-Franka-v0`` environment using an RTX 3090 GPU: * No GUI execution without off-screen rendering enabled: ~65,000 FPS * No GUI execution with off-screen enabled: ~57,000 FPS * GUI execution with full rendering: ~13,000 FPS The viewport camera used for rendering is the default camera in the scene called ``"/OmniverseKit_Persp"``. The camera's pose and image resolution can be configured through the :class:`~envs.ViewerCfg` class. .. dropdown:: Default parameters of the ViewerCfg class: :icon: code .. literalinclude:: ../../../source/extensions/omni.isaac.lab/omni/isaac/lab/envs/base_env_cfg.py :language: python :pyobject: ViewerCfg After adjusting the parameters, you can record videos by wrapping the environment with the :class:`gymnasium.wrappers.RecordVideo` wrapper and enabling the off-screen rendering flag. Additionally, you need to specify the render mode of the environment as ``"rgb_array"``. As an example, the following code records a video of the ``Isaac-Reach-Franka-v0`` environment for 200 steps, and saves it in the ``videos`` folder at a step interval of 1500 steps. .. code:: python """Launch Isaac Sim Simulator first.""" from omni.isaac.lab.app import AppLauncher # launch omniverse app in headless mode with off-screen rendering app_launcher = AppLauncher(headless=True, enable_cameras=True) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym # adjust camera resolution and pose env_cfg.viewer.resolution = (640, 480) env_cfg.viewer.eye = (1.0, 1.0, 1.0) env_cfg.viewer.lookat = (0.0, 0.0, 0.0) # create isaac-env instance # set render mode to rgb_array to obtain images on render calls env = gym.make(task_name, cfg=env_cfg, render_mode="rgb_array") # wrap for video recording video_kwargs = { "video_folder": "videos", "step_trigger": lambda step: step % 1500 == 0, "video_length": 200, } env = gym.wrappers.RecordVideo(env, **video_kwargs) Wrapper for learning frameworks ------------------------------- Every learning framework has its own API for interacting with environments. For example, the `Stable-Baselines3`_ library uses the `gym.Env <https://gymnasium.farama.org/api/env/>`_ interface to interact with environments. However, libraries like `RL-Games`_, `RSL-RL`_ or `SKRL`_ use their own API for interfacing with a learning environments. Since there is no one-size-fits-all solution, we do not base the :class:`~envs.ManagerBasedRLEnv` class on any particular learning framework's environment definition. Instead, we implement wrappers to make it compatible with the learning framework's environment definition. As an example of how to use the RL task environment with Stable-Baselines3: .. code:: python from omni.isaac.lab_tasks.utils.wrappers.sb3 import Sb3VecEnvWrapper # create isaac-env instance env = gym.make(task_name, cfg=env_cfg) # wrap around environment for stable baselines env = Sb3VecEnvWrapper(env) .. caution:: Wrapping the environment with the respective learning framework's wrapper should happen in the end, i.e. after all other wrappers have been applied. This is because the learning framework's wrapper modifies the interpretation of environment's APIs which may no longer be compatible with :class:`gymnasium.Env`. Adding new wrappers ------------------- All new wrappers should be added to the :mod:`omni.isaac.lab_tasks.utils.wrappers` module. They should check that the underlying environment is an instance of :class:`omni.isaac.lab.envs.ManagerBasedRLEnv` before applying the wrapper. This can be done by using the :func:`unwrapped` property. We include a set of wrappers in this module that can be used as a reference to implement your own wrappers. If you implement a new wrapper, please consider contributing it to the framework by opening a pull request. .. _Stable-Baselines3: https://stable-baselines3.readthedocs.io/en/master/ .. _SKRL: https://skrl.readthedocs.io .. _RL-Games: https://github.com/Denys88/rl_games .. _RSL-RL: https://github.com/leggedrobotics/rsl_rl
6,668
reStructuredText
38.934132
117
0.734403
isaac-sim/IsaacLab/docs/source/how-to/draw_markers.rst
Creating Visualization Markers ============================== .. currentmodule:: omni.isaac.lab Visualization markers are useful to debug the state of the environment. They can be used to visualize the frames, commands, and other information in the simulation. While Isaac Sim provides its own :mod:`omni.isaac.debug_draw` extension, it is limited to rendering only points, lines and splines. For cases, where you need to render more complex shapes, you can use the :class:`markers.VisualizationMarkers` class. This guide is accompanied by a sample script ``markers.py`` in the ``IsaacLab/source/standalone/demos`` directory. .. dropdown:: Code for markers.py :icon: code .. literalinclude:: ../../../source/standalone/demos/markers.py :language: python :emphasize-lines: 45-90, 106-107, 136-142 :linenos: Configuring the markers ----------------------- The :class:`~markers.VisualizationMarkersCfg` class provides a simple interface to configure different types of markers. It takes in the following parameters: - :attr:`~markers.VisualizationMarkersCfg.prim_path`: The corresponding prim path for the marker class. - :attr:`~markers.VisualizationMarkersCfg.markers`: A dictionary specifying the different marker prototypes handled by the class. The key is the name of the marker prototype and the value is its spawn configuration. .. note:: In case the marker prototype specifies a configuration with physics properties, these are removed. This is because the markers are not meant to be simulated. Here we show all the different types of markers that can be configured. These range from simple shapes like cones and spheres to more complex geometries like a frame or arrows. The marker prototypes can also be configured from USD files. .. literalinclude:: ../../../source/standalone/demos/markers.py :language: python :lines: 45-90 :dedent: Drawing the markers ------------------- To draw the markers, we call the :class:`~markers.VisualizationMarkers.visualize` method. This method takes in as arguments the pose of the markers and the corresponding marker prototypes to draw. .. literalinclude:: ../../../source/standalone/demos/markers.py :language: python :lines: 136-142 :dedent: Executing the Script -------------------- To run the accompanying script, execute the following command: .. code-block:: bash ./isaaclab.sh -p source/standalone/demos/markers.py The simulation should start, and you can observe the different types of markers arranged in a grid pattern. The markers will rotating around their respective axes. Additionally every few rotations, they will roll forward on the grid. To stop the simulation, close the window, or use ``Ctrl+C`` in the terminal.
2,755
reStructuredText
35.263157
114
0.740109
isaac-sim/IsaacLab/docs/source/how-to/import_new_asset.rst
Importing a New Asset ===================== .. currentmodule:: omni.isaac.lab NVIDIA Omniverse relies on the Universal Scene Description (USD) file format to import and export assets. USD is an open source file format developed by Pixar Animation Studios. It is a scene description format optimized for large-scale, complex data sets. While this format is widely used in the film and animation industry, it is less common in the robotics community. To this end, NVIDIA has developed various importers that allow you to import assets from other file formats into USD. These importers are available as extensions to Omniverse Kit: * **URDF Importer** - Import assets from URDF files. * **MJCF Importer** - Import assets from MJCF files. * **Asset Importer** - Import assets from various file formats, including OBJ, FBX, STL, and glTF. The recommended workflow from NVIDIA is to use the above importers to convert the asset into its USD representation. Once the asset is in USD format, you can use the Omniverse Kit to edit the asset and export it to other file formats. An important note to use assets for large-scale simulation is to ensure that they are in `instanceable`_ format. This allows the asset to be efficiently loaded into memory and used multiple times in a scene. Otherwise, the asset will be loaded into memory multiple times, which can cause performance issues. For more details on instanceable assets, please check the Isaac Sim `documentation`_. Using URDF Importer ------------------- Isaac Sim includes the URDF and MJCF importers by default. These importers support the option to import assets as instanceable assets. By selecting this option, the importer will create two USD files: one for all the mesh data and one for all the non-mesh data (e.g. joints, rigid bodies, etc.). The prims in the mesh data file are referenced in the non-mesh data file. This allows the mesh data (which is often bulky) to be loaded into memory only once and used multiple times in a scene. For using these importers from the GUI, please check the documentation for `MJCF importer`_ and `URDF importer`_ respectively. For using the URDF importers from Python scripts, we include a utility tool called ``convert_urdf.py``. Internally, this script creates an instance of :class:`~sim.converters.UrdfConverterCfg` which is then passed to the :class:`~sim.converters.UrdfConverter` class. The configuration class specifies the default values for the importer. The important settings are: * :attr:`~sim.converters.UrdfConverterCfg.fix_base` - Whether to fix the base of the robot. This depends on whether you have a floating-base or fixed-base robot. * :attr:`~sim.converters.UrdfConverterCfg.make_instanceable` - Whether to create instanceable assets. Usually, this should be set to ``True``. * :attr:`~sim.converters.UrdfConverterCfg.merge_fixed_joints` - Whether to merge the fixed joints. Usually, this should be set to ``True`` to reduce the asset complexity. * :attr:`~sim.converters.UrdfConverterCfg.default_drive_type` - The drive-type for the joints. We recommend this to always be ``"none"``. This allows changing the drive configuration using the actuator models. * :attr:`~sim.converters.UrdfConverterCfg.default_drive_stiffness` - The drive stiffness for the joints. We recommend this to always be ``0.0``. This allows changing the drive configuration using the actuator models. * :attr:`~sim.converters.UrdfConverterCfg.default_drive_damping` - The drive damping for the joints. Similar to the stiffness, we recommend this to always be ``0.0``. Example Usage ~~~~~~~~~~~~~ In this example, we use the pre-processed URDF file of the ANYmal-D robot. To check the pre-process URDF, please check the file the `anymal.urdf`_. The main difference between the pre-processed URDF and the original URDF are: * We removed the ``<gazebo>`` tag from the URDF. This tag is not supported by the URDF importer. * We removed the ``<transmission>`` tag from the URDF. This tag is not supported by the URDF importer. * We removed various collision bodies from the URDF to reduce the complexity of the asset. * We changed all the joint's damping and friction parameters to ``0.0``. This ensures that we can perform effort-control on the joints without PhysX adding additional damping. * We added the ``<dont_collapse>`` tag to fixed joints. This ensures that the importer does not merge these fixed joints. The following shows the steps to clone the repository and run the converter: .. code-block:: bash # create a directory to clone mkdir ~/git && cd ~/git # clone a repository with URDF files git clone [email protected]:isaac-orbit/anymal_d_simple_description.git # go to top of the repository cd IsaacLab # run the converter ./isaaclab.sh -p source/standalone/tools/convert_urdf.py \ ~/git/anymal_d_simple_description/urdf/anymal.urdf \ source/extensions/omni.isaac.lab_assets/data/Robots/ANYbotics/anymal_d.usd \ --merge-joints \ --make-instanceable Executing the above script will create two USD files inside the ``source/extensions/omni.isaac.lab_assets/data/Robots/ANYbotics/`` directory: * ``anymal_d.usd`` - This is the main asset file. It contains all the non-mesh data. * ``Props/instanceable_assets.usd`` - This is the mesh data file. .. note:: Since Isaac Sim 2023.1.1, the URDF importer behavior has changed and it stores the mesh data inside the main asset file even if the ``--make-instanceable`` flag is set. This means that the ``Props/instanceable_assets.usd`` file is created but not used anymore. You can press play on the opened window to see the asset in the scene. The asset should "collapse" if everything is working correctly. If it blows up, then it might be that you have self-collisions present in the URDF. To run the script headless, you can add the ``--headless`` flag. This will not open the GUI and exit the script after the conversion is complete. Using Mesh Importer ------------------- Omniverse Kit includes the mesh converter tool that uses the ASSIMP library to import assets from various mesh formats (e.g. OBJ, FBX, STL, glTF, etc.). The asset converter tool is available as an extension to Omniverse Kit. Please check the `asset converter`_ documentation for more details. However, unlike Isaac Sim's URDF and MJCF importers, the asset converter tool does not support creating instanceable assets. This means that the asset will be loaded into memory multiple times if it is used multiple times in a scene. Thus, we include a utility tool called ``convert_mesh.py`` that uses the asset converter tool to import the asset and then converts it into an instanceable asset. Internally, this script creates an instance of :class:`~sim.converters.MeshConverterCfg` which is then passed to the :class:`~sim.converters.MeshConverter` class. Since the mesh file does not contain any physics information, the configuration class accepts different physics properties (such as mass, collision shape, etc.) as input. Please check the documentation for :class:`~sim.converters.MeshConverterCfg` for more details. Example Usage ~~~~~~~~~~~~~ We use an OBJ file of a cube to demonstrate the usage of the mesh converter. The following shows the steps to clone the repository and run the converter: .. code-block:: bash # create a directory to clone mkdir ~/git && cd ~/git # clone a repository with URDF files git clone [email protected]:NVIDIA-Omniverse/IsaacGymEnvs.git # go to top of the repository cd IsaacLab # run the converter ./isaaclab.sh -p source/standalone/tools/convert_mesh.py \ ~/git/IsaacGymEnvs/assets/trifinger/objects/meshes/cube_multicolor.obj \ source/extensions/omni.isaac.lab_assets/data/Props/CubeMultiColor/cube_multicolor.usd \ --make-instanceable \ --collision-approximation convexDecomposition \ --mass 1.0 Similar to the URDF converter, executing the above script will create two USD files inside the ``source/extensions/omni.isaac.lab_assets/data/Props/CubeMultiColor/`` directory. Additionally, if you press play on the opened window, you should see the asset fall down under the influence of gravity. * If you do not set the ``--mass`` flag, then no rigid body properties will be added to the asset. It will be imported as a static asset. * If you also do not set the ``--collision-approximation`` flag, then the asset will not have any collider properties as well and will be imported as a visual asset. .. _instanceable: https://openusd.org/dev/api/_usd__page__scenegraph_instancing.html .. _documentation: https://docs.omniverse.nvidia.com/isaacsim/latest/isaac_gym_tutorials/tutorial_gym_instanceable_assets.html .. _MJCF importer: https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_mjcf.html .. _URDF importer: https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_urdf.html .. _anymal.urdf: https://github.com/isaac-orbit/anymal_d_simple_description/blob/master/urdf/anymal.urdf .. _asset converter: https://docs.omniverse.nvidia.com/extensions/latest/ext_asset-converter.html
9,151
reStructuredText
50.706214
126
0.76549
isaac-sim/IsaacLab/docs/source/how-to/add_own_library.rst
Adding your own learning library ================================ Isaac Lab comes pre-integrated with a number of libraries (such as RSL-RL, RL-Games, SKRL, Stable Baselines, etc.). However, you may want to integrate your own library with Isaac Lab or use a different version of the libraries than the one installed by Isaac Lab. This is possible as long as the library is available as Python package that supports the Python version used by the underlying simulator. For instance, if you are using Isaac Sim 2023.1.1, you need to ensure that the library is available for Python 3.10. Using a different version of a library -------------------------------------- If you want to use a different version of a library than the one installed by Isaac Lab, you can install the library by building it from source or using a different version of the library available on PyPI. For instance, if you want to use your own modified version of the `rsl-rl`_ library, you can follow these steps: 1. Follow the instructions for installing Isaac Lab. This will install the default version of the ``rsl-rl`` library. 2. Clone the ``rsl-rl`` library from the GitHub repository: .. code-block:: bash git clone [email protected]:leggedrobotics/rsl_rl.git 3. Install the library in your Python environment: .. code-block:: bash # Assuming you are in the root directory of the Isaac Lab repository cd IsaacLab # Note: If you are using a virtual environment, make sure to activate it before running the following command ./isaaclab.sh -p -m pip install -e /path/to/rsl_rl In this case, the ``rsl-rl`` library will be installed in the Python environment used by Isaac Lab. You can now use the ``rsl-rl`` library in your experiments. To check the library version and other details, you can use the following command: .. code-block:: bash ./isaaclab.sh -p -m pip show rsl-rl This should now show the location of the ``rsl-rl`` library as the directory where you cloned the library. For instance, if you cloned the library to ``/home/user/git/rsl_rl``, the output of the above command should be: .. code-block:: bash Name: rsl_rl Version: 2.0.2 Summary: Fast and simple RL algorithms implemented in pytorch Home-page: https://github.com/leggedrobotics/rsl_rl Author: ETH Zurich, NVIDIA CORPORATION Author-email: License: BSD-3 Location: /home/user/git/rsl_rl Requires: torch, torchvision, numpy, GitPython, onnx Required-by: Integrating a new library ------------------------- Adding a new library to Isaac Lab is similar to using a different version of a library. You can install the library in your Python environment and use it in your experiments. However, if you want to integrate the library with Isaac Lab, you can will first need to make a wrapper for the library, as explained in :ref:`how-to-env-wrappers`. The following steps can be followed to integrate a new library with Isaac Lab: 1. Add your library as an extra-dependency in the ``setup.py`` for the extension ``omni.isaac.lab_tasks``. This will ensure that the library is installed when you install Isaac Lab or it will complain if the library is not installed or available. 2. Install your library in the Python environment used by Isaac Lab. You can do this by following the steps mentioned in the previous section. 3. Create a wrapper for the library. You can check the module :mod:`omni.isaac.lab_tasks.utils.wrappers` for examples of wrappers for different libraries. You can create a new wrapper for your library and add it to the module. You can also create a new module for the wrapper if you prefer. 4. Create workflow scripts for your library to train and evaluate agents. You can check the existing workflow scripts in the ``source/standalone/workflows`` directory for examples. You can create new workflow scripts for your library and add them to the directory. Optionally, you can also add some tests and documentation for the wrapper. This will help ensure that the wrapper works as expected and can guide users on how to use the wrapper. * Add some tests to ensure that the wrapper works as expected and remains compatible with the library. These tests can be added to the ``source/extensions/omni.isaac.lab_tasks/test/wrappers`` directory. * Add some documentation for the wrapper. You can add the API documentation to the ``docs/source/api/lab_tasks/omni.isaac.lab_tasks.utils.wrappers.rst`` file. .. _rsl-rl: https://github.com/leggedrobotics/rsl_rl
4,511
reStructuredText
48.043478
119
0.747949
isaac-sim/IsaacLab/docs/source/how-to/make_fixed_prim.rst
Making a physics prim fixed in the simulation ============================================= .. currentmodule:: omni.isaac.lab When a USD prim has physics schemas applied on it, it is affected by physics simulation. This means that the prim can move, rotate, and collide with other prims in the simulation world. However, there are cases where it is desirable to make certain prims static in the simulation world, i.e. the prim should still participate in collisions but its position and orientation should not change. The following sections describe how to spawn a prim with physics schemas and make it static in the simulation world. Static colliders ---------------- Static colliders are prims that are not affected by physics but can collide with other prims in the simulation world. These don't have any rigid body properties applied on them. However, this also means that they can't be accessed using the physics tensor API (i.e., through the :class:`assets.RigidObject` class). For instance, to spawn a cone static in the simulation world, the following code can be used: .. code-block:: python import omni.isaac.lab.sim as sim_utils cone_spawn_cfg = sim_utils.ConeCfg( radius=0.15, height=0.5, collision_props=sim_utils.CollisionPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), ) cone_spawn_cfg.func( "/World/Cone", cone_spawn_cfg, translation=(0.0, 0.0, 2.0), orientation=(0.5, 0.0, 0.5, 0.0) ) Rigid object ------------ Rigid objects (i.e. object only has a single body) can be made static by setting the parameter :attr:`sim.schemas.RigidBodyPropertiesCfg.kinematic_enabled` as True. This will make the object kinematic and it will not be affected by physics. For instance, to spawn a cone static in the simulation world but with rigid body schema on it, the following code can be used: .. code-block:: python import omni.isaac.lab.sim as sim_utils cone_spawn_cfg = sim_utils.ConeCfg( radius=0.15, height=0.5, rigid_props=sim_utils.RigidBodyPropertiesCfg(kinematic_enabled=True), mass_props=sim_utils.MassPropertiesCfg(mass=1.0), collision_props=sim_utils.CollisionPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), ) cone_spawn_cfg.func( "/World/Cone", cone_spawn_cfg, translation=(0.0, 0.0, 2.0), orientation=(0.5, 0.0, 0.5, 0.0) ) Articulation ------------ Fixing the root of an articulation requires having a fixed joint to the root rigid body link of the articulation. This can be achieved by setting the parameter :attr:`sim.schemas.ArticulationRootPropertiesCfg.fix_root_link` as True. Based on the value of this parameter, the following cases are possible: * If set to :obj:`None`, the root link is not modified. * If the articulation already has a fixed root link, this flag will enable or disable the fixed joint. * If the articulation does not have a fixed root link, this flag will create a fixed joint between the world frame and the root link. The joint is created with the name "FixedJoint" under the root link. For instance, to spawn an ANYmal robot and make it static in the simulation world, the following code can be used: .. code-block:: python import omni.isaac.lab.sim as sim_utils from omni.isaac.lab.utils.assets import ISAACLAB_NUCLEUS_DIR anymal_spawn_cfg = sim_utils.UsdFileCfg( usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd", activate_contact_sensors=True, rigid_props=sim_utils.RigidBodyPropertiesCfg( disable_gravity=False, retain_accelerations=False, linear_damping=0.0, angular_damping=0.0, max_linear_velocity=1000.0, max_angular_velocity=1000.0, max_depenetration_velocity=1.0, ), articulation_props=sim_utils.ArticulationRootPropertiesCfg( enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0, fix_root_link=True, ), ) anymal_spawn_cfg.func( "/World/ANYmal", anymal_spawn_cfg, translation=(0.0, 0.0, 0.8), orientation=(1.0, 0.0, 0.0, 0.0) ) This will create a fixed joint between the world frame and the root link of the ANYmal robot at the prim path ``"/World/ANYmal/base/FixedJoint"`` since the root link is at the path ``"/World/ANYmal/base"``. Further notes ------------- Given the flexibility of USD asset designing the following possible scenarios are usually encountered: 1. **Articulation root schema on the rigid body prim without a fixed joint**: This is the most common and recommended scenario for floating-base articulations. The root prim has both the rigid body and the articulation root properties. In this case, the articulation root is parsed as a floating-base with the root prim of the articulation ``Link0Xform``. .. code-block:: text ArticulationXform └── Link0Xform (RigidBody and ArticulationRoot schema) 2. **Articulation root schema on the parent prim with a fixed joint**: This is the expected arrangement for fixed-base articulations. The root prim has only the rigid body properties and the articulation root properties are applied to its parent prim. In this case, the articulation root is parsed as a fixed-base with the root prim of the articulation ``Link0Xform``. .. code-block:: text ArticulationXform (ArticulationRoot schema) └── Link0Xform (RigidBody schema) └── FixedJoint (connecting the world frame and Link0Xform) 3. **Articulation root schema on the parent prim without a fixed joint**: This is a scenario where the root prim has only the rigid body properties and the articulation root properties are applied to its parent prim. However, the fixed joint is not created between the world frame and the root link. In this case, the articulation is parsed as a floating-base system. However, the PhysX parser uses its own heuristic (such as alphabetical order) to determine the root prim of the articulation. It may select the root prim at ``Link0Xform`` or choose another prim as the root prim. .. code-block:: text ArticulationXform (ArticulationRoot schema) └── Link0Xform (RigidBody schema) 4. **Articulation root schema on the rigid body prim with a fixed joint**: While this is a valid scenario, it is not recommended as it may lead to unexpected behavior. In this case, the articulation is still parsed as a floating-base system. However, the fixed joint, created between the world frame and the root link, is considered as a part of the maximal coordinate tree. This is different from PhysX considering the articulation as a fixed-base system. Hence, the simulation may not behave as expected. .. code-block:: text ArticulationXform └── Link0Xform (RigidBody and ArticulationRoot schema) └── FixedJoint (connecting the world frame and Link0Xform) For floating base articulations, the root prim usually has both the rigid body and the articulation root properties. However, directly connecting this prim to the world frame will cause the simulation to consider the fixed joint as a part of the maximal coordinate tree. This is different from PhysX considering the articulation as a fixed-base system. Internally, when the parameter :attr:`sim.schemas.ArticulationRootPropertiesCfg.fix_root_link` is set to True and the articulation is detected as a floating-base system, the fixed joint is created between the world frame the root rigid body link of the articulation. However, to make the PhysX parser consider the articulation as a fixed-base system, the articulation root properties are removed from the root rigid body prim and applied to its parent prim instead. .. note:: In future release of Isaac Sim, an explicit flag will be added to the articulation root schema from PhysX to toggle between fixed-base and floating-base systems. This will resolve the need of the above workaround.
8,205
reStructuredText
44.588889
117
0.724802
isaac-sim/IsaacLab/docs/source/how-to/master_omniverse.rst
Mastering Omniverse for Robotics ================================ NVIDIA Omniverse offers a large suite of tools for 3D content workflows. There are three main components (relevant to robotics) in Omniverse: - **USD Composer**: This is based on a novel file format (Universal Scene Description) from the animation (originally Pixar) community that is used in Omniverse - **PhysX SDK**: This is the main physics engine behind Omniverse that leverages GPU-based parallelization for massive scenes - **RTX-enabled Renderer**: This uses ray-tracing kernels in NVIDIA RTX GPUs for real-time physically-based rendering Of these, the first two require a deeper understanding to start working with Omniverse and its constituent applications (Isaac Sim and Isaac Lab). The main things to learn: - How to use the Composer GUI efficiently? - What are USD prims and schemas? - How do you compose a USD scene? - What is the difference between references and payloads in USD? - What is meant by scene-graph instancing? - How to apply PhysX schemas on prims? What all schemas are possible? - How to write basic operations in USD for creating prims and modifying their attributes? Part 1: Using USD Composer -------------------------- While several `video tutorials <https://www.youtube.com/@NVIDIA-Studio>`__ and `documentation <https://docs.omniverse.nvidia.com/>`__ exist out there on NVIDIA Omniverse, going through all of them would take an extensive amount of time and effort. Thus, we have curated these resources to guide you through using Omniverse, specifically for robotics. Introduction to Omniverse and USD - `What is NVIDIA Omniverse? <https://youtu.be/dvdB-ndYJBM>`__ - `What is the USD File Type? \| Getting Started in NVIDIA Omniverse <https://youtu.be/GOdyx-oSs2M>`__ - `What Makes USD Unique in NVIDIA Omniverse <https://youtu.be/o2x-30-PTkw>`__ Using Omniverse USD Composer - `Introduction to Omniverse USD Composer <https://youtu.be/_30Pf3nccuE>`__ - `Navigation Basics in Omniverse USD Composer <https://youtu.be/kb4ZA3TyMak>`__ - `Lighting Basics in NVIDIA Omniverse USD Composer <https://youtu.be/c7qyI8pZvF4>`__ - `Rendering Overview in NVIDIA Omniverse USD Composer <https://youtu.be/dCvq2ZyYmu4>`__ Materials and MDL - `Five Things to Know About Materials in NVIDIA Omniverse <https://youtu.be/C0HmcQXaENc>`__ - `How to apply materials? <https://docs.omniverse.nvidia.com/materials-and-rendering/latest/materials.html%23applying-materials>`__ Omniverse Physics and PhysX SDK - `Basics - Setting Up Physics and Toolbar Overview <https://youtu.be/nsJ0S9MycJI>`__ - `Basics - Demos Overview <https://youtu.be/-y0-EVTj10s>`__ - `Rigid Bodies - Mass Editing <https://youtu.be/GHl2RwWeRuM>`__ - `Materials - Friction Restitution and Defaults <https://youtu.be/oTW81DltNiE>`__ - `Overview of Simulation Ready Assets Physics in Omniverse <https://youtu.be/lFtEMg86lJc>`__ Importing assets - `Omniverse Create - Importing FBX Files \| NVIDIA Omniverse Tutorials <https://youtu.be/dQI0OpzfVHw>`__ - `Omniverse Asset Importer <https://docs.omniverse.nvidia.com/extensions/latest/ext_asset-importer.html>`__ - `Isaac Sim URDF impoter <https://docs.omniverse.nvidia.com/isaacsim/latest/ext_omni_isaac_urdf.html>`__ Part 2: Scripting in Omniverse ------------------------------ The above links mainly introduced how to use the USD Composer and its functionalities through UI operations. However, often developers need to write scripts to perform operations. This is especially true when you want to automate certain tasks or create custom applications that use Omniverse as a backend. This section will introduce you to scripting in Omniverse. USD is the main file format Omniverse operates with. So naturally, the APIs (from OpenUSD) for modifying USD are at the core of Omniverse. Most of the APIs are in C++ and Python bindings are provided for them. Thus, to script in Omniverse, you need to understand the USD APIs. .. note:: While Isaac Sim and Isaac Lab try to "relieve" users from understanding the core USD concepts and APIs, understanding these basics still help a lot once you start diving inside the codebase and modifying it for your own application. Before diving into USD scripting, it is good to get acquainted with the terminologies used in USD. We recommend the following `introduction to USD basics <https://www.sidefx.com/docs/houdini/solaris/usd.html>`__ by Houdini, which is a 3D animation software. Make sure to go through the following sections: - `Quick example <https://www.sidefx.com/docs/houdini/solaris/usd.html%23quick-example>`__ - `Attributes and primvars <https://www.sidefx.com/docs/houdini/solaris/usd.html%23attrs>`__ - `Composition <https://www.sidefx.com/docs/houdini/solaris/usd.html%23compose>`__ - `Schemas <https://www.sidefx.com/docs/houdini/solaris/usd.html%23schemas>`__ - `Instances <https://www.sidefx.com/docs/houdini/solaris/usd.html%23instancing>`__ and `Scene-graph Instancing <https://openusd.org/dev/api/_usd__page__scenegraph_instancing.html>`__ As a test of understanding, make sure you can answer the following: - What are prims? What is meant by a prim path in a stage? - How are attributes related to prims? - How are schemas related to prims? - What is the difference between attributes and schemas? - What is asset instancing? Part 3: More Resources ---------------------- - `Omniverse Glossary of Terms <https://docs.omniverse.nvidia.com/isaacsim/latest/common/glossary-of-terms.html>`__ - `Omniverse Code Samples <https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref.html>`__ - `PhysX Collider Compatibility <https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/rigid-bodies.html#collidercompatibility>`__ - `PhysX Limitations <https://docs.omniverse.nvidia.com/isaacsim/latest/features/physics/physX_limitations.html>`__ - `PhysX Documentation <https://nvidia-omniverse.github.io/PhysX/physx/>`__.
5,979
reStructuredText
46.84
140
0.748787
isaac-sim/IsaacLab/docs/source/how-to/write_articulation_cfg.rst
.. _how-to-write-articulation-config: Writing an Asset Configuration ============================== .. currentmodule:: omni.isaac.lab This guide walks through the process of creating an :class:`~assets.ArticulationCfg`. The :class:`~assets.ArticulationCfg` is a configuration object that defines the properties of an :class:`~assets.Articulation` in Isaac Lab. .. note:: While we only cover the creation of an :class:`~assets.ArticulationCfg` in this guide, the process is similar for creating any other asset configuration object. We will use the Cartpole example to demonstrate how to create an :class:`~assets.ArticulationCfg`. The Cartpole is a simple robot that consists of a cart with a pole attached to it. The cart is free to move along a rail, and the pole is free to rotate about the cart. .. dropdown:: Code for Cartpole configuration :icon: code .. literalinclude:: ../../../source/extensions/omni.isaac.lab_assets/omni/isaac/lab_assets/cartpole.py :language: python :linenos: Defining the spawn configuration -------------------------------- As explained in :ref:`tutorial-spawn-prims` tutorials, the spawn configuration defines the properties of the assets to be spawned. This spawning may happen procedurally, or through an existing asset file (e.g. USD or URDF). In this example, we will spawn the Cartpole from a USD file. When spawning an asset from a USD file, we define its :class:`~sim.spawners.from_files.UsdFileCfg`. This configuration object takes in the following parameters: * :class:`~sim.spawners.from_files.UsdFileCfg.usd_path`: The USD file path to spawn from * :class:`~sim.spawners.from_files.UsdFileCfg.rigid_props`: The properties of the articulation's root * :class:`~sim.spawners.from_files.UsdFileCfg.articulation_props`: The properties of all the articulation's links The last two parameters are optional. If not specified, they are kept at their default values in the USD file. .. literalinclude:: ../../../source/extensions/omni.isaac.lab_assets/omni/isaac/lab_assets/cartpole.py :language: python :lines: 15-31 :dedent: To import articulation from a URDF file instead of a USD file, you can replace the :class:`~sim.spawners.from_files.UsdFileCfg` with a :class:`~sim.spawners.from_files.UrdfFileCfg`. For more details, please check the API documentation. Defining the initial state -------------------------- Every asset requires defining their initial or *default* state in the simulation through its configuration. This configuration is stored into the asset's default state buffers that can be accessed when the asset's state needs to be reset. .. note:: The initial state of an asset is defined w.r.t. its local environment frame. This then needs to be transformed into the global simulation frame when resetting the asset's state. For more details, please check the :ref:`tutorial-interact-articulation` tutorial. For an articulation, the :class:`~assets.ArticulationCfg.InitialStateCfg` object defines the initial state of the root of the articulation and the initial state of all its joints. In this example, we will spawn the Cartpole at the origin of the XY plane at a Z height of 2.0 meters. Meanwhile, the joint positions and velocities are set to 0.0. .. literalinclude:: ../../../source/extensions/omni.isaac.lab_assets/omni/isaac/lab_assets/cartpole.py :language: python :lines: 32-34 :dedent: Defining the actuator configuration ----------------------------------- Actuators are a crucial component of an articulation. Through this configuration, it is possible to define the type of actuator model to use. We can use the internal actuator model provided by the physics engine (i.e. the implicit actuator model), or use a custom actuator model which is governed by a user-defined system of equations (i.e. the explicit actuator model). For more details on actuators, see :ref:`feature-actuators`. The cartpole's articulation has two actuators, one corresponding to its each joint: ``cart_to_pole`` and ``slider_to_cart``. We use two different actuator models for these actuators as an example. However, since they are both using the same actuator model, it is possible to combine them into a single actuator model. .. dropdown:: Actuator model configuration with separate actuator models :icon: code .. literalinclude:: ../../../source/extensions/omni.isaac.lab_assets/omni/isaac/lab_assets/cartpole.py :language: python :lines: 35-45 :dedent: .. dropdown:: Actuator model configuration with a single actuator model :icon: code .. code-block:: python actuators={ "all_joints": ImplicitActuatorCfg( joint_names_expr=[".*"], effort_limit=400.0, velocity_limit=100.0, stiffness={"slider_to_cart": 0.0, "cart_to_pole": 0.0}, damping={"slider_to_cart": 10.0, "cart_to_pole": 0.0}, ), },
4,943
reStructuredText
41.25641
113
0.726077
isaac-sim/IsaacLab/docs/source/how-to/record_animation.rst
Recording Animations of Simulations =================================== .. currentmodule:: omni.isaac.lab Omniverse includes tools to record animations of physics simulations. The `Stage Recorder`_ extension listens to all the motion and USD property changes within a USD stage and records them to a USD file. This file contains the time samples of the changes, which can be played back to render the animation. The timeSampled USD file only contains the changes to the stage. It uses the same hierarchy as the original stage at the time of recording. This allows adding the animation to the original stage, or to a different stage with the same hierarchy. The timeSampled file can be directly added as a sublayer to the original stage to play back the animation. .. note:: Omniverse only supports playing animation or playing physics on a USD prim at the same time. If you want to play back the animation of a USD prim, you need to disable the physics simulation on the prim. In Isaac Lab, we directly use the `Stage Recorder`_ extension to record the animation of the physics simulation. This is available as a feature in the :class:`~omni.isaac.lab.envs.ui.BaseEnvWindow` class. However, to record the animation of a simulation, you need to disable `Fabric`_ to allow reading and writing all the changes (such as motion and USD properties) to the USD stage. Stage Recorder Settings ~~~~~~~~~~~~~~~~~~~~~~~ Isaac Lab integration of the `Stage Recorder`_ extension assumes certain default settings. If you want to change the settings, you can directly use the `Stage Recorder`_ extension in the Omniverse Create application. .. dropdown:: Settings used in base_env_window.py :icon: code .. literalinclude:: ../../../source/extensions/omni.isaac.lab/omni/isaac/lab/envs/ui/base_env_window.py :language: python :linenos: :pyobject: BaseEnvWindow._toggle_recording_animation_fn Example Usage ~~~~~~~~~~~~~ In all environment standalone scripts, Fabric can be disabled by passing the ``--disable_fabric`` flag to the script. Here we run the state-machine example and record the animation of the simulation. .. code-block:: bash ./isaaclab.sh -p source/standalone/environments/state_machine/lift_cube_sm.py --num_envs 8 --cpu --disable_fabric On running the script, the Isaac Lab UI window opens with the button "Record Animation" in the toolbar. Clicking this button starts recording the animation of the simulation. On clicking the button again, the recording stops. The recorded animation and the original stage (with all physics disabled) are saved to the ``recordings`` folder in the current working directory. The files are stored in the ``usd`` format: - ``Stage.usd``: The original stage with all physics disabled - ``TimeSample_tk001.usd``: The timeSampled file containing the recorded animation You can open Omniverse Isaac Sim application to play back the animation. There are many ways to launch the application (such as from terminal or `Omniverse Launcher`_). Here we use the terminal to open the application and play the animation. .. code-block:: bash ./isaaclab.sh -s # Opens Isaac Sim application through _isaac_sim/isaac-sim.sh On a new stage, add the ``Stage.usd`` as a sublayer and then add the ``TimeSample_tk001.usd`` as a sublayer. You can do this by dragging and dropping the files from the file explorer to the stage. Please check out the `tutorial on layering in Omniverse`_ for more details. You can then play the animation by pressing the play button. .. _Stage Recorder: https://docs.omniverse.nvidia.com/extensions/latest/ext_animation_stage-recorder.html .. _Fabric: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usd_fabric_usdrt.html .. _Omniverse Launcher: https://docs.omniverse.nvidia.com/launcher/latest/index.html .. _tutorial on layering in Omniverse: https://www.youtube.com/watch?v=LTwmNkSDh-c&ab_channel=NVIDIAOmniverse
3,924
reStructuredText
48.683544
117
0.762742
isaac-sim/IsaacLab/docs/source/how-to/index.rst
How-to Guides ============= This section includes guides that help you use Isaac Lab. These are intended for users who have already worked through the tutorials and are looking for more information on how to use Isaac Lab. If you are new to Isaac Lab, we recommend you start with the tutorials. .. note:: This section is a work in progress. If you have a question that is not answered here, please open an issue on our `GitHub page <https://github.com/isaac-sim/IsaacLab>`_. .. toctree:: :maxdepth: 1 import_new_asset write_articulation_cfg make_fixed_prim save_camera_output draw_markers wrap_rl_env add_own_library master_omniverse record_animation
704
reStructuredText
27.199999
90
0.711648
isaac-sim/IsaacLab/docs/source/tutorials/index.rst
Tutorials ========= Welcome to the Isaac Lab tutorials! These tutorials provide a step-by-step guide to help you understand and use various features of the framework. All the tutorials are written as Python scripts. You can find the source code for each tutorial in the ``source/standalone/tutorials`` directory of the Isaac Lab repository. .. note:: We would love to extend the tutorials to cover more topics and use cases, so please let us know if you have any suggestions. We recommend that you go through the tutorials in the order they are listed here. .. toctree:: :maxdepth: 2 00_sim/index 01_assets/index 02_scene/index 03_envs/index 04_sensors/index 05_controllers/index
722
reStructuredText
27.919999
104
0.736842
isaac-sim/IsaacLab/docs/source/tutorials/01_assets/run_articulation.rst
.. _tutorial-interact-articulation: Interacting with an articulation ================================ .. currentmodule:: omni.isaac.lab This tutorial shows how to interact with an articulated robot in the simulation. It is a continuation of the :ref:`tutorial-interact-rigid-object` tutorial, where we learned how to interact with a rigid object. On top of setting the root state, we will see how to set the joint state and apply commands to the articulated robot. The Code ~~~~~~~~ The tutorial corresponds to the ``run_articulation.py`` script in the ``source/standalone/tutorials/01_assets`` directory. .. dropdown:: Code for run_articulation.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_articulation.py :language: python :emphasize-lines: 58-69, 91-104, 108-111, 116-117 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Designing the scene ------------------- Similar to the previous tutorial, we populate the scene with a ground plane and a distant light. Instead of spawning rigid objects, we now spawn a cart-pole articulation from its USD file. The cart-pole is a simple robot consisting of a cart and a pole attached to it. The cart is free to move along the x-axis, and the pole is free to rotate about the cart. The USD file for the cart-pole contains the robot's geometry, joints, and other physical properties. For the cart-pole, we use its pre-defined configuration object, which is an instance of the :class:`assets.ArticulationCfg` class. This class contains information about the articulation's spawning strategy, default initial state, actuator models for different joints, and other meta-information. A deeper-dive into how to create this configuration object is provided in the :ref:`how-to-write-articulation-config` tutorial. As seen in the previous tutorial, we can spawn the articulation into the scene in a similar fashion by creating an instance of the :class:`assets.Articulation` class by passing the configuration object to its constructor. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_articulation.py :language: python :start-at: # Create separate groups called "Origin1", "Origin2", "Origin3" :end-at: cartpole = Articulation(cfg=cartpole_cfg) Running the simulation loop --------------------------- Continuing from the previous tutorial, we reset the simulation at regular intervals, set commands to the articulation, step the simulation, and update the articulation's internal buffers. Resetting the simulation """""""""""""""""""""""" Similar to a rigid object, an articulation also has a root state. This state corresponds to the root body in the articulation tree. On top of the root state, an articulation also has joint states. These states correspond to the joint positions and velocities. To reset the articulation, we first set the root state by calling the :meth:`Articulation.write_root_state_to_sim` method. Similarly, we set the joint states by calling the :meth:`Articulation.write_joint_state_to_sim` method. Finally, we call the :meth:`Articulation.reset` method to reset any internal buffers and caches. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_articulation.py :language: python :start-at: # reset the scene entities :end-at: robot.reset() Stepping the simulation """"""""""""""""""""""" Applying commands to the articulation involves two steps: 1. *Setting the joint targets*: This sets the desired joint position, velocity, or effort targets for the articulation. 2. *Writing the data to the simulation*: Based on the articulation's configuration, this step handles any :ref:`actuation conversions <feature-actuators>` and writes the converted values to the PhysX buffer. In this tutorial, we control the articulation using joint effort commands. For this to work, we need to set the articulation's stiffness and damping parameters to zero. This is done a-priori inside the cart-pole's pre-defined configuration object. At every step, we randomly sample joint efforts and set them to the articulation by calling the :meth:`Articulation.set_joint_effort_target` method. After setting the targets, we call the :meth:`Articulation.write_data_to_sim` method to write the data to the PhysX buffer. Finally, we step the simulation. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_articulation.py :language: python :start-at: # Apply random action :end-at: robot.write_data_to_sim() Updating the state """""""""""""""""" Every articulation class contains a :class:`assets.ArticulationData` object. This stores the state of the articulation. To update the state inside the buffer, we call the :meth:`assets.Articulation.update` method. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_articulation.py :language: python :start-at: # Update buffers :end-at: robot.update(sim_dt) The Code Execution ~~~~~~~~~~~~~~~~~~ To run the code and see the results, let's run the script from the terminal: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/01_assets/run_articulation.py This command should open a stage with a ground plane, lights, and two cart-poles that are moving around randomly. To stop the simulation, you can either close the window, press the ``STOP`` button in the UI, or press ``Ctrl+C`` in the terminal. In this tutorial, we learned how to create and interact with a simple articulation. We saw how to set the state of an articulation (its root and joint state) and how to apply commands to it. We also saw how to update its buffers to read the latest state from the simulation. In addition to this tutorial, we also provide a few other scripts that spawn different robots.These are included in the ``source/standalone/demos`` directory. You can run these scripts as: .. code-block:: bash # Spawn many different single-arm manipulators ./isaaclab.sh -p source/standalone/demos/arms.py # Spawn many different quadrupeds ./isaaclab.sh -p source/standalone/demos/quadrupeds.py
6,125
reStructuredText
42.140845
119
0.745469
isaac-sim/IsaacLab/docs/source/tutorials/01_assets/run_rigid_object.rst
.. _tutorial-interact-rigid-object: Interacting with a rigid object =============================== .. currentmodule:: omni.isaac.lab In the previous tutorials, we learned the essential workings of the standalone script and how to spawn different objects (or *prims*) into the simulation. This tutorial shows how to create and interact with a rigid object. For this, we will use the :class:`assets.RigidObject` class provided in Isaac Lab. The Code ~~~~~~~~ The tutorial corresponds to the ``run_rigid_object.py`` script in the ``source/standalone/tutorials/01_assets`` directory. .. dropdown:: Code for run_rigid_object.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_rigid_object.py :language: python :emphasize-lines: 55-74, 76-78, 98-108, 111-112, 118-119, 132-134, 139-140 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ In this script, we split the ``main`` function into two separate functions, which highlight the two main steps of setting up any simulation in the simulator: 1. **Design scene**: As the name suggests, this part is responsible for adding all the prims to the scene. 2. **Run simulation**: This part is responsible for stepping the simulator, interacting with the prims in the scene, e.g., changing their poses, and applying any commands to them. A distinction between these two steps is necessary because the second step only happens after the first step is complete and the simulator is reset. Once the simulator is reset (which automatically plays the simulation), no new (physics-enabled) prims should be added to the scene as it may lead to unexpected behaviors. However, the prims can be interacted with through their respective handles. Designing the scene ------------------- Similar to the previous tutorial, we populate the scene with a ground plane and a light source. In addition, we add a rigid object to the scene using the :class:`assets.RigidObject` class. This class is responsible for spawning the prims at the input path and initializes their corresponding rigid body physics handles. In this tutorial, we create a conical rigid object using the spawn configuration similar to the rigid cone in the :ref:`Spawn Objects <tutorial-spawn-prims>` tutorial. The only difference is that now we wrap the spawning configuration into the :class:`assets.RigidObjectCfg` class. This class contains information about the asset's spawning strategy, default initial state, and other meta-information. When this class is passed to the :class:`assets.RigidObject` class, it spawns the object and initializes the corresponding physics handles when the simulation is played. As an example on spawning the rigid object prim multiple times, we create its parent Xform prims, ``/World/Origin{i}``, that correspond to different spawn locations. When the regex expression ``/World/Origin*/Cone`` is passed to the :class:`assets.RigidObject` class, it spawns the rigid object prim at each of the ``/World/Origin{i}`` locations. For instance, if ``/World/Origin1`` and ``/World/Origin2`` are present in the scene, the rigid object prims are spawned at the locations ``/World/Origin1/Cone`` and ``/World/Origin2/Cone`` respectively. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_rigid_object.py :language: python :start-at: # Create separate groups called "Origin1", "Origin2", "Origin3" :end-at: cone_object = RigidObject(cfg=cone_cfg) Since we want to interact with the rigid object, we pass this entity back to the main function. This entity is then used to interact with the rigid object in the simulation loop. In later tutorials, we will see a more convenient way to handle multiple scene entities using the :class:`scene.InteractiveScene` class. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_rigid_object.py :language: python :start-at: # return the scene information :end-at: return scene_entities, origins Running the simulation loop --------------------------- We modify the simulation loop to interact with the rigid object to include three steps -- resetting the simulation state at fixed intervals, stepping the simulation, and updating the internal buffers of the rigid object. For the convenience of this tutorial, we extract the rigid object's entity from the scene dictionary and store it in a variable. Resetting the simulation state """""""""""""""""""""""""""""" To reset the simulation state of the spawned rigid object prims, we need to set their pose and velocity. Together they define the root state of the spawned rigid objects. It is important to note that this state is defined in the **simulation world frame**, and not of their parent Xform prim. This is because the physics engine only understands the world frame and not the parent Xform prim's frame. Thus, we need to transform desired state of the rigid object prim into the world frame before setting it. We use the :attr:`assets.RigidObject.data.default_root_state` attribute to get the default root state of the spawned rigid object prims. This default state can be configured from the :attr:`assets.RigidObjectCfg.init_state` attribute, which we left as identity in this tutorial. We then randomize the translation of the root state and set the desired state of the rigid object prim using the :meth:`assets.RigidObject.write_root_state_to_sim` method. As the name suggests, this method writes the root state of the rigid object prim into the simulation buffer. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_rigid_object.py :language: python :start-at: # reset root state :end-at: cone_object.reset() Stepping the simulation """"""""""""""""""""""" Before stepping the simulation, we perform the :meth:`assets.RigidObject.write_data_to_sim` method. This method writes other data, such as external forces, into the simulation buffer. In this tutorial, we do not apply any external forces to the rigid object, so this method is not necessary. However, it is included for completeness. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_rigid_object.py :language: python :start-at: # apply sim data :end-at: cone_object.write_data_to_sim() Updating the state """""""""""""""""" After stepping the simulation, we update the internal buffers of the rigid object prims to reflect their new state inside the :class:`assets.RigidObject.data` attribute. This is done using the :meth:`assets.RigidObject.update` method. .. literalinclude:: ../../../../source/standalone/tutorials/01_assets/run_rigid_object.py :language: python :start-at: # update buffers :end-at: cone_object.update(sim_dt) The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/01_assets/run_rigid_object.py This should open a stage with a ground plane, lights, and several green cones. The cones must be dropping from a random height and settling on to the ground. To stop the simulation, you can either close the window, or press the ``STOP`` button in the UI, or press ``Ctrl+C`` in the terminal This tutorial showed how to spawn rigid objects and wrap them in a :class:`RigidObject` class to initialize their physics handles which allows setting and obtaining their state. In the next tutorial, we will see how to interact with an articulated object which is a collection of rigid objects connected by joints.
7,572
reStructuredText
50.168919
122
0.750528
isaac-sim/IsaacLab/docs/source/tutorials/01_assets/index.rst
Interacting with Assets ======================= Having spawned objects in the scene, these tutorials show you how to create physics handles for these objects and interact with them. These revolve around the :class:`~omni.isaac.lab.assets.AssetBase` class and its derivatives such as :class:`~omni.isaac.lab.assets.RigidObject` and :class:`~omni.isaac.lab.assets.Articulation`. .. toctree:: :maxdepth: 1 :titlesonly: run_rigid_object run_articulation
469
reStructuredText
30.333331
101
0.722814
isaac-sim/IsaacLab/docs/source/tutorials/02_scene/create_scene.rst
.. _tutorial-interactive-scene: Using the Interactive Scene =========================== .. currentmodule:: omni.isaac.lab So far in the tutorials, we manually spawned assets into the simulation and created object instances to interact with them. However, as the complexity of the scene increases, it becomes tedious to perform these tasks manually. In this tutorial, we will introduce the :class:`scene.InteractiveScene` class, which provides a convenient interface for spawning prims and managing them in the simulation. At a high-level, the interactive scene is a collection of scene entities. Each entity can be either a non-interactive prim (e.g. ground plane, light source), an interactive prim (e.g. articulation, rigid object), or a sensor (e.g. camera, lidar). The interactive scene provides a convenient interface for spawning these entities and managing them in the simulation. Compared the manual approach, it provides the following benefits: * Alleviates the user needing to spawn each asset separately as this is handled implicitly. * Enables user-friendly cloning of scene prims for multiple environments. * Collects all the scene entities into a single object, which makes them easier to manage. In this tutorial, we take the cartpole example from the :ref:`tutorial-interact-articulation` tutorial and replace the ``design_scene`` function with an :class:`scene.InteractiveScene` object. While it may seem like overkill to use the interactive scene for this simple example, it will become more useful in the future as more assets and sensors are added to the scene. The Code ~~~~~~~~ This tutorial corresponds to the ``create_scene.py`` script within ``source/standalone/tutorials/02_scene``. .. dropdown:: Code for create_scene.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/02_scene/create_scene.py :language: python :emphasize-lines: 50-63, 68-70, 91-92, 99-100, 105-106, 116-118 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ While the code is similar to the previous tutorial, there are a few key differences that we will go over in detail. Scene configuration ------------------- The scene is composed of a collection of entities, each with their own configuration. These are specified in a configuration class that inherits from :class:`scene.InteractiveSceneCfg`. The configuration class is then passed to the :class:`scene.InteractiveScene` constructor to create the scene. For the cartpole example, we specify the same scene as in the previous tutorial, but list them now in the configuration class :class:`CartpoleSceneCfg` instead of manually spawning them. .. literalinclude:: ../../../../source/standalone/tutorials/02_scene/create_scene.py :language: python :pyobject: CartpoleSceneCfg The variable names in the configuration class are used as keys to access the corresponding entity from the :class:`scene.InteractiveScene` object. For example, the cartpole can be accessed via ``scene["cartpole"]``. However, we will get to that later. First, let's look at how individual scene entities are configured. Similar to how a rigid object and articulation were configured in the previous tutorials, the configurations are specified using a configuration class. However, there is a key difference between the configurations for the ground plane and light source and the configuration for the cartpole. The ground plane and light source are non-interactive prims, while the cartpole is an interactive prim. This distinction is reflected in the configuration classes used to specify them. The configurations for the ground plane and light source are specified using an instance of the :class:`assets.AssetBaseCfg` class while the cartpole is configured using an instance of the :class:`assets.ArticulationCfg`. Anything that is not an interactive prim (i.e., neither an asset nor a sensor) is not *handled* by the scene during simulation steps. Another key difference to note is in the specification of the prim paths for the different prims: * Ground plane: ``/World/defaultGroundPlane`` * Light source: ``/World/Light`` * Cartpole: ``{ENV_REGEX_NS}/Robot`` As we learned earlier, Omniverse creates a graph of prims in the USD stage. The prim paths are used to specify the location of the prim in the graph. The ground plane and light source are specified using absolute paths, while the cartpole is specified using a relative path. The relative path is specified using the ``ENV_REGEX_NS`` variable, which is a special variable that is replaced with the environment name during scene creation. Any entity that has the ``ENV_REGEX_NS`` variable in its prim path will be cloned for each environment. This path is replaced by the scene object with ``/World/envs/env_{i}`` where ``i`` is the environment index. Scene instantiation ------------------- Unlike before where we called the ``design_scene`` function to create the scene, we now create an instance of the :class:`scene.InteractiveScene` class and pass in the configuration object to its constructor. While creating the configuration instance of ``CartpoleSceneCfg`` we specify how many environment copies we want to create using the ``num_envs`` argument. This will be used to clone the scene for each environment. .. literalinclude:: ../../../../source/standalone/tutorials/02_scene/create_scene.py :language: python :start-at: # Design scene :end-at: scene = InteractiveScene(scene_cfg) Accessing scene elements ------------------------ Similar to how entities were accessed from a dictionary in the previous tutorials, the scene elements can be accessed from the :class:`InteractiveScene` object using the ``[]`` operator. The operator takes in a string key and returns the corresponding entity. The key is specified through the configuration class for each entity. For example, the cartpole is specified using the key ``"cartpole"`` in the configuration class. .. literalinclude:: ../../../../source/standalone/tutorials/02_scene/create_scene.py :language: python :start-at: # Extract scene entities :end-at: robot = scene["cartpole"] Running the simulation loop --------------------------- The rest of the script looks similar to previous scripts that interfaced with :class:`assets.Articulation`, with a few small differences in the methods called: * :meth:`assets.Articulation.reset` ⟶ :meth:`scene.InteractiveScene.reset` * :meth:`assets.Articulation.write_data_to_sim` ⟶ :meth:`scene.InteractiveScene.write_data_to_sim` * :meth:`assets.Articulation.update` ⟶ :meth:`scene.InteractiveScene.update` Under the hood, the methods of :class:`scene.InteractiveScene` call the corresponding methods of the entities in the scene. The Code Execution ~~~~~~~~~~~~~~~~~~ Let's run the script to simulate 32 cartpoles in the scene. We can do this by passing the ``--num_envs`` argument to the script. .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/02_scene/create_scene.py --num_envs 32 This should open a stage with 32 cartpoles swinging around randomly. You can use the mouse to rotate the camera and the arrow keys to move around the scene. In this tutorial, we saw how to use :class:`scene.InteractiveScene` to create a scene with multiple assets. We also saw how to use the ``num_envs`` argument to clone the scene for multiple environments. There are many more example usages of the :class:`scene.InteractiveSceneCfg` in the tasks found under the ``omni.isaac.lab_tasks`` extension. Please check out the source code to see how they are used for more complex scenes.
7,592
reStructuredText
45.87037
107
0.761855
isaac-sim/IsaacLab/docs/source/tutorials/02_scene/index.rst
Creating a Scene ================ With the basic concepts of the framework covered, the tutorials move to a more intuitive scene interface that uses the :class:`~omni.isaac.lab.scene.InteractiveScene` class. This class provides a higher level abstraction for creating scenes easily. .. toctree:: :maxdepth: 1 :titlesonly: create_scene
350
reStructuredText
25.999998
94
0.728571
isaac-sim/IsaacLab/docs/source/tutorials/03_envs/run_rl_training.rst
Training with an RL Agent ========================= .. currentmodule:: omni.isaac.lab In the previous tutorials, we covered how to define an RL task environment, register it into the ``gym`` registry, and interact with it using a random agent. We now move on to the next step: training an RL agent to solve the task. Although the :class:`envs.ManagerBasedRLEnv` conforms to the :class:`gymnasium.Env` interface, it is not exactly a ``gym`` environment. The input and outputs of the environment are not numpy arrays, but rather based on torch tensors with the first dimension being the number of environment instances. Additionally, most RL libraries expect their own variation of an environment interface. For example, `Stable-Baselines3`_ expects the environment to conform to its `VecEnv API`_ which expects a list of numpy arrays instead of a single tensor. Similarly, `RSL-RL`_, `RL-Games`_ and `SKRL`_ expect a different interface. Since there is no one-size-fits-all solution, we do not base the :class:`envs.ManagerBasedRLEnv` on any particular learning library. Instead, we implement wrappers to convert the environment into the expected interface. These are specified in the :mod:`omni.isaac.lab_tasks.utils.wrappers` module. In this tutorial, we will use `Stable-Baselines3`_ to train an RL agent to solve the cartpole balancing task. .. caution:: Wrapping the environment with the respective learning framework's wrapper should happen in the end, i.e. after all other wrappers have been applied. This is because the learning framework's wrapper modifies the interpretation of environment's APIs which may no longer be compatible with :class:`gymnasium.Env`. The Code -------- For this tutorial, we use the training script from `Stable-Baselines3`_ workflow in the ``source/standalone/workflows/sb3`` directory. .. dropdown:: Code for train.py :icon: code .. literalinclude:: ../../../../source/standalone/workflows/sb3/train.py :language: python :emphasize-lines: 57, 66, 68-70, 81, 90-98, 100, 105-113, 115-116, 121-126, 133-136 :linenos: The Code Explained ------------------ .. currentmodule:: omni.isaac.lab_tasks.utils Most of the code above is boilerplate code to create logging directories, saving the parsed configurations, and setting up different Stable-Baselines3 components. For this tutorial, the important part is creating the environment and wrapping it with the Stable-Baselines3 wrapper. There are three wrappers used in the code above: 1. :class:`gymnasium.wrappers.RecordVideo`: This wrapper records a video of the environment and saves it to the specified directory. This is useful for visualizing the agent's behavior during training. 2. :class:`wrappers.sb3.Sb3VecEnvWrapper`: This wrapper converts the environment into a Stable-Baselines3 compatible environment. 3. `stable_baselines3.common.vec_env.VecNormalize`_: This wrapper normalizes the environment's observations and rewards. Each of these wrappers wrap around the previous wrapper by following ``env = wrapper(env, *args, **kwargs)`` repeatedly. The final environment is then used to train the agent. For more information on how these wrappers work, please refer to the :ref:`how-to-env-wrappers` documentation. The Code Execution ------------------ We train a PPO agent from Stable-Baselines3 to solve the cartpole balancing task. Training the agent ~~~~~~~~~~~~~~~~~~ There are three main ways to train the agent. Each of them has their own advantages and disadvantages. It is up to you to decide which one you prefer based on your use case. Headless execution """""""""""""""""" If the ``--headless`` flag is set, the simulation is not rendered during training. This is useful when training on a remote server or when you do not want to see the simulation. Typically, it speeds up the training process since only physics simulation step is performed. .. code-block:: bash ./isaaclab.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --num_envs 64 --headless Headless execution with off-screen render """"""""""""""""""""""""""""""""""""""""" Since the above command does not render the simulation, it is not possible to visualize the agent's behavior during training. To visualize the agent's behavior, we pass the ``--enable_cameras`` which enables off-screen rendering. Additionally, we pass the flag ``--video`` which records a video of the agent's behavior during training. .. code-block:: bash ./isaaclab.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --num_envs 64 --headless --enable_cameras --video The videos are saved to the ``logs/sb3/Isaac-Cartpole-v0/<run-dir>/videos`` directory. You can open these videos using any video player. Interactive execution """"""""""""""""""""" .. currentmodule:: omni.isaac.lab While the above two methods are useful for training the agent, they don't allow you to interact with the simulation to see what is happening. In this case, you can ignore the ``--headless`` flag and run the training script as follows: .. code-block:: bash ./isaaclab.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --num_envs 64 This will open the Isaac Sim window and you can see the agent training in the environment. However, this will slow down the training process since the simulation is rendered on the screen. As a workaround, you can switch between different render modes in the ``"Isaac Lab"`` window that is docked on the bottom-right corner of the screen. To learn more about these render modes, please check the :class:`sim.SimulationContext.RenderMode` class. Viewing the logs ~~~~~~~~~~~~~~~~ On a separate terminal, you can monitor the training progress by executing the following command: .. code:: bash # execute from the root directory of the repository ./isaaclab.sh -p -m tensorboard.main --logdir logs/sb3/Isaac-Cartpole-v0 Playing the trained agent ~~~~~~~~~~~~~~~~~~~~~~~~~ Once the training is complete, you can visualize the trained agent by executing the following command: .. code:: bash # execute from the root directory of the repository ./isaaclab.sh -p source/standalone/workflows/sb3/play.py --task Isaac-Cartpole-v0 --num_envs 32 --use_last_checkpoint The above command will load the latest checkpoint from the ``logs/sb3/Isaac-Cartpole-v0`` directory. You can also specify a specific checkpoint by passing the ``--checkpoint`` flag. .. _Stable-Baselines3: https://stable-baselines3.readthedocs.io/en/master/ .. _VecEnv API: https://stable-baselines3.readthedocs.io/en/master/guide/vec_envs.html#vecenv-api-vs-gym-api .. _`stable_baselines3.common.vec_env.VecNormalize`: https://stable-baselines3.readthedocs.io/en/master/guide/vec_envs.html#vecnormalize .. _RL-Games: https://github.com/Denys88/rl_games .. _RSL-RL: https://github.com/leggedrobotics/rsl_rl .. _SKRL: https://skrl.readthedocs.io
6,928
reStructuredText
43.703226
136
0.747835
isaac-sim/IsaacLab/docs/source/tutorials/03_envs/create_rl_env.rst
.. _tutorial-create-rl-env: Creating a Manager-Based RL Environment ======================================= .. currentmodule:: omni.isaac.lab Having learnt how to create a base environment in :ref:`tutorial-create-base-env`, we will now look at how to create a manager-based task environment for reinforcement learning. The base environment is designed as an sense-act environment where the agent can send commands to the environment and receive observations from the environment. This minimal interface is sufficient for many applications such as traditional motion planning and controls. However, many applications require a task-specification which often serves as the learning objective for the agent. For instance, in a navigation task, the agent may be required to reach a goal location. To this end, we use the :class:`envs.ManagerBasedRLEnv` class which extends the base environment to include a task specification. Similar to other components in Isaac Lab, instead of directly modifying the base class :class:`envs.ManagerBasedRLEnv`, we encourage users to simply implement a configuration :class:`envs.ManagerBasedRLEnvCfg` for their task environment. This practice allows us to separate the task specification from the environment implementation, making it easier to reuse components of the same environment for different tasks. In this tutorial, we will configure the cartpole environment using the :class:`envs.ManagerBasedRLEnvCfg` to create a manager-based task for balancing the pole upright. We will learn how to specify the task using reward terms, termination criteria, curriculum and commands. The Code ~~~~~~~~ For this tutorial, we use the cartpole environment defined in ``omni.isaac.lab_tasks.manager_based.classic.cartpole`` module. .. dropdown:: Code for cartpole_env_cfg.py :icon: code .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py :language: python :emphasize-lines: 63-68, 124-149, 152-162, 165-169, 187-192 :linenos: The script for running the environment ``run_cartpole_rl_env.py`` is present in the ``isaaclab/source/standalone/tutorials/03_envs`` directory. The script is similar to the ``cartpole_base_env.py`` script in the previous tutorial, except that it uses the :class:`envs.ManagerBasedRLEnv` instead of the :class:`envs.ManagerBasedEnv`. .. dropdown:: Code for run_cartpole_rl_env.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/run_cartpole_rl_env.py :language: python :emphasize-lines: 38-42, 56-57 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ We already went through parts of the above in the :ref:`tutorial-create-base-env` tutorial to learn about how to specify the scene, observations, actions and events. Thus, in this tutorial, we will focus only on the RL components of the environment. In Isaac Lab, we provide various implementations of different terms in the :mod:`envs.mdp` module. We will use some of these terms in this tutorial, but users are free to define their own terms as well. These are usually placed in their task-specific sub-package (for instance, in :mod:`omni.isaac.lab_tasks.manager_based.classic.cartpole.mdp`). Defining rewards ---------------- The :class:`managers.RewardManager` is used to compute the reward terms for the agent. Similar to the other managers, its terms are configured using the :class:`managers.RewardTermCfg` class. The :class:`managers.RewardTermCfg` class specifies the function or callable class that computes the reward as well as the weighting associated with it. It also takes in dictionary of arguments, ``"params"`` that are passed to the reward function when it is called. For the cartpole task, we will use the following reward terms: * **Alive Reward**: Encourage the agent to stay alive for as long as possible. * **Terminating Reward**: Similarly penalize the agent for terminating. * **Pole Angle Reward**: Encourage the agent to keep the pole at the desired upright position. * **Cart Velocity Reward**: Encourage the agent to keep the cart velocity as small as possible. * **Pole Velocity Reward**: Encourage the agent to keep the pole velocity as small as possible. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py :language: python :pyobject: RewardsCfg Defining termination criteria ----------------------------- Most learning tasks happen over a finite number of steps that we call an episode. For instance, in the cartpole task, we want the agent to balance the pole for as long as possible. However, if the agent reaches an unstable or unsafe state, we want to terminate the episode. On the other hand, if the agent is able to balance the pole for a long time, we want to terminate the episode and start a new one so that the agent can learn to balance the pole from a different starting configuration. The :class:`managers.TerminationsCfg` configures what constitutes for an episode to terminate. In this example, we want the task to terminate when either of the following conditions is met: * **Episode Length** The episode length is greater than the defined max_episode_length * **Cart out of bounds** The cart goes outside of the bounds [-3, 3] The flag :attr:`managers.TerminationsCfg.time_out` specifies whether the term is a time-out (truncation) term or terminated term. These are used to indicate the two types of terminations as described in `Gymnasium's documentation <https://gymnasium.farama.org/tutorials/gymnasium_basics/handling_time_limits/>`_. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py :language: python :pyobject: TerminationsCfg Defining commands ----------------- For various goal-conditioned tasks, it is useful to specify the goals or commands for the agent. These are handled through the :class:`managers.CommandManager`. The command manager handles resampling and updating the commands at each step. It can also be used to provide the commands as an observation to the agent. For this simple task, we do not use any commands. This is specified by using a command term with the :class:`envs.mdp.NullCommandCfg` configuration. However, you can see an example of command definitions in the locomotion or manipulation tasks. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py :language: python :pyobject: CommandsCfg Defining curriculum ------------------- Often times when training a learning agent, it helps to start with a simple task and gradually increase the tasks's difficulty as the agent training progresses. This is the idea behind curriculum learning. In Isaac Lab, we provide a :class:`managers.CurriculumManager` class that can be used to define a curriculum for your environment. In this tutorial we don't implement a curriculum for simplicity, but you can see an example of a curriculum definition in the other locomotion or manipulation tasks. We use a simple pass-through curriculum to define a curriculum manager that does not modify the environment. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py :language: python :pyobject: CurriculumCfg Tying it all together --------------------- With all the above components defined, we can now create the :class:`ManagerBasedRLEnvCfg` configuration for the cartpole environment. This is similar to the :class:`ManagerBasedEnvCfg` defined in :ref:`tutorial-create-base-env`, only with the added RL components explained in the above sections. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py :language: python :pyobject: CartpoleEnvCfg Running the simulation loop --------------------------- Coming back to the ``run_cartpole_rl_env.py`` script, the simulation loop is similar to the previous tutorial. The only difference is that we create an instance of :class:`envs.ManagerBasedRLEnv` instead of the :class:`envs.ManagerBasedEnv`. Consequently, now the :meth:`envs.ManagerBasedRLEnv.step` method returns additional signals such as the reward and termination status. The information dictionary also maintains logging of quantities such as the reward contribution from individual terms, the termination status of each term, the episode length etc. .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/run_cartpole_rl_env.py :language: python :pyobject: main The Code Execution ~~~~~~~~~~~~~~~~~~ Similar to the previous tutorial, we can run the environment by executing the ``run_cartpole_rl_env.py`` script. .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/03_envs/run_cartpole_rl_env.py --num_envs 32 This should open a similar simulation as in the previous tutorial. However, this time, the environment returns more signals that specify the reward and termination status. Additionally, the individual environments reset themselves when they terminate based on the termination criteria specified in the configuration. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal where you started the simulation. In this tutorial, we learnt how to create a task environment for reinforcement learning. We do this by extending the base environment to include the rewards, terminations, commands and curriculum terms. We also learnt how to use the :class:`envs.ManagerBasedRLEnv` class to run the environment and receive various signals from it. While it is possible to manually create an instance of :class:`envs.ManagerBasedRLEnv` class for a desired task, this is not scalable as it requires specialized scripts for each task. Thus, we exploit the :meth:`gymnasium.make` function to create the environment with the gym interface. We will learn how to do this in the next tutorial.
10,197
reStructuredText
51.297436
145
0.7665
isaac-sim/IsaacLab/docs/source/tutorials/03_envs/create_base_env.rst
.. _tutorial-create-base-env: Creating a Manager-Based Base Environment ========================================= .. currentmodule:: omni.isaac.lab Environments bring together different aspects of the simulation such as the scene, observations and actions spaces, reset events etc. to create a coherent interface for various applications. In Isaac Lab, manager-based environments are implemented as :class:`envs.ManagerBasedEnv` and :class:`envs.ManagerBasedRLEnv` classes. The two classes are very similar, but :class:`envs.ManagerBasedRLEnv` is useful for reinforcement learning tasks and contains rewards, terminations, curriculum and command generation. The :class:`envs.ManagerBasedEnv` class is useful for traditional robot control and doesn't contain rewards and terminations. In this tutorial, we will look at the base class :class:`envs.ManagerBasedEnv` and its corresponding configuration class :class:`envs.ManagerBasedEnvCfg` for the manager-based workflow. We will use the cartpole environment from earlier to illustrate the different components in creating a new :class:`envs.ManagerBasedEnv` environment. The Code ~~~~~~~~ The tutorial corresponds to the ``create_cartpole_base_env`` script in the ``source/standalone/tutorials/03_envs`` directory. .. dropdown:: Code for create_cartpole_base_env.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/create_cartpole_base_env.py :language: python :emphasize-lines: 47-51, 54-71, 74-108, 111-130, 135-139, 144, 148, 153-154, 160-161 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ The base class :class:`envs.ManagerBasedEnv` wraps around many intricacies of the simulation interaction and provides a simple interface for the user to run the simulation and interact with it. It is composed of the following components: * :class:`scene.InteractiveScene` - The scene that is used for the simulation. * :class:`managers.ActionManager` - The manager that handles actions. * :class:`managers.ObservationManager` - The manager that handles observations. * :class:`managers.EventManager` - The manager that schedules operations (such as domain randomization) at specified simulation events. For instance, at startup, on resets, or periodic intervals. By configuring these components, the user can create different variations of the same environment with minimal effort. In this tutorial, we will go through the different components of the :class:`envs.ManagerBasedEnv` class and how to configure them to create a new environment. Designing the scene ------------------- The first step in creating a new environment is to configure its scene. For the cartpole environment, we will be using the scene from the previous tutorial. Thus, we omit the scene configuration here. For more details on how to configure a scene, see :ref:`tutorial-interactive-scene`. Defining actions ---------------- In the previous tutorial, we directly input the action to the cartpole using the :meth:`assets.Articulation.set_joint_effort_target` method. In this tutorial, we will use the :class:`managers.ActionManager` to handle the actions. The action manager can comprise of multiple :class:`managers.ActionTerm`. Each action term is responsible for applying *control* over a specific aspect of the environment. For instance, for robotic arm, we can have two action terms -- one for controlling the joints of the arm, and the other for controlling the gripper. This composition allows the user to define different control schemes for different aspects of the environment. In the cartpole environment, we want to control the force applied to the cart to balance the pole. Thus, we will create an action term that controls the force applied to the cart. .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/create_cartpole_base_env.py :language: python :pyobject: ActionsCfg Defining observations --------------------- While the scene defines the state of the environment, the observations define the states that are observable by the agent. These observations are used by the agent to make decisions on what actions to take. In Isaac Lab, the observations are computed by the :class:`managers.ObservationManager` class. Similar to the action manager, the observation manager can comprise of multiple observation terms. These are further grouped into observation groups which are used to define different observation spaces for the environment. For instance, for hierarchical control, we may want to define two observation groups -- one for the low level controller and the other for the high level controller. It is assumed that all the observation terms in a group have the same dimensions. For this tutorial, we will only define one observation group named ``"policy"``. While not completely prescriptive, this group is a necessary requirement for various wrappers in Isaac Lab. We define a group by inheriting from the :class:`managers.ObservationGroupCfg` class. This class collects different observation terms and help define common properties for the group, such as enabling noise corruption or concatenating the observations into a single tensor. The individual terms are defined by inheriting from the :class:`managers.ObservationTermCfg` class. This class takes in the :attr:`managers.ObservationTermCfg.func` that specifies the function or callable class that computes the observation for that term. It includes other parameters for defining the noise model, clipping, scaling, etc. However, we leave these parameters to their default values for this tutorial. .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/create_cartpole_base_env.py :language: python :pyobject: ObservationsCfg Defining events --------------- At this point, we have defined the scene, actions and observations for the cartpole environment. The general idea for all these components is to define the configuration classes and then pass them to the corresponding managers. The event manager is no different. The :class:`managers.EventManager` class is responsible for events corresponding to changes in the simulation state. This includes resetting (or randomizing) the scene, randomizing physical properties (such as mass, friction, etc.), and varying visual properties (such as colors, textures, etc.). Each of these are specified through the :class:`managers.EventTermCfg` class, which takes in the :attr:`managers.EventTermCfg.func` that specifies the function or callable class that performs the event. Additionally, it expects the **mode** of the event. The mode specifies when the event term should be applied. It is possible to specify your own mode. For this, you'll need to adapt the :class:`~envs.ManagerBasedEnv` class. However, out of the box, Isaac Lab provides three commonly used modes: * ``"startup"`` - Event that takes place only once at environment startup. * ``"reset"`` - Event that occurs on environment termination and reset. * ``"interval"`` - Event that are executed at a given interval, i.e., periodically after a certain number of steps. For this example, we define events that randomize the pole's mass on startup. This is done only once since this operation is expensive and we don't want to do it on every reset. We also create an event to randomize the initial joint state of the cartpole and the pole at every reset. .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/create_cartpole_base_env.py :language: python :pyobject: EventCfg Tying it all together --------------------- Having defined the scene and manager configurations, we can now define the environment configuration through the :class:`envs.ManagerBasedEnvCfg` class. This class takes in the scene, action, observation and event configurations. In addition to these, it also takes in the :attr:`envs.ManagerBasedEnvCfg.sim` which defines the simulation parameters such as the timestep, gravity, etc. This is initialized to the default values, but can be modified as needed. We recommend doing so by defining the :meth:`__post_init__` method in the :class:`envs.ManagerBasedEnvCfg` class, which is called after the configuration is initialized. .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/create_cartpole_base_env.py :language: python :pyobject: CartpoleEnvCfg Running the simulation ---------------------- Lastly, we revisit the simulation execution loop. This is now much simpler since we have abstracted away most of the details into the environment configuration. We only need to call the :meth:`envs.ManagerBasedEnv.reset` method to reset the environment and :meth:`envs.ManagerBasedEnv.step` method to step the environment. Both these functions return the observation and an info dictionary which may contain additional information provided by the environment. These can be used by an agent for decision-making. The :class:`envs.ManagerBasedEnv` class does not have any notion of terminations since that concept is specific for episodic tasks. Thus, the user is responsible for defining the termination condition for the environment. In this tutorial, we reset the simulation at regular intervals. .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/create_cartpole_base_env.py :language: python :pyobject: main An important thing to note above is that the entire simulation loop is wrapped inside the :meth:`torch.inference_mode` context manager. This is because the environment uses PyTorch operations under-the-hood and we want to ensure that the simulation is not slowed down by the overhead of PyTorch's autograd engine and gradients are not computed for the simulation operations. The Code Execution ~~~~~~~~~~~~~~~~~~ To run the base environment made in this tutorial, you can use the following command: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/03_envs/create_cartpole_base_env.py --num_envs 32 This should open a stage with a ground plane, light source, and cartpoles. The simulation should be playing with random actions on the cartpole. Additionally, it opens a UI window on the bottom right corner of the screen named ``"Isaac Lab"``. This window contains different UI elements that can be used for debugging and visualization. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal where you started the simulation. In this tutorial, we learned about the different managers that help define a base environment. We include more examples of defining the base environment in the ``source/standalone/tutorials/03_envs`` directory. For completeness, they can be run using the following commands: .. code-block:: bash # Floating cube environment with custom action term for PD control ./isaaclab.sh -p source/standalone/tutorials/03_envs/create_cube_base_env.py --num_envs 32 # Quadrupedal locomotion environment with a policy that interacts with the environment ./isaaclab.sh -p source/standalone/tutorials/03_envs/create_quadruped_base_env.py --num_envs 32 In the following tutorial, we will look at the :class:`envs.ManagerBasedRLEnv` class and how to use it to create a Markovian Decision Process (MDP).
11,244
reStructuredText
50.347032
115
0.775969
isaac-sim/IsaacLab/docs/source/tutorials/03_envs/create_direct_rl_env.rst
.. _tutorial-create-oige-rl-env: Creating a Direct Workflow RL Environment ========================================= .. currentmodule:: omni.isaac.lab In addition to the :class:`envs.ManagerBasedRLEnv` class, which encourages the use of configuration classes for more modular environments, the :class:`~omni.isaac.lab.envs.DirectRLEnv` class allows for more direct control in the scripting of environment. Instead of using Manager classes for defining rewards and observations, the direct workflow tasks implement the full reward and observation functions directly in the task script. This allows for more control in the implementation of the methods, such as using pytorch jit features, and provides a less abstracted framework that makes it easier to find the various pieces of code. In this tutorial, we will configure the cartpole environment using the direct workflow implementation to create a task for balancing the pole upright. We will learn how to specify the task using by implementing functions for scene creation, actions, resets, rewards and observations. The Code ~~~~~~~~ For this tutorial, we use the cartpole environment defined in ``omni.isaac.lab_tasks.direct.cartpole`` module. .. dropdown:: Code for cartpole_env.py :icon: code .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py :language: python :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Similar to the manager-based environments, a configuration class is defined for the task to hold settings for the simulation parameters, the scene, the actors, and the task. With the direct workflow implementation, the :class:`envs.DirectRLEnvCfg` class is used as the base class for configurations. Since the direct workflow implementation does not use Action and Observation managers, the task config should define the number of actions and observations for the environment. .. code-block:: python @configclass class CartpoleEnvCfg(DirectRLEnvCfg): ... num_actions = 1 num_observations = 4 num_states = 0 The config class can also be used to define task-specific attributes, such as scaling for reward terms and thresholds for reset conditions. .. code-block:: python @configclass class CartpoleEnvCfg(DirectRLEnvCfg): ... # reset max_cart_pos = 3.0 initial_pole_angle_range = [-0.25, 0.25] # reward scales rew_scale_alive = 1.0 rew_scale_terminated = -2.0 rew_scale_pole_pos = -1.0 rew_scale_cart_vel = -0.01 rew_scale_pole_vel = -0.005 When creating a new environment, the code should define a new class that inherits from :class:`~omni.isaac.lab.envs.DirectRLEnv`. .. code-block:: python class CartpoleEnv(DirectRLEnv): cfg: CartpoleEnvCfg def __init__(self, cfg: CartpoleEnvCfg, render_mode: str | None = None, **kwargs): super().__init__(cfg, render_mode, **kwargs) The class can also hold class variables that are accessible by all functions in the class, including functions for applying actions, computing resets, rewards, and observations. Scene Creation -------------- In contrast to manager-based environments where the scene creation is taken care of by the framework, the direct workflow implementation provides flexibility for users to implement their own scene creation function. This includes adding actors into the stage, cloning the environments, filtering collisions between the environments, adding the actors into the scene, and adding any additional props to the scene, such as ground plane and lights. These operations should be implemented in the ``_setup_scene(self)`` method. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py :language: python :pyobject: CartpoleEnv._setup_scene Defining Rewards ---------------- Reward function should be defined in the ``_get_rewards(self)`` API, which returns the reward buffer as a return value. Within this function, the task is free to implement the logic of the reward function. In this example, we implement a Pytorch jitted function that computes the various components of the reward function. .. code-block:: python def _get_rewards(self) -> torch.Tensor: total_reward = compute_rewards( self.cfg.rew_scale_alive, self.cfg.rew_scale_terminated, self.cfg.rew_scale_pole_pos, self.cfg.rew_scale_cart_vel, self.cfg.rew_scale_pole_vel, self.joint_pos[:, self._pole_dof_idx[0]], self.joint_vel[:, self._pole_dof_idx[0]], self.joint_pos[:, self._cart_dof_idx[0]], self.joint_vel[:, self._cart_dof_idx[0]], self.reset_terminated, ) return total_reward @torch.jit.script def compute_rewards( rew_scale_alive: float, rew_scale_terminated: float, rew_scale_pole_pos: float, rew_scale_cart_vel: float, rew_scale_pole_vel: float, pole_pos: torch.Tensor, pole_vel: torch.Tensor, cart_pos: torch.Tensor, cart_vel: torch.Tensor, reset_terminated: torch.Tensor, ): rew_alive = rew_scale_alive * (1.0 - reset_terminated.float()) rew_termination = rew_scale_terminated * reset_terminated.float() rew_pole_pos = rew_scale_pole_pos * torch.sum(torch.square(pole_pos), dim=-1) rew_cart_vel = rew_scale_cart_vel * torch.sum(torch.abs(cart_vel), dim=-1) rew_pole_vel = rew_scale_pole_vel * torch.sum(torch.abs(pole_vel), dim=-1) total_reward = rew_alive + rew_termination + rew_pole_pos + rew_cart_vel + rew_pole_vel return total_reward Defining Observations --------------------- The observation buffer should be computed in the ``_get_observations(self)`` function, which constructs the observation buffer for the environment. At the end of this API, a dictionary should be returned that contains ``policy`` as the key, and the full observation buffer as the value. For asymmetric policies, the dictionary should also include the key ``critic`` and the states buffer as the value. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py :language: python :pyobject: CartpoleEnv._get_observations Computing Dones and Performing Resets ------------------------------------- Populating the ``dones`` buffer should be done in the ``_get_dones(self)`` method. This method is free to implement logic that computes which environments would need to be reset and which environments have reached the episode length limit. Both results should be returned by the ``_get_dones(self)`` function, in the form of a tuple of boolean tensors. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py :language: python :pyobject: CartpoleEnv._get_dones Once the indices for environments requiring reset have been computed, the ``_reset_idx(self, env_ids)`` function performs the reset operations on those environments. Within this function, new states for the environments requiring reset should be set directly into simulation. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py :language: python :pyobject: CartpoleEnv._reset_idx Applying Actions ---------------- There are two APIs that are designed for working with actions. The ``_pre_physics_step(self, actions)`` takes in actions from the policy as an argument and is called once per RL step, prior to taking any physics steps. This function can be used to process the actions buffer from the policy and cache the data in a class variable for the environment. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py :language: python :pyobject: CartpoleEnv._pre_physics_step The ``_apply_action(self)`` API is called ``decimation`` number of times for each RL step, prior to taking each physics step. This provides more flexibility for environments where actions should be applied for each physics step. .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py :language: python :pyobject: CartpoleEnv._apply_action The Code Execution ~~~~~~~~~~~~~~~~~~ To run training for the direct workflow Cartpole environment, we can use the following command: .. code-block:: bash ./isaaclab.sh -p source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-Direct-v0 All direct workflow tasks have the suffix ``-Direct`` added to the task name to differentiate the implementation style. Domain Randomization ~~~~~~~~~~~~~~~~~~~~ In the direct workflow, domain randomization configuration uses the :class:`~omni.isaac.lab.utils.configclass` module to specify a configuration class consisting of :class:`~managers.EventTermCfg` variables. Below is an example of a configuration class for domain randomization: .. code-block:: python @configclass class EventCfg: robot_physics_material = EventTerm( func=mdp.randomize_rigid_body_material, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", body_names=".*"), "static_friction_range": (0.7, 1.3), "dynamic_friction_range": (1.0, 1.0), "restitution_range": (1.0, 1.0), "num_buckets": 250, }, ) robot_joint_stiffness_and_damping = EventTerm( func=mdp.randomize_actuator_gains, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", joint_names=".*"), "stiffness_distribution_params": (0.75, 1.5), "damping_distribution_params": (0.3, 3.0), "operation": "scale", "distribution": "log_uniform", }, ) reset_gravity = EventTerm( func=mdp.randomize_physics_scene_gravity, mode="interval", is_global_time=True, interval_range_s=(36.0, 36.0), # time_s = num_steps * (decimation * dt) params={ "gravity_distribution_params": ([0.0, 0.0, 0.0], [0.0, 0.0, 0.4]), "operation": "add", "distribution": "gaussian", }, ) Each ``EventTerm`` object is of the :class:`~managers.EventTermCfg` class and takes in a ``func`` parameter for specifying the function to call during randomization, a ``mode`` parameter, which can be ``startup``, ``reset`` or ``interval``. THe ``params`` dictionary should provide the necessary arguments to the function that is specified in the ``func`` parameter. Functions specified as ``func`` for the ``EventTerm`` can be found in the :class:`~envs.mdp.events` module. Note that as part of the ``"asset_cfg": SceneEntityCfg("robot", body_names=".*")`` parameter, the name of the actor ``"robot"`` is provided, along with the body or joint names specified as a regex expression, which will be the actors and bodies/joints that will have randomization applied. Once the ``configclass`` for the randomization terms have been set up, the class must be added to the base config class for the task and be assigned to the variable ``events``. .. code-block:: python @configclass class MyTaskConfig: events: EventCfg = EventCfg() Action and Observation Noise ---------------------------- Actions and observation noise can also be added using the :class:`~utils.configclass` module. Action and observation noise configs must be added to the main task config using the ``action_noise_model`` and ``observation_noise_model`` variables: .. code-block:: python @configclass class MyTaskConfig: # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset action_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.05, operation="add"), bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.015, operation="abs"), ) # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset observation_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.002, operation="add"), bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.0001, operation="abs"), ) :class:`~.utils.noise.NoiseModelWithAdditiveBiasCfg` can be used to sample both uncorrelated noise per step as well as correlated noise that is re-sampled at reset time. The ``noise_cfg`` term specifies the Gaussian distribution that will be sampled at each step for all environments. This noise will be added to the corresponding actions and observations buffers at every step. The ``bias_noise_cfg`` term specifies the Gaussian distribution for the correlated noise that will be sampled at reset time for the environments being reset. The same noise will be applied each step for the remaining of the episode for the environments and resampled at the next reset. If only per-step noise is desired, :class:`~utils.noise.GaussianNoiseCfg` can be used to specify an additive Gaussian distribution that adds the sampled noise to the input buffer. .. code-block:: python @configclass class MyTaskConfig: action_noise_model: GaussianNoiseCfg = GaussianNoiseCfg(mean=0.0, std=0.05, operation="add") In this tutorial, we learnt how to create a direct workflow task environment for reinforcement learning. We do this by extending the base environment to include the scene setup, actions, dones, reset, reward and observaion functions. While it is possible to manually create an instance of :class:`~omni.isaac.lab.envs.DirectRLEnv` class for a desired task, this is not scalable as it requires specialized scripts for each task. Thus, we exploit the :meth:`gymnasium.make` function to create the environment with the gym interface. We will learn how to do this in the next tutorial.
14,115
reStructuredText
41.137313
129
0.71045
isaac-sim/IsaacLab/docs/source/tutorials/03_envs/register_rl_env_gym.rst
Registering an Environment ========================== .. currentmodule:: omni.isaac.lab In the previous tutorial, we learned how to create a custom cartpole environment. We manually created an instance of the environment by importing the environment class and its configuration class. .. dropdown:: Environment creation in the previous tutorial :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/03_envs/run_cartpole_rl_env.py :language: python :start-at: # create environment configuration :end-at: env = ManagerBasedRLEnv(cfg=env_cfg) While straightforward, this approach is not scalable as we have a large suite of environments. In this tutorial, we will show how to use the :meth:`gymnasium.register` method to register environments with the ``gymnasium`` registry. This allows us to create the environment through the :meth:`gymnasium.make` function. .. dropdown:: Environment creation in this tutorial :icon: code .. literalinclude:: ../../../../source/standalone/environments/random_agent.py :language: python :lines: 36-47 The Code ~~~~~~~~ The tutorial corresponds to the ``random_agent.py`` script in the ``source/standalone/environments`` directory. .. dropdown:: Code for random_agent.py :icon: code .. literalinclude:: ../../../../source/standalone/environments/random_agent.py :language: python :emphasize-lines: 36-37, 42-47 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ The :class:`envs.ManagerBasedRLEnv` class inherits from the :class:`gymnasium.Env` class to follow a standard interface. However, unlike the traditional Gym environments, the :class:`envs.ManagerBasedRLEnv` implements a *vectorized* environment. This means that multiple environment instances are running simultaneously in the same process, and all the data is returned in a batched fashion. Similarly, the :class:`envs.DirectRLEnv` class also inherits from the :class:`gymnasium.Env` class for the direct workflow. Using the gym registry ---------------------- To register an environment, we use the :meth:`gymnasium.register` method. This method takes in the environment name, the entry point to the environment class, and the entry point to the environment configuration class. .. note:: The ``gymnasium`` registry is a global registry. Hence, it is important to ensure that the environment names are unique. Otherwise, the registry will throw an error when registering the environment. Manager-Based Environments ^^^^^^^^^^^^^^^^^^^^^^^^^^ For manager-based environments, the following shows the registration call for the cartpole environment in the ``omni.isaac.lab_tasks.manager_based.classic.cartpole`` sub-package: .. literalinclude:: ../../../../source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/__init__.py :language: python :lines: 10- :emphasize-lines: 11, 12, 15 The ``id`` argument is the name of the environment. As a convention, we name all the environments with the prefix ``Isaac-`` to make it easier to search for them in the registry. The name of the environment is typically followed by the name of the task, and then the name of the robot. For instance, for legged locomotion with ANYmal C on flat terrain, the environment is called ``Isaac-Velocity-Flat-Anymal-C-v0``. The version number ``v<N>`` is typically used to specify different variations of the same environment. Otherwise, the names of the environments can become too long and difficult to read. The ``entry_point`` argument is the entry point to the environment class. The entry point is a string of the form ``<module>:<class>``. In the case of the cartpole environment, the entry point is ``omni.isaac.lab.envs:ManagerBasedRLEnv``. The entry point is used to import the environment class when creating the environment instance. The ``env_cfg_entry_point`` argument specifies the default configuration for the environment. The default configuration is loaded using the :meth:`omni.isaac.lab_tasks.utils.parse_env_cfg` function. It is then passed to the :meth:`gymnasium.make` function to create the environment instance. The configuration entry point can be both a YAML file or a python configuration class. Direct Environemtns ^^^^^^^^^^^^^^^^^^^ For direct-based environments, the following shows the registration call for the cartpole environment in the ``omni.isaac.lab_tasks.direct.cartpole`` sub-package: .. code-block:: python import gymnasium as gym from . import agents from .cartpole_env import CartpoleEnv, CartpoleEnvCfg ## # Register Gym environments. ## gym.register( id="Isaac-Cartpole-Direct-v0", entry_point="omni.isaac.lab_tasks.direct.cartpole:CartpoleEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": CartpoleEnvCfg, "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.CartpolePPORunnerCfg, "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", }, ) The ``id`` argument is the name of the environment. As a convention, we name all the environments with the prefix ``Isaac-`` to make it easier to search for them in the registry. For direct environments, we also add the suffix ``-Direct``. The name of the environment is typically followed by the name of the task, and then the name of the robot. For instance, for legged locomotion with ANYmal C on flat terrain, the environment is called ``Isaac-Velocity-Flat-Anymal-C-Direct-v0``. The version number ``v<N>`` is typically used to specify different variations of the same environment. Otherwise, the names of the environments can become too long and difficult to read. The ``entry_point`` argument is the entry point to the environment class. The entry point is a string of the form ``<module>:<class>``. In the case of the cartpole environment, the entry point is ``omni.isaac.lab_tasks.direct.cartpole:CartpoleEnv``. The entry point is used to import the environment class when creating the environment instance. The ``env_cfg_entry_point`` argument specifies the default configuration for the environment. The default configuration is loaded using the :meth:`omni.isaac.lab_tasks.utils.parse_env_cfg` function. It is then passed to the :meth:`gymnasium.make` function to create the environment instance. The configuration entry point can be both a YAML file or a python configuration class. Creating the environment ------------------------ To inform the ``gym`` registry with all the environments provided by the ``omni.isaac.lab_tasks`` extension, we must import the module at the start of the script. This will execute the ``__init__.py`` file which iterates over all the sub-packages and registers their respective environments. .. literalinclude:: ../../../../source/standalone/environments/random_agent.py :language: python :start-at: import omni.isaac.lab_tasks # noqa: F401 :end-at: import omni.isaac.lab_tasks # noqa: F401 In this tutorial, the task name is read from the command line. The task name is used to parse the default configuration as well as to create the environment instance. In addition, other parsed command line arguments such as the number of environments, the simulation device, and whether to render, are used to override the default configuration. .. literalinclude:: ../../../../source/standalone/environments/random_agent.py :language: python :start-at: # create environment configuration :end-at: env = gym.make(args_cli.task, cfg=env_cfg) Once creating the environment, the rest of the execution follows the standard resetting and stepping. The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./isaaclab.sh -p source/standalone/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32 This should open a stage with everything similar to the previous :ref:`tutorial-create-rl-env` tutorial. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. In addition, you can also change the simulation device from GPU to CPU by adding the ``--cpu`` flag: .. code-block:: bash ./isaaclab.sh -p source/standalone/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32 --cpu With the ``--cpu`` flag, the simulation will run on the CPU. This is useful for debugging the simulation. However, the simulation will run much slower than on the GPU.
8,643
reStructuredText
43.328205
134
0.738517
isaac-sim/IsaacLab/docs/source/tutorials/03_envs/index.rst
Designing an Environment ======================== The following tutorials introduce the concept of manager-based environments: :class:`~omni.isaac.lab.envs.ManagerBasedEnv` and its derivative :class:`~omni.isaac.lab.envs.ManagerBasedRLEnv`, as well as the direct workflow base class :class:`~omni.isaac.lab.envs.DirectRLEnv`. These environments bring-in together different aspects of the framework to create a simulation environment for agent interaction. .. toctree:: :maxdepth: 1 :titlesonly: create_base_env create_rl_env create_direct_rl_env register_rl_env_gym run_rl_training
613
reStructuredText
33.111109
122
0.735726
isaac-sim/IsaacLab/docs/source/tutorials/05_controllers/run_diff_ik.rst
Using a task-space controller ============================= .. currentmodule:: omni.isaac.lab In the previous tutorials, we have joint-space controllers to control the robot. However, in many cases, it is more intuitive to control the robot using a task-space controller. For example, if we want to teleoperate the robot, it is easier to specify the desired end-effector pose rather than the desired joint positions. In this tutorial, we will learn how to use a task-space controller to control the robot. We will use the :class:`controllers.DifferentialIKController` class to track a desired end-effector pose command. The Code ~~~~~~~~ The tutorial corresponds to the ``run_diff_ik.py`` script in the ``source/standalone/tutorials/05_controllers`` directory. .. dropdown:: Code for run_diff_ik.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :emphasize-lines: 98-100, 121-136, 155-157, 161-171 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ While using any task-space controller, it is important to ensure that the provided quantities are in the correct frames. When parallelizing environment instances, they are all existing in the same unique simulation world frame. However, typically, we want each environment itself to have its own local frame. This is accessible through the :attr:`scene.InteractiveScene.env_origins` attribute. In our APIs, we use the following notation for frames: - The simulation world frame (denoted as ``w``), which is the frame of the entire simulation. - The local environment frame (denoted as ``e``), which is the frame of the local environment. - The robot's base frame (denoted as ``b``), which is the frame of the robot's base link. Since the asset instances are not "aware" of the local environment frame, they return their states in the simulation world frame. Thus, we need to convert the obtained quantities to the local environment frame. This is done by subtracting the local environment origin from the obtained quantities. Creating an IK controller ------------------------- The :class:`~controllers.DifferentialIKController` class computes the desired joint positions for a robot to reach a desired end-effector pose. The included implementation performs the computation in a batched format and uses PyTorch operations. It supports different types of inverse kinematics solvers, including the damped least-squares method and the pseudo-inverse method. These solvers can be specified using the :attr:`~controllers.DifferentialIKControllerCfg.ik_method` argument. Additionally, the controller can handle commands as both relative and absolute poses. In this tutorial, we will use the damped least-squares method to compute the desired joint positions. Additionally, since we want to track desired end-effector poses, we will use the absolute pose command mode. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # Create controller :end-at: diff_ik_controller = DifferentialIKController(diff_ik_cfg, num_envs=scene.num_envs, device=sim.device) Obtaining the robot's joint and body indices -------------------------------------------- The IK controller implementation is a computation-only class. Thus, it expects the user to provide the necessary information about the robot. This includes the robot's joint positions, current end-effector pose, and the Jacobian matrix. While the attribute :attr:`assets.ArticulationData.joint_pos` provides the joint positions, we only want the joint positions of the robot's arm, and not the gripper. Similarly, while the attribute :attr:`assets.ArticulationData.body_state_w` provides the state of all the robot's bodies, we only want the state of the robot's end-effector. Thus, we need to index into these arrays to obtain the desired quantities. For this, the articulation class provides the methods :meth:`~assets.Articulation.find_joints` and :meth:`~assets.Articulation.find_bodies`. These methods take in the names of the joints and bodies and return their corresponding indices. While you may directly use these methods to obtain the indices, we recommend using the :attr:`~managers.SceneEntityCfg` class to resolve the indices. This class is used in various places in the APIs to extract certain information from a scene entity. Internally, it calls the above methods to obtain the indices. However, it also performs some additional checks to ensure that the provided names are valid. Thus, it is a safer option to use this class. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # Specify robot-specific parameters :end-before: # Define simulation stepping Computing robot command ----------------------- The IK controller separates the operation of setting the desired command and computing the desired joint positions. This is done to allow for the user to run the IK controller at a different frequency than the robot's control frequency. The :meth:`~controllers.DifferentialIKController.set_command` method takes in the desired end-effector pose as a single batched array. The pose is specified in the robot's base frame. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # reset controller :end-at: diff_ik_controller.set_command(ik_commands) We can then compute the desired joint positions using the :meth:`~controllers.DifferentialIKController.compute` method. The method takes in the current end-effector pose (in base frame), Jacobian, and current joint positions. We read the Jacobian matrix from the robot's data, which uses its value computed from the physics engine. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # obtain quantities from simulation :end-at: joint_pos_des = diff_ik_controller.compute(ee_pos_b, ee_quat_b, jacobian, joint_pos) The computed joint position targets can then be applied on the robot, as done in the previous tutorials. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # apply actions :end-at: scene.write_data_to_sim() The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/05_controllers/run_diff_ik.py --robot franka_panda --num_envs 128 The script will start a simulation with 128 robots. The robots will be controlled using the IK controller. The current and desired end-effector poses should be displayed using frame markers. When the robot reaches the desired pose, the command should cycle through to the next pose specified in the script. To stop the simulation, you can either close the window, or press the ``STOP`` button in the UI, or press ``Ctrl+C`` in the terminal.
7,086
reStructuredText
44.72258
114
0.758256
isaac-sim/IsaacLab/docs/source/tutorials/05_controllers/index.rst
Using Motion Generators ======================= While the robots in the simulation environment can be controlled at the joint-level, the following tutorials show you how to use motion generators to control the robots at the task-level. .. toctree:: :maxdepth: 1 :titlesonly: run_diff_ik
302
reStructuredText
24.249998
98
0.695364
isaac-sim/IsaacLab/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst
.. _tutorial-add-sensors-on-robot: Adding sensors on a robot ========================= .. currentmodule:: omni.isaac.lab While the asset classes allow us to create and simulate the physical embodiment of the robot, sensors help in obtaining information about the environment. They typically update at a lower frequency than the simulation and are useful for obtaining different proprioceptive and exteroceptive information. For example, a camera sensor can be used to obtain the visual information of the environment, and a contact sensor can be used to obtain the contact information of the robot with the environment. In this tutorial, we will see how to add different sensors to a robot. We will use the ANYmal-C robot for this tutorial. The ANYmal-C robot is a quadrupedal robot with 12 degrees of freedom. It has 4 legs, each with 3 degrees of freedom. The robot has the following sensors: - A camera sensor on the head of the robot which provides RGB-D images - A height scanner sensor that provides terrain height information - Contact sensors on the feet of the robot that provide contact information We continue this tutorial from the previous tutorial on :ref:`tutorial-interactive-scene`, where we learned about the :class:`scene.InteractiveScene` class. The Code ~~~~~~~~ The tutorial corresponds to the ``add_sensors_on_robot.py`` script in the ``source/standalone/tutorials/04_sensors`` directory. .. dropdown:: Code for add_sensors_on_robot.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :emphasize-lines: 72-95, 143-153, 167-168 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Similar to the previous tutorials, where we added assets to the scene, the sensors are also added to the scene using the scene configuration. All sensors inherit from the :class:`sensors.SensorBase` class and are configured through their respective config classes. Each sensor instance can define its own update period, which is the frequency at which the sensor is updated. The update period is specified in seconds through the :attr:`sensors.SensorBaseCfg.update_period` attribute. Depending on the specified path and the sensor type, the sensors are attached to the prims in the scene. They may have an associated prim that is created in the scene or they may be attached to an existing prim. For instance, the camera sensor has a corresponding prim that is created in the scene, whereas for the contact sensor, the activating the contact reporting is a property on a rigid body prim. In the following, we introduce the different sensors we use in this tutorial and how they are configured. For more description about them, please check the :mod:`sensors` module. Camera sensor ------------- A camera is defined using the :class:`sensors.CameraCfg`. It is based on the USD Camera sensor and the different data types are captured using Omniverse Replicator API. Since it has a corresponding prim in the scene, the prims are created in the scene at the specified prim path. The configuration of the camera sensor includes the following parameters: * :attr:`~sensors.CameraCfg.spawn`: The type of USD camera to create. This can be either :class:`~sim.spawners.sensors.PinholeCameraCfg` or :class:`~sim.spawners.sensors.FisheyeCameraCfg`. * :attr:`~sensors.CameraCfg.offset`: The offset of the camera sensor from the parent prim. * :attr:`~sensors.CameraCfg.data_types`: The data types to capture. This can be ``rgb``, ``distance_to_image_plane``, ``normals``, or other types supported by the USD Camera sensor. To attach an RGB-D camera sensor to the head of the robot, we specify an offset relative to the base frame of the robot. The offset is specified as a translation and rotation relative to the base frame, and the :attr:`~sensors.CameraCfg.OffsetCfg.convention` in which the offset is specified. In the following, we show the configuration of the camera sensor used in this tutorial. We set the update period to 0.1s, which means that the camera sensor is updated at 10Hz. The prim path expression is set to ``{ENV_REGEX_NS}/Robot/base/front_cam`` where the ``{ENV_REGEX_NS}`` is the environment namespace, ``"Robot"`` is the name of the robot, ``"base"`` is the name of the prim to which the camera is attached, and ``"front_cam"`` is the name of the prim associated with the camera sensor. .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: camera = CameraCfg( :end-before: height_scanner = RayCasterCfg( Height scanner -------------- The height-scanner is implemented as a virtual sensor using the NVIDIA Warp ray-casting kernels. Through the :class:`sensors.RayCasterCfg`, we can specify the pattern of rays to cast and the meshes against which to cast the rays. Since they are virtual sensors, there is no corresponding prim created in the scene for them. Instead they are attached to a prim in the scene, which is used to specify the location of the sensor. For this tutorial, the ray-cast based height scanner is attached to the base frame of the robot. The pattern of rays is specified using the :attr:`~sensors.RayCasterCfg.pattern` attribute. For a uniform grid pattern, we specify the pattern using :class:`~sensors.patterns.GridPatternCfg`. Since we only care about the height information, we do not need to consider the roll and pitch of the robot. Hence, we set the :attr:`~sensors.RayCasterCfg.attach_yaw_only` to true. For the height-scanner, you can visualize the points where the rays hit the mesh. This is done by setting the :attr:`~sensors.SensorBaseCfg.debug_vis` attribute to true. The entire configuration of the height-scanner is as follows: .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: height_scanner = RayCasterCfg( :end-before: contact_forces = ContactSensorCfg( Contact sensor -------------- Contact sensors wrap around the PhysX contact reporting API to obtain the contact information of the robot with the environment. Since it relies of PhysX, the contact sensor expects the contact reporting API to be enabled on the rigid bodies of the robot. This can be done by setting the :attr:`~sim.spawners.RigidObjectSpawnerCfg.activate_contact_sensors` to true in the asset configuration. Through the :class:`sensors.ContactSensorCfg`, it is possible to specify the prims for which we want to obtain the contact information. Additional flags can be set to obtain more information about the contact, such as the contact air time, contact forces between filtered prims, etc. In this tutorial, we attach the contact sensor to the feet of the robot. The feet of the robot are named ``"LF_FOOT"``, ``"RF_FOOT"``, ``"LH_FOOT"``, and ``"RF_FOOT"``. We pass a Regex expression ``".*_FOOT"`` to simplify the prim path specification. This Regex expression matches all prims that end with ``"_FOOT"``. We set the update period to 0 to update the sensor at the same frequency as the simulation. Additionally, for contact sensors, we can specify the history length of the contact information to store. For this tutorial, we set the history length to 6, which means that the contact information for the last 6 simulation steps is stored. The entire configuration of the contact sensor is as follows: .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: contact_forces = ContactSensorCfg( :lines: 1-3 Running the simulation loop --------------------------- Similar to when using assets, the buffers and physics handles for the sensors are initialized only when the simulation is played, i.e., it is important to call ``sim.reset()`` after creating the scene. .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: # Play the simulator :end-at: sim.reset() Besides that, the simulation loop is similar to the previous tutorials. The sensors are updated as part of the scene update and they internally handle the updating of their buffers based on their update periods. The data from the sensors can be accessed through their ``data`` attribute. As an example, we show how to access the data for the different sensors created in this tutorial: .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: # print information from the sensors :end-at: print("Received max contact force of: ", torch.max(scene["contact_forces"].data.net_forces_w).item()) The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/04_sensors/add_sensors_on_robot.py --num_envs 2 This command should open a stage with a ground plane, lights, and two quadrupedal robots. Around the robots, you should see red spheres that indicate the points where the rays hit the mesh. Additionally, you can switch the viewport to the camera view to see the RGB image captured by the camera sensor. Please check `here <https://youtu.be/htPbcKkNMPs?feature=shared>`_ for more information on how to switch the viewport to the camera view. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. While in this tutorial, we went over creating and using different sensors, there are many more sensors available in the :mod:`sensors` module. We include minimal examples of using these sensors in the ``source/standalone/tutorials/04_sensors`` directory. For completeness, these scripts can be run using the following commands: .. code-block:: bash # Frame Transformer ./isaaclab.sh -p source/standalone/tutorials/04_sensors/run_frame_transformer.py # Ray Caster ./isaaclab.sh -p source/standalone/tutorials/04_sensors/run_ray_caster.py # Ray Caster Camera ./isaaclab.sh -p source/standalone/tutorials/04_sensors/run_ray_caster_camera.py # USD Camera ./isaaclab.sh -p source/standalone/tutorials/04_sensors/run_usd_camera.py
10,248
reStructuredText
48.995122
113
0.759563
isaac-sim/IsaacLab/docs/source/tutorials/04_sensors/index.rst
Integrating Sensors =================== The following tutorial shows you how to integrate sensors into the simulation environment. The tutorials introduce the :class:`~omni.isaac.lab.sensors.SensorBase` class and its derivatives such as :class:`~omni.isaac.lab.sensors.Camera` and :class:`~omni.isaac.lab.sensors.RayCaster`. .. toctree:: :maxdepth: 1 :titlesonly: add_sensors_on_robot
400
reStructuredText
29.846152
95
0.725
isaac-sim/IsaacLab/docs/source/tutorials/00_sim/spawn_prims.rst
.. _tutorial-spawn-prims: Spawning prims into the scene ============================= .. currentmodule:: omni.isaac.lab This tutorial explores how to spawn various objects (or prims) into the scene in Isaac Lab from Python. It builds upon the previous tutorial on running the simulator from a standalone script and demonstrates how to spawn a ground plane, lights, primitive shapes, and meshes from USD files. The Code ~~~~~~~~ The tutorial corresponds to the ``spawn_prims.py`` script in the ``source/standalone/tutorials/00_sim`` directory. Let's take a look at the Python script: .. dropdown:: Code for spawn_prims.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :emphasize-lines: 40-79, 91-92 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Scene designing in Omniverse is built around a software system and file format called USD (Universal Scene Description). It allows describing 3D scenes in a hierarchical manner, similar to a file system. Since USD is a comprehensive framework, we recommend reading the `USD documentation`_ to learn more about it. For completeness, we introduce the must know concepts of USD in this tutorial. * **Primitives (Prims)**: These are the basic building blocks of a USD scene. They can be thought of as nodes in a scene graph. Each node can be a mesh, a light, a camera, or a transform. It can also be a group of other prims under it. * **Attributes**: These are the properties of a prim. They can be thought of as key-value pairs. For example, a prim can have an attribute called ``color`` with a value of ``red``. * **Relationships**: These are the connections between prims. They can be thought of as pointers to other prims. For example, a mesh prim can have a relationship to a material prim for shading. A collection of these prims, with their attributes and relationships, is called a **USD stage**. It can be thought of as a container for all prims in a scene. When we say we are designing a scene, we are actually designing a USD stage. While working with direct USD APIs provides a lot of flexibility, it can be cumbersome to learn and use. To make it easier to design scenes, Isaac Lab builds on top of the USD APIs to provide a configuration-driven interface to spawn prims into a scene. These are included in the :mod:`sim.spawners` module. When spawning prims into the scene, each prim requires a configuration class instance that defines the prim's attributes and relationships (through material and shading information). The configuration class is then passed to its respective function where the prim name and transformation are specified. The function then spawns the prim into the scene. At a high-level, this is how it works: .. code-block:: python # Create a configuration class instance cfg = MyPrimCfg() prim_path = "/path/to/prim" # Spawn the prim into the scene using the corresponding spawner function spawn_my_prim(prim_path, cfg, translation=[0, 0, 0], orientation=[1, 0, 0, 0], scale=[1, 1, 1]) # OR # Use the spawner function directly from the configuration class cfg.func(prim_path, cfg, translation=[0, 0, 0], orientation=[1, 0, 0, 0], scale=[1, 1, 1]) In this tutorial, we demonstrate the spawning of various different prims into the scene. For more information on the available spawners, please refer to the :mod:`sim.spawners` module in Isaac Lab. .. attention:: All the scene designing must happen before the simulation starts. Once the simulation starts, we recommend keeping the scene frozen and only altering the properties of the prim. This is particularly important for GPU simulation as adding new prims during simulation may alter the physics simulation buffers on GPU and lead to unexpected behaviors. Spawning a ground plane ----------------------- The :class:`~sim.spawners.from_files.GroundPlaneCfg` configures a grid-like ground plane with modifiable properties such as its appearance and size. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # Ground-plane :end-at: cfg_ground.func("/World/defaultGroundPlane", cfg_ground) Spawning lights --------------- It is possible to spawn `different light prims`_ into the stage. These include distant lights, sphere lights, disk lights, and cylinder lights. In this tutorial, we spawn a distant light which is a light that is infinitely far away from the scene and shines in a single direction. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn distant light :end-at: cfg_light_distant.func("/World/lightDistant", cfg_light_distant, translation=(1, 0, 10)) Spawning primitive shapes ------------------------- Before spawning primitive shapes, we introduce the concept of a transform prim or Xform. A transform prim is a prim that contains only transformation properties. It is used to group other prims under it and to transform them as a group. Here we make an Xform prim to group all the primitive shapes under it. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # create a new xform prim for all objects to be spawned under :end-at: prim_utils.create_prim("/World/Objects", "Xform") Next, we spawn a cone using the :class:`~sim.spawners.shapes.ConeCfg` class. It is possible to specify the radius, height, physics properties, and material properties of the cone. By default, the physics and material properties are disabled. The first two cones we spawn ``Cone1`` and ``Cone2`` are visual elements and do not have physics enabled. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn a red cone :end-at: cfg_cone.func("/World/Objects/Cone2", cfg_cone, translation=(-1.0, -1.0, 1.0)) For the third cone ``ConeRigid``, we add rigid body physics to it by setting the attributes for that in the configuration class. Through these attributes, we can specify the mass, friction, and restitution of the cone. If unspecified, they default to the default values set by USD Physics. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn a green cone with colliders and rigid body :end-before: # spawn a usd file of a table into the scene Spawning from another file -------------------------- Lastly, it is possible to spawn prims from other file formats such as other USD, URDF, or OBJ files. In this tutorial, we spawn a USD file of a table into the scene. The table is a mesh prim and has a material prim associated with it. All of this information is stored in its USD file. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn a usd file of a table into the scene :end-at: cfg.func("/World/Objects/Table", cfg, translation=(0.0, 0.0, 1.05)) The table above is added as a reference to the scene. In layman terms, this means that the table is not actually added to the scene, but a ``pointer`` to the table asset is added. This allows us to modify the table asset and have the changes reflected in the scene in a non-destructive manner. For example, we can change the material of the table without actually modifying the underlying file for the table asset directly. Only the changes are stored in the USD stage. Executing the Script ~~~~~~~~~~~~~~~~~~~~ Similar to the tutorial before, to run the script, execute the following command: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/00_sim/spawn_prims.py Once the simulation starts, you should see a window with a ground plane, a light, some cones, and a table. The green cone, which has rigid body physics enabled, should fall and collide with the table and the ground plane. The other cones are visual elements and should not move. To stop the simulation, you can close the window, or press ``Ctrl+C`` in the terminal. This tutorial provided a foundation for spawning various prims into the scene in Isaac Lab. Although simple, it demonstrates the basic concepts of scene designing in Isaac Lab and how to use the spawners. In the coming tutorials, we will now look at how to interact with the scene and the simulation. .. _`USD documentation`: https://graphics.pixar.com/usd/docs/index.html .. _`different light prims`: https://youtu.be/c7qyI8pZvF4?feature=shared
8,598
reStructuredText
47.039106
123
0.739009
isaac-sim/IsaacLab/docs/source/tutorials/00_sim/launch_app.rst
Deep-dive into AppLauncher ========================== .. currentmodule:: omni.isaac.lab In this tutorial, we will dive into the :class:`app.AppLauncher` class to configure the simulator using CLI arguments and environment variables (envars). Particularly, we will demonstrate how to use :class:`~app.AppLauncher` to enable livestreaming and configure the :class:`omni.isaac.kit.SimulationApp` instance it wraps, while also allowing user-provided options. The :class:`~app.AppLauncher` is a wrapper for :class:`~omni.isaac.kit.SimulationApp` to simplify its configuration. The :class:`~omni.isaac.kit.SimulationApp` has many extensions that must be loaded to enable different capabilities, and some of these extensions are order- and inter-dependent. Additionally, there are startup options such as ``headless`` which must be set at instantiation time, and which have an implied relationship with some extensions, e.g. the livestreaming extensions. The :class:`~app.AppLauncher` presents an interface that can handle these extensions and startup options in a portable manner across a variety of use cases. To achieve this, we offer CLI and envar flags which can be merged with user-defined CLI args, while passing forward arguments intended for :class:`~omni.isaac.kit.SimulationApp`. The Code -------- The tutorial corresponds to the ``launch_app.py`` script in the ``source/standalone/tutorials/00_sim`` directory. .. dropdown:: Code for launch_app.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/launch_app.py :language: python :emphasize-lines: 18-40 :linenos: The Code Explained ------------------ Adding arguments to the argparser ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :class:`~app.AppLauncher` is designed to be compatible with custom CLI args that users need for their own scripts, while still providing a portable CLI interface. In this tutorial, a standard :class:`argparse.ArgumentParser` is instantiated and given the script-specific ``--size`` argument, as well as the arguments ``--height`` and ``--width``. The latter are ingested by :class:`~omni.isaac.kit.SimulationApp`. The argument ``--size`` is not used by :class:`~app.AppLauncher`, but will merge seamlessly with the :class:`~app.AppLauncher` interface. In-script arguments can be merged with the :class:`~app.AppLauncher` interface via the :meth:`~app.AppLauncher.add_app_launcher_args` method, which will return a modified :class:`~argparse.ArgumentParser` with the :class:`~app.AppLauncher` arguments appended. This can then be processed into an :class:`argparse.Namespace` using the standard :meth:`argparse.ArgumentParser.parse_args` method and passed directly to :class:`~app.AppLauncher` for instantiation. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/launch_app.py :language: python :start-at: import argparse :end-at: simulation_app = app_launcher.app The above only illustrates only one of several ways of passing arguments to :class:`~app.AppLauncher`. Please consult its documentation page to see further options. Understanding the output of --help ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ While executing the script, we can pass the ``--help`` argument and see the combined outputs of the custom arguments and those from :class:`~app.AppLauncher`. .. code-block:: console ./isaaclab.sh -p source/standalone/tutorials/00_sim/launch_app.py --help [INFO] Using python from: /isaac-sim/python.sh [INFO][AppLauncher]: The argument 'width' will be used to configure the SimulationApp. [INFO][AppLauncher]: The argument 'height' will be used to configure the SimulationApp. usage: launch_app.py [-h] [--size SIZE] [--width WIDTH] [--height HEIGHT] [--headless] [--livestream {0,1,2}] [--enable_cameras] [--verbose] [--experience EXPERIENCE] Tutorial on running IsaacSim via the AppLauncher. options: -h, --help show this help message and exit --size SIZE Side-length of cuboid --width WIDTH Width of the viewport and generated images. Defaults to 1280 --height HEIGHT Height of the viewport and generated images. Defaults to 720 app_launcher arguments: --headless Force display off at all times. --livestream {0,1,2} Force enable livestreaming. Mapping corresponds to that for the "LIVESTREAM" environment variable. --enable_cameras Enable cameras when running without a GUI. --verbose Enable verbose terminal logging from the SimulationApp. --experience EXPERIENCE The experience file to load when launching the SimulationApp. * If an empty string is provided, the experience file is determined based on the headless flag. * If a relative path is provided, it is resolved relative to the `apps` folder in Isaac Sim and Isaac Lab (in that order). This readout details the ``--size``, ``--height``, and ``--width`` arguments defined in the script directly, as well as the :class:`~app.AppLauncher` arguments. The ``[INFO]`` messages preceding the help output also reads out which of these arguments are going to be interpreted as arguments to the :class:`~omni.isaac.kit.SimulationApp` instance which the :class:`~app.AppLauncher` class wraps. In this case, it is ``--height`` and ``--width``. These are classified as such because they match the name and type of an argument which can be processed by :class:`~omni.isaac.kit.SimulationApp`. Please refer to the `specification`_ for such arguments for more examples. Using environment variables ^^^^^^^^^^^^^^^^^^^^^^^^^^^ As noted in the help message, the :class:`~app.AppLauncher` arguments (``--livestream``, ``--headless``) have corresponding environment variables (envar) as well. These are detailed in :mod:`omni.isaac.lab.app` documentation. Providing any of these arguments through CLI is equivalent to running the script in a shell environment where the corresponding envar is set. The support for :class:`~app.AppLauncher` envars are simply a convenience to provide session-persistent configurations, and can be set in the user's ``${HOME}/.bashrc`` for persistent settings between sessions. In the case where these arguments are provided from the CLI, they will override their corresponding envar, as we will demonstrate later in this tutorial. These arguments can be used with any script that starts the simulation using :class:`~app.AppLauncher`, with one exception, ``--enable_cameras``. This setting sets the rendering pipeline to use the offscreen renderer. However, this setting is only compatible with the :class:`omni.isaac.lab.sim.SimulationContext`. It will not work with Isaac Sim's :class:`omni.isaac.core.simulation_context.SimulationContext` class. For more information on this flag, please see the :class:`~app.AppLauncher` API documentation. The Code Execution ------------------ We will now run the example script: .. code-block:: console LIVESTREAM=1 ./isaaclab.sh -p source/standalone/tutorials/00_sim/launch_app.py --size 0.5 This will spawn a 0.5m\ :sup:`3` volume cuboid in the simulation. No GUI will appear, equivalent to if we had passed the ``--headless`` flag because headlessness is implied by our ``LIVESTREAM`` envar. If a visualization is desired, we could get one via Isaac's `Native Livestreaming`_. Streaming is currently the only supported method of visualization from within the container. The process can be killed by pressing ``Ctrl+C`` in the launching terminal. Now, let's look at how :class:`~app.AppLauncher` handles conflicting commands: .. code-block:: console export LIVESTREAM=0 ./isaaclab.sh -p source/standalone/tutorials/00_sim/launch_app.py --size 0.5 --livestream 1 This will cause the same behavior as in the previous run, because although we have set ``LIVESTREAM=0`` in our envars, CLI args such as ``--livestream`` take precedence in determining behavior. The process can be killed by pressing ``Ctrl+C`` in the launching terminal. Finally, we will examine passing arguments to :class:`~omni.isaac.kit.SimulationApp` through :class:`~app.AppLauncher`: .. code-block:: console export LIVESTREAM=1 ./isaaclab.sh -p source/standalone/tutorials/00_sim/launch_app.py --size 0.5 --width 1920 --height 1080 This will cause the same behavior as before, but now the viewport will be rendered at 1920x1080p resolution. This can be useful when we want to gather high-resolution video, or we can specify a lower resolution if we want our simulation to be more performant. The process can be killed by pressing ``Ctrl+C`` in the launching terminal. .. _specification: https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.kit/docs/index.html#omni.isaac.kit.SimulationApp.DEFAULT_LAUNCHER_CONFIG .. _Native Livestreaming: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/manual_livestream_clients.html#omniverse-streaming-client
9,049
reStructuredText
50.714285
166
0.734004
isaac-sim/IsaacLab/docs/source/tutorials/00_sim/create_empty.rst
Creating an empty scene ======================= .. currentmodule:: omni.isaac.lab This tutorial shows how to launch and control Isaac Sim simulator from a standalone Python script. It sets up an empty scene in Isaac Lab and introduces the two main classes used in the framework, :class:`app.AppLauncher` and :class:`sim.SimulationContext`. Please review `Isaac Sim Interface`_ and `Isaac Sim Workflows`_ prior to beginning this tutorial to get an initial understanding of working with the simulator. The Code ~~~~~~~~ The tutorial corresponds to the ``create_empty.py`` script in the ``source/standalone/tutorials/00_sim`` directory. .. dropdown:: Code for create_empty.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :emphasize-lines: 18-30,34,40-44,46-47,51-54,60-61 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Launching the simulator ----------------------- The first step when working with standalone Python scripts is to launch the simulation application. This is necessary to do at the start since various dependency modules of Isaac Sim are only available after the simulation app is running. This can be done by importing the :class:`app.AppLauncher` class. This utility class wraps around :class:`omni.isaac.kit.SimulationApp` class to launch the simulator. It provides mechanisms to configure the simulator using command-line arguments and environment variables. For this tutorial, we mainly look at adding the command-line options to a user-defined :class:`argparse.ArgumentParser`. This is done by passing the parser instance to the :meth:`app.AppLauncher.add_app_launcher_args` method, which appends different parameters to it. These include launching the app headless, configuring different Livestream options, and enabling off-screen rendering. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: import argparse :end-at: simulation_app = app_launcher.app Importing python modules ------------------------ Once the simulation app is running, it is possible to import different Python modules from Isaac Sim and other libraries. Here we import the following module: * :mod:`omni.isaac.lab.sim`: A sub-package in Isaac Lab for all the core simulator-related operations. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: from omni.isaac.lab.sim import SimulationCfg, SimulationContext :end-at: from omni.isaac.lab.sim import SimulationCfg, SimulationContext Configuring the simulation context ---------------------------------- When launching the simulator from a standalone script, the user has complete control over playing, pausing and stepping the simulator. All these operations are handled through the **simulation context**. It takes care of various timeline events and also configures the `physics scene`_ for simulation. In Isaac Lab, the :class:`sim.SimulationContext` class inherits from Isaac Sim's :class:`omni.isaac.core.simulation_context.SimulationContext` to allow configuring the simulation through Python's ``dataclass`` object and handle certain intricacies of the simulation stepping. For this tutorial, we set the physics and rendering time step to 0.01 seconds. This is done by passing these quantities to the :class:`sim.SimulationCfg`, which is then used to create an instance of the simulation context. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: # Initialize the simulation context :end-at: sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) Following the creation of the simulation context, we have only configured the physics acting on the simulated scene. This includes the device to use for simulation, the gravity vector, and other advanced solver parameters. There are now two main steps remaining to run the simulation: 1. Designing the simulation scene: Adding sensors, robots and other simulated objects 2. Running the simulation loop: Stepping the simulator, and setting and getting data from the simulator In this tutorial, we look at Step 2 first for an empty scene to focus on the simulation control first. In the following tutorials, we will look into Step 1 and working with simulation handles for interacting with the simulator. Running the simulation ---------------------- The first thing, after setting up the simulation scene, is to call the :meth:`sim.SimulationContext.reset` method. This method plays the timeline and initializes the physics handles in the simulator. It must always be called the first time before stepping the simulator. Otherwise, the simulation handles are not initialized properly. .. note:: :meth:`sim.SimulationContext.reset` is different from :meth:`sim.SimulationContext.play` method as the latter only plays the timeline and does not initializes the physics handles. After playing the simulation timeline, we set up a simple simulation loop where the simulator is stepped repeatedly while the simulation app is running. The method :meth:`sim.SimulationContext.step` takes in as argument :attr:`render`, which dictates whether the step includes updating the rendering-related events or not. By default, this flag is set to True. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: # Play the simulator :end-at: sim.step() Exiting the simulation ---------------------- Lastly, the simulation application is stopped and its window is closed by calling :meth:`omni.isaac.kit.SimulationApp.close` method. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: # close sim app :end-at: simulation_app.close() The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/00_sim/create_empty.py The simulation should be playing, and the stage should be rendering. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. Passing ``--help`` to the above script will show the different command-line arguments added earlier by the :class:`app.AppLauncher` class. To run the script headless, you can execute the following: .. code-block:: bash ./isaaclab.sh -p source/standalone/tutorials/00_sim/create_empty.py --headless Now that we have a basic understanding of how to run a simulation, let's move on to the following tutorial where we will learn how to add assets to the stage. .. _`Isaac Sim Interface`: https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_interface.html#isaac-sim-app-tutorial-intro-interface .. _`Isaac Sim Workflows`: https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html .. _carb: https://docs.omniverse.nvidia.com/kit/docs/carbonite/latest/index.html .. _`physics scene`: https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html#physics-scene
7,231
reStructuredText
43.097561
168
0.753976
isaac-sim/IsaacLab/docs/source/tutorials/00_sim/index.rst
Setting up a Simple Simulation ============================== These tutorials show you how to launch the simulation with different settings and spawn objects in the simulated scene. They cover the following APIs: :class:`~omni.isaac.lab.app.AppLauncher`, :class:`~omni.isaac.lab.sim.SimulationContext`, and :class:`~omni.isaac.lab.sim.spawners`. .. toctree:: :maxdepth: 1 :titlesonly: create_empty spawn_prims launch_app
444
reStructuredText
28.666665
102
0.689189
isaac-sim/IsaacLab/docs/source/setup/faq.rst
Frequently Asked Questions ========================== Where does Isaac Lab fit in the Isaac ecosystem? ------------------------------------------------ Over the years, NVIDIA has developed a number of tools for robotics and AI. These tools leverage the power of GPUs to accelerate the simulation both in terms of speed and realism. They show great promise in the field of simulation technology and are being used by many researchers and companies worldwide. `Isaac Gym`_ :cite:`makoviychuk2021isaac` provides a high performance GPU-based physics simulation for robot learning. It is built on top of `PhysX`_ which supports GPU-accelerated simulation of rigid bodies and a Python API to directly access physics simulation data. Through an end-to-end GPU pipeline, it is possible to achieve high frame rates compared to CPU-based physics engines. The tool has been used successfully in a number of research projects, including legged locomotion :cite:`rudin2022learning` :cite:`rudin2022advanced`, in-hand manipulation :cite:`handa2022dextreme` :cite:`allshire2022transferring`, and industrial assembly :cite:`narang2022factory`. Despite the success of Isaac Gym, it is not designed to be a general purpose simulator for robotics. For example, it does not include interaction between deformable and rigid objects, high-fidelity rendering, and support for ROS. The tool has been primarily designed as a preview release to showcase the capabilities of the underlying physics engine. With the release of `Isaac Sim`_, NVIDIA is building a general purpose simulator for robotics and has integrated the functionalities of Isaac Gym into Isaac Sim. `Isaac Sim`_ is a robot simulation toolkit built on top of Omniverse, which is a general purpose platform that aims to unite complex 3D workflows. Isaac Sim leverages the latest advances in graphics and physics simulation to provide a high-fidelity simulation environment for robotics. It supports ROS/ROS2, various sensor simulation, tools for domain randomization and synthetic data creation. Tiled rendering support in Isaac Sim allows for vectorized rendering across environments, along with support for running in the cloud using `Isaac Automator`_. Overall, it is a powerful tool for roboticists and is a huge step forward in the field of robotics simulation. With the release of above two tools, NVIDIA also released an open-sourced set of environments called `IsaacGymEnvs`_ and `OmniIsaacGymEnvs`_, that have been built on top of Isaac Gym and Isaac Sim respectively. These environments have been designed to display the capabilities of the underlying simulators and provide a starting point to understand what is possible with the simulators for robot learning. These environments can be used for benchmarking but are not designed for developing and testing custom environments and algorithms. This is where Isaac Lab comes in. Isaac Lab is built on top of Isaac Sim to provide a unified and flexible framework for robot learning that exploits latest simulation technologies. It is designed to be modular and extensible, and aims to simplify common workflows in robotics research (such as RL, learning from demonstrations, and motion planning). While it includes some pre-built environments, sensors, and tasks, its main goal is to provide an open-sourced, unified, and easy-to-use interface for developing and testing custom environments and robot learning algorithms. It not only inherits the capabilities of Isaac Sim, but also adds a number of new features that pertain to robot learning research. For example, including actuator dynamics in the simulation, procedural terrain generation, and support to collect data from human demonstrations. Isaac Lab replaces the previous `IsaacGymEnvs`_, `OmniIsaacGymEnvs`_ and `Orbit`_ frameworks and will be the single robot learning framework for Isaac Sim. Previously released frameworks are deprecated and we encourage users to follow our `migration guides`_ to transition over to Isaac Lab. Why should I use Isaac Lab? --------------------------- Since Isaac Sim remains closed-sourced, it is difficult for users to contribute to the simulator and build a common framework for research. On its current path, we see the community using the simulator will simply develop their own frameworks that will result in scattered efforts with a lot of duplication of work. This has happened in the past with other simulators, and we believe that it is not the best way to move forward as a community. Isaac Lab provides an open-sourced platform for the community to drive progress with consolidated efforts toward designing benchmarks and robot learning systems as a joint initiative. This allows us to reuse existing components and algorithms, and to build on top of each other's work. Doing so not only saves time and effort, but also allows us to focus on the more important aspects of research. Our hope with Isaac Lab is that it becomes the de-facto platform for robot learning research and an environment *zoo* that leverages Isaac Sim. As the framework matures, we foresee it benefitting hugely from the latest simulation developments (as part of internal developments at NVIDIA and collaborating partners) and research in robotics. We are already working with labs in universities and research institutions to integrate their work into Isaac Lab and hope that others in the community will join us too in this effort. If you are interested in contributing to Isaac Lab, please reach out to us. .. _PhysX: https://developer.nvidia.com/physx-sdk .. _Isaac Sim: https://developer.nvidia.com/isaac-sim .. _Isaac Gym: https://developer.nvidia.com/isaac-gym .. _IsaacGymEnvs: https://github.com/NVIDIA-Omniverse/IsaacGymEnvs .. _OmniIsaacGymEnvs: https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs .. _Orbit: https://isaac-orbit.github.io/orbit .. _Isaac Automator: https://github.com/isaac-sim/IsaacAutomator .. _migration guides: ../migration/index.html
5,964
reStructuredText
66.78409
113
0.796613
isaac-sim/IsaacLab/docs/source/setup/sample.rst
Running Existing Scripts ======================== Showroom -------- The main core interface extension in Isaac Lab ``omni.isaac.lab`` provides the main modules for actuators, objects, robots and sensors. We provide a list of demo scripts and tutorials. These showcase how to use the provided interfaces within a code in a minimal way. A few quick showroom scripts to run and checkout: - Spawn different quadrupeds and make robots stand using position commands: .. code:: bash ./isaaclab.sh -p source/standalone/demos/quadrupeds.py - Spawn different arms and apply random joint position commands: .. code:: bash ./isaaclab.sh -p source/standalone/demos/arms.py - Spawn different hands and command them to open and close: .. code:: bash ./isaaclab.sh -p source/standalone/demos/hands.py - Spawn procedurally generated terrains with different configurations: .. code:: bash ./isaaclab.sh -p source/standalone/demos/procedural_terrain.py - Spawn multiple markers that are useful for visualizations: .. code:: bash ./isaaclab.sh -p source/standalone/demos/markers.py Workflows --------- With Isaac Lab, we also provide a suite of benchmark environments included in the ``omni.isaac.lab_tasks`` extension. We use the OpenAI Gym registry to register these environments. For each environment, we provide a default configuration file that defines the scene, observations, rewards and action spaces. The list of environments available registered with OpenAI Gym can be found by running: .. code:: bash ./isaaclab.sh -p source/standalone/environments/list_envs.py Basic agents ~~~~~~~~~~~~ These include basic agents that output zero or random agents. They are useful to ensure that the environments are configured correctly. - Zero-action agent on the Cart-pole example .. code:: bash ./isaaclab.sh -p source/standalone/environments/zero_agent.py --task Isaac-Cartpole-v0 --num_envs 32 - Random-action agent on the Cart-pole example: .. code:: bash ./isaaclab.sh -p source/standalone/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32 State machine ~~~~~~~~~~~~~ We include examples on hand-crafted state machines for the environments. These help in understanding the environment and how to use the provided interfaces. The state machines are written in `warp <https://github.com/NVIDIA/warp>`__ which allows efficient execution for large number of environments using CUDA kernels. .. code:: bash ./isaaclab.sh -p source/standalone/environments/state_machine/lift_cube_sm.py --num_envs 32 Teleoperation ~~~~~~~~~~~~~ We provide interfaces for providing commands in SE(2) and SE(3) space for robot control. In case of SE(2) teleoperation, the returned command is the linear x-y velocity and yaw rate, while in SE(3), the returned command is a 6-D vector representing the change in pose. To play inverse kinematics (IK) control with a keyboard device: .. code:: bash ./isaaclab.sh -p source/standalone/environments/teleoperation/teleop_se3_agent.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --device keyboard The script prints the teleoperation events configured. For keyboard, these are as follows: .. code:: text Keyboard Controller for SE(3): Se3Keyboard Reset all commands: L Toggle gripper (open/close): K Move arm along x-axis: W/S Move arm along y-axis: A/D Move arm along z-axis: Q/E Rotate arm along x-axis: Z/X Rotate arm along y-axis: T/G Rotate arm along z-axis: C/V Imitation Learning ~~~~~~~~~~~~~~~~~~ Using the teleoperation devices, it is also possible to collect data for learning from demonstrations (LfD). For this, we support the learning framework `Robomimic <https://robomimic.github.io/>`__ and allow saving data in `HDF5 <https://robomimic.github.io/docs/tutorials/dataset_contents.html#viewing-hdf5-dataset-structure>`__ format. 1. Collect demonstrations with teleoperation for the environment ``Isaac-Lift-Cube-Franka-IK-Rel-v0``: .. code:: bash # step a: collect data with keyboard ./isaaclab.sh -p source/standalone/workflows/robomimic/collect_demonstrations.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --num_demos 10 --device keyboard # step b: inspect the collected dataset ./isaaclab.sh -p source/standalone/workflows/robomimic/tools/inspect_demonstrations.py logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5 2. Split the dataset into train and validation set: .. code:: bash # install the dependencies sudo apt install cmake build-essential # install python module (for robomimic) ./isaaclab.sh -i robomimic # split data ./isaaclab.sh -p source/standalone//workflows/robomimic/tools/split_train_val.py logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5 --ratio 0.2 3. Train a BC agent for ``Isaac-Lift-Cube-Franka-IK-Rel-v0`` with `Robomimic <https://robomimic.github.io/>`__: .. code:: bash ./isaaclab.sh -p source/standalone/workflows/robomimic/train.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --algo bc --dataset logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5 4. Play the learned model to visualize results: .. code:: bash ./isaaclab.sh -p source/standalone//workflows/robomimic/play.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --checkpoint /PATH/TO/model.pth Reinforcement Learning ~~~~~~~~~~~~~~~~~~~~~~ We provide wrappers to different reinforcement libraries. These wrappers convert the data from the environments into the respective libraries function argument and return types. - Training an agent with `Stable-Baselines3 <https://stable-baselines3.readthedocs.io/en/master/index.html>`__ on ``Isaac-Cartpole-v0``: .. code:: bash # install python module (for stable-baselines3) ./isaaclab.sh -i sb3 # run script for training # note: we enable cpu flag since SB3 doesn't optimize for GPU anyway ./isaaclab.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --headless --cpu # run script for playing with 32 environments ./isaaclab.sh -p source/standalone/workflows/sb3/play.py --task Isaac-Cartpole-v0 --num_envs 32 --checkpoint /PATH/TO/model.zip - Training an agent with `SKRL <https://skrl.readthedocs.io>`__ on ``Isaac-Reach-Franka-v0``: .. code:: bash # install python module (for skrl) ./isaaclab.sh -i skrl # run script for training ./isaaclab.sh -p source/standalone/workflows/skrl/train.py --task Isaac-Reach-Franka-v0 --headless # run script for playing with 32 environments ./isaaclab.sh -p source/standalone/workflows/skrl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pt - Training an agent with `RL-Games <https://github.com/Denys88/rl_games>`__ on ``Isaac-Ant-v0``: .. code:: bash # install python module (for rl-games) ./isaaclab.sh -i rl_games # run script for training ./isaaclab.sh -p source/standalone/workflows/rl_games/train.py --task Isaac-Ant-v0 --headless # run script for playing with 32 environments ./isaaclab.sh -p source/standalone/workflows/rl_games/play.py --task Isaac-Ant-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth - Training an agent with `RSL-RL <https://github.com/leggedrobotics/rsl_rl>`__ on ``Isaac-Reach-Franka-v0``: .. code:: bash # install python module (for rsl-rl) ./isaaclab.sh -i rsl_rl # run script for training ./isaaclab.sh -p source/standalone/workflows/rsl_rl/train.py --task Isaac-Reach-Franka-v0 --headless # run script for playing with 32 environments ./isaaclab.sh -p source/standalone/workflows/rsl_rl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth All the scripts above log the training progress to `Tensorboard`_ in the ``logs`` directory in the root of the repository. The logs directory follows the pattern ``logs/<library>/<task>/<date-time>``, where ``<library>`` is the name of the learning framework, ``<task>`` is the task name, and ``<date-time>`` is the timestamp at which the training script was executed. To view the logs, run: .. code:: bash # execute from the root directory of the repository ./isaaclab.sh -p -m tensorboard.main --logdir=logs .. _Tensorboard: https://www.tensorflow.org/tensorboard
8,478
reStructuredText
35.390558
194
0.714437
isaac-sim/IsaacLab/docs/source/setup/developer.rst
Developer's Guide ================= For development, we suggest using `Microsoft Visual Studio Code (VSCode) <https://code.visualstudio.com/>`__. This is also suggested by NVIDIA Omniverse and there exists tutorials on how to `debug Omniverse extensions <https://www.youtube.com/watch?v=Vr1bLtF1f4U&ab_channel=NVIDIAOmniverse>`__ using VSCode. Setting up Visual Studio Code ----------------------------- The ``Isaac Lab`` repository includes the VSCode settings to easily allow setting up your development environment. These are included in the ``.vscode`` directory and include the following files: .. code-block:: bash .vscode ├── tools │   ├── launch.template.json │   ├── settings.template.json │   └── setup_vscode.py ├── extensions.json ├── launch.json # <- this is generated by setup_vscode.py ├── settings.json # <- this is generated by setup_vscode.py └── tasks.json To setup the IDE, please follow these instructions: 1. Open the ``Isaac Lab`` directory on Visual Studio Code IDE 2. Run VSCode `Tasks <https://code.visualstudio.com/docs/editor/tasks>`__, by pressing ``Ctrl+Shift+P``, selecting ``Tasks: Run Task`` and running the ``setup_python_env`` in the drop down menu. .. image:: ../_static/vscode_tasks.png :width: 600px :align: center :alt: VSCode Tasks If everything executes correctly, it should create a file ``.python.env`` in the ``.vscode`` directory. The file contains the python paths to all the extensions provided by Isaac Sim and Omniverse. This helps in indexing all the python modules for intelligent suggestions while writing code. For more information on VSCode support for Omniverse, please refer to the following links: * `Isaac Sim VSCode support <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_standalone_python.html#isaac-sim-python-vscode>`__ * `Debugging with VSCode <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_advanced_python_debugging.html>`__ Configuring the python interpreter ---------------------------------- In the provided configuration, we set the default python interpreter to use the python executable provided by Omniverse. This is specified in the ``.vscode/settings.json`` file: .. code-block:: json { "python.defaultInterpreterPath": "${workspaceFolder}/_isaac_sim/kit/python/bin/python3", "python.envFile": "${workspaceFolder}/.vscode/.python.env", } If you want to use a different python interpreter (for instance, from your conda environment), you need to change the python interpreter used by selecting and activating the python interpreter of your choice in the bottom left corner of VSCode, or opening the command palette (``Ctrl+Shift+P``) and selecting ``Python: Select Interpreter``. For more information on how to set python interpreter for VSCode, please refer to the `VSCode documentation <https://code.visualstudio.com/docs/python/environments#_working-with-python-interpreters>`_. Repository organization ----------------------- The ``Isaac Lab`` repository is structured as follows: .. code-block:: bash IsaacLab ├── .vscode ├── .flake8 ├── LICENSE ├── isaaclab.sh ├── pyproject.toml ├── README.md ├── docs ├── source │   ├── extensions │   │   ├── omni.isaac.lab │   │   └── omni.isaac.lab_tasks │   ├── standalone │   │   ├── demos │   │   ├── environments │   │   ├── tools │   │   ├── tutorials │   │   └── workflows └── VERSION The ``source`` directory contains the source code for all ``Isaac Lab`` *extensions* and *standalone applications*. The two are the different development workflows supported in `Isaac Sim <https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html>`__. These are described in the following sections. Extensions ~~~~~~~~~~ Extensions are the recommended way to develop applications in Isaac Sim. They are modularized packages that formulate the Omniverse ecosystem. Each extension provides a set of functionalities that can be used by other extensions or standalone applications. A folder is recognized as an extension if it contains an ``extension.toml`` file in the ``config`` directory. More information on extensions can be found in the `Omniverse documentation <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html>`__. Isaac Lab in itself provides extensions for robot learning. These are written into the ``source/extensions`` directory. Each extension is written as a python package and follows the following structure: .. code:: bash <extension-name> ├── config │   └── extension.toml ├── docs │   ├── CHANGELOG.md │   └── README.md ├── <extension-name> │ ├── __init__.py │ ├── .... │ └── scripts ├── setup.py └── tests The ``config/extension.toml`` file contains the metadata of the extension. This includes the name, version, description, dependencies, etc. This information is used by Omniverse to load the extension. The ``docs`` directory contains the documentation for the extension with more detailed information about the extension and a CHANGELOG file that contains the changes made to the extension in each version. The ``<extension-name>`` directory contains the main python package for the extension. It may also contains the ``scripts`` directory for keeping python-based applications that are loaded into Omniverse when then extension is enabled using the `Extension Manager <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html>`__. More specifically, when an extension is enabled, the python module specified in the ``config/extension.toml`` file is loaded and scripts that contains children of the :class:`omni.ext.IExt` class are executed. .. code:: python import omni.ext class MyExt(omni.ext.IExt): """My extension application.""" def on_startup(self, ext_id): """Called when the extension is loaded.""" pass def on_shutdown(self): """Called when the extension is unloaded. It releases all references to the extension and cleans up any resources. """ pass While loading extensions into Omniverse happens automatically, using the python package in standalone applications requires additional steps. To simplify the build process and avoiding the need to understand the `premake <https://premake.github.io/>`__ build system used by Omniverse, we directly use the `setuptools <https://setuptools.readthedocs.io/en/latest/>`__ python package to build the python module provided by the extensions. This is done by the ``setup.py`` file in the extension directory. .. note:: The ``setup.py`` file is not required for extensions that are only loaded into Omniverse using the `Extension Manager <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html>`__. Lastly, the ``tests`` directory contains the unit tests for the extension. These are written using the `unittest <https://docs.python.org/3/library/unittest.html>`__ framework. It is important to note that Omniverse also provides a similar `testing framework <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/104.0/guide/testing_exts_python.html>`__. However, it requires going through the build process and does not support testing of the python module in standalone applications. Extension Dependency Management ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Certain extensions may have dependencies which need to be installed before the extension can be run. While Python dependencies can be expressed via the ``INSTALL_REQUIRES`` array in ``setup.py``, we need a separate installation pipeline to handle non-Python dependencies. We have therefore created an additional setup procedure, ``./isaaclab.sh --install-deps {dep_type}``, which scans the ``extension.toml`` file of the directories under ``source/extensions`` for ``apt`` and ``rosdep`` dependencies. This example ``extension.toml`` has both ``apt_deps`` and ``ros_ws`` specified, so both ``apt`` and ``rosdep`` packages will be installed if ``./isaaclab.sh --install-deps all`` is passed: .. code-block:: toml [isaaclab_settings] apt_deps = ["example_package"] ros_ws = "path/from/extension_root/to/ros_ws" From the ``apt_deps`` in the above example, the package ``example_package`` would be installed via ``apt``. From the ``ros_ws``, a ``rosdep install --from-paths {ros_ws}/src --ignore-src`` command will be called. This will install all the `ROS package.xml dependencies <https://docs.ros.org/en/humble/Tutorials/Intermediate/Rosdep.html>`__ in the directory structure below. Currently the ROS distro is assumed to be ``humble``. ``apt`` deps are automatically installed this way during the build process of the ``Dockerfile.base``, and ``rosdep`` deps during the build process of ``Dockerfile.ros2``. Standalone applications ~~~~~~~~~~~~~~~~~~~~~~~ In a typical Omniverse workflow, the simulator is launched first, after which the extensions are enabled that load the python module and run the python application. While this is a recommended workflow, it is not always possible to use this workflow. For example, for robot learning, it is essential to have complete control over simulation stepping and all the other functionalities instead of asynchronously waiting for the simulator to step. In such cases, it is necessary to write a standalone application that launches the simulator using :class:`~omni.isaac.lab.app.AppLauncher` and allows complete control over the simulation through the :class:`~omni.isaac.lab.sim.SimulationContext` class. .. code:: python """Launch Isaac Sim Simulator first.""" from omni.isaac.lab.app import AppLauncher # launch omniverse app app_launcher = AppLauncher(headless=False) simulation_app = app_launcher.app """Rest everything follows.""" from omni.isaac.lab.sim import SimulationContext if __name__ == "__main__": # get simulation context simulation_context = SimulationContext() # reset and play simulation simulation_context.reset() # step simulation simulation_context.step() # stop simulation simulation_context.stop() # close the simulation simulation_app.close() The ``source/standalone`` directory contains various standalone applications designed using the extensions provided by ``Isaac Lab``. These applications are written in python and are structured as follows: * **demos**: Contains various demo applications that showcase the core framework ``omni.isaac.lab``. * **environments**: Contains applications for running environments defined in ``omni.isaac.lab_tasks`` with different agents. These include a random policy, zero-action policy, teleoperation or scripted state machines. * **tools**: Contains applications for using the tools provided by the framework. These include converting assets, generating datasets, etc. * **tutorials**: Contains step-by-step tutorials for using the APIs provided by the framework. * **workflows**: Contains applications for using environments with various learning-based frameworks. These include different reinforcement learning or imitation learning libraries.
11,314
reStructuredText
40.752767
146
0.728566
isaac-sim/IsaacLab/docs/source/setup/template.rst
Building your Own Project ========================= Traditionally, building new projects that utilize Isaac Lab's features required creating your own extensions within the Isaac Lab repository. However, this approach can obscure project visibility and complicate updates from one version of Isaac Lab to another. To circumvent these challenges, we now provide a pre-configured and customizable `extension template <https://github.com/isaac-sim/IsaacLab.ext_template>`_ for creating projects in an isolated environment. This template serves three distinct use cases: * **Project Template**: Provides essential access to Isaac Sim and Isaac Lab's features, making it ideal for projects that require a standalone environment. * **Python Package**: Facilitates integration with Isaac Sim's native or virtual Python environment, allowing for the creation of Python packages that can be shared and reused across multiple projects. * **Omniverse Extension**: Supports direct integration into Omniverse extension workflow. .. note:: We recommend using the extension template for new projects, as it provides a more streamlined and efficient workflow. Additionally it ensures that your project remains up-to-date with the latest features and improvements in Isaac Lab. To get started, please follow the instructions in the `extension template repository <https://github.com/isaac-sim/IsaacLab.ext_template>`_.
1,418
reStructuredText
53.576921
140
0.79055
isaac-sim/IsaacLab/docs/source/setup/installation/pip_installation.rst
Installation using Isaac Sim pip ================================ Installing Isaac Sim -------------------- .. note:: Installing Isaac Sim from pip is currently an experimental feature. If errors occur, please report them to the `Isaac Sim Forums <https://docs.omniverse.nvidia.com/isaacsim/latest/common/feedback.html>`_ and install Isaac Sim from pre-built binaries. - To use the pip installation approach for Isaac Sim, we recommend first creating a virtual environment. Ensure that the python version of the virtual environment is **Python 3.10**. .. tabs:: .. tab:: Conda .. code-block:: bash conda create -n isaaclab python=3.10 conda activate isaaclab .. tab:: Virtual environment (venv) .. code-block:: bash python3.10 -m venv isaaclab # on Linux source isaaclab/bin/activate # on Windows isaaclab\Scripts\activate - Next, install a CUDA-enabled PyTorch 2.2.2 build based on the CUDA version available on your system. .. tabs:: .. tab:: CUDA 11 .. code-block:: bash pip install torch==2.2.2 --index-url https://download.pytorch.org/whl/cu118 .. tab:: CUDA 12 .. code-block:: bash pip install torch==2.2.2 --index-url https://download.pytorch.org/whl/cu121 - Then, install the Isaac Sim packages necessary for running Isaac Lab: .. code-block:: bash pip install isaacsim-rl isaacsim-replicator --index-url https://pypi.nvidia.com/ Installing Isaac Lab -------------------- Cloning Isaac Lab ~~~~~~~~~~~~~~~~~ .. note:: We recommend making a `fork <https://github.com/isaac-sim/IsaacLab/fork>`_ of the Isaac Lab repository to contribute to the project but this is not mandatory to use the framework. If you make a fork, please replace ``isaac-sim`` with your username in the following instructions. Clone the Isaac Lab repository into your workspace: .. code:: bash # Option 1: With SSH git clone [email protected]:isaac-sim/IsaacLab.git # Option 2: With HTTPS git clone https://github.com/isaac-sim/IsaacLab.git .. note:: We provide a helper executable `isaaclab.sh <https://github.com/isaac-sim/IsaacLab/blob/main/isaaclab.sh>`_ that provides utilities to manage extensions: .. tabs:: .. tab:: Linux .. code:: text ./isaaclab.sh --help usage: isaaclab.sh [-h] [-i] [-f] [-p] [-s] [-t] [-o] [-v] [-d] [-c] -- Utility to manage Isaac Lab. optional arguments: -h, --help Display the help content. -i, --install [LIB] Install the extensions inside Isaac Lab and learning frameworks (rl_games, rsl_rl, sb3, skrl) as extra dependencies. Default is 'all'. -f, --format Run pre-commit to format the code and check lints. -p, --python Run the python executable provided by Isaac Sim or virtual environment (if active). -s, --sim Run the simulator executable (isaac-sim.sh) provided by Isaac Sim. -t, --test Run all python unittest tests. -o, --docker Run the docker container helper script (docker/container.sh). -v, --vscode Generate the VSCode settings file from template. -d, --docs Build the documentation from source using sphinx. -c, --conda [NAME] Create the conda environment for Isaac Lab. Default name is 'isaaclab'. .. tab:: Windows .. code:: text isaaclab.bat --help usage: isaaclab.bat [-h] [-i] [-f] [-p] [-s] [-v] [-d] [-c] -- Utility to manage Isaac Lab. optional arguments: -h, --help Display the help content. -i, --install [LIB] Install the extensions inside Isaac Lab and learning frameworks (rl_games, rsl_rl, sb3, skrl) as extra dependencies. Default is 'all'. -f, --format Run pre-commit to format the code and check lints. -p, --python Run the python executable provided by Isaac Sim or virtual environment (if active). -s, --sim Run the simulator executable (isaac-sim.bat) provided by Isaac Sim. -t, --test Run all python unittest tests. -v, --vscode Generate the VSCode settings file from template. -d, --docs Build the documentation from source using sphinx. -c, --conda [NAME] Create the conda environment for Isaac Lab. Default name is 'isaaclab'. Installation ~~~~~~~~~~~~ - Install dependencies using ``apt`` (on Ubuntu): .. code:: bash sudo apt install cmake build-essential - Run the install command that iterates over all the extensions in ``source/extensions`` directory and installs them using pip (with ``--editable`` flag): .. tabs:: .. tab:: Linux .. code:: bash ./isaaclab.sh --install # or "./isaaclab.sh -i" .. tab:: Windows .. code:: bash isaaclab.bat --install :: or "isaaclab.bat -i" .. note:: By default, this will install all the learning frameworks. If you want to install only a specific framework, you can pass the name of the framework as an argument. For example, to install only the ``rl_games`` framework, you can run .. tabs:: .. tab:: Linux .. code:: bash ./isaaclab.sh --install rl_games .. tab:: Windows .. code:: bash isaaclab.bat --install rl_games :: or "isaaclab.bat -i" The valid options are ``rl_games``, ``rsl_rl``, ``sb3``, ``skrl``, ``robomimic``, ``none``.
5,768
reStructuredText
31.965714
170
0.596047
isaac-sim/IsaacLab/docs/source/setup/installation/cloud_installation.rst
Running Isaac Lab in the Cloud ============================== Isaac Lab can be run in various cloud infrastructures with the use of `Isaac Automator <https://github.com/isaac-sim/IsaacAutomator>`__. Isaac Automator allows for quick deployment of Isaac Sim and Isaac Lab onto the public clouds (AWS, GCP, Azure, and Alibaba Cloud are currently supported). The result is a fully configured remote desktop cloud workstation, which can be used for development and testing of Isaac Lab within minutes and on a budget. Isaac Automator supports variety of GPU instances and stop-start functionality to save on cloud costs and a variety of tools to aid the workflow (like uploading and downloading data, autorun, deployment management, etc). Installing Isaac Automator -------------------------- To use Isaac Automator, first clone the repo: .. code-block:: bash git clone https://github.com/isaac-sim/IsaacAutomator.git Isaac Automator requires having ``docker`` pre-installed on the system. * To install Docker, please follow the instructions for your operating system on the `Docker website`_. * Follow the post-installation steps for Docker on the `post-installation steps`_ page. These steps allow you to run Docker without using ``sudo``. Isaac Automator also requires obtaining a NGC API key. * Get access to the `Isaac Sim container`_ by joining the NVIDIA Developer Program credentials. * Generate your `NGC API key`_ to access locked container images from NVIDIA GPU Cloud (NGC). * This step requires you to create an NGC account if you do not already have one. * Once you have your generated API key, you need to log in to NGC from the terminal. .. code:: bash docker login nvcr.io * For the username, enter ``$oauthtoken`` exactly as shown. It is a special username that is used to authenticate with NGC. .. code:: text Username: $oauthtoken Password: <Your NGC API Key> Running Isaac Automator ----------------------- To run Isaac Automator, first build the Isaac Automator container: .. code-block:: bash ./build Next, run the deployed script for your preferred cloud: .. code-block:: bash # AWS ./deploy-aws # Azure ./deploy-azure # GCP ./deploy-gcp # Alibaba Cloud ./deploy-alicloud Follow the prompts for entering information regarding the environment setup and credentials. Once successful, instructions for connecting to the cloud instance will be available in the terminal. Connections can be made using SSH, noVCN, or NoMachine. For details on the credentials and setup required for each cloud, please visit the `Isaac Automator <https://github.com/isaac-sim/IsaacAutomator?tab=readme-ov-file#deploying-isaac-sim>`__ page for more instructions. Running Isaac Lab on the Cloud ------------------------------ Once connected to the cloud instance, the desktop will have an icon showing ``isaaclab.sh``. Launch the ``isaaclab.sh`` executable, which will open a new Terminal. Within the terminal, Isaac Lab commands can be executed in the same way as running locally. For example: .. code-block:: bash ./isaaclab.sh -p source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 Destroying a Development ------------------------- To save costs, deployments can be destroyed when not being used. This can be done from within the Automator container, which can be entered with command ``./run``. To destroy a deployment, run: .. code:: bash ./destroy <deployment-name> .. _`Docker website`: https://docs.docker.com/desktop/install/linux-install/ .. _`post-installation steps`: https://docs.docker.com/engine/install/linux-postinstall/ .. _`Isaac Sim container`: https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim .. _`NGC API key`: https://docs.nvidia.com/ngc/gpu-cloud/ngc-user-guide/index.html#generating-api-key
3,871
reStructuredText
34.522935
378
0.726427
isaac-sim/IsaacLab/docs/source/setup/installation/binaries_installation.rst
Installation using Isaac Sim Binaries ===================================== Installing Isaac Sim -------------------- Downloading pre-built binaries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Please follow the Isaac Sim `documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html>`__ to install the latest Isaac Sim release. To check the minimum system requirements,refer to the documentation `here <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/requirements.html>`__. .. note:: We have tested Isaac Lab with Isaac Sim 4.0 release on Ubuntu 20.04LTS with NVIDIA driver 525.147. .. tabs:: .. tab:: Linux On Linux systems, by default, Isaac Sim is installed in the directory ``${HOME}/.local/share/ov/pkg/isaac_sim-*``, with ``*`` corresponding to the Isaac Sim version. .. tab:: Windows On Windows systems, by default,Isaac Sim is installed in the directory ``C:\Users\user\AppData\Local\ov\pkg\isaac_sim-*``, with ``*`` corresponding to the Isaac Sim version. Installing Isaac Lab -------------------- Cloning Isaac Lab ~~~~~~~~~~~~~~~~~ .. note:: We recommend making a `fork <https://github.com/isaac-sim/IsaacLab/fork>`_ of the Isaac Lab repository to contribute to the project but this is not mandatory to use the framework. If you make a fork, please replace ``isaac-sim`` with your username in the following instructions. Clone the Isaac Lab repository into your workspace: .. code:: bash # Option 1: With SSH git clone [email protected]:isaac-sim/IsaacLab.git # Option 2: With HTTPS git clone https://github.com/isaac-sim/IsaacLab.git .. note:: We provide a helper executable `isaaclab.sh <https://github.com/isaac-sim/IsaacLab/blob/main/isaaclab.sh>`_ that provides utilities to manage extensions: .. tabs:: .. tab:: Linux .. code:: text ./isaaclab.sh --help usage: isaaclab.sh [-h] [-i] [-f] [-p] [-s] [-t] [-o] [-v] [-d] [-c] -- Utility to manage Isaac Lab. optional arguments: -h, --help Display the help content. -i, --install [LIB] Install the extensions inside Isaac Lab and learning frameworks (rl-games, rsl-rl, sb3, skrl) as extra dependencies. Default is 'all'. -f, --format Run pre-commit to format the code and check lints. -p, --python Run the python executable provided by Isaac Sim or virtual environment (if active). -s, --sim Run the simulator executable (isaac-sim.sh) provided by Isaac Sim. -t, --test Run all python unittest tests. -o, --docker Run the docker container helper script (docker/container.sh). -v, --vscode Generate the VSCode settings file from template. -d, --docs Build the documentation from source using sphinx. -c, --conda [NAME] Create the conda environment for Isaac Lab. Default name is 'isaaclab'. .. tab:: Windows .. code:: text isaaclab.bat --help usage: isaaclab.bat [-h] [-i] [-f] [-p] [-s] [-v] [-d] [-c] -- Utility to manage Isaac Lab. optional arguments: -h, --help Display the help content. -i, --install [LIB] Install the extensions inside Isaac Lab and learning frameworks (rl-games, rsl-rl, sb3, skrl) as extra dependencies. Default is 'all'. -f, --format Run pre-commit to format the code and check lints. -p, --python Run the python executable provided by Isaac Sim or virtual environment (if active). -s, --sim Run the simulator executable (isaac-sim.bat) provided by Isaac Sim. -t, --test Run all python unittest tests. -v, --vscode Generate the VSCode settings file from template. -d, --docs Build the documentation from source using sphinx. -c, --conda [NAME] Create the conda environment for Isaac Lab. Default name is 'isaaclab'. Creating the Isaac Sim Symbolic Link ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Set up a symbolic link between the installed Isaac Sim root folder and ``_isaac_sim`` in the Isaac Lab directory. This makes it convenient to index the python modules and look for extensions shipped with Isaac Sim. .. tabs:: .. tab:: Linux .. code:: bash # enter the cloned repository cd IsaacLab # create a symbolic link ln -s path_to_isaac_sim _isaac_sim # For example: ln -s /home/nvidia/.local/share/ov/pkg/isaac-sim-4.0.0 _isaac_sim .. tab:: Windows .. code:: batch :: enter the cloned repository cd IsaacLab :: create a symbolic link - requires launching Command Prompt with Administrator access mklink /D _isaac_sim path_to_isaac_sim # For example: mklink /D _isaac_sim C:/Users/nvidia/AppData/Local/ov/pkg/isaac-sim-4.0.0 Setting up the conda environment (optional) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. attention:: This step is optional. If you are using the bundled python with Isaac Sim, you can skip this step. The executable ``isaaclab.sh`` automatically fetches the python bundled with Isaac Sim, using ``./isaaclab.sh -p`` command (unless inside a virtual environment). This executable behaves like a python executable, and can be used to run any python script or module with the simulator. For more information, please refer to the `documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/manual_standalone_python.html#isaac-sim-python-environment>`__. Although using a virtual environment is optional, we recommend using ``conda``. To install ``conda``, please follow the instructions `here <https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html>`__. In case you want to use ``conda`` to create a virtual environment, you can use the following command: .. tabs:: .. tab:: Linux .. code:: bash # Option 1: Default name for conda environment is 'isaaclab' ./isaaclab.sh --conda # or "./isaaclab.sh -c" # Option 2: Custom name for conda environment ./isaaclab.sh --conda my_env # or "./isaaclab.sh -c my_env" .. tab:: Windows .. code:: batch :: Option 1: Default name for conda environment is 'isaaclab' isaaclab.bat --conda :: or "isaaclab.bat -c" :: Option 2: Custom name for conda environment isaaclab.bat --conda my_env :: or "isaaclab.bat -c my_env" If you are using ``conda`` to create a virtual environment, make sure to activate the environment before running any scripts. For example: .. code:: bash conda activate isaaclab # or "conda activate my_env" Once you are in the virtual environment, you do not need to use ``./isaaclab.sh -p`` / ``isaaclab.bat -p`` to run python scripts. You can use the default python executable in your environment by running ``python`` or ``python3``. However, for the rest of the documentation, we will assume that you are using ``./isaaclab.sh -p`` / ``isaaclab.bat -p`` to run python scripts. This command is equivalent to running ``python`` or ``python3`` in your virtual environment. Installation ~~~~~~~~~~~~ - Install dependencies using ``apt`` (on Ubuntu): .. code:: bash sudo apt install cmake build-essential - Run the install command that iterates over all the extensions in ``source/extensions`` directory and installs them using pip (with ``--editable`` flag): .. tabs:: .. tab:: Linux .. code:: bash ./isaaclab.sh --install # or "./isaaclab.sh -i" .. tab:: Windows .. code:: bash isaaclab.bat --install :: or "isaaclab.bat -i" .. note:: By default, this will install all the learning frameworks. If you want to install only a specific framework, you can pass the name of the framework as an argument. For example, to install only the ``rl_games`` framework, you can run .. tabs:: .. tab:: Linux .. code:: bash ./isaaclab.sh --install rl_games .. tab:: Windows .. code:: bash isaaclab.bat --install rl_games :: or "isaaclab.bat -i" The valid options are ``rl_games``, ``rsl_rl``, ``sb3``, ``skrl``, ``robomimic``, ``none``.
8,488
reStructuredText
35.748918
170
0.627003
isaac-sim/IsaacLab/docs/source/setup/installation/verifying_installation.rst
Verifying the Installation ========================== Verifying the Isaac Sim installation ------------------------------------ Isaac Sim installed from pip ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Make sure that your virtual environment is activated (if applicable) - Check that the simulator runs as expected: .. code:: bash # note: you can pass the argument "--help" to see all arguments possible. isaacsim By default, this will launch an empty mini Kit window. - To run with a specific experience file, run: .. code:: bash # experience files can be absolute path, or relative path searched in isaacsim/apps or omni/apps isaacsim omni.isaac.sim.python.kit .. attention:: When running Isaac Sim for the first time, all dependent extensions will be pulled from the registry. This process can take upwards of 10 minutes and is required on the first run of each experience file. Once the extensions are pulled, consecutive runs using the same experience file will use the cached extensions. In addition, the first run will prompt users to accept the Nvidia Omniverse License Agreement. To accept the EULA, reply ``Yes`` when prompted with the below message: .. code:: bash By installing or using Isaac Sim, I agree to the terms of NVIDIA OMNIVERSE LICENSE AGREEMENT (EULA) in https://docs.omniverse.nvidia.com/isaacsim/latest/common/NVIDIA_Omniverse_License_Agreement.html Do you accept the EULA? (Yes/No): Yes If the simulator does not run or crashes while following the above instructions, it means that something is incorrectly configured. To debug and troubleshoot, please check Isaac Sim `documentation <https://docs.omniverse.nvidia.com/dev-guide/latest/linux-troubleshooting.html>`__ and the `forums <https://docs.omniverse.nvidia.com/isaacsim/latest/isaac_sim_forums.html>`__. Isaac Sim installed from binaries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To avoid the overhead of finding and locating the Isaac Sim installation directory every time, we recommend exporting the following environment variables to your terminal for the remaining of the installation instructions: .. tabs:: .. tab:: Linux .. code:: bash # Isaac Sim root directory export ISAACSIM_PATH="${HOME}/.local/share/ov/pkg/isaac-sim-4.0.0" # Isaac Sim python executable export ISAACSIM_PYTHON_EXE="${ISAACSIM_PATH}/python.sh" .. tab:: Windows .. code:: batch :: Isaac Sim root directory set ISAACSIM_PATH="C:\Users\user\AppData\Local\ov\pkg\isaac-sim-4.0.0" :: Isaac Sim python executable set ISAACSIM_PYTHON_EXE="%ISAACSIM_PATH%\python.bat" For more information on common paths, please check the Isaac Sim `documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_faq.html#common-path-locations>`__. - Check that the simulator runs as expected: .. tabs:: .. tab:: Linux .. code:: bash # note: you can pass the argument "--help" to see all arguments possible. ${ISAACSIM_PATH}/isaac-sim.sh .. tab:: Windows .. code:: batch :: note: you can pass the argument "--help" to see all arguments possible. %ISAACSIM_PATH%\isaac-sim.bat - Check that the simulator runs from a standalone python script: .. tabs:: .. tab:: Linux .. code:: bash # checks that python path is set correctly ${ISAACSIM_PYTHON_EXE} -c "print('Isaac Sim configuration is now complete.')" # checks that Isaac Sim can be launched from python ${ISAACSIM_PYTHON_EXE} ${ISAACSIM_PATH}/standalone_examples/api/omni.isaac.core/add_cubes.py .. tab:: Windows .. code:: batch :: checks that python path is set correctly %ISAACSIM_PYTHON_EXE% -c "print('Isaac Sim configuration is now complete.')" :: checks that Isaac Sim can be launched from python %ISAACSIM_PYTHON_EXE% %ISAACSIM_PATH%\standalone_examples\api\omni.isaac.core\add_cubes.py .. attention:: If you have been using a previous version of Isaac Sim, you need to run the following command for the *first* time after installation to remove all the old user data and cached variables: .. tabs:: .. tab:: Linux .. code:: bash ${ISAACSIM_PATH}/isaac-sim.sh --reset-user .. tab:: Windows .. code:: batch %ISAACSIM_PATH%\isaac-sim.bat --reset-user If the simulator does not run or crashes while following the above instructions, it means that something is incorrectly configured. To debug and troubleshoot, please check Isaac Sim `documentation <https://docs.omniverse.nvidia.com/dev-guide/latest/linux-troubleshooting.html>`__ and the `forums <https://docs.omniverse.nvidia.com/isaacsim/latest/isaac_sim_forums.html>`__. Verifying the Isaac Lab installation ------------------------------------ To verify that the installation was successful, run the following command from the top of the repository: .. tabs:: .. tab:: Linux .. code:: bash # Option 1: Using the isaaclab.sh executable # note: this works for both the bundled python and the virtual environment ./isaaclab.sh -p source/standalone/tutorials/00_sim/create_empty.py # Option 2: Using python in your virtual environment python source/standalone/tutorials/00_sim/create_empty.py .. tab:: Windows .. code:: batch :: Option 1: Using the isaaclab.bat executable :: note: this works for both the bundled python and the virtual environment isaaclab.bat -p source\standalone\tutorials\00_sim\create_empty.py :: Option 2: Using python in your virtual environment python source\standalone\tutorials\00_sim\create_empty.py The above command should launch the simulator and display a window with a black ground plane. You can exit the script by pressing ``Ctrl+C`` on your terminal. On Windows machines, please terminate the process from Command Prompt using ``Ctrl+Break`` or ``Ctrl+fn+B``. If you see this, then the installation was successful! |:tada:|
6,221
reStructuredText
30.744898
122
0.675133
isaac-sim/IsaacLab/docs/source/setup/installation/index.rst
Installation Guide =================== .. image:: https://img.shields.io/badge/IsaacSim-4.0-silver.svg :target: https://developer.nvidia.com/isaac-sim :alt: IsaacSim 4.0 .. image:: https://img.shields.io/badge/python-3.10-blue.svg :target: https://www.python.org/downloads/release/python-31013/ :alt: Python 3.10 .. image:: https://img.shields.io/badge/platform-linux--64-orange.svg :target: https://releases.ubuntu.com/20.04/ :alt: Ubuntu 20.04 .. image:: https://img.shields.io/badge/platform-windows--64-orange.svg :target: https://www.microsoft.com/en-ca/windows/windows-11 :alt: Windows 11 .. caution:: We have dropped support for Isaac Sim versions 2023.1.0 and below. We recommend using the latest Isaac Sim 4.0 release to benefit from the latest features and improvements. For more information, please refer to the `Isaac Sim release notes <https://docs.omniverse.nvidia.com/isaacsim/latest/release_notes.html>`__. .. note:: We recommend system requirements with at least 32GB RAM and 16GB VRAM for Isaac Lab. For the full list of system requirements for Isaac Sim, please refer to the `Isaac Sim system requirements <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/requirements.html#system-requirements>`_. As an experimental feature in Isaac Sim 4.0 release, Isaac Sim can also be installed through pip. This simplifies the installation process by avoiding the need to download the Omniverse Launcher and installing Isaac Sim through the launcher. Therefore, there are two ways to install Isaac Lab: .. toctree:: :maxdepth: 2 Installation using Isaac Sim pip (experimental) <pip_installation> binaries_installation verifying_installation cloud_installation
1,762
reStructuredText
37.326086
140
0.737798
isaac-sim/IsaacLab/docs/source/api/index.rst
API Reference ============= This page gives an overview of all the modules and classes in the Isaac Lab extensions. omni.isaac.lab extension ------------------------ The following modules are available in the ``omni.isaac.lab`` extension: .. currentmodule:: omni.isaac.lab .. autosummary:: :toctree: lab app actuators assets controllers devices envs managers markers scene sensors sim terrains utils .. toctree:: :hidden: lab/omni.isaac.lab.envs.mdp lab/omni.isaac.lab.envs.ui lab/omni.isaac.lab.sensors.patterns lab/omni.isaac.lab.sim.converters lab/omni.isaac.lab.sim.schemas lab/omni.isaac.lab.sim.spawners omni.isaac.lab_tasks extension -------------------------------- The following modules are available in the ``omni.isaac.lab_tasks`` extension: .. currentmodule:: omni.isaac.lab_tasks .. autosummary:: :toctree: lab_tasks utils .. toctree:: :hidden: lab_tasks/omni.isaac.lab_tasks.utils.wrappers lab_tasks/omni.isaac.lab_tasks.utils.data_collector
1,050
reStructuredText
17.120689
87
0.664762
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.managers.rst
omni.isaac.lab.managers ======================= .. automodule:: omni.isaac.lab.managers .. rubric:: Classes .. autosummary:: SceneEntityCfg ManagerBase ManagerTermBase ManagerTermBaseCfg ObservationManager ObservationGroupCfg ObservationTermCfg ActionManager ActionTerm ActionTermCfg EventManager EventTermCfg CommandManager CommandTerm CommandTermCfg RewardManager RewardTermCfg TerminationManager TerminationTermCfg CurriculumManager CurriculumTermCfg Scene Entity ------------ .. autoclass:: SceneEntityCfg :members: :exclude-members: __init__ Manager Base ------------ .. autoclass:: ManagerBase :members: .. autoclass:: ManagerTermBase :members: .. autoclass:: ManagerTermBaseCfg :members: :exclude-members: __init__ Observation Manager ------------------- .. autoclass:: ObservationManager :members: :inherited-members: :show-inheritance: .. autoclass:: ObservationGroupCfg :members: :exclude-members: __init__ .. autoclass:: ObservationTermCfg :members: :exclude-members: __init__ Action Manager -------------- .. autoclass:: ActionManager :members: :inherited-members: :show-inheritance: .. autoclass:: ActionTerm :members: :inherited-members: :show-inheritance: .. autoclass:: ActionTermCfg :members: :exclude-members: __init__ Event Manager ------------- .. autoclass:: EventManager :members: :inherited-members: :show-inheritance: .. autoclass:: EventTermCfg :members: :exclude-members: __init__ Randomization Manager --------------------- .. deprecated:: v0.3 The Randomization Manager is deprecated and will be removed in v0.4. Please use the :class:`EventManager` class instead. .. autoclass:: RandomizationManager :members: :inherited-members: :show-inheritance: .. autoclass:: RandomizationTermCfg :members: :exclude-members: __init__ Command Manager --------------- .. autoclass:: CommandManager :members: .. autoclass:: CommandTerm :members: :exclude-members: __init__, class_type .. autoclass:: CommandTermCfg :members: :exclude-members: __init__, class_type Reward Manager -------------- .. autoclass:: RewardManager :members: :inherited-members: :show-inheritance: .. autoclass:: RewardTermCfg :exclude-members: __init__ Termination Manager ------------------- .. autoclass:: TerminationManager :members: :inherited-members: :show-inheritance: .. autoclass:: TerminationTermCfg :members: :exclude-members: __init__ Curriculum Manager ------------------ .. autoclass:: CurriculumManager :members: :inherited-members: :show-inheritance: .. autoclass:: CurriculumTermCfg :members: :exclude-members: __init__
2,862
reStructuredText
16.672839
72
0.639413
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.utils.rst
omni.isaac.lab.utils ==================== .. automodule:: omni.isaac.lab.utils .. Rubric:: Submodules .. autosummary:: io array assets dict math noise string timer warp .. Rubric:: Functions .. autosummary:: configclass Configuration class ~~~~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.configclass :members: :show-inheritance: IO operations ~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.io :members: :imported-members: :show-inheritance: Array operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.array :members: :show-inheritance: Asset operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.assets :members: :show-inheritance: Dictionary operations ~~~~~~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.dict :members: :show-inheritance: Math operations ~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.math :members: :inherited-members: :show-inheritance: Noise operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.noise :members: :imported-members: :inherited-members: :show-inheritance: :exclude-members: __init__, func String operations ~~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.string :members: :show-inheritance: Timer operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.timer :members: :show-inheritance: Warp operations ~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.lab.utils.warp :members: :imported-members: :show-inheritance:
1,598
reStructuredText
14.831683
48
0.590738
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.devices.rst
omni.isaac.lab.devices ====================== .. automodule:: omni.isaac.lab.devices .. rubric:: Classes .. autosummary:: DeviceBase Se2Gamepad Se3Gamepad Se2Keyboard Se3Keyboard Se3SpaceMouse Se3SpaceMouse Device Base ----------- .. autoclass:: DeviceBase :members: Game Pad -------- .. autoclass:: Se2Gamepad :members: :inherited-members: :show-inheritance: .. autoclass:: Se3Gamepad :members: :inherited-members: :show-inheritance: Keyboard -------- .. autoclass:: Se2Keyboard :members: :inherited-members: :show-inheritance: .. autoclass:: Se3Keyboard :members: :inherited-members: :show-inheritance: Space Mouse ----------- .. autoclass:: Se2SpaceMouse :members: :inherited-members: :show-inheritance: .. autoclass:: Se3SpaceMouse :members: :inherited-members: :show-inheritance:
909
reStructuredText
13.677419
38
0.617162
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.sim.converters.rst
omni.isaac.lab.sim.converters ============================= .. automodule:: omni.isaac.lab.sim.converters .. rubric:: Classes .. autosummary:: AssetConverterBase AssetConverterBaseCfg MeshConverter MeshConverterCfg UrdfConverter UrdfConverterCfg Asset Converter Base -------------------- .. autoclass:: AssetConverterBase :members: .. autoclass:: AssetConverterBaseCfg :members: :exclude-members: __init__ Mesh Converter -------------- .. autoclass:: MeshConverter :members: :inherited-members: :show-inheritance: .. autoclass:: MeshConverterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__ URDF Converter -------------- .. autoclass:: UrdfConverter :members: :inherited-members: :show-inheritance: .. autoclass:: UrdfConverterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__
949
reStructuredText
16.272727
45
0.62803
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.sim.spawners.rst
omni.isaac.lab.sim.spawners =========================== .. automodule:: omni.isaac.lab.sim.spawners .. rubric:: Submodules .. autosummary:: shapes lights sensors from_files materials .. rubric:: Classes .. autosummary:: SpawnerCfg RigidObjectSpawnerCfg Spawners -------- .. autoclass:: SpawnerCfg :members: :exclude-members: __init__ .. autoclass:: RigidObjectSpawnerCfg :members: :show-inheritance: :exclude-members: __init__ Shapes ------ .. automodule:: omni.isaac.lab.sim.spawners.shapes .. rubric:: Classes .. autosummary:: ShapeCfg CapsuleCfg ConeCfg CuboidCfg CylinderCfg SphereCfg .. autoclass:: ShapeCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_capsule .. autoclass:: CapsuleCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cone .. autoclass:: ConeCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cuboid .. autoclass:: CuboidCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cylinder .. autoclass:: CylinderCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_sphere .. autoclass:: SphereCfg :members: :show-inheritance: :exclude-members: __init__, func Lights ------ .. automodule:: omni.isaac.lab.sim.spawners.lights .. rubric:: Classes .. autosummary:: LightCfg CylinderLightCfg DiskLightCfg DistantLightCfg DomeLightCfg SphereLightCfg .. autofunction:: spawn_light .. autoclass:: LightCfg :members: :exclude-members: __init__, func .. autoclass:: CylinderLightCfg :members: :exclude-members: __init__, func .. autoclass:: DiskLightCfg :members: :exclude-members: __init__, func .. autoclass:: DistantLightCfg :members: :exclude-members: __init__, func .. autoclass:: DomeLightCfg :members: :exclude-members: __init__, func .. autoclass:: SphereLightCfg :members: :exclude-members: __init__, func Sensors ------- .. automodule:: omni.isaac.lab.sim.spawners.sensors .. rubric:: Classes .. autosummary:: PinholeCameraCfg FisheyeCameraCfg .. autofunction:: spawn_camera .. autoclass:: PinholeCameraCfg :members: :exclude-members: __init__, func .. autoclass:: FisheyeCameraCfg :members: :exclude-members: __init__, func From Files ---------- .. automodule:: omni.isaac.lab.sim.spawners.from_files .. rubric:: Classes .. autosummary:: UrdfFileCfg UsdFileCfg GroundPlaneCfg .. autofunction:: spawn_from_urdf .. autoclass:: UrdfFileCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_from_usd .. autoclass:: UsdFileCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_ground_plane .. autoclass:: GroundPlaneCfg :members: :exclude-members: __init__, func Materials --------- .. automodule:: omni.isaac.lab.sim.spawners.materials .. rubric:: Classes .. autosummary:: VisualMaterialCfg PreviewSurfaceCfg MdlFileCfg GlassMdlCfg PhysicsMaterialCfg RigidBodyMaterialCfg Visual Materials ~~~~~~~~~~~~~~~~ .. autoclass:: VisualMaterialCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_preview_surface .. autoclass:: PreviewSurfaceCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_from_mdl_file .. autoclass:: MdlFileCfg :members: :exclude-members: __init__, func .. autoclass:: GlassMdlCfg :members: :exclude-members: __init__, func Physical Materials ~~~~~~~~~~~~~~~~~~ .. autoclass:: PhysicsMaterialCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_rigid_body_material .. autoclass:: RigidBodyMaterialCfg :members: :exclude-members: __init__, func
3,980
reStructuredText
15.797468
54
0.640704
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.scene.rst
omni.isaac.lab.scene ==================== .. automodule:: omni.isaac.lab.scene .. rubric:: Classes .. autosummary:: InteractiveScene InteractiveSceneCfg interactive Scene ----------------- .. autoclass:: InteractiveScene :members: :undoc-members: :show-inheritance: .. autoclass:: InteractiveSceneCfg :members: :exclude-members: __init__
378
reStructuredText
14.791666
36
0.611111
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.assets.rst
omni.isaac.lab.assets ===================== .. automodule:: omni.isaac.lab.assets .. rubric:: Classes .. autosummary:: AssetBase AssetBaseCfg RigidObject RigidObjectData RigidObjectCfg Articulation ArticulationData ArticulationCfg .. currentmodule:: omni.isaac.lab.assets Asset Base ---------- .. autoclass:: AssetBase :members: .. autoclass:: AssetBaseCfg :members: :exclude-members: __init__, class_type Rigid Object ------------ .. autoclass:: RigidObject :members: :inherited-members: :show-inheritance: .. autoclass:: RigidObjectData :members: :inherited-members: :show-inheritance: :exclude-members: __init__ .. autoclass:: RigidObjectCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Articulation ------------ .. autoclass:: Articulation :members: :inherited-members: :show-inheritance: .. autoclass:: ArticulationData :members: :inherited-members: :show-inheritance: :exclude-members: __init__ .. autoclass:: ArticulationCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
1,216
reStructuredText
16.385714
42
0.634868
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.sensors.rst
omni.isaac.lab.sensors ====================== .. automodule:: omni.isaac.lab.sensors .. rubric:: Submodules .. autosummary:: patterns .. rubric:: Classes .. autosummary:: SensorBase SensorBaseCfg Camera CameraData CameraCfg ContactSensor ContactSensorData ContactSensorCfg FrameTransformer FrameTransformerData FrameTransformerCfg RayCaster RayCasterData RayCasterCfg RayCasterCamera RayCasterCameraCfg TiledCamera TiledCameraCfg Sensor Base ----------- .. autoclass:: SensorBase :members: .. autoclass:: SensorBaseCfg :members: :exclude-members: __init__, class_type USD Camera ---------- .. autoclass:: Camera :members: :inherited-members: :show-inheritance: .. autoclass:: CameraData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: CameraCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Contact Sensor -------------- .. autoclass:: ContactSensor :members: :inherited-members: :show-inheritance: .. autoclass:: ContactSensorData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: ContactSensorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Frame Transformer ----------------- .. autoclass:: FrameTransformer :members: :inherited-members: :show-inheritance: .. autoclass:: FrameTransformerData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: FrameTransformerCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type .. autoclass:: OffsetCfg :members: :inherited-members: :exclude-members: __init__ Ray-Cast Sensor --------------- .. autoclass:: RayCaster :members: :inherited-members: :show-inheritance: .. autoclass:: RayCasterData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: RayCasterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Ray-Cast Camera --------------- .. autoclass:: RayCasterCamera :members: :inherited-members: :show-inheritance: .. autoclass:: RayCasterCameraCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Tiled Rendering --------------- .. autoclass:: TiledCamera :members: :inherited-members: :show-inheritance: .. autoclass:: TiledCameraCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
2,717
reStructuredText
16.649351
42
0.633419
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.envs.mdp.rst
omni.isaac.lab.envs.mdp ======================= .. automodule:: omni.isaac.lab.envs.mdp Observations ------------ .. automodule:: omni.isaac.lab.envs.mdp.observations :members: Actions ------- .. automodule:: omni.isaac.lab.envs.mdp.actions .. automodule:: omni.isaac.lab.envs.mdp.actions.actions_cfg :members: :show-inheritance: :exclude-members: __init__, class_type Events ------ .. automodule:: omni.isaac.lab.envs.mdp.events :members: Commands -------- .. automodule:: omni.isaac.lab.envs.mdp.commands .. automodule:: omni.isaac.lab.envs.mdp.commands.commands_cfg :members: :show-inheritance: :exclude-members: __init__, class_type Rewards ------- .. automodule:: omni.isaac.lab.envs.mdp.rewards :members: Terminations ------------ .. automodule:: omni.isaac.lab.envs.mdp.terminations :members: Curriculum ---------- .. automodule:: omni.isaac.lab.envs.mdp.curriculums :members:
946
reStructuredText
16.218182
61
0.637421
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.sim.rst
omni.isaac.lab.sim ================== .. automodule:: omni.isaac.lab.sim .. rubric:: Submodules .. autosummary:: converters schemas spawners utils .. rubric:: Classes .. autosummary:: SimulationContext SimulationCfg PhysxCfg .. rubric:: Functions .. autosummary:: simulation_context.build_simulation_context Simulation Context ------------------ .. autoclass:: SimulationContext :members: :show-inheritance: Simulation Configuration ------------------------ .. autoclass:: SimulationCfg :members: :show-inheritance: :exclude-members: __init__ .. autoclass:: PhysxCfg :members: :show-inheritance: :exclude-members: __init__ Simulation Context Builder -------------------------- .. automethod:: simulation_context.build_simulation_context Utilities --------- .. automodule:: omni.isaac.lab.sim.utils :members: :show-inheritance:
911
reStructuredText
14.2
59
0.620198
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.sim.schemas.rst
omni.isaac.lab.sim.schemas ========================== .. automodule:: omni.isaac.lab.sim.schemas .. rubric:: Classes .. autosummary:: ArticulationRootPropertiesCfg RigidBodyPropertiesCfg CollisionPropertiesCfg MassPropertiesCfg JointDrivePropertiesCfg FixedTendonPropertiesCfg .. rubric:: Functions .. autosummary:: define_articulation_root_properties modify_articulation_root_properties define_rigid_body_properties modify_rigid_body_properties activate_contact_sensors define_collision_properties modify_collision_properties define_mass_properties modify_mass_properties modify_joint_drive_properties modify_fixed_tendon_properties Articulation Root ----------------- .. autoclass:: ArticulationRootPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_articulation_root_properties .. autofunction:: modify_articulation_root_properties Rigid Body ---------- .. autoclass:: RigidBodyPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_rigid_body_properties .. autofunction:: modify_rigid_body_properties .. autofunction:: activate_contact_sensors Collision --------- .. autoclass:: CollisionPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_collision_properties .. autofunction:: modify_collision_properties Mass ---- .. autoclass:: MassPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_mass_properties .. autofunction:: modify_mass_properties Joint Drive ----------- .. autoclass:: JointDrivePropertiesCfg :members: :exclude-members: __init__ .. autofunction:: modify_joint_drive_properties Fixed Tendon ------------ .. autoclass:: FixedTendonPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: modify_fixed_tendon_properties
1,893
reStructuredText
19.813187
53
0.703117
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.envs.rst
omni.isaac.lab.envs =================== .. automodule:: omni.isaac.lab.envs .. rubric:: Submodules .. autosummary:: mdp ui .. rubric:: Classes .. autosummary:: ManagerBasedEnv ManagerBasedEnvCfg ViewerCfg ManagerBasedRLEnv ManagerBasedRLEnvCfg DirectRLEnv DirectRLEnvCfg Manager Based Environment ------------------------- .. autoclass:: ManagerBasedEnv :members: .. autoclass:: ManagerBasedEnvCfg :members: :exclude-members: __init__, class_type .. autoclass:: ViewerCfg :members: :exclude-members: __init__ Manager Based RL Environment ---------------------------- .. autoclass:: ManagerBasedRLEnv :members: :inherited-members: :show-inheritance: .. autoclass:: ManagerBasedRLEnvCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Direct RL Environment --------------------- .. autoclass:: DirectRLEnv :members: :inherited-members: :show-inheritance: .. autoclass:: DirectRLEnvCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
1,149
reStructuredText
16.424242
42
0.616188
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.envs.ui.rst
omni.isaac.lab.envs.ui ====================== .. automodule:: omni.isaac.lab.envs.ui .. rubric:: Classes .. autosummary:: BaseEnvWindow ManagerBasedRLEnvWindow ViewportCameraController Base Environment UI ------------------- .. autoclass:: BaseEnvWindow :members: Config Based RL Environment UI ------------------------------ .. autoclass:: ManagerBasedRLEnvWindow :members: :show-inheritance: Viewport Camera Controller -------------------------- .. autoclass:: ViewportCameraController :members:
557
reStructuredText
16.437499
39
0.574506
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.sensors.patterns.rst
omni.isaac.lab.sensors.patterns =============================== .. automodule:: omni.isaac.lab.sensors.patterns .. rubric:: Classes .. autosummary:: PatternBaseCfg GridPatternCfg PinholeCameraPatternCfg BpearlPatternCfg Pattern Base ------------ .. autoclass:: PatternBaseCfg :members: :inherited-members: :exclude-members: __init__ Grid Pattern ------------ .. autofunction:: omni.isaac.lab.sensors.patterns.grid_pattern .. autoclass:: GridPatternCfg :members: :inherited-members: :exclude-members: __init__, func Pinhole Camera Pattern ---------------------- .. autofunction:: omni.isaac.lab.sensors.patterns.pinhole_camera_pattern .. autoclass:: PinholeCameraPatternCfg :members: :inherited-members: :exclude-members: __init__, func RS-Bpearl Pattern ----------------- .. autofunction:: omni.isaac.lab.sensors.patterns.bpearl_pattern .. autoclass:: BpearlPatternCfg :members: :inherited-members: :exclude-members: __init__, func
1,016
reStructuredText
18.557692
72
0.641732
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.controllers.rst
omni.isaac.lab.controllers ========================== .. automodule:: omni.isaac.lab.controllers .. rubric:: Classes .. autosummary:: DifferentialIKController DifferentialIKControllerCfg Differential Inverse Kinematics ------------------------------- .. autoclass:: DifferentialIKController :members: :inherited-members: :show-inheritance: .. autoclass:: DifferentialIKControllerCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
519
reStructuredText
18.999999
42
0.639692
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.actuators.rst
omni.isaac.lab.actuators ======================== .. automodule:: omni.isaac.lab.actuators .. rubric:: Classes .. autosummary:: ActuatorBase ActuatorBaseCfg ImplicitActuator ImplicitActuatorCfg IdealPDActuator IdealPDActuatorCfg DCMotor DCMotorCfg ActuatorNetMLP ActuatorNetMLPCfg ActuatorNetLSTM ActuatorNetLSTMCfg Actuator Base ------------- .. autoclass:: ActuatorBase :members: :inherited-members: .. autoclass:: ActuatorBaseCfg :members: :inherited-members: :exclude-members: __init__, class_type Implicit Actuator ----------------- .. autoclass:: ImplicitActuator :members: :inherited-members: :show-inheritance: .. autoclass:: ImplicitActuatorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Ideal PD Actuator ----------------- .. autoclass:: IdealPDActuator :members: :inherited-members: :show-inheritance: .. autoclass:: IdealPDActuatorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type DC Motor Actuator ----------------- .. autoclass:: DCMotor :members: :inherited-members: :show-inheritance: .. autoclass:: DCMotorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type MLP Network Actuator --------------------- .. autoclass:: ActuatorNetMLP :members: :inherited-members: :show-inheritance: .. autoclass:: ActuatorNetMLPCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type LSTM Network Actuator --------------------- .. autoclass:: ActuatorNetLSTM :members: :inherited-members: :show-inheritance: .. autoclass:: ActuatorNetLSTMCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
1,847
reStructuredText
16.6
40
0.659989
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.app.rst
omni.isaac.lab.app ================== .. automodule:: omni.isaac.lab.app .. rubric:: Classes .. autosummary:: AppLauncher Environment variables --------------------- The following details the behavior of the class based on the environment variables: * **Headless mode**: If the environment variable ``HEADLESS=1``, then SimulationApp will be started in headless mode. If ``LIVESTREAM={1,2}``, then it will supersede the ``HEADLESS`` envvar and force headlessness. * ``HEADLESS=1`` causes the app to run in headless mode. * **Livestreaming**: If the environment variable ``LIVESTREAM={1,2}`` , then `livestream`_ is enabled. Any of the livestream modes being true forces the app to run in headless mode. * ``LIVESTREAM=1`` enables streaming via the Isaac `Native Livestream`_ extension. This allows users to connect through the Omniverse Streaming Client. * ``LIVESTREAM=2`` enables streaming via the `WebRTC Livestream`_ extension. This allows users to connect in a browser using the WebRTC protocol. * **Enable cameras**: If the environment variable ``ENABLE_CAMERAS`` is set to 1, then the cameras are enabled. This is useful for running the simulator without a GUI but still rendering the viewport and camera images. * ``ENABLE_CAMERAS=1``: Enables the offscreen-render pipeline which allows users to render the scene without launching a GUI. .. note:: The off-screen rendering pipeline only works when used in conjunction with the :class:`omni.isaac.lab.sim.SimulationContext` class. This is because the off-screen rendering pipeline enables flags that are internally used by the SimulationContext class. To set the environment variables, one can use the following command in the terminal: .. code:: bash export REMOTE_DEPLOYMENT=3 export ENABLE_CAMERAS=1 # run the python script ./isaaclab.sh -p source/standalone/demo/play_quadrupeds.py Alternatively, one can set the environment variables to the python script directly: .. code:: bash REMOTE_DEPLOYMENT=3 ENABLE_CAMERAS=1 ./isaaclab.sh -p source/standalone/demo/play_quadrupeds.py Overriding the environment variables ------------------------------------ The environment variables can be overridden in the python script itself using the :class:`AppLauncher`. These can be passed as a dictionary, a :class:`argparse.Namespace` object or as keyword arguments. When the passed arguments are not the default values, then they override the environment variables. The following snippet shows how use the :class:`AppLauncher` in different ways: .. code:: python import argparser from omni.isaac.lab.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser() # add your own arguments # .... # add app launcher arguments for cli AppLauncher.add_app_launcher_args(parser) # parse arguments args = parser.parse_args() # launch omniverse isaac-sim app # -- Option 1: Pass the settings as a Namespace object app_launcher = AppLauncher(args).app # -- Option 2: Pass the settings as keywords arguments app_launcher = AppLauncher(headless=args.headless, livestream=args.livestream) # -- Option 3: Pass the settings as a dictionary app_launcher = AppLauncher(vars(args)) # -- Option 4: Pass no settings app_launcher = AppLauncher() # obtain the launched app simulation_app = app_launcher.app Simulation App Launcher ----------------------- .. autoclass:: AppLauncher :members: .. _livestream: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html .. _`Native Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-kit-remote .. _`Websocket Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-livestream-webrtc .. _`WebRTC Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-livestream-websocket
4,077
reStructuredText
36.072727
152
0.730684
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.markers.rst
omni.isaac.lab.markers ====================== .. automodule:: omni.isaac.lab.markers .. rubric:: Classes .. autosummary:: VisualizationMarkers VisualizationMarkersCfg Visualization Markers --------------------- .. autoclass:: VisualizationMarkers :members: :undoc-members: :show-inheritance: .. autoclass:: VisualizationMarkersCfg :members: :exclude-members: __init__
408
reStructuredText
16.041666
38
0.625
isaac-sim/IsaacLab/docs/source/api/lab/omni.isaac.lab.terrains.rst
omni.isaac.lab.terrains ======================= .. automodule:: omni.isaac.lab.terrains .. rubric:: Classes .. autosummary:: TerrainImporter TerrainImporterCfg TerrainGenerator TerrainGeneratorCfg SubTerrainBaseCfg Terrain importer ---------------- .. autoclass:: TerrainImporter :members: :show-inheritance: .. autoclass:: TerrainImporterCfg :members: :exclude-members: __init__, class_type Terrain generator ----------------- .. autoclass:: TerrainGenerator :members: .. autoclass:: TerrainGeneratorCfg :members: :exclude-members: __init__ .. autoclass:: SubTerrainBaseCfg :members: :exclude-members: __init__ Height fields ------------- .. automodule:: omni.isaac.lab.terrains.height_field All sub-terrains must inherit from the :class:`HfTerrainBaseCfg` class which contains the common parameters for all terrains generated from height fields. .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfTerrainBaseCfg :members: :show-inheritance: :exclude-members: __init__, function Random Uniform Terrain ^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.height_field.hf_terrains.random_uniform_terrain .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfRandomUniformTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pyramid Sloped Terrain ^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.height_field.hf_terrains.pyramid_sloped_terrain .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfPyramidSlopedTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidSlopedTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pyramid Stairs Terrain ^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.height_field.hf_terrains.pyramid_stairs_terrain .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Discrete Obstacles Terrain ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.height_field.hf_terrains.discrete_obstacles_terrain .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfDiscreteObstaclesTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Wave Terrain ^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.height_field.hf_terrains.wave_terrain .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfWaveTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Stepping Stones Terrain ^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.height_field.hf_terrains.stepping_stones_terrain .. autoclass:: omni.isaac.lab.terrains.height_field.hf_terrains_cfg.HfSteppingStonesTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Trimesh terrains ---------------- .. automodule:: omni.isaac.lab.terrains.trimesh Flat terrain ^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.flat_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshPlaneTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pyramid terrain ^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.pyramid_stairs_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Inverted pyramid terrain ^^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.inverted_pyramid_stairs_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshInvertedPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Random grid terrain ^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.random_grid_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshRandomGridTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Rails terrain ^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.rails_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshRailsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pit terrain ^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.pit_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshPitTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Box terrain ^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.box_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshBoxTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Gap terrain ^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.gap_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshGapTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Floating ring terrain ^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.floating_ring_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshFloatingRingTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Star terrain ^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.star_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshStarTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Repeated Objects Terrain ^^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.lab.terrains.trimesh.mesh_terrains.repeated_objects_terrain .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedObjectsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedPyramidsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedBoxesTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.lab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedCylindersTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Utilities --------- .. automodule:: omni.isaac.lab.terrains.utils :members: :undoc-members:
7,144
reStructuredText
26.270992
101
0.703807
isaac-sim/IsaacLab/docs/source/api/lab_tasks/omni.isaac.lab_tasks.utils.data_collector.rst
omni.isaac.lab_tasks.utils.data_collector ========================================= .. automodule:: omni.isaac.lab_tasks.utils.data_collector .. Rubric:: Classes .. autosummary:: RobomimicDataCollector Robomimic Data Collector ------------------------ .. autoclass:: RobomimicDataCollector :members: :show-inheritance:
350
reStructuredText
18.499999
57
0.574286
isaac-sim/IsaacLab/docs/source/api/lab_tasks/omni.isaac.lab_tasks.utils.wrappers.rst
omni.isaac.lab_tasks.utils.wrappers =================================== .. automodule:: omni.isaac.lab_tasks.utils.wrappers RL-Games Wrapper ---------------- .. automodule:: omni.isaac.lab_tasks.utils.wrappers.rl_games :members: :show-inheritance: RSL-RL Wrapper -------------- .. automodule:: omni.isaac.lab_tasks.utils.wrappers.rsl_rl :members: :imported-members: :show-inheritance: SKRL Wrapper ------------ .. automodule:: omni.isaac.lab_tasks.utils.wrappers.skrl :members: :show-inheritance: Stable-Baselines3 Wrapper ------------------------- .. automodule:: omni.isaac.lab_tasks.utils.wrappers.sb3 :members: :show-inheritance:
671
reStructuredText
18.764705
60
0.614009
isaac-sim/IsaacLab/docs/source/api/lab_tasks/omni.isaac.lab_tasks.utils.rst
omni.isaac.lab_tasks.utils ========================== .. automodule:: omni.isaac.lab_tasks.utils :members: :imported-members: .. rubric:: Submodules .. autosummary:: data_collector wrappers
219
reStructuredText
14.714285
42
0.56621
isaac-sim/IsaacLab/docs/source/features/multi_gpu.rst
Multi-GPU and Multi-Node Training ================================= .. currentmodule:: omni.isaac.lab Isaac Lab supports multi-GPU and multi-node reinforcement learning on Linux. Multi-GPU Training ------------------ For complex reinforcement learning environments, it may be desirable to scale up training across multiple GPUs. This is possible in Isaac Lab with the ``rl_games`` RL library through the use of the `PyTorch distributed <https://pytorch.org/docs/stable/distributed.html>`_ framework. In this workflow, ``torch.distributed`` is used to launch multiple processes of training, where the number of processes must be equal to or less than the number of GPUs available. Each process runs on a dedicated GPU and launches its own instance of Isaac Sim and the Isaac Lab environment. Each process collects its own rollouts during the training process and has its own copy of the policy network. During training, gradients are aggregated across the processes and broadcasted back to the process at the end of the epoch. .. image:: ../_static/multigpu.png :align: center :alt: Multi-GPU training paradigm To train with multiple GPUs, use the following command, where ``--proc_per_node`` represents the number of available GPUs: .. code-block:: shell python -m torch.distributed.run --nnodes=1 --nproc_per_node=2 source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 --headless --distributed Due to limitations of NCCL on Windows, this feature is currently supported on Linux only. Multi-Node Training ------------------- To scale up training beyond multiple GPUs on a single machine, it is also possible to train across multiple nodes. To train across multiple nodes/machines, it is required to launch an individual process on each node. For the master node, use the following command, where ``--proc_per_node`` represents the number of available GPUs, and ``--nnodes`` represents the number of nodes: .. code-block:: shell python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=0 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=localhost:5555 source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 --headless --distributed Note that the port (``5555``) can be replaced with any other available port. For non-master nodes, use the following command, replacing ``--node_rank`` with the index of each machine: .. code-block:: shell python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=1 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=ip_of_master_machine:5555 source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 --headless --distributed For more details on multi-node training with PyTorch, please visit the `PyTorch documentation <https://pytorch.org/tutorials/intermediate/ddp_series_multinode.html>`_. As mentioned in the PyTorch documentation, "multinode training is bottlenecked by inter-node communication latencies". When this latency is high, it is possible multi-node training will perform worse than running on a single node instance. Due to limitations of NCCL on Windows, this feature is currently supported on Linux only.
3,178
reStructuredText
52.881355
407
0.758024
isaac-sim/IsaacLab/docs/source/features/actuators.rst
.. _feature-actuators: Actuators ========= An articulated system comprises of actuated joints, also called the degrees of freedom (DOF). In a physical system, the actuation typically happens either through active components, such as electric or hydraulic motors, or passive components, such as springs. These components can introduce certain non-linear characteristics which includes delays or maximum producible velocity or torque. In simulation, the joints are either position, velocity, or torque-controlled. For position and velocity control, the physics engine internally implements a spring-damp (PD) controller which computes the torques applied on the actuated joints. In torque-control, the commands are set directly as the joint efforts. While this mimics an ideal behavior of the joint mechanism, it does not truly model how the drives work in the physical world. Thus, we provide a mechanism to inject external models to compute the joint commands that would represent the physical robot's behavior. Actuator models --------------- We name two different types of actuator models: 1. **implicit**: corresponds to the ideal simulation mechanism (provided by physics engine). 2. **explicit**: corresponds to external drive models (implemented by user). The explicit actuator model performs two steps: 1) it computes the desired joint torques for tracking the input commands, and 2) it clips the desired torques based on the motor capabilities. The clipped torques are the desired actuation efforts that are set into the simulation. As an example of an ideal explicit actuator model, we provide the :class:`omni.isaac.lab.actuators.IdealPDActuator` class, which implements a PD controller with feed-forward effort, and simple clipping based on the configured maximum effort: .. math:: \tau_{j, computed} & = k_p * (q - q_{des}) + k_d * (\dot{q} - \dot{q}_{des}) + \tau_{ff} \\ \tau_{j, applied} & = clip(\tau_{computed}, -\tau_{j, max}, \tau_{j, max}) where, :math:`k_p` and :math:`k_d` are joint stiffness and damping gains, :math:`q` and :math:`\dot{q}` are the current joint positions and velocities, :math:`q_{des}`, :math:`\dot{q}_{des}` and :math:`\tau_{ff}` are the desired joint positions, velocities and torques commands. The parameters :math:`\gamma` and :math:`\tau_{motor, max}` are the gear box ratio and the maximum motor effort possible. Actuator groups --------------- The actuator models by themselves are computational blocks that take as inputs the desired joint commands and output the the joint commands to apply into the simulator. They do not contain any knowledge about the joints they are acting on themselves. These are handled by the :class:`omni.isaac.lab.assets.Articulation` class, which wraps around the physics engine's articulation class. Actuator are collected as a set of actuated joints on an articulation that are using the same actuator model. For instance, the quadruped, ANYmal-C, uses series elastic actuator, ANYdrive 3.0, for all its joints. This grouping configures the actuator model for those joints, translates the input commands to the joint level commands, and returns the articulation action to set into the simulator. Having an arm with a different actuator model, such as a DC motor, would require configuring a different actuator group. The following figure shows the actuator groups for a legged mobile manipulator: .. image:: ../_static/actuator_groups.svg :width: 600 :align: center :alt: Actuator groups for a legged mobile manipulator .. seealso:: We provide implementations for various explicit actuator models. These are detailed in `omni.isaac.lab.actuators <../api/lab.actuators.html>`_ sub-package.
3,719
reStructuredText
51.394365
115
0.763377
isaac-sim/IsaacLab/docs/source/features/motion_generators.rst
Motion Generators ================= Robotic tasks are typically defined in task-space in terms of desired end-effector trajectory, while control actions are executed in the joint-space. This naturally leads to *joint-space* and *task-space* (operational-space) control methods. However, successful execution of interaction tasks using motion control often requires an accurate model of both the robot manipulator as well as its environment. While a sufficiently precise manipulator's model might be known, detailed description of environment is hard to obtain :cite:p:`siciliano2009force`. Planning errors caused by this mismatch can be overcome by introducing a *compliant* behavior during interaction. While compliance is achievable passively through robot's structure (such as elastic actuators, soft robot arms), we are more interested in controller designs that focus on active interaction control. These are broadly categorized into: 1. **impedance control:** indirect control method where motion deviations caused during interaction relates to contact force as a mass-spring-damper system with adjustable parameters (stiffness and damping). A specialized case of this is *stiffness* control where only the static relationship between position error and contact force is considered. 2. **hybrid force/motion control:** active control method which controls motion and force along unconstrained and constrained task directions respectively. Among the various schemes for hybrid motion control, the provided implementation is based on inverse dynamics control in the operational space :cite:p:`khatib1987osc`. .. note:: To provide an even broader set of motion generators, we welcome contributions from the community. If you are interested, please open an issue to start a discussion! Joint-space controllers ----------------------- Torque control ~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In torque control mode, the input actions are directly set as feed-forward joint torque commands, i.e. at every time-step, .. math:: \tau = \tau_{des} Thus, this control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"t_abs"``. Velocity control ~~~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In velocity control mode, a proportional control law is required to reduce the error between the current and desired joint velocities. Based on input actions, the joint torques commands are computed as: .. math:: \tau = k_d (\dot{q}_{des} - \dot{q}) where :math:`k_d` are the gains parsed from configuration. This control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"v_abs"`` or ``"v_rel"``. .. attention:: While performing velocity control, in many cases, gravity compensation is required to ensure better tracking of the command. In this case, we suggest disabling gravity for the links in the articulation in simulation. Position control with fixed impedance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In position control mode, a proportional-damping (PD) control law is employed to track the desired joint positions and ensuring the articulation remains still at the desired location (i.e., desired joint velocities are zero). Based on the input actions, the joint torque commands are computed as: .. math:: \tau = k_p (q_{des} - q) - k_d \dot{q} where :math:`k_p` and :math:`k_d` are the gains parsed from configuration. In its simplest above form, the control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"p_abs"`` or ``"p_rel"``. However, a more complete formulation which considers the dynamics of the articulation would be: .. math:: \tau = M \left( k_p (q_{des} - q) - k_d \dot{q} \right) + g where :math:`M` is the joint-space inertia matrix of size :math:`n \times n`, and :math:`g` is the joint-space gravity vector. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"fixed"``. The gains :math:`k_p` are parsed from the input configuration and :math:`k_d` are computed while considering the system as a decoupled point-mass oscillator, i.e., .. math:: k_d = 2 \sqrt{k_p} \times D where :math:`D` is the damping ratio of the system. Critical damping is achieved for :math:`D = 1`, overcritical damping for :math:`D > 1` and undercritical damping for :math:`D < 1`. Additionally, it is possible to disable the inertial or gravity compensation in the controller by setting the flags :attr:`inertial_compensation` and :attr:`gravity_compensation` in the configuration to :obj:`False`, respectively. Position control with variable stiffness ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"2n"`` (number of joints) In stiffness control, the same formulation as above is employed, however, the gains :math:`k_p` are part of the input commands. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"variable_kp"``. Position control with variable impedance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"3n"`` (number of joints) In impedance control, the same formulation as above is employed, however, both :math:`k_p` and :math:`k_d` are part of the input commands. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"variable"``. Task-space controllers ---------------------- Differential inverse kinematics (IK) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"3"`` (relative/absolute position), ``"6"`` (relative pose), or ``"7"`` (absolute pose) Inverse kinematics converts the task-space tracking error to joint-space error. In its most typical implementation, the pose error in the task-sace, :math:`\Delta \chi_e = (\Delta p_e, \Delta \phi_e)`, is computed as the cartesian distance between the desired and current task-space positions, and the shortest distance in :math:`\mathbb{SO}(3)` between the desired and current task-space orientations. Using the geometric Jacobian :math:`J_{eO} \in \mathbb{R}^{6 \times n}`, that relates task-space velocity to joint-space velocities, we design the control law to obtain the desired joint positions as: .. math:: q_{des} = q + \eta J_{eO}^{-} \Delta \chi_e where :math:`\eta` is a scaling parameter and :math:`J_{eO}^{-}` is the pseudo-inverse of the Jacobian. It is possible to compute the pseudo-inverse of the Jacobian using different formulations: * Moore-Penrose pseduo-inverse: :math:`A^{-} = A^T(AA^T)^{-1}`. * Levenberg-Marquardt pseduo-inverse (damped least-squares): :math:`A^{-} = A^T (AA^T + \lambda \mathbb{I})^{-1}`. * Tanspose pseudo-inverse: :math:`A^{-} = A^T`. * Adaptive singular-vale decomposition (SVD) pseduo-inverse from :cite:t:`buss2004ik`. These implementations are available through the :class:`DifferentialInverseKinematics` class. Impedance controller ~~~~~~~~~~~~~~~~~~~~ It uses task-space pose error and Jacobian to compute join torques through mass-spring-damper system with a) fixed stiffness, b) variable stiffness (stiffness control), and c) variable stiffness and damping (impedance control). Operational-space controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Similar to task-space impedance control but uses the Equation of Motion (EoM) for computing the task-space force Closed-loop proportional force controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It uses a proportional term to track the desired wrench command with respect to current wrench at the end-effector. Hybrid force-motion controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It combines closed-loop force control and operational-space motion control to compute the desired wrench at the end-effector. It uses selection matrices that define the unconstrainted and constrained task directions. Reactive planners ----------------- Typical task-space controllers do not account for motion constraints such as joint limits, self-collision and environment collision. Instead they rely on high-level planners (such as RRT) to handle these non-Euclidean constraints and give joint/task-space way-points to the controller. However, these methods are often conservative and have undesirable deceleration when close to an object. More recently, different approaches combine the constraints directly into an optimization problem, thereby providing a holistic solution for motion generation and control. We currently support the following planners: - **RMPFlow (lula):** An acceleration-based policy that composes various Reimannian Motion Policies (RMPs) to solve a hierarchy of tasks :cite:p:`cheng2021rmpflow`. It is capable of performing dynamic collision avoidance while navigating the end-effector to a target. - **MPC (OCS2):** A receding horizon control policy based on sequential linear-quadratic (SLQ) programming. It formulates various constraints into a single optimization problem via soft-penalties and uses automatic differentiation to compute derivatives of the system dynamics, constraints and costs. Currently, we support the MPC formulation for end-effector trajectory tracking in fixed-arm and mobile manipulators. The formulation considers a kinematic system model with joint limits and self-collision avoidance :cite:p:`mittal2021articulated`. .. warning:: We wrap around the python bindings for these reactive planners to perform a batched computing of robot actions. However, their current implementations are CPU-based which may cause certain slowdown for learning.
9,828
reStructuredText
41.734782
132
0.737993
isaac-sim/IsaacLab/docs/source/features/workflows.rst
.. _feature-workflows: Task Design Workflows ===================== .. currentmodule:: omni.isaac.lab Reinforcement learning environments can be implemented using two different workflows: Manager-based and Direct. This page outlines the two workflows, explaining their benefits and usecases. In addition, multi-GPU and multi-node reinforcement learning support is explained, along with the tiled rendering API, which can be used for efficient vectorized rendering across environments. Manager-Based Environments -------------------------- Manager-based environments promote modular implementations of reinforcement learning tasks through the use of Managers. Each component of the task, such as rewards, observations, termination can all be specified as individual configuration classes that are then passed to the corresponding manager classes. Each manager is responsible for parsing the configurations and processing the contents specified in each config class. The manager implementations are taken care of by the base class :class:`envs.ManagerBasedRLEnv`. With this approach, it is simple to switch implementations of some components in the task while leaving the remaining of the code intact. This is desirable when collaborating with others on implementing a reinforcement learning environment, where contributors may choose to use different combinations of configurations for the reinforcement learning components of the task. A class definition of a manager-based environment consists of defining a task configuration class that inherits from :class:`envs.ManagerBasedRLEnvCfg`. This class should contain variables assigned to various configuration classes for each of the components of the RL task, such as the ``ObservationCfg`` or ``RewardCfg``. The entry point of the environment becomes the base class :class:`envs.ManagerBasedRLEnv`, which will process the main task config and iterate through the individual configuration classes that are defined in the task config class. An example of implementing the reward function for the Cartpole task using the manager-based implementation is as follow: .. code-block:: python @configclass class RewardsCfg: """Reward terms for the MDP.""" # (1) Constant running reward alive = RewTerm(func=mdp.is_alive, weight=1.0) # (2) Failure penalty terminating = RewTerm(func=mdp.is_terminated, weight=-2.0) # (3) Primary task: keep pole upright pole_pos = RewTerm( func=mdp.joint_pos_target_l2, weight=-1.0, params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), "target": 0.0}, ) # (4) Shaping tasks: lower cart velocity cart_vel = RewTerm( func=mdp.joint_vel_l1, weight=-0.01, params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"])}, ) # (5) Shaping tasks: lower pole angular velocity pole_vel = RewTerm( func=mdp.joint_vel_l1, weight=-0.005, params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])}, ) .. seealso:: We provide a more detailed tutorial for setting up a RL environment using the manager-based workflow at `Creating a manager-based RL Environment <../tutorials/03_envs/create_rl_env.html>`_. Direct Environments ------------------- The direct-style environment more closely aligns with traditional implementations of reinforcement learning environments, where a single script implements the reward function, observation function, resets, and all other components of the environment. This approach does not use the Manager classes. Instead, users are left with the freedom to implement the APIs from the base class :class:`envs.DirectRLEnv`. For users migrating from the IsaacGymEnvs or OmniIsaacGymEnvs framework, this workflow will have a closer implementation to the previous frameworks. When defining an environment following the direct-style implementation, a task configuration class inheriting from :class:`envs.DirectRLEnvCfg` is used for defining task environment configuration variables, such as the number of observations and actions. Adding configuration classes for the managers are not required and will not be processed by the base class. In addition to the configuration class, the logic of the task should be defined in a new task class that inherits from the base class :class:`envs.DirectRLEnv`. This class will then implement the main task logics, including setting up the scene, processing the actions, computing resets, rewards, and observations. This approach may bring more performance benefits for the environment, as it allows implementing large chunks of logic with optimized frameworks such as `PyTorch Jit <https://pytorch.org/docs/stable/jit.html>`_ or `Warp <https://github.com/NVIDIA/warp>`_. This may be important when scaling up training for large and complex environments. Additionally, data may be cached in class variables and reused in multiple APIs for the class. This method provides more transparency in the implementations of the environments, as logic is defined within the task class instead of abstracted with the use the Managers. An example of implementing the reward function for the Cartpole task using the Direct-style implementation is as follow: .. code-block:: python def _get_rewards(self) -> torch.Tensor: total_reward = compute_rewards( self.cfg.rew_scale_alive, self.cfg.rew_scale_terminated, self.cfg.rew_scale_pole_pos, self.cfg.rew_scale_cart_vel, self.cfg.rew_scale_pole_vel, self.joint_pos[:, self._pole_dof_idx[0]], self.joint_vel[:, self._pole_dof_idx[0]], self.joint_pos[:, self._cart_dof_idx[0]], self.joint_vel[:, self._cart_dof_idx[0]], self.reset_terminated, ) return total_reward @torch.jit.script def compute_rewards( rew_scale_alive: float, rew_scale_terminated: float, rew_scale_pole_pos: float, rew_scale_cart_vel: float, rew_scale_pole_vel: float, pole_pos: torch.Tensor, pole_vel: torch.Tensor, cart_pos: torch.Tensor, cart_vel: torch.Tensor, reset_terminated: torch.Tensor, ): rew_alive = rew_scale_alive * (1.0 - reset_terminated.float()) rew_termination = rew_scale_terminated * reset_terminated.float() rew_pole_pos = rew_scale_pole_pos * torch.sum(torch.square(pole_pos), dim=-1) rew_cart_vel = rew_scale_cart_vel * torch.sum(torch.abs(cart_vel), dim=-1) rew_pole_vel = rew_scale_pole_vel * torch.sum(torch.abs(pole_vel), dim=-1) total_reward = rew_alive + rew_termination + rew_pole_pos + rew_cart_vel + rew_pole_vel return total_reward .. seealso:: We provide a more detailed tutorial for setting up a RL environment using the direct workflow at `Creating a Direct Workflow RL Environment <../tutorials/03_envs/create_direct_rl_env.html>`_. Multi-GPU Training ------------------ For complex reinforcement learning environments, it may be desirable to scale up training across multiple GPUs. This is possible in Isaac Lab with the ``rl_games`` RL library through the use of the `PyTorch distributed <https://pytorch.org/docs/stable/distributed.html>`_ framework. In this workflow, ``torch.distributed`` is used to launch multiple processes of training, where the number of processes must be equal to or less than the number of GPUs available. Each process runs on a dedicated GPU and launches its own instance of Isaac Sim and the Isaac Lab environment. Each process collects its own rollouts during the training process and has its own copy of the policy network. During training, gradients are aggregated across the processes and broadcasted back to the process at the end of the epoch. .. image:: ../_static/multigpu.png :align: center :alt: Multi-GPU training paradigm To train with multiple GPUs, use the following command, where ``--proc_per_node`` represents the number of available GPUs: .. code-block:: shell python -m torch.distributed.run --nnodes=1 --nproc_per_node=2 source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 --headless --distributed Multi-Node Training ------------------- To scale up training beyond multiple GPUs on a single machine, it is also possible to train across multiple nodes. To train across multiple nodes/machines, it is required to launch an individual process on each node. For the master node, use the following command, where ``--proc_per_node`` represents the number of available GPUs, and ``--nnodes`` represents the number of nodes: .. code-block:: shell python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=0 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=localhost:5555 source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 --headless --distributed Note that the port (``5555``) can be replaced with any other available port. For non-master nodes, use the following command, replacing ``--node_rank`` with the index of each machine: .. code-block:: shell python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=1 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=ip_of_master_machine:5555 source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 --headless --distributed For more details on multi-node training with PyTorch, please visit the `PyTorch documentation <https://pytorch.org/tutorials/intermediate/ddp_series_multinode.html>`_. As mentioned in the PyTorch documentation, "multinode training is bottlenecked by inter-node communication latencies". When this latency is high, it is possible multi-node training will perform worse than running on a single node instance. Tiled Rendering --------------- Tiled rendering APIs provide a vectorized interface for collecting data from camera sensors. This is useful for reinforcement learning environments requiring vision in the loop. Tiled rendering works by concatenating camera outputs from multiple cameras and rending one single large image instead of multiple smaller images that would have been produced by each individual camera. This reduces the amount of time required for rendering and provides a more efficient API for working with vision data. Isaac Lab provides tiled rendering APIs for RGB and depth data through the :class:`~sensors.TiledCamera` class. Configurations for the tiled rendering APIs can be defined through the :class:`~sensors.TiledCameraCfg` class, specifying parameters such as the regex expression for all camera paths, the transform for the cameras, the desired data type, the type of cameras to add to the scene, and the camera resolution. .. code-block:: python tiled_camera: TiledCameraCfg = TiledCameraCfg( prim_path="/World/envs/env_.*/Camera", offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), data_types=["rgb"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) ), width=80, height=80, ) To access the tiled rendering interface, a :class:`~sensors.TiledCamera` object can be created and used to retrieve data from the cameras. .. code-block:: python tiled_camera = TiledCamera(cfg.tiled_camera) data_type = "rgb" data = tiled_camera.data.output[data_type] The returned data will be transformed into the shape (num_cameras, height, width, num_channels), which can be used directly as observation for reinforcement learning. When working with rendering, make sure to add the ``--enable_cameras`` argument when launching the environment. For example: .. code-block:: shell python source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-RGB-Camera-Direct-v0 --headless --enable_cameras
12,063
reStructuredText
49.476987
407
0.735555
isaac-sim/IsaacLab/docs/source/features/tiled_rendering.rst
Tiled Rendering and Recording ============================= .. currentmodule:: omni.isaac.lab Tiled Rendering --------------- .. note:: This feature is only available from Isaac Sim version 4.0.0. Tiled rendering APIs provide a vectorized interface for collecting data from camera sensors. This is useful for reinforcement learning environments requiring vision in the loop. Tiled rendering works by concatenating camera outputs from multiple cameras and rendering one single large image instead of multiple smaller images that would have been produced by each individual camera. This reduces the amount of time required for rendering and provides a more efficient API for working with vision data. Isaac Lab provides tiled rendering APIs for RGB and depth data through the :class:`~sensors.TiledCamera` class. Configurations for the tiled rendering APIs can be defined through the :class:`~sensors.TiledCameraCfg` class, specifying parameters such as the regex expression for all camera paths, the transform for the cameras, the desired data type, the type of cameras to add to the scene, and the camera resolution. .. code-block:: python tiled_camera: TiledCameraCfg = TiledCameraCfg( prim_path="/World/envs/env_.*/Camera", offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), data_types=["rgb"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) ), width=80, height=80, ) To access the tiled rendering interface, a :class:`~sensors.TiledCamera` object can be created and used to retrieve data from the cameras. .. code-block:: python tiled_camera = TiledCamera(cfg.tiled_camera) data_type = "rgb" data = tiled_camera.data.output[data_type] The returned data will be transformed into the shape (num_cameras, height, width, num_channels), which can be used directly as observation for reinforcement learning. When working with rendering, make sure to add the ``--enable_cameras`` argument when launching the environment. For example: .. code-block:: shell python source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-RGB-Camera-Direct-v0 --headless --enable_cameras Recording during training ------------------------- Isaac Lab supports recording video clips during training using the `gymnasium.wrappers.RecordVideo <https://gymnasium.farama.org/main/_modules/gymnasium/wrappers/record_video/>`_ class. This feature can be enabled by using the following command line arguments with the training script: * ``--video`` - enables video recording during training * ``--video_length`` - length of each recorded video (in steps) * ``--video_interval`` - interval between each video recording (in steps) Make sure to also add the ``--enable_cameras`` argument when running headless. Note that enabling recording is equivalent to enabling rendering during training, which will slow down both startup and runtime performance. Example usage: .. code-block:: shell python source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-v0 --headless --enable_cameras --video --video_length 100 --video_interval 500 Recorded videos will be saved in the same directory as the training checkpoints, under ``IsaacLab/logs/<rl_workflow>/<task>/<run>/videos``.
3,424
reStructuredText
41.28395
185
0.740362
isaac-sim/IsaacLab/docs/source/features/environments.rst
Environments ============ The following lists comprises of all the RL tasks implementations that are available in Isaac Lab. While we try to keep this list up-to-date, you can always get the latest list of environments by running the following command: .. code-block:: bash ./isaaclab.sh -p source/standalone/environments/list_envs.py We are actively working on adding more environments to the list. If you have any environments that you would like to add to Isaac Lab, please feel free to open a pull request! Classic ------- Classic environments that are based on IsaacGymEnvs implementation of MuJoCo-style environments. .. table:: :widths: 33 37 30 +------------------+-----------------------------+-------------------------------------------------------------------------+ | World | Environment ID | Description | +==================+=============================+=========================================================================+ | |humanoid| | | |humanoid-link| | Move towards a direction with the MuJoCo humanoid robot | | | | |humanoid-direct-link| | | +------------------+-----------------------------+-------------------------------------------------------------------------+ | |ant| | | |ant-link| | Move towards a direction with the MuJoCo ant robot | | | | |ant-direct-link| | | +------------------+-----------------------------+-------------------------------------------------------------------------+ | |cartpole| | | |cartpole-link| | Move the cart to keep the pole upwards in the classic cartpole control | | | | |cartpole-direct-link| | | | | | |cartpole-camera-rgb-link|| | | | | |cartpole-camera-dpt-link|| | +------------------+-----------------------------+-------------------------------------------------------------------------+ .. |humanoid| image:: ../_static/tasks/classic/humanoid.jpg .. |ant| image:: ../_static/tasks/classic/ant.jpg .. |cartpole| image:: ../_static/tasks/classic/cartpole.jpg .. |humanoid-link| replace:: `Isaac-Humanoid-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py>`__ .. |ant-link| replace:: `Isaac-Ant-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/ant_env_cfg.py>`__ .. |cartpole-link| replace:: `Isaac-Cartpole-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py>`__ .. |humanoid-direct-link| replace:: `Isaac-Humanoid-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/humanoid/humanoid_env.py>`__ .. |ant-direct-link| replace:: `Isaac-Ant-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/ant/ant_env.py>`__ .. |cartpole-direct-link| replace:: `Isaac-Cartpole-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py>`__ .. |cartpole-camera-rgb-link| replace:: `Isaac-Cartpole-RGB-Camera-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_camera_env.py>`__ .. |cartpole-camera-dpt-link| replace:: `Isaac-Cartpole-Depth-Camera-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_camera_env.py>`__ Manipulation ------------ Environments based on fixed-arm manipulation tasks. For many of these tasks, we include configurations with different arm action spaces. For example, for the reach environment: * |lift-cube-link|: Franka arm with joint position control * |lift-cube-ik-abs-link|: Franka arm with absolute IK control * |lift-cube-ik-rel-link|: Franka arm with relative IK control .. table:: :widths: 33 37 30 +----------------+---------------------------+-----------------------------------------------------------------------------+ | World | Environment ID | Description | +================+===========================+=============================================================================+ | |reach-franka| | |reach-franka-link| | Move the end-effector to a sampled target pose with the Franka robot | +----------------+---------------------------+-----------------------------------------------------------------------------+ | |reach-ur10| | |reach-ur10-link| | Move the end-effector to a sampled target pose with the UR10 robot | +----------------+---------------------------+-----------------------------------------------------------------------------+ | |lift-cube| | |lift-cube-link| | Pick a cube and bring it to a sampled target position with the Franka robot | +----------------+---------------------------+-----------------------------------------------------------------------------+ | |cabi-franka| | |cabi-franka-link| | Grasp the handle of a cabinet's drawer and open it with the Franka robot | +----------------+---------------------------+-----------------------------------------------------------------------------+ | |cube-allegro| | |cube-allegro-link| | In-hand reorientation of a cube using Allegro hand | +----------------+---------------------------+-----------------------------------------------------------------------------+ | |cube-shadow| | | |cube-shadow-link| | In-hand reorientation of a cube using Shadow hand | | | | |cube-shadow-ff-link| | | | | | |cube-shadow-lstm-link| | | +----------------+---------------------------+-----------------------------------------------------------------------------+ .. |reach-franka| image:: ../_static/tasks/manipulation/franka_reach.jpg .. |reach-ur10| image:: ../_static/tasks/manipulation/ur10_reach.jpg .. |lift-cube| image:: ../_static/tasks/manipulation/franka_lift.jpg .. |cabi-franka| image:: ../_static/tasks/manipulation/franka_open_drawer.jpg .. |cube-allegro| image:: ../_static/tasks/manipulation/allegro_cube.jpg .. |cube-shadow| image:: ../_static/tasks/manipulation/shadow_cube.jpg .. |reach-franka-link| replace:: `Isaac-Reach-Franka-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py>`__ .. |reach-ur10-link| replace:: `Isaac-Reach-UR10-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py>`__ .. |lift-cube-link| replace:: `Isaac-Lift-Cube-Franka-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/manipulation/lift/config/franka/joint_pos_env_cfg.py>`__ .. |lift-cube-ik-abs-link| replace:: `Isaac-Lift-Cube-Franka-IK-Abs-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/manipulation/lift/config/franka/ik_abs_env_cfg.py>`__ .. |lift-cube-ik-rel-link| replace:: `Isaac-Lift-Cube-Franka-IK-Rel-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/manipulation/lift/config/franka/ik_rel_env_cfg.py>`__ .. |cabi-franka-link| replace:: `Isaac-Open-Drawer-Franka-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/manipulation/cabinet/config/franka/joint_pos_env_cfg.py>`__ .. |cube-allegro-link| replace:: `Isaac-Repose-Cube-Allegro-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/manipulation/inhand/config/allegro_hand/allegro_env_cfg.py>`__ .. |cube-shadow-link| replace:: `Isaac-Shadow-Hand-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/shadow_hand_env.py>`__ .. |cube-shadow-ff-link| replace:: `Isaac-Shadow-Hand-OpenAI-FF-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/shadow_hand_env.py>`__ .. |cube-shadow-lstm-link| replace:: `Isaac-Shadow-Hand-OpenAI-LSTM-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/shadow_hand_env.py>`__ Locomotion ---------- Environments based on legged locomotion tasks. .. table:: :widths: 33 37 30 +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | World | Environment ID | Description | +==============================+==============================================+=========================================================================+ | |velocity-flat-anymal-b| | |velocity-flat-anymal-b-link| | Track a velocity command on flat terrain with the Anymal B robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-b| | |velocity-rough-anymal-b-link| | Track a velocity command on rough terrain with the Anymal B robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-anymal-c| | | |velocity-flat-anymal-c-link| | Track a velocity command on flat terrain with the Anymal C robot | | | | |velocity-flat-anymal-c-direct-link| | | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-c| | | |velocity-rough-anymal-c-link| | Track a velocity command on rough terrain with the Anymal C robot | | | | |velocity-rough-anymal-c-direct-link| | | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-anymal-d| | |velocity-flat-anymal-d-link| | Track a velocity command on flat terrain with the Anymal D robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-d| | |velocity-rough-anymal-d-link| | Track a velocity command on rough terrain with the Anymal D robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-a1| | |velocity-flat-unitree-a1-link| | Track a velocity command on flat terrain with the Unitree A1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-a1| | |velocity-rough-unitree-a1-link| | Track a velocity command on rough terrain with the Unitree A1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-go1| | |velocity-flat-unitree-go1-link| | Track a velocity command on flat terrain with the Unitree Go1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-go1| | |velocity-rough-unitree-go1-link| | Track a velocity command on rough terrain with the Unitree Go1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-go2| | |velocity-flat-unitree-go2-link| | Track a velocity command on flat terrain with the Unitree Go2 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-go2| | |velocity-rough-unitree-go2-link| | Track a velocity command on rough terrain with the Unitree Go2 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-h1| | |velocity-flat-h1-link| | Track a velocity command on flat terrain with the Unitree H1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-h1| | |velocity-rough-h1-link| | Track a velocity command on rough terrain with the Unitree H1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ .. |velocity-flat-anymal-b-link| replace:: `Isaac-Velocity-Flat-Anymal-B-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py>`__ .. |velocity-rough-anymal-b-link| replace:: `Isaac-Velocity-Rough-Anymal-B-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py>`__ .. |velocity-flat-anymal-c-link| replace:: `Isaac-Velocity-Flat-Anymal-C-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py>`__ .. |velocity-rough-anymal-c-link| replace:: `Isaac-Velocity-Rough-Anymal-C-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py>`__ .. |velocity-flat-anymal-c-direct-link| replace:: `Isaac-Velocity-Flat-Anymal-C-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/anymal_c_env.py>`__ .. |velocity-rough-anymal-c-direct-link| replace:: `Isaac-Velocity-Rough-Anymal-C-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/anymal_c_env.py>`__ .. |velocity-flat-anymal-d-link| replace:: `Isaac-Velocity-Flat-Anymal-D-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py>`__ .. |velocity-rough-anymal-d-link| replace:: `Isaac-Velocity-Rough-Anymal-D-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py>`__ .. |velocity-flat-unitree-a1-link| replace:: `Isaac-Velocity-Flat-Unitree-A1-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/unitree_a1/flat_env_cfg.py>`__ .. |velocity-rough-unitree-a1-link| replace:: `Isaac-Velocity-Rough-Unitree-A1-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/unitree_a1/rough_env_cfg.py>`__ .. |velocity-flat-unitree-go1-link| replace:: `Isaac-Velocity-Flat-Unitree-Go1-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/unitree_go1/flat_env_cfg.py>`__ .. |velocity-rough-unitree-go1-link| replace:: `Isaac-Velocity-Rough-Unitree-Go1-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/unitree_go1/rough_env_cfg.py>`__ .. |velocity-flat-unitree-go2-link| replace:: `Isaac-Velocity-Flat-Unitree-Go2-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/unitree_go2/flat_env_cfg.py>`__ .. |velocity-rough-unitree-go2-link| replace:: `Isaac-Velocity-Rough-Unitree-Go2-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/unitree_go2/rough_env_cfg.py>`__ .. |velocity-flat-h1-link| replace:: `Isaac-Velocity-Flat-H1-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py>`__ .. |velocity-rough-h1-link| replace:: `Isaac-Velocity-Rough-H1-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py>`__ .. |velocity-flat-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_flat.jpg .. |velocity-rough-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_rough.jpg .. |velocity-flat-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_flat.jpg .. |velocity-rough-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_rough.jpg .. |velocity-flat-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_flat.jpg .. |velocity-rough-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_rough.jpg .. |velocity-flat-unitree-a1| image:: ../_static/tasks/locomotion/a1_flat.jpg .. |velocity-rough-unitree-a1| image:: ../_static/tasks/locomotion/a1_rough.jpg .. |velocity-flat-unitree-go1| image:: ../_static/tasks/locomotion/go1_flat.jpg .. |velocity-rough-unitree-go1| image:: ../_static/tasks/locomotion/go1_rough.jpg .. |velocity-flat-unitree-go2| image:: ../_static/tasks/locomotion/go2_flat.jpg .. |velocity-rough-unitree-go2| image:: ../_static/tasks/locomotion/go2_rough.jpg .. |velocity-flat-h1| image:: ../_static/tasks/locomotion/h1_flat.jpg .. |velocity-rough-h1| image:: ../_static/tasks/locomotion/h1_rough.jpg Navigation ---------- .. table:: :widths: 33 37 30 +----------------+---------------------+-----------------------------------------------------------------------------+ | World | Environment ID | Description | +================+=====================+=============================================================================+ | |anymal_c_nav| | |anymal_c_nav-link| | Navigate towards a target x-y position and heading with the ANYmal C robot. | +----------------+---------------------+-----------------------------------------------------------------------------+ .. |anymal_c_nav-link| replace:: `Isaac-Navigation-Flat-Anymal-C-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/navigation/config/anymal_c/navigation_env_cfg.py>`__ .. |anymal_c_nav| image:: ../_static/tasks/navigation/anymal_c_nav.jpg Others ------ .. table:: :widths: 33 37 30 +----------------+---------------------+-----------------------------------------------------------------------------+ | World | Environment ID | Description | +================+=====================+=============================================================================+ | |quadcopter| | |quadcopter-link| | Fly and hover the Crazyflie copter at a goal point by applying thrust. | +----------------+---------------------+-----------------------------------------------------------------------------+ .. |quadcopter-link| replace:: `Isaac-Quadcopter-Direct-v0 <https://github.com/isaac-sim/IsaacLab/blob/main/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/quadcopter/quadcopter_env.py>`__ .. |quadcopter| image:: ../_static/tasks/others/quadcopter.jpg
22,201
reStructuredText
99.461538
266
0.516553
isaac-sim/IsaacLab/docs/source/deployment/cluster.rst
.. _deployment-cluster: Cluster Guide ============= Clusters are a great way to speed up training and evaluation of learning algorithms. While the Isaac Lab Docker image can be used to run jobs on a cluster, many clusters only support singularity images. This is because `singularity`_ is designed for ease-of-use on shared multi-user systems and high performance computing (HPC) environments. It does not require root privileges to run containers and can be used to run user-defined containers. Singularity is compatible with all Docker images. In this section, we describe how to convert the Isaac Lab Docker image into a singularity image and use it to submit jobs to a cluster. .. attention:: Cluster setup varies across different institutions. The following instructions have been tested on the `ETH Zurich Euler`_ cluster, which uses the SLURM workload manager. The instructions may need to be adapted for other clusters. If you have successfully adapted the instructions for another cluster, please consider contributing to the documentation. Setup Instructions ------------------ In order to export the Docker Image to a singularity image, `apptainer`_ is required. A detailed overview of the installation procedure for ``apptainer`` can be found in its `documentation`_. For convenience, we summarize the steps here for a local installation: .. code:: bash sudo apt update sudo apt install -y software-properties-common sudo add-apt-repository -y ppa:apptainer/ppa sudo apt update sudo apt install -y apptainer For simplicity, we recommend that an SSH connection is set up between the local development machine and the cluster. Such a connection will simplify the file transfer and prevent the user cluster password from being requested multiple times. .. attention:: The workflow has been tested with ``apptainer version 1.2.5-1.el7`` and ``docker version 24.0.7``. - ``apptainer``: There have been reported binding issues with previous versions (such as ``apptainer version 1.1.3-1.el7``). Please ensure that you are using the latest version. - ``Docker``: The latest versions (``25.x``) cannot be used as they are not compatible yet with apptainer/ singularity. We are waiting for an update from the apptainer team. To track this issue, please check the `forum post`_. Configuring the cluster parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ First, you need to configure the cluster-specific parameters in ``docker/.env.base`` file. The following describes the parameters that need to be configured: - ``CLUSTER_ISAAC_SIM_CACHE_DIR``: The directory on the cluster where the Isaac Sim cache is stored. This directory has to end on ``docker-isaac-sim``. This directory will be copied to the compute node and mounted into the singularity container. It should increase the speed of starting the simulation. - ``CLUSTER_ISAACLAB_DIR``: The directory on the cluster where the Isaac Lab code is stored. This directory has to end on ``isaaclab``. This directory will be copied to the compute node and mounted into the singularity container. When a job is submitted, the latest local changes will be copied to the cluster. - ``CLUSTER_LOGIN``: The login to the cluster. Typically, this is the user and cluster names, e.g., ``[email protected]``. - ``CLUSTER_SIF_PATH``: The path on the cluster where the singularity image will be stored. The image will be copied to the compute node but not uploaded again to the cluster when a job is submitted. - ``CLUSTER_PYTHON_EXECUTABLE``: The path within Isaac Lab to the Python executable that should be executed in the submitted job. Exporting to singularity image ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Next, we need to export the Docker image to a singularity image and upload it to the cluster. This step is only required once when the first job is submitted or when the Docker image is updated. For instance, due to an upgrade of the Isaac Sim version, or additional requirements for your project. To export to a singularity image, execute the following command: .. code:: bash ./docker/container.sh push [profile] This command will create a singularity image under ``docker/exports`` directory and upload it to the defined location on the cluster. Be aware that creating the singularity image can take a while. ``[profile]`` is an optional argument that specifies the container profile to be used. If no profile is specified, the default profile ``base`` will be used. .. note:: By default, the singularity image is created without root access by providing the ``--fakeroot`` flag to the ``apptainer build`` command. In case the image creation fails, you can try to create it with root access by removing the flag in ``docker/container.sh``. Job Submission and Execution ---------------------------- Defining the job parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The job parameters are defined inside the ``docker/cluster/submit_job.sh``. A typical SLURM operation requires specifying the number of CPUs and GPUs, the memory, and the time limit. For more information, please check the `SLURM documentation`_. The default configuration is as follows: .. literalinclude:: ../../../docker/cluster/submit_job.sh :language: bash :lines: 12-19 :linenos: :lineno-start: 12 An essential requirement for the cluster is that the compute node has access to the internet at all times. This is required to load assets from the Nucleus server. For some cluster architectures, extra modules must be loaded to allow internet access. For instance, on ETH Zurich Euler cluster, the ``eth_proxy`` module needs to be loaded. This can be done by adding the following line to the ``submit_job.sh`` script: .. literalinclude:: ../../../docker/cluster/submit_job.sh :language: bash :lines: 3-5 :linenos: :lineno-start: 3 Submitting a job ~~~~~~~~~~~~~~~~ To submit a job on the cluster, the following command can be used: .. code:: bash ./docker/container.sh job [profile] "argument1" "argument2" ... This command will copy the latest changes in your code to the cluster and submit a job. Please ensure that your Python executable's output is stored under ``isaaclab/logs`` as this directory will be copied again from the compute node to ``CLUSTER_ISAACLAB_DIR``. ``[profile]`` is an optional argument that specifies which singularity image corresponding to the container profile will be used. If no profile is specified, the default profile ``base`` will be used. The profile has be defined directlty after the ``job`` command. All other arguments are passed to the Python executable. If no profile is defined, all arguments are passed to the Python executable. The training arguments are passed to the Python executable. As an example, the standard ANYmal rough terrain locomotion training can be executed with the following command: .. code:: bash ./docker/container.sh job --task Isaac-Velocity-Rough-Anymal-C-v0 --headless --video --enable_cameras The above will, in addition, also render videos of the training progress and store them under ``isaaclab/logs`` directory. .. note:: The ``./docker/container.sh job`` command will copy the latest changes in your code to the cluster. However, it will not delete any files that have been deleted locally. These files will still exist on the cluster which can lead to issues. In this case, we recommend removing the ``CLUSTER_ISAACLAB_DIR`` directory on the cluster and re-run the command. .. _Singularity: https://docs.sylabs.io/guides/2.6/user-guide/index.html .. _ETH Zurich Euler: https://scicomp.ethz.ch/wiki/Euler .. _apptainer: https://apptainer.org/ .. _documentation: www.apptainer.org/docs/admin/main/installation.html#install-ubuntu-packages .. _SLURM documentation: www.slurm.schedmd.com/sbatch.html .. _forum post: https://forums.docker.com/t/trouble-after-upgrade-to-docker-ce-25-0-1-on-debian-12/139613
7,970
reStructuredText
43.283333
122
0.746048
isaac-sim/IsaacLab/docs/source/deployment/run_docker_example.rst
Running an example with Docker ============================== From the root of the ``Isaac Lab`` repository, the ``docker`` directory contains all the Docker relevant files. These include the three files (**Dockerfile**, **docker-compose.yaml**, **.env**) which are used by Docker, and an additional script that we use to interface with them, **container.sh**. In this tutorial, we will learn how to use the Isaac Lab Docker container for development. For a detailed description of the Docker setup, including installation and obtaining access to an Isaac Sim image, please reference the :ref:`deployment-docker`. For a description of Docker in general, please refer to `their official documentation <https://docs.docker.com/get-started/overview/>`_. Building the Container ~~~~~~~~~~~~~~~~~~~~~~ To build the Isaac Lab container from the root of the Isaac Lab repository, we will run the following: .. code-block:: console ./docker/container.sh start The terminal will first pull the base IsaacSim image, build the Isaac Lab image's additional layers on top of it, and run the Isaac Lab container. This should take several minutes upon the first build but will be shorter in subsequent runs as Docker's caching prevents repeated work. If we run the command ``docker container ls`` on the terminal, the output will list the containers that are running on the system. If everything has been set up correctly, a container with the ``NAME`` **isaaclab** should appear, similar to below: .. code-block:: console CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 483d1d5e2def isaaclab "bash" 30 seconds ago Up 30 seconds isaaclab Once the container is up and running, we can enter it from our terminal. .. code-block:: console ./docker/container.sh enter On entering the Isaac Lab container, we are in the terminal as the superuser, ``root``. This environment contains a copy of the Isaac Lab repository, but also has access to the directories and libraries of Isaac Sim. We can run experiments from this environment using a few convenient aliases that have been put into the ``root`` **.bashrc**. For instance, we have made the **isaaclab.sh** script usable from anywhere by typing its alias ``isaaclab``. Additionally in the container, we have `bind mounted`_ the ``IsaacLab/source`` directory from the host machine. This means that if we modify files under this directory from an editor on the host machine, the changes are reflected immediately within the container without requiring us to rebuild the Docker image. We will now run a sample script from within the container to demonstrate how to extract artifacts from the Isaac Lab Docker container. The Code ~~~~~~~~ The tutorial corresponds to the ``log_time.py`` script in the ``IsaacLab/source/standalone/tutorials/00_sim`` directory. .. dropdown:: Code for log_time.py :icon: code .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :emphasize-lines: 46-55, 72-79 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ The Isaac Lab Docker container has several `volumes`_ to facilitate persistent storage between the host computer and the container. One such volume is the ``/workspace/isaaclab/logs`` directory. The ``log_time.py`` script designates this directory as the location to which a ``log.txt`` should be written: .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :start-at: # Specify that the logs must be in logs/docker_tutorial :end-at: print(f"[INFO] Logging experiment to directory: {log_dir_path}") As the comments note, :func:`os.path.abspath()` will prepend ``/workspace/isaaclab`` because in the Docker container all python execution is done through ``/workspace/isaaclab/isaaclab.sh``. The output will be a file, ``log.txt``, with the ``sim_time`` written on a newline at every simulation step: .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :start-at: # Prepare to count sim_time :end-at: sim_time += sim_dt Executing the Script ~~~~~~~~~~~~~~~~~~~~ We will execute the script to produce a log, adding a ``--headless`` flag to our execution to prevent a GUI: .. code-block:: bash isaaclab -p source/standalone/tutorials/00_sim/log_time.py --headless Now ``log.txt`` will have been produced at ``/workspace/isaaclab/logs/docker_tutorial``. If we exit the container by typing ``exit``, we will return to ``IsaacLab/docker`` in our host terminal environment. We can then enter the following command to retrieve our logs from the Docker container and put them on our host machine: .. code-block:: console ./container.sh copy We will see a terminal readout reporting the artifacts we have retrieved from the container. If we navigate to ``/isaaclab/docker/artifacts/logs/docker_tutorial``, we will see a copy of the ``log.txt`` file which was produced by the script above. Each of the directories under ``artifacts`` corresponds to Docker `volumes`_ mapped to directories within the container and the ``container.sh copy`` command copies them from those `volumes`_ to these directories. We could return to the Isaac Lab Docker terminal environment by running ``container.sh enter`` again, but we have retrieved our logs and wish to go inspect them. We can stop the Isaac Lab Docker container with the following command: .. code-block:: console ./container.sh stop This will bring down the Docker Isaac Lab container. The image will persist and remain available for further use, as will the contents of any `volumes`_. If we wish to free up the disk space taken by the image, (~20.1GB), and do not mind repeating the build process when we next run ``./container.sh start``, we may enter the following command to delete the **isaaclab** image: .. code-block:: console docker image rm isaaclab A subsequent run of ``docker image ls``` will show that the image tagged **isaaclab** is now gone. We can repeat the process for the underlying NVIDIA container if we wish to free up more space. If a more powerful method of freeing resources from Docker is desired, please consult the documentation for the `docker prune`_ commands. .. _volumes: https://docs.docker.com/storage/volumes/ .. _bind mounted: https://docs.docker.com/storage/bind-mounts/ .. _docker prune: https://docs.docker.com/config/pruning/
6,476
reStructuredText
44.612676
146
0.737956
isaac-sim/IsaacLab/docs/source/deployment/docker.rst
.. _deployment-docker: Docker Guide ============ .. caution:: Due to the dependency on Isaac Sim docker image, by running this container you are implicitly agreeing to the `NVIDIA Omniverse EULA`_. If you do not agree to the EULA, do not run this container. Setup Instructions ------------------ .. note:: The following steps are taken from the NVIDIA Omniverse Isaac Sim documentation on `container installation`_. They have been added here for the sake of completeness. Docker and Docker Compose ~~~~~~~~~~~~~~~~~~~~~~~~~ We have tested the container using Docker Engine version 26.0.0 and Docker Compose version 2.25.0 We recommend using these versions or newer. * To install Docker, please follow the instructions for your operating system on the `Docker website`_. * To install Docker Compose, please follow the instructions for your operating system on the `docker compose`_ page. * Follow the post-installation steps for Docker on the `post-installation steps`_ page. These steps allow you to run Docker without using ``sudo``. * To build and run GPU-accelerated containers, you also need install the `NVIDIA Container Toolkit`_. Please follow the instructions on the `Container Toolkit website`_ for installation steps. .. note:: Due to limitations with `snap <https://snapcraft.io/docs/home-outside-home>`_, please make sure the Isaac Lab directory is placed under the ``/home`` directory tree when using docker. Obtaining the Isaac Sim Container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Get access to the `Isaac Sim container`_ by joining the NVIDIA Developer Program credentials. * Generate your `NGC API key`_ to access locked container images from NVIDIA GPU Cloud (NGC). * This step requires you to create an NGC account if you do not already have one. * You would also need to install the NGC CLI to perform operations from the command line. * Once you have your generated API key and have installed the NGC CLI, you need to log in to NGC from the terminal. .. code:: bash ngc config set * Use the command line to pull the Isaac Sim container image from NGC. .. code:: bash docker login nvcr.io * For the username, enter ``$oauthtoken`` exactly as shown. It is a special username that is used to authenticate with NGC. .. code:: text Username: $oauthtoken Password: <Your NGC API Key> Directory Organization ---------------------- The root of the Isaac Lab repository contains the ``docker`` directory that has various files and scripts needed to run Isaac Lab inside a Docker container. A subset of these are summarized below: * ``Dockerfile.base``: Defines the isaaclab image by overlaying Isaac Lab dependencies onto the Isaac Sim Docker image. ``Dockerfiles`` which end with something else, (i.e. ``Dockerfile.ros2``) build an `image_extension <#isaac-lab-image-extensions>`_. * ``docker-compose.yaml``: Creates mounts to allow direct editing of Isaac Lab code from the host machine that runs the container. It also creates several named volumes such as ``isaac-cache-kit`` to store frequently re-used resources compiled by Isaac Sim, such as shaders, and to retain logs, data, and documents. * ``base.env``: Stores environment variables required for the ``base`` build process and the container itself. ``.env`` files which end with something else (i.e. ``.env.ros2``) define these for `image_extension <#isaac-lab-image-extensions>`_. * ``container.sh``: A script that wraps the ``docker compose`` command to build the image and run the container. Running the Container --------------------- .. note:: The docker container copies all the files from the repository into the container at the location ``/workspace/isaaclab`` at build time. This means that any changes made to the files in the container would not normally be reflected in the repository after the image has been built, i.e. after ``./container.sh start`` is run. For a faster development cycle, we mount the following directories in the Isaac Lab repository into the container so that you can edit their files from the host machine: * ``source``: This is the directory that contains the Isaac Lab source code. * ``docs``: This is the directory that contains the source code for Isaac Lab documentation. This is overlaid except for the ``_build`` subdirectory where build artifacts are stored. The script ``container.sh`` wraps around three basic ``docker compose`` commands. Each can accept an `image_extension argument <#isaac-lab-image-extensions>`_, or else they will default to image_extension ``base``: 1. ``start``: This builds the image and brings up the container in detached mode (i.e. in the background). 2. ``enter``: This begins a new bash process in an existing isaaclab container, and which can be exited without bringing down the container. 3. ``copy``: This copies the ``logs``, ``data_storage`` and ``docs/_build`` artifacts, from the ``isaac-lab-logs``, ``isaac-lab-data`` and ``isaac-lab-docs`` volumes respectively, to the ``docker/artifacts`` directory. These artifacts persist between docker container instances and are shared between image extensions. 4. ``stop``: This brings down the container and removes it. The following shows how to launch the container in a detached state and enter it: .. code:: bash # Launch the container in detached mode # We don't pass an image extension arg, so it defaults to 'base' ./docker/container.sh start # Enter the container # We pass 'base' explicitly, but if we hadn't it would default to 'base' ./docker/container.sh enter base To copy files from the base container to the host machine, you can use the following command: .. code:: bash # Copy the file /workspace/isaaclab/logs to the current directory docker cp isaac-lab-base:/workspace/isaaclab/logs . The script ``container.sh`` provides a wrapper around this command to copy the ``logs`` , ``data_storage`` and ``docs/_build`` directories to the ``docker/artifacts`` directory. This is useful for copying the logs, data and documentation: .. code:: # stop the container ./docker/container.sh stop Python Interpreter ~~~~~~~~~~~~~~~~~~ The container uses the Python interpreter provided by Isaac Sim. This interpreter is located at ``/isaac-sim/python.sh``. We set aliases inside the container to make it easier to run the Python interpreter. You can use the following commands to run the Python interpreter: .. code:: bash # Run the Python interpreter -> points to /isaac-sim/python.sh python Understanding the mounted volumes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``docker-compose.yaml`` file creates several named volumes that are mounted to the container. These are summarized below: * ``isaac-cache-kit``: This volume is used to store cached Kit resources (`/isaac-sim/kit/cache` in container) * ``isaac-cache-ov``: This volume is used to store cached OV resources (`/root/.cache/ov` in container) * ``isaac-cache-pip``: This volume is used to store cached pip resources (`/root/.cache/pip`` in container) * ``isaac-cache-gl``: This volume is used to store cached GLCache resources (`/root/.cache/nvidia/GLCache` in container) * ``isaac-cache-compute``: This volume is used to store cached compute resources (`/root/.nv/ComputeCache` in container) * ``isaac-logs``: This volume is used to store logs generated by Omniverse. (`/root/.nvidia-omniverse/logs` in container) * ``isaac-carb-logs``: This volume is used to store logs generated by carb. (`/isaac-sim/kit/logs/Kit/Isaac-Sim` in container) * ``isaac-data``: This volume is used to store data generated by Omniverse. (`/root/.local/share/ov/data` in container) * ``isaac-docs``: This volume is used to store documents generated by Omniverse. (`/root/Documents` in container) * ``isaac-lab-docs``: This volume is used to store documentation of Isaac Lab when built inside the container. (`/workspace/isaaclab/docs/_build` in container) * ``isaac-lab-logs``: This volume is used to store logs generated by Isaac Lab workflows when run inside the container. (`/workspace/isaaclab/logs` in container) * ``isaac-lab-data``: This volume is used to store whatever data users may want to preserve between container runs. (`/workspace/isaaclab/data_storage` in container) To view the contents of these volumes, you can use the following command: .. code:: bash # list all volumes docker volume ls # inspect a specific volume, e.g. isaac-cache-kit docker volume inspect isaac-cache-kit Isaac Lab Image Extensions -------------------------- The produced image depends upon the arguments passed to ``./container.sh start`` and ``./container.sh stop``. These commands accept an ``image_extension`` as an additional argument. If no argument is passed, then these commands default to ``base``. Currently, the only valid ``image_extension`` arguments are (``base``, ``ros2``). Only one ``image_extension`` can be passed at a time, and the produced container will be named ``isaaclab``. .. code:: bash # start base by default ./container.sh start # stop base explicitly ./container.sh stop base # start ros2 container ./container.sh start ros2 # stop ros2 container ./container.sh stop ros2 The passed ``image_extension`` argument will build the image defined in ``Dockerfile.${image_extension}``, with the corresponding `profile`_ in the ``docker-compose.yaml`` and the envars from ``.env.${image_extension}`` in addition to the ``.env.base``, if any. ROS2 Image Extension ~~~~~~~~~~~~~~~~~~~~ In ``Dockerfile.ros2``, the container installs ROS2 Humble via an `apt package`_, and it is sourced in the ``.bashrc``. The exact version is specified by the variable ``ROS_APT_PACKAGE`` in the ``.env.ros2`` file, defaulting to ``ros-base``. Other relevant ROS2 variables are also specified in the ``.env.ros2`` file, including variables defining the `various middleware`_ options. The container defaults to ``FastRTPS``, but ``CylconeDDS`` is also supported. Each of these middlewares can be `tuned`_ using their corresponding ``.xml`` files under ``docker/.ros``. Known Issues ------------ Invalid mount config for type "bind" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you see the following error when building the container: .. code:: text ⠋ Container isaaclab Creating 0.0s Error response from daemon: invalid mount config for type "bind": bind source path does not exist: ${HOME}/.Xauthority This means that the ``.Xauthority`` file is not present in the home directory of the host machine. The portion of the docker-compose.yaml that enables this is commented out by default, so this shouldn't happen unless it has been altered. This file is required for X11 forwarding to work. To fix this, you can create an empty ``.Xauthority`` file in your home directory. .. code:: bash touch ${HOME}/.Xauthority A similar error but requires a different fix: .. code:: text ⠋ Container isaaclab Creating 0.0s Error response from daemon: invalid mount config for type "bind": bind source path does not exist: /tmp/.X11-unix This means that the folder/files are either not present or not accessible on the host machine. The portion of the docker-compose.yaml that enables this is commented out by default, so this shouldn't happen unless it has been altered. This usually happens when you have multiple docker versions installed on your machine. To fix this, you can try the following: * Remove all docker versions from your machine. .. code:: bash sudo apt remove docker* sudo apt remove docker docker-engine docker.io containerd runc docker-desktop docker-compose-plugin sudo snap remove docker sudo apt clean autoclean && sudo apt autoremove --yes * Install the latest version of docker based on the instructions in the setup section. WebRTC Streaming ~~~~~~~~~~~~~~~~ When streaming the GUI from Isaac Sim, there are `several streaming clients`_ available. There is a `known issue`_ when attempting to use WebRTC streaming client on Google Chrome and Safari while running Isaac Sim inside a container. To avoid this problem, we suggest using the Native Streaming Client or using the Mozilla Firefox browser on which WebRTC works. Streaming is the only supported method for visualizing the Isaac GUI from within the container. The Omniverse Streaming Client is freely available from the Omniverse app, and is easy to use. The other streaming methods similarly require only a web browser. If users want to use X11 forwarding in order to have the apps behave as local GUI windows, they can uncomment the relevant portions in docker-compose.yaml. .. _`NVIDIA Omniverse EULA`: https://docs.omniverse.nvidia.com/platform/latest/common/NVIDIA_Omniverse_License_Agreement.html .. _`container installation`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_container.html .. _`Docker website`: https://docs.docker.com/desktop/install/linux-install/ .. _`docker compose`: https://docs.docker.com/compose/install/linux/#install-using-the-repository .. _`NVIDIA Container Toolkit`: https://github.com/NVIDIA/nvidia-container-toolkit .. _`Container Toolkit website`: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html .. _`post-installation steps`: https://docs.docker.com/engine/install/linux-postinstall/ .. _`Isaac Sim container`: https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim .. _`NGC API key`: https://docs.nvidia.com/ngc/gpu-cloud/ngc-user-guide/index.html#generating-api-key .. _`several streaming clients`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/manual_livestream_clients.html .. _`known issue`: https://forums.developer.nvidia.com/t/unable-to-use-webrtc-when-i-run-runheadless-webrtc-sh-in-remote-headless-container/222916 .. _`profile`: https://docs.docker.com/compose/compose-file/15-profiles/ .. _`apt package`: https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html#install-ros-2-packages .. _`various middleware`: https://docs.ros.org/en/humble/How-To-Guides/Working-with-multiple-RMW-implementations.html .. _`tuned`: https://docs.ros.org/en/foxy/How-To-Guides/DDS-tuning.html
14,638
reStructuredText
49.47931
207
0.715603
isaac-sim/IsaacLab/docs/source/deployment/index.rst
Container Deployment ==================== Docker is a tool that allows for the creation of containers, which are isolated environments that can be used to run applications. They are useful for ensuring that an application can run on any machine that has Docker installed, regardless of the host machine's operating system or installed libraries. We include a Dockerfile and docker-compose.yaml file that can be used to build a Docker image that contains Isaac Lab and all of its dependencies. This image can then be used to run Isaac Lab in a container. The Dockerfile is based on the Isaac Sim image provided by NVIDIA, which includes the Omniverse application launcher and the Isaac Sim application. The Dockerfile installs Isaac Lab and its dependencies on top of this image. The following guides provide instructions for building the Docker image and running Isaac Lab in a container. .. toctree:: :maxdepth: 1 docker cluster run_docker_example
962
reStructuredText
40.869563
108
0.787942
isaac-sim/IsaacLab/docs/source/refs/migration.rst
Migration Guide (Isaac Sim) =========================== Moving from Isaac Sim 2022.2.1 to 2023.1.0 brings in a number of changes to the APIs and the way the application is built. This document outlines the changes and how to migrate your code to the new APIs. Many of these changes attribute to the underlying Omniverse Kit upgrade from 104.2 to 105.1. The new upgrade brings the following notable changes: * Update to USD 22.11 * Upgrading the Python from 3.7 to 3.10 .. warning:: This document is a work in progress and will be updated as we move closer to the release of Isaac Sim 2023.1.0. Renaming of PhysX Flatcache to PhysX Fabric ------------------------------------------- The PhysX Flatcache has been renamed to PhysX Fabric. The new name is more descriptive of the functionality and is consistent with the naming convention used by Omniverse called `Fabric`_. Consequently, the Python module name has also been changed from :mod:`omni.physxflatcache` to :mod:`omni.physxfabric`. Following this, on the Isaac Sim side, various renaming have occurred: * The parameter passed to :class:`SimulationContext` constructor via the keyword :obj:`sim_params` now expects the key ``use_fabric`` instead of ``use_flatcache``. * The Python attribute :attr:`SimulationContext.get_physics_context().use_flatcache` is now :attr:`SimulationContext.get_physics_context().use_fabric`. * The Python function :meth:`SimulationContext.get_physics_context().enable_flatcache` is now :meth:`SimulationContext.get_physics_context().enable_fabric`. Renaming of the URDF and MJCF Importers --------------------------------------- Starting from Isaac Sim 2023.1, the URDF and MJCF importers have been renamed to be more consistent with the other asset importers in Omniverse. The importers are now available on NVIDIA-Omniverse GitHub as open source projects. Due to the extension name change, the Python module names have also been changed: * URDF Importer: :mod:`omni.importer.urdf` (previously :mod:`omni.isaac.urdf`) * MJCF Importer: :mod:`omni.importer.mjcf` (previously :mod:`omni.isaac.mjcf`) Deprecation of :class:`UsdLux.Light` API ---------------------------------------- As highlighted in the release notes of `USD 22.11`_, the ``UsdLux.Light`` API has been deprecated in favor of the new ``UsdLuxLightAPI`` API. In the new API the attributes are prefixed with ``inputs:``. For example, the ``intensity`` attribute is now available as ``inputs:intensity``. The following example shows how to create a sphere light using the old API and the new API. .. dropdown:: Code for Isaac Sim 2022.2.1 and below :icon: code .. code-block:: python import omni.isaac.core.utils.prims as prim_utils prim_utils.create_prim( "/World/Light/GreySphere", "SphereLight", translation=(4.5, 3.5, 10.0), attributes={"radius": 2.5, "intensity": 600.0, "color": (0.75, 0.75, 0.75)}, ) .. dropdown:: Code for Isaac Sim 2023.1.0 and above :icon: code .. code-block:: python import omni.isaac.core.utils.prims as prim_utils prim_utils.create_prim( "/World/Light/WhiteSphere", "SphereLight", translation=(-4.5, 3.5, 10.0), attributes={ "inputs:radius": 2.5, "inputs:intensity": 600.0, "inputs:color": (1.0, 1.0, 1.0) }, ) .. _Fabric: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usd_fabric_usdrt.html .. _`USD 22.11`: https://github.com/PixarAnimationStudios/OpenUSD/blob/release/CHANGELOG.md
3,578
reStructuredText
36.28125
103
0.686138
isaac-sim/IsaacLab/docs/source/refs/changelog.rst
Extensions Changelog ==================== All notable changes to this project are documented in this file. The format is based on `Keep a Changelog <https://keepachangelog.com/en/1.0.0/>`__ and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`__. For a broader information about the changes in the framework, please refer to the `release notes <https://github.com/isaac-sim/IsaacLab/releases/>`__. Each extension has its own changelog. The changelog for each extension is located in the ``docs`` directory of the extension. The changelog for each extension is also included in this changelog to make it easier to find the changelog for a specific extension. omni.isaac.lab -------------- Extension containing the core framework of Isaac Lab. .. include:: ../../../source/extensions/omni.isaac.lab/docs/CHANGELOG.rst :start-line: 3 omni.isaac.lab_assets --------------------- Extension for configurations of various assets and sensors for Isaac Lab. .. include:: ../../../source/extensions/omni.isaac.lab_assets/docs/CHANGELOG.rst :start-line: 3 omni.isaac.lab_tasks -------------------- Extension containing the environments built using Isaac Lab. .. include:: ../../../source/extensions/omni.isaac.lab_tasks/docs/CHANGELOG.rst :start-line: 3
1,299
reStructuredText
32.333333
89
0.712086
isaac-sim/IsaacLab/docs/source/refs/issues.rst
Known Issues ============ .. attention:: Please also refer to the `Omniverse Isaac Sim documentation`_ for known issues and workarounds. Stale values after resetting the environment -------------------------------------------- When resetting the environment, some of the data fields of assets and sensors are not updated. These include the poses of links in a kinematic chain, the camera images, the contact sensor readings, and the lidar point clouds. This is a known issue which has to do with the way the PhysX and rendering engines work in Omniverse. Many physics engines do a simulation step as a two-level call: ``forward()`` and ``simulate()``, where the kinematic and dynamic states are updated, respectively. Unfortunately, PhysX has only a single ``step()`` call where the two operations are combined. Due to computations through GPU kernels, it is not so straightforward for them to split these operations. Thus, at the moment, it is not possible to set the root and/or joint states and do a forward call to update the kinematic states of links. This affects both initialization as well as episodic resets. Similarly for RTX rendering related sensors (such as cameras), the sensor data is not updated immediately after setting the state of the sensor. The rendering engine update is bundled with the simulator's ``step()`` call which only gets called when the simulation is stepped forward. This means that the sensor data is not updated immediately after a reset and it will hold outdated values. While the above is erroneous, there is currently no direct workaround for it. From our experience in using IsaacGym, the reset values affect the agent learning critically depending on how frequently the environment terminates. Eventually if the agent is learning successfully, this number drops and does not affect the performance that critically. We have made a feature request to the respective Omniverse teams to have complete control over stepping different parts of the simulation app. However, at this point, there is no set timeline for this feature request. Non-determinism in physics simulation ------------------------------------- Due to GPU work scheduling, there's a possibility that runtime changes to simulation parameters may alter the order in which operations take place. This occurs because environment updates can happen while the GPU is occupied with other tasks. Due to the inherent nature of floating-point numeric storage, any modification to the execution ordering can result in minor changes in the least significant bits of output data. These changes may lead to divergent execution over the course of simulating thousands of environments and simulation frames. An illustrative example of this issue is observed with the runtime domain randomization of object's physics materials. This process can introduce both determinancy and simulation issues when executed on the GPU due to the way these parameters are passed from the CPU to the GPU in the lower-level APIs. Consequently, it is strongly advised to perform this operation only at setup time, before the environment stepping commences. For more information, please refer to the `PhysX Determinism documentation`_. In addition, due to floating point precision, states across different environments in the simulation may be non-deterministic when the same set of actions are applied to the same initial states. This occurs as environments are placed further apart from the world origin at (0, 0, 0). As actors get placed at different origins in the world, floating point errors may build up and result in slight variance in results even when starting from the same initial states. One possible workaround for this issue is to place all actors/environments at the world origin at (0, 0, 0) and filter out collisions between the environments. Note that this may induce a performance degradation of around 15-50%, depending on the complexity of actors and environment. Blank initial frames from the camera ------------------------------------ When using the :class:`omni.isaac.lab.sensors.Camera` sensor in standalone scripts, the first few frames may be blank. This is a known issue with the simulator where it needs a few steps to load the material textures properly and fill up the render targets. A hack to work around this is to add the following after initializing the camera sensor and setting its pose: .. code-block:: python from omni.isaac.lab.sim import SimulationContext sim = SimulationContext.instance() # note: the number of steps might vary depending on how complicated the scene is. for _ in range(12): sim.render() Using instanceable assets for markers ------------------------------------- When using `instanceable assets`_ for markers, the markers do not work properly, since Omniverse does not support instanceable assets when using the :class:`UsdGeom.PointInstancer` schema. This is a known issue and will hopefully be fixed in a future release. If you use an instanceable assets for markers, the marker class removes all the physics properties of the asset. This is then replicated across other references of the same asset since physics properties of instanceable assets are stored in the instanceable asset's USD file and not in its stage reference's USD file. .. _instanceable assets: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_instanceable_assets.html .. _Omniverse Isaac Sim documentation: https://docs.omniverse.nvidia.com/isaacsim/latest/known_issues.html .. _PhysX Determinism documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/docs/BestPractices.html#determinism Exiting the process ------------------- When exiting a process with ``Ctrl+C``, occasionally the below error may appear: .. code-block:: bash [Error] [omni.physx.plugin] Subscribtion cannot be changed during the event call. This is due to the termination occurring in the middle of a physics event call and should not affect the functionality of Isaac Lab. It is safe to ignore the error message and continue with terminating the process. On Windows systems, please use ``Ctrl+Break`` or ``Ctrl+fn+B`` to terminate the process.
6,219
reStructuredText
51.711864
125
0.775205
isaac-sim/IsaacLab/docs/source/refs/troubleshooting.rst
Tricks and Troubleshooting ========================== .. note:: The following lists some of the common tricks and troubleshooting methods that we use in our common workflows. Please also check the `troubleshooting page on Omniverse <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/linux_troubleshooting.html>`__ for more assistance. Checking the internal logs from the simulator --------------------------------------------- When running the simulator from a standalone script, it logs warnings and errors to the terminal. At the same time, it also logs internal messages to a file. These are useful for debugging and understanding the internal state of the simulator. Depending on your system, the log file can be found in the locations listed `here <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_faq.html#common-path-locations>`_. To obtain the exact location of the log file, you need to check the first few lines of the terminal output when you run the standalone script. The log file location is printed at the start of the terminal output. For example: .. code:: bash [INFO] Using python from: /home/${USER}/git/IsaacLab/_isaac_sim/python.sh ... Passing the following args to the base kit application: [] Loading user config located at: '.../data/Kit/Isaac-Sim/2023.1/user.config.json' [Info] [carb] Logging to file: '.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log' In the above example, the log file is located at ``.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log``, ``...`` is the path to the user's log directory. The log file is named ``kit_20240328_183346.log`` You can open this file to check the internal logs from the simulator. Also when reporting issues, please include this log file to help us debug the issue. Using CPU Scaling Governor for performance ------------------------------------------ By default on many systems, the CPU frequency governor is set to “powersave” mode, which sets the CPU to lowest static frequency. To increase the maximum performance, we recommend setting the CPU frequency governor to “performance” mode. For more details, please check the the link `here <https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/power_management_guide/cpufreq_governors>`__. .. warning:: We advice not to set the governor to “performance” mode on a system with poor cooling (such as laptops), since it may cause the system to overheat. - To view existing ``scaling_governor`` value per CPU: .. code:: bash cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor - To change the governor to “performance” mode for each CPU: .. code:: bash echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor Observing long load times at the start of the simulation -------------------------------------------------------- The first time you run the simulator, it will take a long time to load up. This is because the simulator is compiling shaders and loading assets. Subsequent runs should be faster to start up, but may still take some time. Please note that once the Isaac Sim app loads, the environment creation time may scale linearly with the number of environments. Please expect a longer load time if running with thousands of environments or if each environment contains a larger number of assets. We are continually working on improving the time needed for this. When an instance of Isaac Sim is already running, launching another Isaac Sim instance in a different process may appear to hang at startup for the first time. Please be patient and give it some time as the second process will take longer to start up due to slower shader compilation. Receiving a “PhysX error” when running simulation on GPU -------------------------------------------------------- When using the GPU pipeline, the buffers used for the physics simulation are allocated on the GPU only once at the start of the simulation. This means that they do not grow dynamically as the number of collisions or objects in the scene changes. If the number of collisions or objects in the scene exceeds the size of the buffers, the simulation will fail with an error such as the following: .. code:: bash PhysX error: the application need to increase the PxgDynamicsMemoryConfig::foundLostPairsCapacity parameter to 3072, otherwise the simulation will miss interactions In this case, you need to increase the size of the buffers passed to the :class:`~omni.isaac.lab.sim.SimulationContext` class. The size of the buffers can be increased by setting the :attr:`~omni.isaac.lab.sim.PhysxCfg.gpu_found_lost_pairs_capacity` parameter in the :class:`~omni.isaac.lab.sim.PhysxCfg` class. For example, to increase the size of the buffers to 4096, you can use the following code: .. code:: python import omni.isaac.lab.sim as sim_utils sim_cfg = sim_utils.SimulationConfig() sim_cfg.physx.gpu_found_lost_pairs_capacity = 4096 sim = SimulationContext(sim_params=sim_cfg) Please see the documentation for :class:`~omni.isaac.lab.sim.SimulationCfg` for more details on the parameters that can be used to configure the simulation. Preventing memory leaks in the simulator ---------------------------------------- Memory leaks in the Isaac Sim simulator can occur when C++ callbacks are registered with Python objects. This happens when callback functions within classes maintain references to the Python objects they are associated with. As a result, Python's garbage collection is unable to reclaim memory associated with these objects, preventing the corresponding C++ objects from being destroyed. Over time, this can lead to memory leaks and increased resource usage. To prevent memory leaks in the Isaac Sim simulator, it is essential to use weak references when registering callbacks with the simulator. This ensures that Python objects can be garbage collected when they are no longer needed, thereby avoiding memory leaks. The `weakref <https://docs.python.org/3/library/weakref.html>`_ module from the Python standard library can be employed for this purpose. For example, consider a class with a callback function ``on_event_callback`` that needs to be registered with the simulator. If you use a strong reference to the ``MyClass`` object when passing the callback, the reference count of the ``MyClass`` object will be incremented. This prevents the ``MyClass`` object from being garbage collected when it is no longer needed, i.e., the ``__del__`` destructor will not be called. .. code:: python import omni.kit class MyClass: def __init__(self): app_interface = omni.kit.app.get_app_interface() self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( self.on_event_callback ) def __del__(self): self._handle.unsubscribe() self._handle = None def on_event_callback(self, event): # do something with the message To fix this issue, it's crucial to employ weak references when registering the callback. While this approach adds some verbosity to the code, it ensures that the ``MyClass`` object can be garbage collected when no longer in use. Here's the modified code: .. code:: python import omni.kit import weakref class MyClass: def __init__(self): app_interface = omni.kit.app.get_app_interface() self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( lambda event, obj=weakref.proxy(self): obj.on_event_callback(event) ) def __del__(self): self._handle.unsubscribe() self._handle = None def on_event_callback(self, event): # do something with the message In this revised code, the weak reference ``weakref.proxy(self)`` is used when registering the callback, allowing the ``MyClass`` object to be properly garbage collected. By following this pattern, you can prevent memory leaks and maintain a more efficient and stable simulation. Understanding the error logs from crashes ----------------------------------------- Many times the simulator crashes due to a bug in the implementation. This swamps the terminal with exceptions, some of which are coming from the python interpreter calling ``__del__()`` destructor of the simulation application. These typically look like the following: .. code:: bash ... [INFO]: Completed setting up the environment... Traceback (most recent call last): File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 166, in <module> main() File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 126, in main actions = pre_process_actions(delta_pose, gripper_command) File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 57, in pre_process_actions return torch.concat([delta_pose, gripper_vel], dim=1) TypeError: expected Tensor as element 1 in argument 0, but got int Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80> Traceback (most recent call last): File "../IsaacLab/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ File "../IsaacLab/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy TypeError: 'NoneType' object is not callable Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80> Traceback (most recent call last): File "../IsaacLab/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ File "../IsaacLab/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy TypeError: 'NoneType' object is not callable Exception ignored in: <function SettingChangeSubscription.__del__ at 0x7fa2ea173e60> Traceback (most recent call last): File "../IsaacLab/_isaac_sim/kit/kernel/py/omni/kit/app/_impl/__init__.py", line 114, in __del__ AttributeError: 'NoneType' object has no attribute 'get_settings' Exception ignored in: <function RegisteredActions.__del__ at 0x7f935f5cae60> Traceback (most recent call last): File "../IsaacLab/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 345, in __del__ File "../IsaacLab/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 350, in destroy TypeError: 'NoneType' object is not callable 2022-12-02 15:41:54 [18,514ms] [Warning] [carb.audio.context] 1 contexts were leaked ../IsaacLab/_isaac_sim/python.sh: line 41: 414372 Segmentation fault (core dumped) $python_exe "$@" $args There was an error running python This is a known error with running standalone scripts with the Isaac Sim simulator. Please scroll above the exceptions thrown with ``registry`` to see the actual error log. In the above case, the actual error is: .. code:: bash Traceback (most recent call last): File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 166, in <module> main() File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 126, in main actions = pre_process_actions(delta_pose, gripper_command) File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 57, in pre_process_actions return torch.concat([delta_pose, gripper_vel], dim=1) TypeError: expected Tensor as element 1 in argument 0, but got int
11,911
reStructuredText
47.620408
154
0.72496
isaac-sim/IsaacLab/docs/source/refs/bibliography.rst
Bibliography ============ .. bibliography::
45
reStructuredText
8.199998
17
0.533333
isaac-sim/IsaacLab/docs/source/refs/license.rst
.. _license: License ======== NVIDIA Isaac Sim is available freely under `individual license <https://www.nvidia.com/en-us/omniverse/download/>`_. For more information about its license terms, please check `here <https://docs.omniverse.nvidia.com/app_isaacsim/common/NVIDIA_Omniverse_License_Agreement.html#software-support-supplement>`_. The license files for all its dependencies and included assets are available in its `documentation <https://docs.omniverse.nvidia.com/app_isaacsim/common/licenses.html>`_. The Isaac Lab framework is open-sourced under the `BSD-3-Clause license <https://opensource.org/licenses/BSD-3-Clause>`_. .. code-block:: text Copyright (c) 2022-2024, The Isaac Lab Project Developers. All rights reserved. SPDX-License-Identifier: BSD-3-Clause Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2,293
reStructuredText
46.791666
170
0.772787
isaac-sim/IsaacLab/docs/source/refs/contributing.rst
Contribution Guidelines ======================= We wholeheartedly welcome contributions to the project to make the framework more mature and useful for everyone. These may happen in forms of: * Bug reports: Please report any bugs you find in the `issue tracker <https://github.com/isaac-sim/IsaacLab/issues>`__. * Feature requests: Please suggest new features you would like to see in the `discussions <https://github.com/isaac-sim/IsaacLab/discussions>`__. * Code contributions: Please submit a `pull request <https://github.com/isaac-sim/IsaacLab/pulls>`__. * Bug fixes * New features * Documentation improvements * Tutorials and tutorial improvements .. attention:: We prefer GitHub `discussions <https://github.com/isaac-sim/IsaacLab/discussions>`_ for discussing ideas, asking questions, conversations and requests for new features. Please use the `issue tracker <https://github.com/isaac-sim/IsaacLab/issues>`_ only to track executable pieces of work with a definite scope and a clear deliverable. These can be fixing bugs, new features, or general updates. Contributing Code ----------------- We use `GitHub <https://github.com/isaac-sim/IsaacLab>`__ for code hosting. Please follow the following steps to contribute code: 1. Create an issue in the `issue tracker <https://github.com/isaac-sim/IsaacLab/issues>`__ to discuss the changes or additions you would like to make. This helps us to avoid duplicate work and to make sure that the changes are aligned with the roadmap of the project. 2. Fork the repository. 3. Create a new branch for your changes. 4. Make your changes and commit them. 5. Push your changes to your fork. 6. Submit a pull request to the `main branch <https://github.com/isaac-sim/IsaacLab/compare>`__. 7. Ensure all the checks on the pull request template are performed. After sending a pull request, the maintainers will review your code and provide feedback. Please ensure that your code is well-formatted, documented and passes all the tests. .. tip:: It is important to keep the pull request as small as possible. This makes it easier for the maintainers to review your code. If you are making multiple changes, please send multiple pull requests. Large pull requests are difficult to review and may take a long time to merge. Coding Style ------------ We follow the `Google Style Guides <https://google.github.io/styleguide/pyguide.html>`__ for the codebase. For Python code, the PEP guidelines are followed. Most important ones are `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`__ for code comments and layout, `PEP-484 <http://www.python.org/dev/peps/pep-0484>`__ and `PEP-585 <https://www.python.org/dev/peps/pep-0585/>`__ for type-hinting. For documentation, we adopt the `Google Style Guide <https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html>`__ for docstrings. We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ for generating the documentation. Please make sure that your code is well-documented and follows the guidelines. Circular Imports ^^^^^^^^^^^^^^^^ Circular imports happen when two modules import each other, which is a common issue in Python. You can prevent circular imports by adhering to the best practices outlined in this `StackOverflow post <https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python>`__. In general, it is essential to avoid circular imports as they can lead to unpredictable behavior. However, in our codebase, we encounter circular imports at a sub-package level. This situation arises due to our specific code structure. We organize classes or functions and their corresponding configuration objects into separate files. This separation enhances code readability and maintainability. Nevertheless, it can result in circular imports because, in many configuration objects, we specify classes or functions as default values using the attributes ``class_type`` and ``func`` respectively. To address circular imports, we leverage the `typing.TYPE_CHECKING <https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING>`_ variable. This special variable is evaluated only during type-checking, allowing us to import classes or functions in the configuration objects without triggering circular imports. It is important to note that this is the sole instance within our codebase where circular imports are used and are acceptable. In all other scenarios, we adhere to best practices and recommend that you do the same. Type-hinting ^^^^^^^^^^^^ To make the code more readable, we use `type hints <https://docs.python.org/3/library/typing.html>`__ for all the functions and classes. This helps in understanding the code and makes it easier to maintain. Following this practice also helps in catching bugs early with static type checkers like `mypy <https://mypy.readthedocs.io/en/stable/>`__. To avoid duplication of efforts, we do not specify type hints for the arguments and return values in the docstrings. However, if your function or class is not self-explanatory, please add a docstring with the type hints. Tools ^^^^^ We use the following tools for maintaining code quality: * `pre-commit <https://pre-commit.com/>`__: Runs a list of formatters and linters over the codebase. * `black <https://black.readthedocs.io/en/stable/>`__: The uncompromising code formatter. * `flake8 <https://flake8.pycqa.org/en/latest/>`__: A wrapper around PyFlakes, pycodestyle and McCabe complexity checker. Please check `here <https://pre-commit.com/#install>`__ for instructions to set these up. To run over the entire repository, please execute the following command in the terminal: .. code:: bash ./isaaclab.sh --format # or "./isaaclab.sh -f" Contributing Documentation -------------------------- Contributing to the documentation is as easy as contributing to the codebase. All the source files for the documentation are located in the ``IsaacLab/docs`` directory. The documentation is written in `reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format. We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ with the `Book Theme <https://sphinx-book-theme.readthedocs.io/en/stable/>`__ for maintaining the documentation. Sending a pull request for the documentation is the same as sending a pull request for the codebase. Please follow the steps mentioned in the `Contributing Code`_ section. .. caution:: To build the documentation, we recommend creating a `virtual environment <https://docs.python.org/3/library/venv.html>`__ to install the dependencies. This can also be a `conda environment <https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html>`__. To build the documentation, run the following command in the terminal which installs the required python packages and builds the documentation using the ``docs/Makefile``: .. code:: bash ./isaaclab.sh --docs # or "./isaaclab.sh -d" The documentation is generated in the ``docs/_build`` directory. To view the documentation, open the ``index.html`` file in the ``html`` directory. This can be done by running the following command in the terminal: .. code:: bash xdg-open docs/_build/html/index.html .. hint:: The ``xdg-open`` command is used to open the ``index.html`` file in the default browser. If you are using a different operating system, you can use the appropriate command to open the file in the browser. To do a clean build, run the following command in the terminal: .. code:: bash rm -rf docs/_build && ./isaaclab.sh --docs Contributing assets ------------------- Currently, we host the assets for the extensions on `NVIDIA Nucleus Server <https://docs.omniverse.nvidia.com/nucleus/latest/index.html>`__. Nucleus is a cloud-based storage service that allows users to store and share large files. It is integrated with the `NVIDIA Omniverse Platform <https://developer.nvidia.com/omniverse>`__. Since all assets are hosted on Nucleus, we do not need to include them in the repository. However, we need to include the links to the assets in the documentation. The included assets are part of the `Isaac Sim Content <https://docs.omniverse.nvidia.com/isaacsim/latest/features/environment_setup/assets/usd_assets_overview.html>`__. To use this content, you need to download the files to a Nucleus server or create an **Isaac** Mount on a Nucleus server. Please check the `Isaac Sim documentation <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_faq.html#assets-and-nucleus>`__ for more information on how to download the assets. .. attention:: We are currently working on a better way to contribute assets. We will update this section once we have a solution. In the meantime, please follow the steps mentioned below. To host your own assets, the current solution is: 1. Create a separate repository for the assets and add it over there 2. Make sure the assets are licensed for use and distribution 3. Include images of the assets in the README file of the repository 4. Send a pull request with a link to the repository We will then verify the assets, its licensing, and include the assets into the Nucleus server for hosting. In case you have any questions, please feel free to reach out to us through e-mail or by opening an issue in the repository. Maintaining a changelog ----------------------- Each extension maintains a changelog in the ``CHANGELOG.rst`` file in the ``docs`` directory. The file is written in `reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format. It contains a curated, chronologically ordered list of notable changes for each version of the extension. The goal of this changelog is to help users and contributors see precisely what notable changes have been made between each release (or version) of the extension. This is a *MUST* for every extension. For updating the changelog, please follow the following guidelines: * Each version should have a section with the version number and the release date. * The version number is updated according to `Semantic Versioning <https://semver.org/>`__. The release date is the date on which the version is released. * Each version is divided into subsections based on the type of changes made. * ``Added``: For new features. * ``Changed``: For changes in existing functionality. * ``Deprecated``: For soon-to-be removed features. * ``Removed``: For now removed features. * ``Fixed``: For any bug fixes. * Each change is described in its corresponding sub-section with a bullet point. * The bullet points are written in the past tense and in imperative mode. For example, the following is a sample changelog: .. code:: rst Changelog --------- 0.1.0 (2021-02-01) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Added a new feature. Changed ^^^^^^^ * Changed an existing feature. Deprecated ^^^^^^^^^^ * Deprecated an existing feature. Removed ^^^^^^^ * Removed an existing feature. Fixed ^^^^^ * Fixed a bug. 0.0.1 (2021-01-01) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Added a new feature.
11,187
reStructuredText
40.284133
169
0.744614
isaac-sim/IsaacLab/docs/source/migration/migrating_from_omniisaacgymenvs.rst
.. _migrating-from-omniisaacgymenvs: Migrating from OmniIsaacGymEnvs =============================== .. currentmodule:: omni.isaac.lab OmniIsaacGymEnvs was a reinforcement learning framework using the Isaac Sim platform. Features from OmniIsaacGymEnvs have been integrated into the Isaac Lab framework. We have updated OmniIsaacGymEnvs to Isaac Sim version 4.0.0 to support the migration process to Isaac Lab. Moving forward, OmniIsaacGymEnvs will be deprecated and future development will continue in Isaac Lab. Task Config Setup ~~~~~~~~~~~~~~~~~ In OmniIsaacGymEnvs, task config files were defined in ``.yaml`` format. With Isaac Lab, configs are now specified using a specialized Python class :class:`~omni.isaac.lab.utils.configclass`. The :class:`~omni.isaac.lab.utils.configclass` module provides a wrapper on top of Python's ``dataclasses`` module. Each environment should specify its own config class annotated by ``@configclass`` that inherits from :class:`~envs.DirectRLEnvCfg`, which can include simulation parameters, environment scene parameters, robot parameters, and task-specific parameters. Below is an example skeleton of a task config class: .. code-block:: python from omni.isaac.lab.envs import DirectRLEnvCfg from omni.isaac.lab.scene import InteractiveSceneCfg from omni.isaac.lab.sim import SimulationCfg @configclass class MyEnvCfg(DirectRLEnvCfg): # simulation sim: SimulationCfg = SimulationCfg() # robot robot_cfg: ArticulationCfg = ArticulationCfg() # scene scene: InteractiveSceneCfg = InteractiveSceneCfg() # env decimation = 2 episode_length_s = 5.0 num_actions = 1 num_observations = 4 num_states = 0 # task-specific parameters ... Simulation Config ----------------- Simulation related parameters are defined as part of the :class:`~omni.isaac.lab.sim.SimulationCfg` class, which is a :class:`~omni.isaac.lab.utils.configclass` module that holds simulation parameters such as ``dt``, ``device``, and ``gravity``. Each task config must have a variable named ``sim`` defined that holds the type :class:`~omni.isaac.lab.sim.SimulationCfg`. Simulation parameters for articulations and rigid bodies such as ``num_position_iterations``, ``num_velocity_iterations``, ``contact_offset``, ``rest_offset``, ``bounce_threshold_velocity``, ``max_depenetration_velocity`` can all be specified on a per-actor basis in the config class for each individual articulation and rigid body. When running simulation on the GPU, buffers in PhysX require pre-allocation for computing and storing information such as contacts, collisions and aggregate pairs. These buffers may need to be adjusted depending on the complexity of the environment, the number of expected contacts and collisions, and the number of actors in the environment. The :class:`~omni.isaac.lab.sim.PhysxCfg` class provides access for setting the GPU buffer dimensions. +--------------------------------------------------------------+-------------------------------------------------------------------+ | | | |.. code-block:: yaml |.. code-block:: python | | | | | # OmniIsaacGymEnvs | # IsaacLab | | sim: | sim: SimulationCfg = SimulationCfg( | | dt: 0.0083 # 1/120 s | dt=1 / 120, | | use_gpu_pipeline: ${eq:${...pipeline},"gpu"} | use_gpu_pipeline=True, | | use_fabric: True | use_fabric=True, | | enable_scene_query_support: False | enable_scene_query_support=False, | | disable_contact_processing: False | disable_contact_processing=False, | | gravity: [0.0, 0.0, -9.81] | gravity=(0.0, 0.0, -9.81), | | | | | default_physics_material: | physics_material=RigidBodyMaterialCfg( | | static_friction: 1.0 | static_friction=1.0, | | dynamic_friction: 1.0 | dynamic_friction=1.0, | | restitution: 0.0 | restitution=0.0 | | | ) | | physx: | physx: PhysxCfg = PhysxCfg( | | worker_thread_count: ${....num_threads} | # worker_thread_count is no longer needed | | solver_type: ${....solver_type} | solver_type=1, | | use_gpu: ${contains:"cuda",${....sim_device}} | use_gpu=True, | | solver_position_iteration_count: 4 | max_position_iteration_count=4, | | solver_velocity_iteration_count: 0 | max_velocity_iteration_count=0, | | contact_offset: 0.02 | # moved to actor config | | rest_offset: 0.001 | # moved to actor config | | bounce_threshold_velocity: 0.2 | bounce_threshold_velocity=0.2, | | friction_offset_threshold: 0.04 | friction_offset_threshold=0.04, | | friction_correlation_distance: 0.025 | friction_correlation_distance=0.025, | | enable_sleeping: True | # enable_sleeping is no longer needed | | enable_stabilization: True | enable_stabilization=True, | | max_depenetration_velocity: 100.0 | # moved to RigidBodyPropertiesCfg | | | | | gpu_max_rigid_contact_count: 524288 | gpu_max_rigid_contact_count=2**23, | | gpu_max_rigid_patch_count: 81920 | gpu_max_rigid_patch_count=5 * 2**15, | | gpu_found_lost_pairs_capacity: 1024 | gpu_found_lost_pairs_capacity=2**21, | | gpu_found_lost_aggregate_pairs_capacity: 262144 | gpu_found_lost_aggregate_pairs_capacity=2**25, | | gpu_total_aggregate_pairs_capacity: 1024 | gpu_total_aggregate_pairs_capacity=2**21, | | gpu_heap_capacity: 67108864 | gpu_heap_capacity=2**26, | | gpu_temp_buffer_capacity: 16777216 | gpu_temp_buffer_capacity=2**24, | | gpu_max_num_partitions: 8 | gpu_max_num_partitions=8, | | gpu_max_soft_body_contacts: 1048576 | gpu_max_soft_body_contacts=2**20, | | gpu_max_particle_contacts: 1048576 | gpu_max_particle_contacts=2**20, | | | ) | | | ) | +--------------------------------------------------------------+-------------------------------------------------------------------+ Parameters such as ``add_ground_plane`` and ``add_distant_light`` are now part of the task logic when creating the scene. ``enable_cameras`` is now a command line argument ``--enable_cameras`` that can be passed directly to the training script. Scene Config ------------ The :class:`~omni.isaac.lab.scene.InteractiveSceneCfg` class can be used to specify parameters related to the scene, such as the number of environments and the spacing between environments. Each task config must have a variable named ``scene`` defined that holds the type :class:`~omni.isaac.lab.scene.InteractiveSceneCfg`. +--------------------------------------------------------------+-------------------------------------------------------------------+ | | | |.. code-block:: yaml |.. code-block:: python | | | | | # OmniIsaacGymEnvs | # IsaacLab | | env: | scene: InteractiveSceneCfg = InteractiveSceneCfg( | | numEnvs: ${resolve_default:512,${...num_envs}} | num_envs=512, | | envSpacing: 4.0 | env_spacing=4.0) | +--------------------------------------------------------------+-------------------------------------------------------------------+ Task Config ----------- Each environment should specify its own config class that holds task specific parameters, such as the dimensions of the observation and action buffers. Reward term scaling parameters can also be specified in the config class. In Isaac Lab, the ``controlFrequencyInv`` parameter has been renamed to ``decimation``, which must be specified as a parameter in the config class. In addition, the maximum episode length parameter (now ``episode_length_s``) is in seconds instead of steps as it was in OmniIsaacGymEnvs. To convert between step count to seconds, use the equation: ``episode_length_s = dt * decimation * num_steps``. The following parameters must be set for each environment config: .. code-block:: python decimation = 2 episode_length_s = 5.0 num_actions = 1 num_observations = 4 num_states = 0 RL Config Setup ~~~~~~~~~~~~~~~ RL config files for the rl_games library can continue to be defined in ``.yaml`` files in Isaac Lab. Most of the content of the config file can be copied directly from OmniIsaacGymEnvs. Note that in Isaac Lab, we do not use hydra to resolve relative paths in config files. Please replace any relative paths such as ``${....device}`` with the actual values of the parameters. Additionally, the observation and action clip ranges have been moved to the RL config file. For any ``clipObservations`` and ``clipActions`` parameters that were defined in the IsaacGymEnvs task config file, they should be moved to the RL config file in Isaac Lab. +--------------------------+----------------------------+ | | | | IsaacGymEnvs Task Config | Isaac Lab RL Config | +--------------------------+----------------------------+ |.. code-block:: yaml |.. code-block:: yaml | | | | | # OmniIsaacGymEnvs | # IsaacLab | | env: | params: | | clipObservations: 5.0 | env: | | clipActions: 1.0 | clip_observations: 5.0 | | | clip_actions: 1.0 | +--------------------------+----------------------------+ Environment Creation ~~~~~~~~~~~~~~~~~~~~ In OmniIsaacGymEnvs, environment creation generally happened in the ``set_up_scene()`` API, which involved creating the initial environment, cloning the environment, filtering collisions, adding the ground plane and lights, and creating the ``View`` classes for the actors. Similar functionality is performed in Isaac Lab in the ``_setup_scene()`` API. The main difference is that the base class ``_setup_scene()`` no longer performs operations for cloning the environment and adding ground plane and lights. Instead, these operations should now be implemented in individual tasks' ``_setup_scene`` implementations to provide more flexibility around the scene setup process. Also note that by defining an ``Articulation`` or ``RigidObject`` object, the actors will be added to the scene by parsing the ``spawn`` parameter in the actor config and a ``View`` class will automatically be created for the actor. This avoids the need to separately define an ``ArticulationView`` or ``RigidPrimView`` object for the actors. +------------------------------------------------------------------------------+------------------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +------------------------------------------------------------------------------+------------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def set_up_scene(self, scene) -> None: | def _setup_scene(self): | | self.get_cartpole() | self.cartpole = Articulation(self.cfg.robot_cfg) | | super().set_up_scene(scene) | # add ground plane | | | spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg() | | self._cartpoles = ArticulationView( | # clone, filter, and replicate | | prim_paths_expr="/World/envs/.*/Cartpole", | self.scene.clone_environments(copy_from_source=False) | | name="cartpole_view", reset_xform_properties=False | self.scene.filter_collisions(global_prim_paths=[]) | | ) | # add articultion to scene | | scene.add(self._cartpoles) | self.scene.articulations["cartpole"] = self.cartpole | | | # add lights | | | light_cfg = sim_utils.DomeLightCfg(intensity=2000.0) | | | light_cfg.func("/World/Light", light_cfg) | +------------------------------------------------------------------------------+------------------------------------------------------------------------+ Ground Plane ------------ In addition to the above example, more sophisticated ground planes can be defined using the :class:`~terrains.TerrainImporterCfg` class. .. code-block:: python from omni.isaac.lab.terrains import TerrainImporterCfg terrain = TerrainImporterCfg( prim_path="/World/ground", terrain_type="plane", collision_group=-1, physics_material=sim_utils.RigidBodyMaterialCfg( friction_combine_mode="multiply", restitution_combine_mode="multiply", static_friction=1.0, dynamic_friction=1.0, restitution=0.0, ), ) The terrain can then be added to the scene in ``_setup_scene(self)`` by referencing the ``TerrainImporterCfg`` object: .. code-block::python def _setup_scene(self): ... self.cfg.terrain.num_envs = self.scene.cfg.num_envs self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing self._terrain = self.cfg.terrain.class_type(self.cfg.terrain) Actors ------ In Isaac Lab, each Articulation and Rigid Body actor can have its own config class. The :class:`~omni.isaac.lab.assets.ArticulationCfg` can be used to define parameters for articulation actors, including file path, simulation parameters, actuator properties, and initial states. .. code-block::python from omni.isaac.lab.actuators import ImplicitActuatorCfg from omni.isaac.lab.assets import ArticulationCfg CARTPOLE_CFG = ArticulationCfg( spawn=sim_utils.UsdFileCfg( usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd", rigid_props=sim_utils.RigidBodyPropertiesCfg( rigid_body_enabled=True, max_linear_velocity=1000.0, max_angular_velocity=1000.0, max_depenetration_velocity=100.0, enable_gyroscopic_forces=True, ), articulation_props=sim_utils.ArticulationRootPropertiesCfg( enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0, sleep_threshold=0.005, stabilization_threshold=0.001, ), ), init_state=ArticulationCfg.InitialStateCfg( pos=(0.0, 0.0, 2.0), joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} ), actuators={ "cart_actuator": ImplicitActuatorCfg( joint_names_expr=["slider_to_cart"], effort_limit=400.0, velocity_limit=100.0, stiffness=0.0, damping=10.0, ), "pole_actuator": ImplicitActuatorCfg( joint_names_expr=["cart_to_pole"], effort_limit=400.0, velocity_limit=100.0, stiffness=0.0, damping=0.0 ), }, ) Within the :class:`~assets.ArticulationCfg`, the ``spawn`` attribute can be used to add the robot to the scene by specifying the path to the robot file. In addition, :class:`~omni.isaac.lab.sim.schemas.RigidBodyPropertiesCfg` can be used to specify simulation properties for the rigid bodies in the articulation. Similarly, :class:`~omni.isaac.lab.sim.schemas.ArticulationRootPropertiesCfg` can be used to specify simulation properties for the articulation. Joint and dof properties are now specified as part of the ``actuators`` dictionary using :class:`~actuators.ImplicitActuatorCfg`. Joints and dofs with the same properties can be grouped into regex expressions or provided as a list of names or expressions. Actors are added to the scene by simply calling ``self.cartpole = Articulation(self.cfg.robot_cfg)``, where ``self.cfg.robot_cfg`` is an :class:`~assets.ArticulationCfg` object. Once initialized, they should also be added to the :class:`~scene.InteractiveScene` by calling ``self.scene.articulations["cartpole"] = self.cartpole`` so that the :class:`~scene.InteractiveScene` can traverse through actors in the scene for writing values to the simulation and resetting. Accessing States from Simulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ APIs for accessing physics states in Isaac Lab require the creation of an :class:`~assets.Articulation` or :class:`~assets.RigidObject` object. Multiple objects can be initialized for different articulations or rigid bodies in the scene by defining corresponding :class:`~assets.ArticulationCfg` or :class:`~assets.RigidObjectCfg` config, as outlined in the section above. This replaces the previously used ``ArticulationView`` and ``RigidPrimView`` classes used in OmniIsaacGymEnvs. However, functionality between the classes are similar: +------------------------------------------------------------------+-----------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +------------------------------------------------------------------+-----------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | dof_pos = self._cartpoles.get_joint_positions(clone=False) | self.joint_pos = self._robot.data.joint_pos | | dof_vel = self._cartpoles.get_joint_velocities(clone=False) | self.joint_vel = self._robot.data.joint_vel | +------------------------------------------------------------------+-----------------------------------------------------------------+ In Isaac Lab, :class:`~assets.Articulation` and :class:`~assets.RigidObject` classes both have a ``data`` class. The data classes (:class:`~assets.ArticulationData` and :class:`~assets.RigidObjectData`) contain buffers that hold the states for the articulation and rigid objects and provide a more performant way of retrieving states from the actors. Apart from some renamings of APIs, setting states for actors can also be performed similarly between OmniIsaacGymEnvs and Isaac Lab. +---------------------------------------------------------------------------+---------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +---------------------------------------------------------------------------+---------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | indices = env_ids.to(dtype=torch.int32) | self._robot.write_joint_state_to_sim(joint_pos, joint_vel, | | self._cartpoles.set_joint_positions(dof_pos, indices=indices) | joint_ids, env_ids) | | self._cartpoles.set_joint_velocities(dof_vel, indices=indices) | | +---------------------------------------------------------------------------+---------------------------------------------------------------+ In Isaac Lab, ``root_pose`` and ``root_velocity`` have been combined into single buffers and no longer split between ``root_position``, ``root_orientation``, ``root_linear_velocity`` and ``root_angular_velocity``. .. code-block::python self.cartpole.write_root_pose_to_sim(default_root_state[:, :7], env_ids) self.cartpole.write_root_velocity_to_sim(default_root_state[:, 7:], env_ids) Creating a New Environment ~~~~~~~~~~~~~~~~~~~~~~~~~~ Each environment in Isaac Lab should be in its own directory following this structure: .. code-block:: none my_environment/ - agents/ - __init__.py - rl_games_ppo_cfg.py - __init__.py my_env.py * ``my_environment`` is the root directory of the task. * ``my_environment/agents`` is the directory containing all RL config files for the task. Isaac Lab supports multiple RL libraries that can each have its own individual config file. * ``my_environment/__init__.py`` is the main file that registers the environment with the Gymnasium interface. This allows the training and inferencing scripts to find the task by its name. The content of this file should be as follow: .. code-block:: python import gymnasium as gym from . import agents from .cartpole_env import CartpoleEnv, CartpoleEnvCfg ## # Register Gym environments. ## gym.register( id="Isaac-Cartpole-Direct-v0", entry_point="omni.isaac.lab_tasks.direct_workflow.cartpole:CartpoleEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": CartpoleEnvCfg, "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml" }, ) * ``my_environment/my_env.py`` is the main python script that implements the task logic and task config class for the environment. Task Logic ~~~~~~~~~~ The ``post_reset`` API in OmniIsaacGymEnvs is no longer required in Isaac Lab. Everything that was previously done in ``post_reset`` can be done in the ``__init__`` method after executing the base class's ``__init__``. At this point, simulation has already started. In OmniIsaacGymEnvs, due to limitations of the GPU APIs, resets could not be performed based on states of the current step. Instead, resets have to be performed at the beginning of the next time step. This restriction has been eliminated in Isaac Lab, and thus, tasks follow the correct workflow of applying actions, stepping simulation, collecting states, computing dones, calculating rewards, performing resets, and finally computing observations. This workflow is done automatically by the framework such that a ``post_physics_step`` API is not required in the task. However, individual tasks can override the ``step()`` API to control the workflow. In Isaac Lab, we also separate the ``pre_physics_step`` API for processing actions from the policy with the ``apply_action`` API, which sets the actions into the simulation. This provides more flexibility in controlling when actions should be written to simulation when ``decimation`` is used. ``pre_physics_step`` will be called once per step before stepping simulation. ``apply_actions`` will be called ``decimation`` number of times for each RL step, once before each simulation step call. The ordering of the calls are as follow: +----------------------------------+----------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +----------------------------------+----------------------------------+ |.. code-block:: none |.. code-block:: none | | | | | pre_physics_step | pre_physics_step | | |-- reset_idx() | |-- _pre_physics_step(action)| | |-- apply_action | |-- _apply_action() | | | | | post_physics_step | post_physics_step | | |-- get_observations() | |-- _get_dones() | | |-- calculate_metrics() | |-- _get_rewards() | | |-- is_done() | |-- _reset_idx() | | | |-- _get_observations() | +----------------------------------+----------------------------------+ With this approach, resets are performed based on actions from the current step instead of the previous step. Observations will also be computed with the correct states after resets. We have also performed some renamings of APIs: * ``set_up_scene(self, scene)`` --> ``_setup_scene(self)`` * ``post_reset(self)`` --> ``__init__(...)`` * ``pre_physics_step(self, actions)`` --> ``_pre_physics_step(self, actions)`` and ``_apply_action(self)`` * ``reset_idx(self, env_ids)`` --> ``_reset_idx(self, env_ids)`` * ``get_observations(self)`` --> ``_get_observations(self)`` - ``_get_observations()`` should now return a dictionary ``{"policy": obs}`` * ``calculate_metrics(self)`` --> ``_get_rewards(self)`` - ``_get_rewards()`` should now return the reward buffer * ``is_done(self)`` --> ``_get_dones(self)`` - ``_get_dones()`` should now return 2 buffers: ``reset`` and ``time_out`` buffers Putting It All Together ~~~~~~~~~~~~~~~~~~~~~~~ The Cartpole environment is shown here in completion to fully show the comparison between the OmniIsaacGymEnvs implementation and the Isaac Lab implementation. Task Config ----------- Task config in Isaac Lab can be split into the main task configuration class and individual config objects for the actors. +-----------------------------------------------------------------+-----------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +-----------------------------------------------------------------+-----------------------------------------------------------------+ |.. code-block:: yaml |.. code-block:: python | | | | | # used to create the object | @configclass | | | class CartpoleEnvCfg(DirectRLEnvCfg): | | name: Cartpole | | | | # simulation | | physics_engine: ${..physics_engine} | sim: SimulationCfg = SimulationCfg(dt=1 / 120) | | | # robot | | # if given, will override the device setting in gym. | robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace( | | env: | prim_path="/World/envs/env_.*/Robot") | | | cart_dof_name = "slider_to_cart" | | numEnvs: ${resolve_default:512,${...num_envs}} | pole_dof_name = "cart_to_pole" | | envSpacing: 4.0 | # scene | | resetDist: 3.0 | scene: InteractiveSceneCfg = InteractiveSceneCfg( | | maxEffort: 400.0 | num_envs=4096, env_spacing=4.0, replicate_physics=True) | | | # env | | clipObservations: 5.0 | decimation = 2 | | clipActions: 1.0 | episode_length_s = 5.0 | | controlFrequencyInv: 2 # 60 Hz | action_scale = 100.0 # [N] | | | num_actions = 1 | | sim: | num_observations = 4 | | | num_states = 0 | | dt: 0.0083 # 1/120 s | # reset | | use_gpu_pipeline: ${eq:${...pipeline},"gpu"} | max_cart_pos = 3.0 | | gravity: [0.0, 0.0, -9.81] | initial_pole_angle_range = [-0.25, 0.25] | | add_ground_plane: True | # reward scales | | add_distant_light: False | rew_scale_alive = 1.0 | | use_fabric: True | rew_scale_terminated = -2.0 | | enable_scene_query_support: False | rew_scale_pole_pos = -1.0 | | disable_contact_processing: False | rew_scale_cart_vel = -0.01 | | | rew_scale_pole_vel = -0.005 | | enable_cameras: False | | | | | | default_physics_material: | CARTPOLE_CFG = ArticulationCfg( | | static_friction: 1.0 | spawn=sim_utils.UsdFileCfg( | | dynamic_friction: 1.0 | usd_path=f"{ISAACLAB_NUCLEUS_DIR}/.../cartpole.usd", | | restitution: 0.0 | rigid_props=sim_utils.RigidBodyPropertiesCfg( | | | rigid_body_enabled=True, | | physx: | max_linear_velocity=1000.0, | | worker_thread_count: ${....num_threads} | max_angular_velocity=1000.0, | | solver_type: ${....solver_type} | max_depenetration_velocity=100.0, | | use_gpu: ${eq:${....sim_device},"gpu"} # set to False to... | enable_gyroscopic_forces=True, | | solver_position_iteration_count: 4 | ), | | solver_velocity_iteration_count: 0 | articulation_props=sim_utils.ArticulationRootPropertiesCfg( | | contact_offset: 0.02 | enabled_self_collisions=False, | | rest_offset: 0.001 | solver_position_iteration_count=4, | | bounce_threshold_velocity: 0.2 | solver_velocity_iteration_count=0, | | friction_offset_threshold: 0.04 | sleep_threshold=0.005, | | friction_correlation_distance: 0.025 | stabilization_threshold=0.001, | | enable_sleeping: True | ), | | enable_stabilization: True | ), | | max_depenetration_velocity: 100.0 | init_state=ArticulationCfg.InitialStateCfg( | | | pos=(0.0, 0.0, 2.0), | | # GPU buffers | joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} | | gpu_max_rigid_contact_count: 524288 | ), | | gpu_max_rigid_patch_count: 81920 | actuators={ | | gpu_found_lost_pairs_capacity: 1024 | "cart_actuator": ImplicitActuatorCfg( | | gpu_found_lost_aggregate_pairs_capacity: 262144 | joint_names_expr=["slider_to_cart"], | | gpu_total_aggregate_pairs_capacity: 1024 | effort_limit=400.0, | | gpu_max_soft_body_contacts: 1048576 | velocity_limit=100.0, | | gpu_max_particle_contacts: 1048576 | stiffness=0.0, | | gpu_heap_capacity: 67108864 | damping=10.0, | | gpu_temp_buffer_capacity: 16777216 | ), | | gpu_max_num_partitions: 8 | "pole_actuator": ImplicitActuatorCfg( | | | joint_names_expr=["cart_to_pole"], effort_limit=400.0, | | Cartpole: | velocity_limit=100.0, stiffness=0.0, damping=0.0 | | override_usd_defaults: False | ), | | enable_self_collisions: False | }, | | enable_gyroscopic_forces: True | ) | | solver_position_iteration_count: 4 | | | solver_velocity_iteration_count: 0 | | | sleep_threshold: 0.005 | | | stabilization_threshold: 0.001 | | | density: -1 | | | max_depenetration_velocity: 100.0 | | | contact_offset: 0.02 | | | rest_offset: 0.001 | | +-----------------------------------------------------------------+-----------------------------------------------------------------+ Task Setup ---------- The ``post_reset`` API in OmniIsaacGymEnvs is no longer required in Isaac Lab. Everything that was previously done in ``post_reset`` can be done in the ``__init__`` method after executing the base class's ``__init__``. At this point, simulation has already started. +-------------------------------------------------------------------------+-------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +-------------------------------------------------------------------------+-------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | class CartpoleTask(RLTask): | class CartpoleEnv(DirectRLEnv): | | | cfg: CartpoleEnvCfg | | def __init__(self, name, sim_config, env, offset=None) -> None: | def __init__(self, cfg: CartpoleEnvCfg, | | | render_mode: str | None = None, **kwargs): | | self.update_config(sim_config) | super().__init__(cfg, render_mode, **kwargs) | | self._max_episode_length = 500 | | | | | | self._num_observations = 4 | self._cart_dof_idx, _ = self.cartpole.find_joints( | | self._num_actions = 1 | self.cfg.cart_dof_name) | | | self._pole_dof_idx, _ = self.cartpole.find_joints( | | RLTask.__init__(self, name, env) | self.cfg.pole_dof_name) | | | self.action_scale=self.cfg.action_scale | | def update_config(self, sim_config): | | | self._sim_config = sim_config | self.joint_pos = self.cartpole.data.joint_pos | | self._cfg = sim_config.config | self.joint_vel = self.cartpole.data.joint_vel | | self._task_cfg = sim_config. | | | task_config | | | | | | self._num_envs = self._task_cfg["env"]["numEnvs"] | | | self._env_spacing = self._task_cfg["env"]["envSpacing"] | | | self._cartpole_positions = torch.tensor([0.0, 0.0, 2.0]) | | | | | | self._reset_dist = self._task_cfg["env"]["resetDist"] | | | self._max_push_effort = self._task_cfg["env"]["maxEffort"] | | | | | | | | | def post_reset(self): | | | self._cart_dof_idx = self._cartpoles.get_dof_index( | | | "cartJoint") | | | self._pole_dof_idx = self._cartpoles.get_dof_index( | | | "poleJoint") | | | # randomize all envs | | | indices = torch.arange( | | | self._cartpoles.count, dtype=torch.int64, | | | device=self._device) | | | self.reset_idx(indices) | | +-------------------------------------------------------------------------+-------------------------------------------------------------+ Scene Setup ----------- ``set_up_scene`` in OmniIsaacGymEnvs has been replaced by ``_setup_scene``. In Isaac Lab, cloning and collision filtering have been provided as APIs for the task class to call when necessary. Similarly, adding ground plane and lights should also be taken care of in the task class. Adding actors to the scene has been replaced by ``self.scene.articulations["cartpole"] = self.cartpole``. +-----------------------------------------------------------+----------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +-----------------------------------------------------------+----------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def set_up_scene(self, scene) -> None: | def _setup_scene(self): | | | self.cartpole = Articulation(self.cfg.robot_cfg) | | self.get_cartpole() | # add ground plane | | super().set_up_scene(scene) | spawn_ground_plane(prim_path="/World/ground", | | self._cartpoles = ArticulationView( | cfg=GroundPlaneCfg()) | | prim_paths_expr="/World/envs/.*/Cartpole", | # clone, filter, and replicate | | name="cartpole_view", | self.scene.clone_environments( | | reset_xform_properties=False | copy_from_source=False) | | ) | self.scene.filter_collisions( | | scene.add(self._cartpoles) | global_prim_paths=[]) | | return | # add articultion to scene | | | self.scene.articulations["cartpole"] = self.cartpole | | def get_cartpole(self): | | | cartpole = Cartpole( | # add lights | | prim_path=self.default_zero_env_path+"/Cartpole", | light_cfg = sim_utils.DomeLightCfg( | | name="Cartpole", | intensity=2000.0, color=(0.75, 0.75, 0.75)) | | translation=self._cartpole_positions | light_cfg.func("/World/Light", light_cfg) | | ) | | | # applies articulation settings from the | | | # task configuration yaml file | | | self._sim_config.apply_articulation_settings( | | | "Cartpole", get_prim_at_path(cartpole.prim_path), | | | self._sim_config.parse_actor_config("Cartpole") | | | ) | | +-----------------------------------------------------------+----------------------------------------------------------+ Pre-Physics Step ---------------- Note that resets are no longer performed in the ``pre_physics_step`` API. In addition, the separation of ``_pre_physics_step`` and ``_apply_action`` allow for more flexibility in processing the action buffer and setting actions into simulation. +------------------------------------------------------------------+-------------------------------------------------------------+ | OmniIsaacGymEnvs | IsaacLab | +------------------------------------------------------------------+-------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def pre_physics_step(self, actions) -> None: | def _pre_physics_step(self, | | if not self.world.is_playing(): | actions: torch.Tensor) -> None: | | return | self.actions = self.action_scale * actions | | | | | reset_env_ids = self.reset_buf.nonzero( | def _apply_action(self) -> None: | | as_tuple=False).squeeze(-1) | self.cartpole.set_joint_effort_target( | | if len(reset_env_ids) > 0: | self.actions, joint_ids=self._cart_dof_idx) | | self.reset_idx(reset_env_ids) | | | | | | actions = actions.to(self._device) | | | | | | forces = torch.zeros((self._cartpoles.count, | | | self._cartpoles.num_dof), | | | dtype=torch.float32, device=self._device) | | | forces[:, self._cart_dof_idx] = | | | self._max_push_effort * actions[:, 0] | | | | | | indices = torch.arange(self._cartpoles.count, | | | dtype=torch.int32, device=self._device) | | | self._cartpoles.set_joint_efforts( | | | forces, indices=indices) | | +------------------------------------------------------------------+-------------------------------------------------------------+ Dones and Resets ---------------- In Isaac Lab, ``dones`` are computed in the ``_get_dones()`` method and should return two variables: ``resets`` and ``time_out``. ``_reset_idx()`` is also called after stepping simulation instead of before, as it was done in OmniIsaacGymEnvs. ``progress_buf`` has been renamed to ``episode_length_buf`` in Isaac Lab and bookkeeping is now done automatically by the framework. Task implementations should no longer increment and reset the ``episode_length_buf`` buffer. +------------------------------------------------------------------+--------------------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +------------------------------------------------------------------+--------------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def is_done(self) -> None: | def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: | | resets = torch.where( | self.joint_pos = self.cartpole.data.joint_pos | | torch.abs(self.cart_pos) > self._reset_dist, 1, 0) | self.joint_vel = self.cartpole.data.joint_vel | | resets = torch.where( | | | torch.abs(self.pole_pos) > math.pi / 2, 1, resets) | time_out = self.episode_length_buf >= self.max_episode_length - 1 | | resets = torch.where( | out_of_bounds = torch.any(torch.abs( | | self.progress_buf >= self._max_episode_length, 1, resets) | self.joint_pos[:, self._pole_dof_idx] > self.cfg.max_cart_pos), | | self.reset_buf[:] = resets | dim=1) | | | out_of_bounds = out_of_bounds | torch.any( | | | torch.abs(self.joint_pos[:, self._pole_dof_idx]) > math.pi / 2, | | | dim=1) | | | return out_of_bounds, time_out | | | | | def reset_idx(self, env_ids): | def _reset_idx(self, env_ids: Sequence[int] | None): | | num_resets = len(env_ids) | if env_ids is None: | | | env_ids = self.cartpole._ALL_INDICES | | # randomize DOF positions | super()._reset_idx(env_ids) | | dof_pos = torch.zeros((num_resets, self._cartpoles.num_dof), | | | device=self._device) | joint_pos = self.cartpole.data.default_joint_pos[env_ids] | | dof_pos[:, self._cart_dof_idx] = 1.0 * ( | joint_pos[:, self._pole_dof_idx] += sample_uniform( | | 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | self.cfg.initial_pole_angle_range[0] * math.pi, | | dof_pos[:, self._pole_dof_idx] = 0.125 * math.pi * ( | self.cfg.initial_pole_angle_range[1] * math.pi, | | 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | joint_pos[:, self._pole_dof_idx].shape, | | | joint_pos.device, | | # randomize DOF velocities | ) | | dof_vel = torch.zeros((num_resets, self._cartpoles.num_dof), | joint_vel = self.cartpole.data.default_joint_vel[env_ids] | | device=self._device) | | | dof_vel[:, self._cart_dof_idx] = 0.5 * ( | default_root_state = self.cartpole.data.default_root_state[env_ids] | | 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | default_root_state[:, :3] += self.scene.env_origins[env_ids] | | dof_vel[:, self._pole_dof_idx] = 0.25 * math.pi * ( | | | 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | self.joint_pos[env_ids] = joint_pos | | | self.joint_vel[env_ids] = joint_vel | | # apply resets | | | indices = env_ids.to(dtype=torch.int32) | self.cartpole.write_root_pose_to_sim( | | self._cartpoles.set_joint_positions(dof_pos, indices=indices) | default_root_state[:, :7], env_ids) | | self._cartpoles.set_joint_velocities(dof_vel, indices=indices) | self.cartpole.write_root_velocity_to_sim( | | | default_root_state[:, 7:], env_ids) | | # bookkeeping | self.cartpole.write_joint_state_to_sim( | | self.reset_buf[env_ids] = 0 | joint_pos, joint_vel, None, env_ids) | | self.progress_buf[env_ids] = 0 | | | | | | | | +------------------------------------------------------------------+--------------------------------------------------------------------------+ Rewards ------- In Isaac Lab, rewards are implemented in the ``_get_rewards`` API and should return the reward buffer instead of assigning it directly to ``self.rew_buf``. Computation in the reward function can also be performed using pytorch jit through defining functions with the ``@torch.jit.script`` annotation. +-------------------------------------------------------+-----------------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +-------------------------------------------------------+-----------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def calculate_metrics(self) -> None: | def _get_rewards(self) -> torch.Tensor: | | reward = (1.0 - self.pole_pos * self.pole_pos | total_reward = compute_rewards( | | - 0.01 * torch.abs(self.cart_vel) - 0.005 | self.cfg.rew_scale_alive, | | * torch.abs(self.pole_vel)) | self.cfg.rew_scale_terminated, | | reward = torch.where( | self.cfg.rew_scale_pole_pos, | | torch.abs(self.cart_pos) > self._reset_dist, | self.cfg.rew_scale_cart_vel, | | torch.ones_like(reward) * -2.0, reward) | self.cfg.rew_scale_pole_vel, | | reward = torch.where( | self.joint_pos[:, self._pole_dof_idx[0]], | | torch.abs(self.pole_pos) > np.pi / 2, | self.joint_vel[:, self._pole_dof_idx[0]], | | torch.ones_like(reward) * -2.0, reward) | self.joint_pos[:, self._cart_dof_idx[0]], | | | self.joint_vel[:, self._cart_dof_idx[0]], | | self.rew_buf[:] = reward | self.reset_terminated, | | | ) | | | return total_reward | | | | | | @torch.jit.script | | | def compute_rewards( | | | rew_scale_alive: float, | | | rew_scale_terminated: float, | | | rew_scale_pole_pos: float, | | | rew_scale_cart_vel: float, | | | rew_scale_pole_vel: float, | | | pole_pos: torch.Tensor, | | | pole_vel: torch.Tensor, | | | cart_pos: torch.Tensor, | | | cart_vel: torch.Tensor, | | | reset_terminated: torch.Tensor, | | | ): | | | rew_alive = rew_scale_alive * (1.0 - reset_terminated.float()) | | | rew_termination = rew_scale_terminated * reset_terminated.float() | | | rew_pole_pos = rew_scale_pole_pos * torch.sum( | | | torch.square(pole_pos), dim=-1) | | | rew_cart_vel = rew_scale_cart_vel * torch.sum( | | | torch.abs(cart_vel), dim=-1) | | | rew_pole_vel = rew_scale_pole_vel * torch.sum( | | | torch.abs(pole_vel), dim=-1) | | | total_reward = (rew_alive + rew_termination | | | + rew_pole_pos + rew_cart_vel + rew_pole_vel) | | | return total_reward | +-------------------------------------------------------+-----------------------------------------------------------------------+ Observations ------------ In Isaac Lab, the ``_get_observations()`` API must return a dictionary with the key ``policy`` that has the observation buffer as the value. When working with asymmetric actor-critic states, the states for the critic should have the key ``critic`` and be returned with the observation buffer in the same dictionary. +------------------------------------------------------------------+-------------------------------------------------------------+ | OmniIsaacGymEnvs | Isaac Lab | +------------------------------------------------------------------+-------------------------------------------------------------+ |.. code-block:: python |.. code-block:: | | | | | def get_observations(self) -> dict: | def _get_observations(self) -> dict: | | dof_pos = self._cartpoles.get_joint_positions(clone=False) | obs = torch.cat( | | dof_vel = self._cartpoles.get_joint_velocities(clone=False) | ( | | | self.joint_pos[:, self._pole_dof_idx[0]], | | self.cart_pos = dof_pos[:, self._cart_dof_idx] | self.joint_vel[:, self._pole_dof_idx[0]], | | self.cart_vel = dof_vel[:, self._cart_dof_idx] | self.joint_pos[:, self._cart_dof_idx[0]], | | self.pole_pos = dof_pos[:, self._pole_dof_idx] | self.joint_vel[:, self._cart_dof_idx[0]], | | self.pole_vel = dof_vel[:, self._pole_dof_idx] | ), | | self.obs_buf[:, 0] = self.cart_pos | dim=-1, | | self.obs_buf[:, 1] = self.cart_vel | ) | | self.obs_buf[:, 2] = self.pole_pos | observations = {"policy": obs} | | self.obs_buf[:, 3] = self.pole_vel | return observations | | | | | observations = {self._cartpoles.name: | | | {"obs_buf": self.obs_buf}} | | | return observations | | +------------------------------------------------------------------+-------------------------------------------------------------+ Domain Randomization ~~~~~~~~~~~~~~~~~~~~ In OmniIsaacGymEnvs, domain randomization was specified through the task ``.yaml`` config file. In Isaac Lab, the domain randomization configuration uses the :class:`~omni.isaac.lab.utils.configclass` module to specify a configuration class consisting of :class:`~managers.EventTermCfg` variables. Below is an example of a configuration class for domain randomization: .. code-block:: python @configclass class EventCfg: robot_physics_material = EventTerm( func=mdp.randomize_rigid_body_material, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", body_names=".*"), "static_friction_range": (0.7, 1.3), "dynamic_friction_range": (1.0, 1.0), "restitution_range": (1.0, 1.0), "num_buckets": 250, }, ) robot_joint_stiffness_and_damping = EventTerm( func=mdp.randomize_actuator_gains, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", joint_names=".*"), "stiffness_distribution_params": (0.75, 1.5), "damping_distribution_params": (0.3, 3.0), "operation": "scale", "distribution": "log_uniform", }, ) reset_gravity = EventTerm( func=mdp.randomize_physics_scene_gravity, mode="interval", is_global_time=True, interval_range_s=(36.0, 36.0), # time_s = num_steps * (decimation * dt) params={ "gravity_distribution_params": ([0.0, 0.0, 0.0], [0.0, 0.0, 0.4]), "operation": "add", "distribution": "gaussian", }, ) Each ``EventTerm`` object is of the :class:`~managers.EventTermCfg` class and takes in a ``func`` parameter for specifying the function to call during randomization, a ``mode`` parameter, which can be ``startup``, ``reset`` or ``interval``. THe ``params`` dictionary should provide the necessary arguments to the function that is specified in the ``func`` parameter. Functions specified as ``func`` for the ``EventTerm`` can be found in the :class:`~envs.mdp.events` module. Note that as part of the ``"asset_cfg": SceneEntityCfg("robot", body_names=".*")`` parameter, the name of the actor ``"robot"`` is provided, along with the body or joint names specified as a regex expression, which will be the actors and bodies/joints that will have randomization applied. One difference with OmniIsaacGymEnvs is that ``interval`` randomization is now specified as seconds instead of steps. When ``mode="interval"``, the ``interval_range_s`` parameter must also be provided, which specifies the range of seconds for which randomization should be applied. This range will then be randomized to determine a specific time in seconds when the next randomization will occur for the term. To convert between steps to seconds, use the equation ``time_s = num_steps * (decimation * dt)``. Similar to OmniIsaacGymEnvs, randomization APIs are available for randomizing articulation properties, such as joint stiffness and damping, joint limits, rigid body materials, fixed tendon properties, as well as rigid body properties, such as mass and rigid body materials. Randomization of the physics scene gravity is also supported. Note that randomization of scale is current not supported in Isaac Lab. To randomize scale, please set up the scene in a way where each environment holds the actor at a different scale. Once the ``configclass`` for the randomization terms have been set up, the class must be added to the base config class for the task and be assigned to the variable ``events``. .. code-block:: python @configclass class MyTaskConfig: events: EventCfg = EventCfg() Action and Observation Noise ---------------------------- Actions and observation noise can also be added using the :class:`~utils.configclass` module. Action and observation noise configs must be added to the main task config using the ``action_noise_model`` and ``observation_noise_model`` variables: .. code-block:: python @configclass class MyTaskConfig: # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset action_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.05, operation="add"), bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.015, operation="abs"), ) # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset observation_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.002, operation="add"), bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.0001, operation="abs"), ) :class:`~.utils.noise.NoiseModelWithAdditiveBiasCfg` can be used to sample both uncorrelated noise per step as well as correlated noise that is re-sampled at reset time. The ``noise_cfg`` term specifies the Gaussian distribution that will be sampled at each step for all environments. This noise will be added to the corresponding actions and observations buffers at every step. The ``bias_noise_cfg`` term specifies the Gaussian distribution for the correlated noise that will be sampled at reset time for the environments being reset. The same noise will be applied each step for the remaining of the episode for the environments and resampled at the next reset. This replaces the following setup in OmniIsaacGymEnvs: .. code-block:: yaml domain_randomization: randomize: True randomization_params: observations: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, .0001] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0, .002] actions: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, 0.015] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0., 0.05] Launching Training ~~~~~~~~~~~~~~~~~~ To launch a training in Isaac Lab, use the command: .. code-block:: bash python source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-Direct-v0 --headless Launching Inferencing ~~~~~~~~~~~~~~~~~~~~~ To launch inferencing in Isaac Lab, use the command: .. code-block:: bash python source/standalone/workflows/rl_games/play.py --task=Isaac-Cartpole-Direct-v0 --num_envs=25 --checkpoint=<path/to/checkpoint>
78,349
reStructuredText
79.194473
235
0.381932
isaac-sim/IsaacLab/docs/source/migration/migrating_from_isaacgymenvs.rst
.. _migrating-from-isaacgymenvs: Migrating from IsaacGymEnvs and Isaac Gym Preview Release ========================================================= .. currentmodule:: omni.isaac.lab IsaacGymEnvs was a reinforcement learning framework designed for the Isaac Gym Preview Release. As both IsaacGymEnvs and the Isaac Gym Preview Release are now deprecated, the following guide walks through the key differences between IsaacGymEnvs and Isaac Lab, as well as differences in APIs between Isaac Gym Preview Release and Isaac Sim. Task Config Setup ~~~~~~~~~~~~~~~~~ In IsaacGymEnvs, task config files were defined in ``.yaml`` format. With Isaac Lab, configs are now specified using a specialized Python class :class:`~omni.isaac.lab.utils.configclass`. The :class:`~omni.isaac.lab.utils.configclass` module provides a wrapper on top of Python's ``dataclasses`` module. Each environment should specify its own config class annotated by ``@configclass`` that inherits from :class:`~envs.DirectRLEnvCfg`, which can include simulation parameters, environment scene parameters, robot parameters, and task-specific parameters. Below is an example skeleton of a task config class: .. code-block:: python from omni.isaac.lab.envs import DirectRLEnvCfg from omni.isaac.lab.scene import InteractiveSceneCfg from omni.isaac.lab.sim import SimulationCfg @configclass class MyEnvCfg(DirectRLEnvCfg): # simulation sim: SimulationCfg = SimulationCfg() # robot robot_cfg: ArticulationCfg = ArticulationCfg() # scene scene: InteractiveSceneCfg = InteractiveSceneCfg() # env decimation = 2 episode_length_s = 5.0 num_actions = 1 num_observations = 4 num_states = 0 # task-specific parameters ... Simulation Config ----------------- Simulation related parameters are defined as part of the :class:`~omni.isaac.lab.sim.SimulationCfg` class, which is a :class:`~omni.isaac.lab.utils.configclass` module that holds simulation parameters such as ``dt``, ``device``, and ``gravity``. Each task config must have a variable named ``sim`` defined that holds the type :class:`~omni.isaac.lab.sim.SimulationCfg`. In Isaac Lab, the use of ``substeps`` has been replaced by a combination of the simulation ``dt`` and the ``decimation`` parameters. For example, in IsaacGymEnvs, having ``dt=1/60`` and ``substeps=2`` is equivalent to taking 2 simulation steps with ``dt=1/120``, but running the task step at ``1/60`` seconds. The ``decimation`` parameter is a task parameter that controls the number of simulation steps to take for each task (or RL) step, replacing the ``controlFrequencyInv`` parameter in IsaacGymEnvs. Thus, the same setup in Isaac Lab will become ``dt=1/120`` and ``decimation=2``. In Isaac Sim, physx simulation parameters such as ``num_position_iterations``, ``num_velocity_iterations``, ``contact_offset``, ``rest_offset``, ``bounce_threshold_velocity``, ``max_depenetration_velocity`` can all be specified on a per-actor basis. These parameters have been moved from the physx simulation config to each individual articulation and rigid body config. When running simulation on the GPU, buffers in PhysX require pre-allocation for computing and storing information such as contacts, collisions and aggregate pairs. These buffers may need to be adjusted depending on the complexity of the environment, the number of expected contacts and collisions, and the number of actors in the environment. The :class:`~omni.isaac.lab.sim.PhysxCfg` class provides access for setting the GPU buffer dimensions. +--------------------------------------------------------------+-------------------------------------------------------------------+ | | | |.. code-block:: yaml |.. code-block:: python | | | | | # IsaacGymEnvs | # IsaacLab | | sim: | sim: SimulationCfg = SimulationCfg( | | dt: 0.0166 # 1/60 s | dt=1 / 120, | | substeps: 2 | # decimation will be set in the task config | | up_axis: "z" | # up axis will always be Z in isaac sim | | use_gpu_pipeline: ${eq:${...pipeline},"gpu"} | use_gpu_pipeline=True, | | gravity: [0.0, 0.0, -9.81] | gravity=(0.0, 0.0, -9.81), | | physx: | physx: PhysxCfg = PhysxCfg( | | num_threads: ${....num_threads} | # num_threads is no longer needed | | solver_type: ${....solver_type} | solver_type=1, | | use_gpu: ${contains:"cuda",${....sim_device}} | use_gpu=True, | | num_position_iterations: 4 | max_position_iteration_count=4, | | num_velocity_iterations: 0 | max_velocity_iteration_count=0, | | contact_offset: 0.02 | # moved to actor config | | rest_offset: 0.001 | # moved to actor config | | bounce_threshold_velocity: 0.2 | bounce_threshold_velocity=0.2, | | max_depenetration_velocity: 100.0 | # moved to actor config | | default_buffer_size_multiplier: 2.0 | # default_buffer_size_multiplier is no longer needed | | max_gpu_contact_pairs: 1048576 # 1024*1024 | gpu_max_rigid_contact_count=2**23 | | num_subscenes: ${....num_subscenes} | # num_subscenes is no longer needed | | contact_collection: 0 | # contact_collection is no longer needed | | | )) | +--------------------------------------------------------------+-------------------------------------------------------------------+ Scene Config ------------ The :class:`~omni.isaac.lab.scene.InteractiveSceneCfg` class can be used to specify parameters related to the scene, such as the number of environments and the spacing between environments. Each task config must have a variable named ``scene`` defined that holds the type :class:`~omni.isaac.lab.scene.InteractiveSceneCfg`. +--------------------------------------------------------------+-------------------------------------------------------------------+ | | | |.. code-block:: yaml |.. code-block:: python | | | | | # IsaacGymEnvs | # IsaacLab | | env: | scene: InteractiveSceneCfg = InteractiveSceneCfg( | | numEnvs: ${resolve_default:512,${...num_envs}} | num_envs=512, | | envSpacing: 4.0 | env_spacing=4.0) | +--------------------------------------------------------------+-------------------------------------------------------------------+ Task Config ----------- Each environment should specify its own config class that holds task specific parameters, such as the dimensions of the observation and action buffers. Reward term scaling parameters can also be specified in the config class. The following parameters must be set for each environment config: .. code-block:: python decimation = 2 episode_length_s = 5.0 num_actions = 1 num_observations = 4 num_states = 0 Note that the maximum episode length parameter (now ``episode_length_s``) is in seconds instead of steps as it was in IsaacGymEnvs. To convert between step count to seconds, use the equation: ``episode_length_s = dt * decimation * num_steps`` RL Config Setup ~~~~~~~~~~~~~~~ RL config files for the rl_games library can continue to be defined in ``.yaml`` files in Isaac Lab. Most of the content of the config file can be copied directly from IsaacGymEnvs. Note that in Isaac Lab, we do not use hydra to resolve relative paths in config files. Please replace any relative paths such as ``${....device}`` with the actual values of the parameters. Additionally, the observation and action clip ranges have been moved to the RL config file. For any ``clipObservations`` and ``clipActions`` parameters that were defined in the IsaacGymEnvs task config file, they should be moved to the RL config file in Isaac Lab. +--------------------------+----------------------------+ | | | | IsaacGymEnvs Task Config | Isaac Lab RL Config | +--------------------------+----------------------------+ |.. code-block:: yaml |.. code-block:: yaml | | | | | # IsaacGymEnvs | # IsaacLab | | env: | params: | | clipObservations: 5.0 | env: | | clipActions: 1.0 | clip_observations: 5.0 | | | clip_actions: 1.0 | +--------------------------+----------------------------+ Environment Creation ~~~~~~~~~~~~~~~~~~~~ In IsaacGymEnvs, environment creation generally included four components: creating the sim object with ``create_sim()``, creating the ground plane, importing the assets from MJCF or URDF files, and finally creating the environments by looping through each environment and adding actors into the environments. Isaac Lab no longer requires calling the ``create_sim()`` method to retrieve the sim object. Instead, the simulation context is retrieved automatically by the framework. It is also no longer required to use the ``sim`` as an argument for the simulation APIs. In replacement of ``create_sim()``, tasks can implement the ``_setup_scene()`` method in Isaac Lab. This method can be used for adding actors into the scene, adding ground plane, cloning the actors, and adding any other optional objects into the scene, such as lights. +------------------------------------------------------------------------------+------------------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +------------------------------------------------------------------------------+------------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def create_sim(self): | def _setup_scene(self): | | # set the up axis to be z-up | self.cartpole = Articulation(self.cfg.robot_cfg) | | self.up_axis = self.cfg["sim"]["up_axis"] | # add ground plane | | | spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg() | | self.sim = super().create_sim(self.device_id, self.graphics_device_id, | # clone, filter, and replicate | | self.physics_engine, self.sim_params) | self.scene.clone_environments(copy_from_source=False) | | self._create_ground_plane() | self.scene.filter_collisions(global_prim_paths=[]) | | self._create_envs(self.num_envs, self.cfg["env"]['envSpacing'], | # add articultion to scene | | int(np.sqrt(self.num_envs))) | self.scene.articulations["cartpole"] = self.cartpole | | | # add lights | | | light_cfg = sim_utils.DomeLightCfg(intensity=2000.0) | | | light_cfg.func("/World/Light", light_cfg) | +------------------------------------------------------------------------------+------------------------------------------------------------------------+ Ground Plane ------------ In Isaac Lab, most of the environment creation process has been simplified into configs with the :class:`~omni.isaac.lab.utils.configclass` module. The ground plane can be defined using the :class:`~terrains.TerrainImporterCfg` class. .. code-block:: python from omni.isaac.lab.terrains import TerrainImporterCfg terrain = TerrainImporterCfg( prim_path="/World/ground", terrain_type="plane", collision_group=-1, physics_material=sim_utils.RigidBodyMaterialCfg( friction_combine_mode="multiply", restitution_combine_mode="multiply", static_friction=1.0, dynamic_friction=1.0, restitution=0.0, ), ) The terrain can then be added to the scene in ``_setup_scene(self)`` by referencing the ``TerrainImporterCfg`` object: .. code-block::python def _setup_scene(self): ... self.cfg.terrain.num_envs = self.scene.cfg.num_envs self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing self._terrain = self.cfg.terrain.class_type(self.cfg.terrain) Actors ------ Isaac Lab and Isaac Sim both use the `USD (Universal Scene Description) <https://github.com/PixarAnimationStudios/OpenUSD>`_ library for describing the scene. Assets defined in MJCF and URDF formats can be imported to USD using importer tools described in the `Importing a New Asset <../../how-to/import_new_asset.rst>`_ tutorial. Each Articulation and Rigid Body actor can also have its own config class. The :class:`~omni.isaac.lab.assets.ArticulationCfg` can be used to define parameters for articulation actors, including file path, simulation parameters, actuator properties, and initial states. .. code-block::python from omni.isaac.lab.actuators import ImplicitActuatorCfg from omni.isaac.lab.assets import ArticulationCfg CARTPOLE_CFG = ArticulationCfg( spawn=sim_utils.UsdFileCfg( usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd", rigid_props=sim_utils.RigidBodyPropertiesCfg( rigid_body_enabled=True, max_linear_velocity=1000.0, max_angular_velocity=1000.0, max_depenetration_velocity=100.0, enable_gyroscopic_forces=True, ), articulation_props=sim_utils.ArticulationRootPropertiesCfg( enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0, sleep_threshold=0.005, stabilization_threshold=0.001, ), ), init_state=ArticulationCfg.InitialStateCfg( pos=(0.0, 0.0, 2.0), joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} ), actuators={ "cart_actuator": ImplicitActuatorCfg( joint_names_expr=["slider_to_cart"], effort_limit=400.0, velocity_limit=100.0, stiffness=0.0, damping=10.0, ), "pole_actuator": ImplicitActuatorCfg( joint_names_expr=["cart_to_pole"], effort_limit=400.0, velocity_limit=100.0, stiffness=0.0, damping=0.0 ), }, ) Within the :class:`~assets.ArticulationCfg`, the ``spawn`` attribute can be used to add the robot to the scene by specifying the path to the robot file. In addition, :class:`~omni.isaac.lab.sim.schemas.RigidBodyPropertiesCfg` can be used to specify simulation properties for the rigid bodies in the articulation. Similarly, :class:`~omni.isaac.lab.sim.schemas.ArticulationRootPropertiesCfg` can be used to specify simulation properties for the articulation. Joint and dof properties are now specified as part of the ``actuators`` dictionary using :class:`~actuators.ImplicitActuatorCfg`. Joints and dofs with the same properties can be grouped into regex expressions or provided as a list of names or expressions. Actors are added to the scene by simply calling ``self.cartpole = Articulation(self.cfg.robot_cfg)``, where ``self.cfg.robot_cfg`` is an :class:`~assets.ArticulationCfg` object. Once initialized, they should also be added to the :class:`~scene.InteractiveScene` by calling ``self.scene.articulations["cartpole"] = self.cartpole`` so that the :class:`~scene.InteractiveScene` can traverse through actors in the scene for writing values to the simulation and resetting. Simulation Parameters for Actors """""""""""""""""""""""""""""""" Some simulation parameters related to Rigid Bodies and Articulations may have different default values between Isaac Gym Preview Release and Isaac Sim. It may be helpful to double check the USD assets to ensure that the default values are applicable for the asset. For instance, the following parameters in the ``RigidBodyAPI`` could be different between Isaac Gym Preview Release and Isaac Sim: .. list-table:: :widths: 50 50 50 :header-rows: 1 * - RigidBodyAPI Parameter - Default Value in Isaac Sim - Default Value in Isaac Gym Preview Release * - Linear Damping - 0.00 - 0.00 * - Angular Damping - 0.05 - 0.0 * - Max Linear Velocity - inf - 1000 * - Max Angular Velocity - 5729.58008 (degree/s) - 64.0 (rad/s) * - Max Contact Impulse - inf - 1e32 Articulation parameters for the ``JointAPI`` and ``DriveAPI`` could be altered as well. Note that the Isaac Sim UI assumes the unit of angle to be degrees. It is particularly worth noting that the ``Damping`` and ``Stiffness`` parameters in the ``DriveAPI`` have the unit of ``1/deg`` in the Isaac Sim UI but ``1/rad`` in Isaac Gym Preview Release. .. list-table:: :widths: 50 50 50 :header-rows: 1 * - Joint Parameter - Default Value in Isaac Sim - Default Value in Isaac Gym Preview Releases * - Maximum Joint Velocity - 1000000.0 (deg) - 100.0 (rad) Cloner ------ Isaac Sim introduced a concept of ``Cloner``, which is a class designed for replication during the scene creation process. In IsaacGymEnvs, scenes had to be created by looping through the number of environments. Within each iteration, actors were added to each environment and their handles had to be cached. Isaac Lab eliminates the need for looping through the environments by using the ``Cloner`` APIs. The scene creation process is as follow: #. Construct a single environment (what the scene would look like if number of environments = 1) #. Call ``clone_environments()`` to replicate the single environment #. Call ``filter_collisions()`` to filter out collision between environments (if required) .. code-block:: python # construct a single environment with the Cartpole robot self.cartpole = Articulation(self.cfg.robot_cfg) # clone the environment self.scene.clone_environments(copy_from_source=False) # filter collisions self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path]) Accessing States from Simulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ APIs for accessing physics states in Isaac Lab require the creation of an :class:`~assets.Articulation` or :class:`~assets.RigidObject` object. Multiple objects can be initialized for different articulations or rigid bodies in the scene by defining corresponding :class:`~assets.ArticulationCfg` or :class:`~assets.RigidObjectCfg` config as outlined in the section above. This approach eliminates the need of retrieving body handles to slice states for specific bodies in the scene. .. code-block:: python self._robot = Articulation(self.cfg.robot) self._cabinet = Articulation(self.cfg.cabinet) self._object = RigidObject(self.cfg.object_cfg) We have also removed ``acquire`` and ``refresh`` APIs in Isaac Lab. Physics states can be directly applied or retrieved using APIs defined for the articulations and rigid objects. APIs provided in Isaac Lab no longer require explicit wrapping and un-wrapping of underlying buffers. APIs can now work with tensors directly for reading and writing data. +------------------------------------------------------------------+-----------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +------------------------------------------------------------------+-----------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | dof_state_tensor = self.gym.acquire_dof_state_tensor(self.sim) | self.joint_pos = self._robot.data.joint_pos | | self.dof_state = gymtorch.wrap_tensor(dof_state_tensor) | self.joint_vel = self._robot.data.joint_vel | | self.gym.refresh_dof_state_tensor(self.sim) | | +------------------------------------------------------------------+-----------------------------------------------------------------+ Note some naming differences between APIs in Isaac Gym Preview Release and Isaac Lab. Most ``dof`` related APIs have been named to ``joint`` in Isaac Lab. APIs in Isaac Lab also no longer follow the explicit ``_tensors`` or ``_tensor_indexed`` suffixes in naming. Indexed versions of APIs now happen implicitly through the optional ``indices`` parameter. Most APIs in Isaac Lab also provide the option to specify an ``indices`` parameter, which can be used when reading or writing data for a subset of environments. Note that when setting states with the ``indices`` parameter, the shape of the states buffer should match with the dimension of the ``indices`` list. +---------------------------------------------------------------------------+---------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +---------------------------------------------------------------------------+---------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | env_ids_int32 = env_ids.to(dtype=torch.int32) | self._robot.write_joint_state_to_sim(joint_pos, joint_vel, | | self.gym.set_dof_state_tensor_indexed(self.sim, | joint_ids, env_ids) | | gymtorch.unwrap_tensor(self.dof_state), | | | gymtorch.unwrap_tensor(env_ids_int32), len(env_ids_int32)) | | +---------------------------------------------------------------------------+---------------------------------------------------------------+ Quaternion Convention --------------------- Isaac Lab and Isaac Sim both adopt ``wxyz`` as the quaternion convention. However, the quaternion convention used in Isaac Gym Preview Release was ``xyzw``. Remember to switch all quaternions to use the ``xyzw`` convention when working indexing rotation data. Similarly, please ensure all quaternions are in ``wxyz`` before passing them to Isaac Lab APIs. Articulation Joint Order ------------------------ Physics simulation in Isaac Sim and Isaac Lab assumes a breadth-first ordering for the joints in a given kinematic tree. However, Isaac Gym Preview Release assumed a depth-first ordering for joints in the kinematic tree. This means that indexing joints based on their ordering may be different in IsaacGymEnvs and Isaac Lab. In Isaac Lab, the list of joint names can be retrieved with ``Articulation.data.joint_names``, which will also correspond to the ordering of the joints in the Articulation. Creating a New Environment ~~~~~~~~~~~~~~~~~~~~~~~~~~ Each environment in Isaac Lab should be in its own directory following this structure: .. code-block:: none my_environment/ - agents/ - __init__.py - rl_games_ppo_cfg.py - __init__.py my_env.py * ``my_environment`` is the root directory of the task. * ``my_environment/agents`` is the directory containing all RL config files for the task. Isaac Lab supports multiple RL libraries that can each have its own individual config file. * ``my_environment/__init__.py`` is the main file that registers the environment with the Gymnasium interface. This allows the training and inferencing scripts to find the task by its name. The content of this file should be as follow: .. code-block:: python import gymnasium as gym from . import agents from .cartpole_env import CartpoleEnv, CartpoleEnvCfg ## # Register Gym environments. ## gym.register( id="Isaac-Cartpole-Direct-v0", entry_point="omni.isaac.lab_tasks.direct_workflow.cartpole:CartpoleEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": CartpoleEnvCfg, "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml" }, ) * ``my_environment/my_env.py`` is the main python script that implements the task logic and task config class for the environment. Task Logic ~~~~~~~~~~ In Isaac Lab, the ``post_physics_step`` function has been moved to the framework in the base class. Tasks are not required to implement this method, but can choose to override it if a different workflow is desired. By default, Isaac Lab follows the following flow in logic: +----------------------------------+----------------------------------+ | IsaacGymEnvs | Isaac Lab | +----------------------------------+----------------------------------+ |.. code-block:: none |.. code-block:: none | | | | | pre_physics_step | pre_physics_step | | |-- apply_action | |-- _pre_physics_step(action)| | | |-- _apply_action() | | | | | post_physics_step | post_physics_step | | |-- reset_idx() | |-- _get_dones() | | |-- compute_observation() | |-- _get_rewards() | | |-- compute_reward() | |-- _reset_idx() | | | |-- _get_observations() | +----------------------------------+----------------------------------+ In Isaac Lab, we also separate the ``pre_physics_step`` API for processing actions from the policy with the ``apply_action`` API, which sets the actions into the simulation. This provides more flexibility in controlling when actions should be written to simulation when ``decimation`` is used. ``pre_physics_step`` will be called once per step before stepping simulation. ``apply_actions`` will be called ``decimation`` number of times for each RL step, once before each simulation step call. With this approach, resets are performed based on actions from the current step instead of the previous step. Observations will also be computed with the correct states after resets. We have also performed some renamings of APIs: * ``create_sim(self)`` --> ``_setup_scene(self)`` * ``pre_physics_step(self, actions)`` --> ``_pre_physics_step(self, actions)`` and ``_apply_action(self)`` * ``reset_idx(self, env_ids)`` --> ``_reset_idx(self, env_ids)`` * ``compute_observations(self)`` --> ``_get_observations(self)`` - ``_get_observations()`` should now return a dictionary ``{"policy": obs}`` * ``compute_reward(self)`` --> ``_get_rewards(self)`` - ``_get_rewards()`` should now return the reward buffer * ``post_physics_step(self)`` --> moved to the base class * In addition, Isaac Lab requires the implementation of ``_is_done(self)``, which should return two buffers: the ``reset`` buffer and the ``time_out`` buffer. Putting It All Together ~~~~~~~~~~~~~~~~~~~~~~~ The Cartpole environment is shown here in completion to fully show the comparison between the IsaacGymEnvs implementation and the Isaac Lab implementation. Task Config ----------- +--------------------------------------------------------+---------------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +--------------------------------------------------------+---------------------------------------------------------------------+ |.. code-block:: yaml |.. code-block:: python | | | | | # used to create the object | @configclass | | name: Cartpole | class CartpoleEnvCfg(DirectRLEnvCfg): | | | | | physics_engine: ${..physics_engine} | # simulation | | | sim: SimulationCfg = SimulationCfg(dt=1 / 120) | | # if given, will override the device setting in gym. | # robot | | env: | robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace( | | numEnvs: ${resolve_default:512,${...num_envs}} | prim_path="/World/envs/env_.*/Robot") | | envSpacing: 4.0 | cart_dof_name = "slider_to_cart" | | resetDist: 3.0 | pole_dof_name = "cart_to_pole" | | maxEffort: 400.0 | # scene | | | scene: InteractiveSceneCfg = InteractiveSceneCfg( | | clipObservations: 5.0 | num_envs=4096, env_spacing=4.0, replicate_physics=True) | | clipActions: 1.0 | # env | | | decimation = 2 | | asset: | episode_length_s = 5.0 | | assetRoot: "../../assets" | action_scale = 100.0 # [N] | | assetFileName: "urdf/cartpole.urdf" | num_actions = 1 | | | num_observations = 4 | | enableCameraSensors: False | num_states = 0 | | | # reset | | sim: | max_cart_pos = 3.0 | | dt: 0.0166 # 1/60 s | initial_pole_angle_range = [-0.25, 0.25] | | substeps: 2 | # reward scales | | up_axis: "z" | rew_scale_alive = 1.0 | | use_gpu_pipeline: ${eq:${...pipeline},"gpu"} | rew_scale_terminated = -2.0 | | gravity: [0.0, 0.0, -9.81] | rew_scale_pole_pos = -1.0 | | physx: | rew_scale_cart_vel = -0.01 | | num_threads: ${....num_threads} | rew_scale_pole_vel = -0.005 | | solver_type: ${....solver_type} | | | use_gpu: ${contains:"cuda",${....sim_device}} | | | num_position_iterations: 4 | | | num_velocity_iterations: 0 | | | contact_offset: 0.02 | | | rest_offset: 0.001 | | | bounce_threshold_velocity: 0.2 | | | max_depenetration_velocity: 100.0 | | | default_buffer_size_multiplier: 2.0 | | | max_gpu_contact_pairs: 1048576 # 1024*1024 | | | num_subscenes: ${....num_subscenes} | | | contact_collection: 0 | | +--------------------------------------------------------+---------------------------------------------------------------------+ Task Setup ---------- Isaac Lab no longer requires pre-initialization of buffers through the ``acquire_*`` APIs that were used in IsaacGymEnvs. It is also no longer necessary to ``wrap`` and ``unwrap`` tensors. +-------------------------------------------------------------------------+-------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +-------------------------------------------------------------------------+-------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | class Cartpole(VecTask): | class CartpoleEnv(DirectRLEnv): | | | cfg: CartpoleEnvCfg | | def __init__(self, cfg, rl_device, sim_device, graphics_device_id, | def __init__(self, cfg: CartpoleEnvCfg, | | headless, virtual_screen_capture, force_render): | render_mode: str | None = None, **kwargs): | | self.cfg = cfg | | | | super().__init__(cfg, render_mode, **kwargs) | | self.reset_dist = self.cfg["env"]["resetDist"] | | | | self._cart_dof_idx, _ = self.cartpole.find_joints( | | self.max_push_effort = self.cfg["env"]["maxEffort"] | self.cfg.cart_dof_name) | | self.max_episode_length = 500 | self._pole_dof_idx, _ = self.cartpole.find_joints( | | | self.cfg.pole_dof_name) | | self.cfg["env"]["numObservations"] = 4 | self.action_scale = self.cfg.action_scale | | self.cfg["env"]["numActions"] = 1 | | | | self.joint_pos = self.cartpole.data.joint_pos | | super().__init__(config=self.cfg, | self.joint_vel = self.cartpole.data.joint_vel | | rl_device=rl_device, sim_device=sim_device, | | | graphics_device_id=graphics_device_id, headless=headless, | | | virtual_screen_capture=virtual_screen_capture, | | | force_render=force_render) | | | | | | dof_state_tensor = self.gym.acquire_dof_state_tensor(self.sim) | | | self.dof_state = gymtorch.wrap_tensor(dof_state_tensor) | | | self.dof_pos = self.dof_state.view( | | | self.num_envs, self.num_dof, 2)[..., 0] | | | self.dof_vel = self.dof_state.view( | | | self.num_envs, self.num_dof, 2)[..., 1] | | +-------------------------------------------------------------------------+-------------------------------------------------------------+ Scene Setup ----------- Scene setup is now done through the ``Cloner`` API and by specifying actor attributes in config objects. This eliminates the need to loop through the number of environments to set up the environments and avoids the need to set simulation parameters for actors in the task implementation. +------------------------------------------------------------------------+---------------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +------------------------------------------------------------------------+---------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def create_sim(self): | def _setup_scene(self): | | # set the up axis to be z-up given that assets are y-up by default | self.cartpole = Articulation(self.cfg.robot_cfg) | | self.up_axis = self.cfg["sim"]["up_axis"] | # add ground plane | | | spawn_ground_plane(prim_path="/World/ground", | | self.sim = super().create_sim(self.device_id, | cfg=GroundPlaneCfg()) | | self.graphics_device_id, self.physics_engine, | # clone, filter, and replicate | | self.sim_params) | self.scene.clone_environments( | | self._create_ground_plane() | copy_from_source=False) | | self._create_envs(self.num_envs, | self.scene.filter_collisions( | | self.cfg["env"]['envSpacing'], | global_prim_paths=[]) | | int(np.sqrt(self.num_envs))) | # add articultion to scene | | | self.scene.articulations["cartpole"] = self.cartpole | | def _create_ground_plane(self): | # add lights | | plane_params = gymapi.PlaneParams() | light_cfg = sim_utils.DomeLightCfg( | | # set the normal force to be z dimension | intensity=2000.0, color=(0.75, 0.75, 0.75)) | | plane_params.normal = (gymapi.Vec3(0.0, 0.0, 1.0) | light_cfg.func("/World/Light", light_cfg) | | if self.up_axis == 'z' | | | else gymapi.Vec3(0.0, 1.0, 0.0)) | CARTPOLE_CFG = ArticulationCfg( | | self.gym.add_ground(self.sim, plane_params) | spawn=sim_utils.UsdFileCfg( | | | usd_path=f"{ISAACLAB_NUCLEUS_DIR}/.../cartpole.usd", | | def _create_envs(self, num_envs, spacing, num_per_row): | rigid_props=sim_utils.RigidBodyPropertiesCfg( | | # define plane on which environments are initialized | rigid_body_enabled=True, | | lower = (gymapi.Vec3(0.5 * -spacing, -spacing, 0.0) | max_linear_velocity=1000.0, | | if self.up_axis == 'z' | max_angular_velocity=1000.0, | | else gymapi.Vec3(0.5 * -spacing, 0.0, -spacing)) | max_depenetration_velocity=100.0, | | upper = gymapi.Vec3(0.5 * spacing, spacing, spacing) | enable_gyroscopic_forces=True, | | | ), | | asset_root = os.path.join(os.path.dirname( | articulation_props=sim_utils.ArticulationRootPropertiesCfg( | | os.path.abspath(__file__)), "../../assets") | enabled_self_collisions=False, | | asset_file = "urdf/cartpole.urdf" | solver_position_iteration_count=4, | | | solver_velocity_iteration_count=0, | | if "asset" in self.cfg["env"]: | sleep_threshold=0.005, | | asset_root = os.path.join(os.path.dirname( | stabilization_threshold=0.001, | | os.path.abspath(__file__)), | ), | | self.cfg["env"]["asset"].get("assetRoot", asset_root)) | ), | | asset_file = self.cfg["env"]["asset"].get( | init_state=ArticulationCfg.InitialStateCfg( | | "assetFileName", asset_file) | pos=(0.0, 0.0, 2.0), | | | joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} | | asset_path = os.path.join(asset_root, asset_file) | ), | | asset_root = os.path.dirname(asset_path) | actuators={ | | asset_file = os.path.basename(asset_path) | "cart_actuator": ImplicitActuatorCfg( | | | joint_names_expr=["slider_to_cart"], | | asset_options = gymapi.AssetOptions() | effort_limit=400.0, | | asset_options.fix_base_link = True | velocity_limit=100.0, | | cartpole_asset = self.gym.load_asset(self.sim, | stiffness=0.0, | | asset_root, asset_file, asset_options) | damping=10.0, | | self.num_dof = self.gym.get_asset_dof_count( | ), | | cartpole_asset) | "pole_actuator": ImplicitActuatorCfg( | | | joint_names_expr=["cart_to_pole"], effort_limit=400.0, | | pose = gymapi.Transform() | velocity_limit=100.0, stiffness=0.0, damping=0.0 | | if self.up_axis == 'z': | ), | | pose.p.z = 2.0 | }, | | pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) | ) | | else: | | | pose.p.y = 2.0 | | | pose.r = gymapi.Quat( | | | -np.sqrt(2)/2, 0.0, 0.0, np.sqrt(2)/2) | | | | | | self.cartpole_handles = [] | | | self.envs = [] | | | for i in range(self.num_envs): | | | # create env instance | | | env_ptr = self.gym.create_env( | | | self.sim, lower, upper, num_per_row | | | ) | | | cartpole_handle = self.gym.create_actor( | | | env_ptr, cartpole_asset, pose, | | | "cartpole", i, 1, 0) | | | | | | dof_props = self.gym.get_actor_dof_properties( | | | env_ptr, cartpole_handle) | | | dof_props['driveMode'][0] = gymapi.DOF_MODE_EFFORT | | | dof_props['driveMode'][1] = gymapi.DOF_MODE_NONE | | | dof_props['stiffness'][:] = 0.0 | | | dof_props['damping'][:] = 0.0 | | | self.gym.set_actor_dof_properties(env_ptr, c | | | artpole_handle, dof_props) | | | | | | self.envs.append(env_ptr) | | | self.cartpole_handles.append(cartpole_handle) | | +------------------------------------------------------------------------+---------------------------------------------------------------------+ Pre and Post Physics Step ------------------------- In IsaacGymEnvs, due to limitations of the GPU APIs, observations had stale data when environments had to perform resets. This restriction has been eliminated in Isaac Lab, and thus, tasks follow the correct workflow of applying actions, stepping simulation, collecting states, computing dones, calculating rewards, performing resets, and finally computing observations. This workflow is done automatically by the framework such that a ``post_physics_step`` API is not required in the task. However, individual tasks can override the ``step()`` API to control the workflow. +------------------------------------------------------------------+-------------------------------------------------------------+ | IsaacGymEnvs | IsaacLab | +------------------------------------------------------------------+-------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def pre_physics_step(self, actions): | def _pre_physics_step(self, actions: torch.Tensor) -> None: | | actions_tensor = torch.zeros( | self.actions = self.action_scale * actions | | self.num_envs * self.num_dof, | | | device=self.device, dtype=torch.float) | def _apply_action(self) -> None: | | actions_tensor[::self.num_dof] = actions.to( | self.cartpole.set_joint_effort_target( | | self.device).squeeze() * self.max_push_effort | self.actions, joint_ids=self._cart_dof_idx) | | forces = gymtorch.unwrap_tensor(actions_tensor) | | | self.gym.set_dof_actuation_force_tensor( | | | self.sim, forces) | | | | | | def post_physics_step(self): | | | self.progress_buf += 1 | | | | | | env_ids = self.reset_buf.nonzero( | | | as_tuple=False).squeeze(-1) | | | if len(env_ids) > 0: | | | self.reset_idx(env_ids) | | | | | | self.compute_observations() | | | self.compute_reward() | | +------------------------------------------------------------------+-------------------------------------------------------------+ Dones and Resets ---------------- In Isaac Lab, ``dones`` are computed in the ``_get_dones()`` method and should return two variables: ``resets`` and ``time_out``. Tracking of the ``progress_buf`` has been moved to the base class and is now automatically incremented and reset by the framework. The ``progress_buf`` variable has also been renamed to ``episode_length_buf``. +-----------------------------------------------------------------------+---------------------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +-----------------------------------------------------------------------+---------------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def reset_idx(self, env_ids): | def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: | | positions = 0.2 * (torch.rand((len(env_ids), self.num_dof), | self.joint_pos = self.cartpole.data.joint_pos | | device=self.device) - 0.5) | self.joint_vel = self.cartpole.data.joint_vel | | velocities = 0.5 * (torch.rand((len(env_ids), self.num_dof), | | | device=self.device) - 0.5) | time_out = self.episode_length_buf >= self.max_episode_length - 1 | | | out_of_bounds = torch.any(torch.abs( | | self.dof_pos[env_ids, :] = positions[:] | self.joint_pos[:, self._pole_dof_idx] > self.cfg.max_cart_pos), | | self.dof_vel[env_ids, :] = velocities[:] | dim=1) | | | out_of_bounds = out_of_bounds | torch.any( | | env_ids_int32 = env_ids.to(dtype=torch.int32) | torch.abs(self.joint_pos[:, self._pole_dof_idx]) > math.pi / 2, | | self.gym.set_dof_state_tensor_indexed(self.sim, | dim=1) | | gymtorch.unwrap_tensor(self.dof_state), | return out_of_bounds, time_out | | gymtorch.unwrap_tensor(env_ids_int32), len(env_ids_int32)) | | | self.reset_buf[env_ids] = 0 | def _reset_idx(self, env_ids: Sequence[int] | None): | | self.progress_buf[env_ids] = 0 | if env_ids is None: | | | env_ids = self.cartpole._ALL_INDICES | | | super()._reset_idx(env_ids) | | | | | | joint_pos = self.cartpole.data.default_joint_pos[env_ids] | | | joint_pos[:, self._pole_dof_idx] += sample_uniform( | | | self.cfg.initial_pole_angle_range[0] * math.pi, | | | self.cfg.initial_pole_angle_range[1] * math.pi, | | | joint_pos[:, self._pole_dof_idx].shape, | | | joint_pos.device, | | | ) | | | joint_vel = self.cartpole.data.default_joint_vel[env_ids] | | | | | | default_root_state = self.cartpole.data.default_root_state[env_ids] | | | default_root_state[:, :3] += self.scene.env_origins[env_ids] | | | | | | self.joint_pos[env_ids] = joint_pos | | | | | | self.cartpole.write_root_pose_to_sim( | | | default_root_state[:, :7], env_ids) | | | self.cartpole.write_root_velocity_to_sim( | | | default_root_state[:, 7:], env_ids) | | | self.cartpole.write_joint_state_to_sim( | | | joint_pos, joint_vel, None, env_ids) | +-----------------------------------------------------------------------+---------------------------------------------------------------------------+ Observations ------------ In Isaac Lab, the ``_get_observations()`` API should now return a dictionary containing the ``policy`` key with the observation buffer as the value. For asymmetric policies, the dictionary should also include a ``critic`` key that holds the state buffer. +--------------------------------------------------------------------------+---------------------------------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +--------------------------------------------------------------------------+---------------------------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def compute_observations(self, env_ids=None): | def _get_observations(self) -> dict: | | if env_ids is None: | obs = torch.cat( | | env_ids = np.arange(self.num_envs) | ( | | | self.joint_pos[:, self._pole_dof_idx[0]], | | self.gym.refresh_dof_state_tensor(self.sim) | self.joint_vel[:, self._pole_dof_idx[0]], | | | self.joint_pos[:, self._cart_dof_idx[0]], | | self.obs_buf[env_ids, 0] = self.dof_pos[env_ids, 0] | self.joint_vel[:, self._cart_dof_idx[0]], | | self.obs_buf[env_ids, 1] = self.dof_vel[env_ids, 0] | ), | | self.obs_buf[env_ids, 2] = self.dof_pos[env_ids, 1] | dim=-1, | | self.obs_buf[env_ids, 3] = self.dof_vel[env_ids, 1] | ) | | | observations = {"policy": obs} | | return self.obs_buf | return observations | +--------------------------------------------------------------------------+---------------------------------------------------------------------------------------+ Rewards ------- In Isaac Lab, the reward method ``_get_rewards`` should return the reward buffer as a return value. Similar to IsaacGymEnvs, computations in the reward function can also be performed using pytorch jit by adding the ``@torch.jit.script`` annotation. +--------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ | IsaacGymEnvs | Isaac Lab | +--------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ |.. code-block:: python |.. code-block:: python | | | | | def compute_reward(self): | def _get_rewards(self) -> torch.Tensor: | | # retrieve environment observations from buffer | total_reward = compute_rewards( | | pole_angle = self.obs_buf[:, 2] | self.cfg.rew_scale_alive, | | pole_vel = self.obs_buf[:, 3] | self.cfg.rew_scale_terminated, | | cart_vel = self.obs_buf[:, 1] | self.cfg.rew_scale_pole_pos, | | cart_pos = self.obs_buf[:, 0] | self.cfg.rew_scale_cart_vel, | | | self.cfg.rew_scale_pole_vel, | | self.rew_buf[:], self.reset_buf[:] = compute_cartpole_reward( | self.joint_pos[:, self._pole_dof_idx[0]], | | pole_angle, pole_vel, cart_vel, cart_pos, | self.joint_vel[:, self._pole_dof_idx[0]], | | self.reset_dist, self.reset_buf, | self.joint_pos[:, self._cart_dof_idx[0]], | | self.progress_buf, self.max_episode_length | self.joint_vel[:, self._cart_dof_idx[0]], | | ) | self.reset_terminated, | | | ) | | @torch.jit.script | return total_reward | | def compute_cartpole_reward(pole_angle, pole_vel, | | | cart_vel, cart_pos, | @torch.jit.script | | reset_dist, reset_buf, | def compute_rewards( | | progress_buf, max_episode_length): | rew_scale_alive: float, | | | rew_scale_terminated: float, | | reward = (1.0 - pole_angle * pole_angle - | rew_scale_pole_pos: float, | | 0.01 * torch.abs(cart_vel) - | rew_scale_cart_vel: float, | | 0.005 * torch.abs(pole_vel)) | rew_scale_pole_vel: float, | | | pole_pos: torch.Tensor, | | # adjust reward for reset agents | pole_vel: torch.Tensor, | | reward = torch.where(torch.abs(cart_pos) > reset_dist, | cart_pos: torch.Tensor, | | torch.ones_like(reward) * -2.0, reward) | cart_vel: torch.Tensor, | | reward = torch.where(torch.abs(pole_angle) > np.pi / 2, | reset_terminated: torch.Tensor, | | torch.ones_like(reward) * -2.0, reward) | ): | | | rew_alive = rew_scale_alive * (1.0 - reset_terminated.float()) | | reset = torch.where(torch.abs(cart_pos) > reset_dist, | rew_termination = rew_scale_terminated * reset_terminated.float() | | torch.ones_like(reset_buf), reset_buf) | rew_pole_pos = rew_scale_pole_pos * torch.sum( | | reset = torch.where(torch.abs(pole_angle) > np.pi / 2, | torch.square(pole_pos), dim=-1) | | torch.ones_like(reset_buf), reset_buf) | rew_cart_vel = rew_scale_cart_vel * torch.sum( | | reset = torch.where(progress_buf >= max_episode_length - 1, | torch.abs(cart_vel), dim=-1) | | torch.ones_like(reset_buf), reset) | rew_pole_vel = rew_scale_pole_vel * torch.sum( | | | torch.abs(pole_vel), dim=-1) | | | total_reward = (rew_alive + rew_termination | | | + rew_pole_pos + rew_cart_vel + rew_pole_vel) | | | return total_reward | +--------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ Launching Training ~~~~~~~~~~~~~~~~~~ To launch a training in Isaac Lab, use the command: .. code-block:: bash python source/standalone/workflows/rl_games/train.py --task=Isaac-Cartpole-Direct-v0 --headless Launching Inferencing ~~~~~~~~~~~~~~~~~~~~~ To launch inferencing in Isaac Lab, use the command: .. code-block:: bash python source/standalone/workflows/rl_games/play.py --task=Isaac-Cartpole-Direct-v0 --num_envs=25 --checkpoint=<path/to/checkpoint>
77,191
reStructuredText
83.919692
330
0.35898
isaac-sim/IsaacLab/docs/source/migration/index.rst
Migration Guides ================ The following guides show the migration process from previous frameworks that are now deprecated, including IsaacGymEnvs, OmniIsaacGymEnvs, and Orbit. .. toctree:: :maxdepth: 1 :titlesonly: migrating_from_isaacgymenvs migrating_from_omniisaacgymenvs migrating_from_orbit
329
reStructuredText
20.999999
97
0.732523
isaac-sim/IsaacLab/docs/source/migration/migrating_from_orbit.rst
.. _migrating-from-orbit: Migrating from Orbit ==================== .. currentmodule:: omni.isaac.lab Since Orbit was used as basis for Isaac Lab, migrating from Orbit to Isaac Lab is straightforward. The following sections describe the changes that need to be made to your code to migrate from Orbit to Isaac Lab. Updates to scripts ~~~~~~~~~~~~~~~~~~ The script ``orbit.sh`` has been renamed to ``isaaclab.sh``. Updates to extensions ~~~~~~~~~~~~~~~~~~~~~ The extensions ``omni.isaac.orbit``, ``omni.isaac.orbit_tasks``, and ``omni.isaac.orbit_assets`` have been renamed to ``omni.isaac.lab``, ``omni.isaac.lab_tasks``, and ``omni.isaac.lab_assets``, respectively. Thus, the new folder structure looks like this: - ``source/extensions/omni.isaac.lab/omni/isaac/lab`` - ``source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks`` - ``source/extensions/omni.isaac.lab_assets/omni/isaac/lab_assets`` The high level imports have to be updated as well: +-------------------------------------+-----------------------------------+ | Orbit | Isaac Lab | +=====================================+===================================+ | ``from omni.isaac.orbit...`` | ``from omni.isaac.lab...`` | +-------------------------------------+-----------------------------------+ | ``from omni.isaac.orbit_tasks...`` | ``from omni.isaac.lab_tasks...`` | +-------------------------------------+-----------------------------------+ | ``from omni.isaac.orbit_assets...`` | ``from omni.isaac.lab_assets...`` | +-------------------------------------+-----------------------------------+ Updates to class names ~~~~~~~~~~~~~~~~~~~~~~ In Isaac Lab, we introduced the concept of task design workflows (see :ref:`feature-workflows`). The Orbit code is using the manager-based workflow and the environment specific class names have been updated to reflect this change: +------------------------+---------------------------------------------------------+ | Orbit | Isaac Lab | +========================+=========================================================+ | ``BaseEnv`` | :class:`omni.isaac.lab.envs.ManagerBasedEnv` | +------------------------+---------------------------------------------------------+ | ``BaseEnvCfg`` | :class:`omni.isaac.lab.envs.ManagerBasedEnvCfg` | +------------------------+---------------------------------------------------------+ | ``RLTaskEnv`` | :class:`omni.isaac.lab.envs.ManagerBasedRLEnv` | +------------------------+---------------------------------------------------------+ | ``RLTaskEnvCfg`` | :class:`omni.isaac.lab.envs.ManagerBasedRLEnvCfg` | +------------------------+---------------------------------------------------------+ | ``RLTaskEnvWindow`` | :class:`omni.isaac.lab.envs.ui.ManagerBasedRLEnvWindow` | +------------------------+---------------------------------------------------------+ Updates to the tasks folder structure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To support the manager-based and direct workflows, we have added two folders in the tasks extension: - ``source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based`` - ``source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct`` The tasks from Orbit can now be found under the ``manager_based`` folder. This change must also be reflected in the imports for your tasks. For example, .. code-block:: python from omni.isaac.orbit_tasks.locomotion.velocity.velocity_env_cfg ... should now be .. code-block:: python from omni.isaac.lab_tasks.manager_based.locomotion.velocity.velocity_env_cfg ... Other Breaking changes ~~~~~~~~~~~~~~~~~~~~~~ Offscreen rendering ------------------- The input argument ``--offscreen_render`` given to :class:`omni.isaac.lab.app.AppLauncher` and the environment variable ``OFFSCREEN_RENDER`` have been renamed to ``--enable_cameras`` and ``ENABLE_CAMERAS`` respectively. Event term distribution configuration ------------------------------------- Some of the event functions in `events.py <https://github.com/isaac-sim/IsaacLab/blob/isaac-lab/source/extensions/omni.isaac.lab/omni/isaac/lab/envs/mdp/events.py>`_ accepted a ``distribution`` parameter and a ``range`` to sample from. In an effort to support arbitrary distributions, we have renamed the input argument ``AAA_range`` to ``AAA_distribution_params`` for these functions. Therefore, event term configurations whose functions have a ``distribution`` argument should be updated. For example, .. code-block:: python :emphasize-lines: 6 add_base_mass = EventTerm( func=mdp.randomize_rigid_body_mass, mode="startup", params={ "asset_cfg": SceneEntityCfg("robot", body_names="base"), "mass_range": (-5.0, 5.0), "operation": "add", }, ) should now be .. code-block:: python :emphasize-lines: 6 add_base_mass = EventTerm( func=mdp.randomize_rigid_body_mass, mode="startup", params={ "asset_cfg": SceneEntityCfg("robot", body_names="base"), "mass_distribution_params": (-5.0, 5.0), "operation": "add", }, )
5,268
reStructuredText
40.164062
165
0.527335
michaltakac/nerf-toy-car-aerodynamics/README.md
# Toy car simulator Example project for Ozaj.tech. This simulator mainly showcases the capabilities of parametrized AI-based physics simulator for simulating aerodynamics of a car, leveraging scientific deep learning methods (physics-informed neural networks and Fourier neural operators).
293
Markdown
47.999992
239
0.832765
michaltakac/nerf-toy-car-aerodynamics/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Toy car aerodynamics example" description="Project commisioned for Faculty of materials, metallurgy and recyclation (FMMR) at Technical university of Košice." # Path (relative to the root) or content of readme markdown file for UI. readme = "README.md" changelog = "docs/CHANGELOG.md" preview_image = "data/toy-car.png" icon = "data/icon.png" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Simulation" # Keywords for the extension keywords = ["modulus", "toy-car", "STL geometry", "scenario"] # Use omni.ui to build simple UI [dependencies] "modulus_ext.core" = {version="22.9.0"} "modulus_ext.ui" = {version="2.0.0"} "hpcvis.vtkm_bridge.core" = {version="1.0.2-alpha-03"} # Main python module this extension provides". [[python.module]] name = "toy-car"
988
TOML
28.088234
128
0.726721
michaltakac/nerf-toy-car-aerodynamics/config/extension.gen.toml
[package] [package.target] python = ["cp37"] [package.publish] date = 1662766157 kitVersion = "103.5+release.6600.0a006a6d.tc"
127
TOML
17.285712
45
0.732283
michaltakac/nerf-toy-car-aerodynamics/docs/CHANGELOG.md
# Toy car aerodynamics example ## [1.0.0] - 2022-10-14 Initial version, working with Modulus 22.09
100
Markdown
19.199996
43
0.72