file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/scripts/random_policy.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import hydra
import numpy as np
import torch
from omegaconf import DictConfig
from omniisaacgymenvs.envs.vec_env_rlgames import VecEnvRLGames
from omniisaacgymenvs.utils.config_utils.path_utils import get_experience
from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import *
from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from omniisaacgymenvs.utils.task_util import initialize_task
@hydra.main(version_base=None, config_name="config", config_path="../cfg")
def parse_hydra_configs(cfg: DictConfig):
cfg_dict = omegaconf_to_dict(cfg)
print_dict(cfg_dict)
headless = cfg.headless
render = not headless
enable_viewport = "enable_cameras" in cfg.task.sim and cfg.task.sim.enable_cameras
# select kit app file
experience = get_experience(headless, cfg.enable_livestream, enable_viewport, cfg.kit_app)
env = VecEnvRLGames(
headless=headless,
sim_device=cfg.device_id,
enable_livestream=cfg.enable_livestream,
enable_viewport=enable_viewport,
experience=experience
)
# sets seed. if seed is -1 will pick a random one
from omni.isaac.core.utils.torch.maths import set_seed
cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic)
cfg_dict["seed"] = cfg.seed
task = initialize_task(cfg_dict, env)
while env._simulation_app.is_running():
if env._world.is_playing():
if env._world.current_time_step_index == 0:
env._world.reset(soft=True)
actions = torch.tensor(
np.array([env.action_space.sample() for _ in range(env.num_envs)]), device=task.rl_device
)
env._task.pre_physics_step(actions)
env._world.step(render=render)
env.sim_frame_count += 1
env._task.post_physics_step()
else:
env._world.step(render=render)
env._simulation_app.close()
if __name__ == "__main__":
parse_hydra_configs()
| 3,559 | Python | 39.91954 | 105 | 0.722113 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/demos/anymal_terrain.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.anymal_terrain import AnymalTerrainTask, wrap_to_pi
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.utils.torch.transformations import tf_combine
import numpy as np
import torch
import math
import omni
import carb
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from omni.kit.viewport.utility import get_viewport_from_window_name
from pxr import Sdf
class AnymalTerrainDemo(AnymalTerrainTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
max_num_envs = 128
if sim_config.task_config["env"]["numEnvs"] >= max_num_envs:
print(f"num_envs reduced to {max_num_envs} for this demo.")
sim_config.task_config["env"]["numEnvs"] = max_num_envs
sim_config.task_config["env"]["learn"]["episodeLength_s"] = 120
AnymalTerrainTask.__init__(self, name, sim_config, env)
self.add_noise = False
self.knee_threshold = 0.05
self.create_camera()
self._current_command = [0.0, 0.0, 0.0, 0.0]
self.set_up_keyboard()
self._prim_selection = omni.usd.get_context().get_selection()
self._selected_id = None
self._previous_selected_id = None
return
def create_camera(self):
stage = omni.usd.get_context().get_stage()
self.view_port = get_viewport_from_window_name("Viewport")
# Create camera
self.camera_path = "/World/Camera"
self.perspective_path = "/OmniverseKit_Persp"
camera_prim = stage.DefinePrim(self.camera_path, "Camera")
camera_prim.GetAttribute("focalLength").Set(8.5)
coi_prop = camera_prim.GetProperty("omni:kit:centerOfInterest")
if not coi_prop or not coi_prop.IsValid():
camera_prim.CreateAttribute(
"omni:kit:centerOfInterest", Sdf.ValueTypeNames.Vector3d, True, Sdf.VariabilityUniform
).Set(Gf.Vec3d(0, 0, -10))
self.view_port.set_active_camera(self.perspective_path)
def set_up_keyboard(self):
self._input = carb.input.acquire_input_interface()
self._keyboard = omni.appwindow.get_default_app_window().get_keyboard()
self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._on_keyboard_event)
T = 1
R = 1
self._key_to_control = {
"UP": [T, 0.0, 0.0, 0.0],
"DOWN": [-T, 0.0, 0.0, 0.0],
"LEFT": [0.0, T, 0.0, 0.0],
"RIGHT": [0.0, -T, 0.0, 0.0],
"Z": [0.0, 0.0, R, 0.0],
"X": [0.0, 0.0, -R, 0.0],
}
def _on_keyboard_event(self, event, *args, **kwargs):
if event.type == carb.input.KeyboardEventType.KEY_PRESS:
if event.input.name in self._key_to_control:
self._current_command = self._key_to_control[event.input.name]
elif event.input.name == "ESCAPE":
self._prim_selection.clear_selected_prim_paths()
elif event.input.name == "C":
if self._selected_id is not None:
if self.view_port.get_active_camera() == self.camera_path:
self.view_port.set_active_camera(self.perspective_path)
else:
self.view_port.set_active_camera(self.camera_path)
elif event.type == carb.input.KeyboardEventType.KEY_RELEASE:
self._current_command = [0.0, 0.0, 0.0, 0.0]
def update_selected_object(self):
self._previous_selected_id = self._selected_id
selected_prim_paths = self._prim_selection.get_selected_prim_paths()
if len(selected_prim_paths) == 0:
self._selected_id = None
self.view_port.set_active_camera(self.perspective_path)
elif len(selected_prim_paths) > 1:
print("Multiple prims are selected. Please only select one!")
else:
prim_splitted_path = selected_prim_paths[0].split("/")
if len(prim_splitted_path) >= 4 and prim_splitted_path[3][0:4] == "env_":
self._selected_id = int(prim_splitted_path[3][4:])
if self._previous_selected_id != self._selected_id:
self.view_port.set_active_camera(self.camera_path)
self._update_camera()
else:
print("The selected prim was not an Anymal")
if self._previous_selected_id is not None and self._previous_selected_id != self._selected_id:
self.commands[self._previous_selected_id, 0] = np.random.uniform(self.command_x_range[0], self.command_x_range[1])
self.commands[self._previous_selected_id, 1] = np.random.uniform(self.command_y_range[0], self.command_y_range[1])
self.commands[self._previous_selected_id, 2] = 0.0
def _update_camera(self):
base_pos = self.base_pos[self._selected_id, :].clone()
base_quat = self.base_quat[self._selected_id, :].clone()
camera_local_transform = torch.tensor([-1.8, 0.0, 0.6], device=self.device)
camera_pos = quat_apply(base_quat, camera_local_transform) + base_pos
camera_state = ViewportCameraState(self.camera_path, self.view_port)
eye = Gf.Vec3d(camera_pos[0].item(), camera_pos[1].item(), camera_pos[2].item())
target = Gf.Vec3d(base_pos[0].item(), base_pos[1].item(), base_pos[2].item()+0.6)
camera_state.set_position_world(eye, True)
camera_state.set_target_world(target, True)
def post_physics_step(self):
self.progress_buf[:] += 1
self.refresh_dof_state_tensors()
self.refresh_body_state_tensors()
self.update_selected_object()
self.common_step_counter += 1
if self.common_step_counter % self.push_interval == 0:
self.push_robots()
# prepare quantities
self.base_lin_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 0:3])
self.base_ang_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 3:6])
self.projected_gravity = quat_rotate_inverse(self.base_quat, self.gravity_vec)
forward = quat_apply(self.base_quat, self.forward_vec)
heading = torch.atan2(forward[:, 1], forward[:, 0])
self.commands[:, 2] = torch.clip(0.5*wrap_to_pi(self.commands[:, 3] - heading), -1., 1.)
self.check_termination()
if self._selected_id is not None:
self.commands[self._selected_id, :] = torch.tensor(self._current_command, device=self.device)
self.timeout_buf[self._selected_id] = 0
self.reset_buf[self._selected_id] = 0
self.get_states()
env_ids = self.reset_buf.nonzero(as_tuple=False).flatten()
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.get_observations()
if self.add_noise:
self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec
self.last_actions[:] = self.actions[:]
self.last_dof_vel[:] = self.dof_vel[:]
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras | 8,841 | Python | 44.577319 | 126 | 0.636127 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/demos/dofbot_reacher.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
# Ref: /omniisaacgymenvs/demos/anymal_terrain.py
from omniisaacgymenvs.tasks.dofbot_reacher import DofbotReacherTask
from omni.isaac.core.utils.torch.rotations import *
import torch
import omni
import carb
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from omni.kit.viewport.utility import get_viewport_from_window_name
from pxr import Sdf
class DofbotReacherDemo(DofbotReacherTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
max_num_envs = 128
if sim_config.task_config["env"]["numEnvs"] >= max_num_envs:
print(f"num_envs reduced to {max_num_envs} for this demo.")
sim_config.task_config["env"]["numEnvs"] = max_num_envs
DofbotReacherTask.__init__(self, name, sim_config, env)
self.add_noise = False
self.create_camera()
self._current_command = [0.0] * 6
self.set_up_keyboard()
self._prim_selection = omni.usd.get_context().get_selection()
self._selected_id = None
self._previous_selected_id = None
return
def create_camera(self):
stage = omni.usd.get_context().get_stage()
self.view_port = get_viewport_from_window_name("Viewport")
# Create camera
self.camera_path = "/World/Camera"
self.perspective_path = "/OmniverseKit_Persp"
camera_prim = stage.DefinePrim(self.camera_path, "Camera")
camera_prim.GetAttribute("focalLength").Set(8.5)
coi_prop = camera_prim.GetProperty("omni:kit:centerOfInterest")
if not coi_prop or not coi_prop.IsValid():
camera_prim.CreateAttribute(
"omni:kit:centerOfInterest", Sdf.ValueTypeNames.Vector3d, True, Sdf.VariabilityUniform
).Set(Gf.Vec3d(0, 0, -10))
self.view_port.set_active_camera(self.perspective_path)
def set_up_keyboard(self):
self._input = carb.input.acquire_input_interface()
self._keyboard = omni.appwindow.get_default_app_window().get_keyboard()
self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._on_keyboard_event)
self._key_to_control = {
# Joint 0
"Q": [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
"A": [1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
# Joint 1
"W": [0.0, -1.0, 0.0, 0.0, 0.0, 0.0],
"S": [0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
# Joint 2
"E": [0.0, 0.0, -1.0, 0.0, 0.0, 0.0],
"D": [0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
# Joint 3
"R": [0.0, 0.0, 0.0, -1.0, 0.0, 0.0],
"F": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0],
# Joint 4
"T": [0.0, 0.0, 0.0, 0.0, -1.0, 0.0],
"G": [0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
# Joint 5
"Y": [0.0, 0.0, 0.0, 0.0, 0.0, -1.0],
"H": [0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
}
def _on_keyboard_event(self, event, *args, **kwargs):
if event.type == carb.input.KeyboardEventType.KEY_PRESS:
if event.input.name in self._key_to_control:
self._current_command = self._key_to_control[event.input.name]
elif event.input.name == "ESCAPE":
self._prim_selection.clear_selected_prim_paths()
elif event.input.name == "C":
if self._selected_id is not None:
if self.view_port.get_active_camera() == self.camera_path:
self.view_port.set_active_camera(self.perspective_path)
else:
self.view_port.set_active_camera(self.camera_path)
elif event.type == carb.input.KeyboardEventType.KEY_RELEASE:
self._current_command = [0.0] * 6
def update_selected_object(self):
self._previous_selected_id = self._selected_id
selected_prim_paths = self._prim_selection.get_selected_prim_paths()
if len(selected_prim_paths) == 0:
self._selected_id = None
self.view_port.set_active_camera(self.perspective_path)
elif len(selected_prim_paths) > 1:
print("Multiple prims are selected. Please only select one!")
else:
prim_splitted_path = selected_prim_paths[0].split("/")
if len(prim_splitted_path) >= 4 and prim_splitted_path[3][0:4] == "env_":
self._selected_id = int(prim_splitted_path[3][4:])
else:
print("The selected prim was not a Dofbot")
def _update_camera(self):
base_pos = self.base_pos[self._selected_id, :].clone()
base_quat = self.base_quat[self._selected_id, :].clone()
camera_local_transform = torch.tensor([-1.8, 0.0, 0.6], device=self.device)
camera_pos = quat_apply(base_quat, camera_local_transform) + base_pos
camera_state = ViewportCameraState(self.camera_path, self.view_port)
eye = Gf.Vec3d(camera_pos[0].item(), camera_pos[1].item(), camera_pos[2].item())
target = Gf.Vec3d(base_pos[0].item(), base_pos[1].item(), base_pos[2].item()+0.6)
camera_state.set_position_world(eye, True)
camera_state.set_target_world(target, True)
def pre_physics_step(self, actions):
if self._selected_id is not None:
actions[self._selected_id, :] = torch.tensor(self._current_command, device=self.device)
result = super().pre_physics_step(actions)
if self._selected_id is not None:
print('selected dofbot id:', self._selected_id)
print('self.rew_buf[idx]:', self.rew_buf[self._selected_id])
print('self.object_pos[idx]:', self.object_pos[self._selected_id])
print('self.goal_pos[idx]:', self.goal_pos[self._selected_id])
return result
def post_physics_step(self):
self.progress_buf[:] += 1
self.update_selected_object()
if self._selected_id is not None:
self.reset_buf[self._selected_id] = 0
self.get_states()
env_ids = self.reset_buf.nonzero(as_tuple=False).flatten()
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.get_observations()
if self.add_noise:
self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec
# Calculate rewards
self.calculate_metrics()
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
| 8,034 | Python | 42.668478 | 110 | 0.615385 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/tests/__init__.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from .runner import * | 1,580 | Python | 53.51724 | 80 | 0.783544 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/tests/runner.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
from datetime import date
import sys
import unittest
import weakref
import omni.kit.test
from omni.kit.test import AsyncTestSuite
from omni.kit.test.async_unittest import AsyncTextTestRunner
import omni.ui as ui
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import btn_builder
from omni.kit.menu.utils import MenuItemDescription, add_menu_items
import omni.timeline
import omni.usd
from omniisaacgymenvs import RLExtension, get_instance
class GymRLTests(omni.kit.test.AsyncTestCase):
def __init__(self, *args, **kwargs):
super(GymRLTests, self).__init__(*args, **kwargs)
self.ext = get_instance()
async def _train(self, task, load=True, experiment=None, max_iterations=None):
task_idx = self.ext._task_list.index(task)
self.ext._task_dropdown.get_item_value_model().set_value(task_idx)
if load:
self.ext._on_load_world()
while True:
_, files_loaded, total_files = omni.usd.get_context().get_stage_loading_status()
if files_loaded or total_files:
await omni.kit.app.get_app().next_update_async()
else:
break
for _ in range(100):
await omni.kit.app.get_app().next_update_async()
self.ext._render_dropdown.get_item_value_model().set_value(2)
overrides = None
if experiment is not None:
overrides = [f"experiment={experiment}"]
if max_iterations is not None:
if overrides is None:
overrides = [f"max_iterations={max_iterations}"]
else:
overrides += [f"max_iterations={max_iterations}"]
await self.ext._on_train_async(overrides=overrides)
async def test_train(self):
date_str = date.today()
tasks = self.ext._task_list
for task in tasks:
await self._train(task, load=True, experiment=f"{task}_{date_str}")
async def test_train_determinism(self):
date_str = date.today()
tasks = self.ext._task_list
for task in tasks:
for i in range(3):
await self._train(task, load=(i==0), experiment=f"{task}_{date_str}_{i}", max_iterations=100)
class TestRunner():
def __init__(self):
self._build_ui()
def _build_ui(self):
menu_items = [make_menu_item_description("RL Examples Tests", "RL Examples Tests", lambda a=weakref.proxy(self): a._menu_callback())]
add_menu_items(menu_items, "Isaac Examples")
self._window = omni.ui.Window(
"RL Examples Tests", width=250, height=0, visible=True, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
main_stack = ui.VStack(spacing=5, height=0)
with main_stack:
dict = {
"label": "Run Tests",
"type": "button",
"text": "Run Tests",
"tooltip": "Run all tests",
"on_clicked_fn": self._run_tests,
}
btn_builder(**dict)
def _menu_callback(self):
self._window.visible = not self._window.visible
def _run_tests(self):
loader = unittest.TestLoader()
loader.SuiteClass = AsyncTestSuite
test_suite = AsyncTestSuite()
test_suite.addTests(loader.loadTestsFromTestCase(GymRLTests))
test_runner = AsyncTextTestRunner(verbosity=2, stream=sys.stdout)
async def single_run():
await test_runner.run(test_suite)
print("=======================================")
print(f"Running Tests")
print("=======================================")
asyncio.ensure_future(single_run())
TestRunner() | 4,254 | Python | 35.059322 | 141 | 0.607428 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/demo_util.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
def initialize_demo(config, env, init_sim=True):
from omniisaacgymenvs.demos.anymal_terrain import AnymalTerrainDemo
from omniisaacgymenvs.demos.dofbot_reacher import DofbotReacherDemo
# Mappings from strings to environments
task_map = {
"AnymalTerrain": AnymalTerrainDemo,
"DofbotReacher": DofbotReacherDemo,
}
from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig
sim_config = SimConfig(config)
cfg = sim_config.config
task = task_map[cfg["task_name"]](
name=cfg["task_name"], sim_config=sim_config, env=env
)
env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim)
return task | 2,322 | Python | 44.549019 | 107 | 0.757967 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/task_util.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
def import_tasks():
from omniisaacgymenvs.tasks.allegro_hand import AllegroHandTask
from omniisaacgymenvs.tasks.ant import AntLocomotionTask
from omniisaacgymenvs.tasks.anymal import AnymalTask
from omniisaacgymenvs.tasks.anymal_terrain import AnymalTerrainTask
from omniisaacgymenvs.tasks.ball_balance import BallBalanceTask
from omniisaacgymenvs.tasks.cartpole import CartpoleTask
from omniisaacgymenvs.tasks.cartpole_camera import CartpoleCameraTask
from omniisaacgymenvs.tasks.crazyflie import CrazyflieTask
from omniisaacgymenvs.tasks.factory.factory_task_nut_bolt_pick import FactoryTaskNutBoltPick
from omniisaacgymenvs.tasks.factory.factory_task_nut_bolt_place import FactoryTaskNutBoltPlace
from omniisaacgymenvs.tasks.factory.factory_task_nut_bolt_screw import FactoryTaskNutBoltScrew
from omniisaacgymenvs.tasks.franka_cabinet import FrankaCabinetTask
from omniisaacgymenvs.tasks.franka_deformable import FrankaDeformableTask
from omniisaacgymenvs.tasks.humanoid import HumanoidLocomotionTask
from omniisaacgymenvs.tasks.ingenuity import IngenuityTask
from omniisaacgymenvs.tasks.quadcopter import QuadcopterTask
from omniisaacgymenvs.tasks.shadow_hand import ShadowHandTask
from omniisaacgymenvs.tasks.dofbot_reacher import DofbotReacherTask
from omniisaacgymenvs.tasks.warp.ant import AntLocomotionTask as AntLocomotionTaskWarp
from omniisaacgymenvs.tasks.warp.cartpole import CartpoleTask as CartpoleTaskWarp
from omniisaacgymenvs.tasks.warp.humanoid import HumanoidLocomotionTask as HumanoidLocomotionTaskWarp
# Mappings from strings to environments
task_map = {
"AllegroHand": AllegroHandTask,
"Ant": AntLocomotionTask,
"Anymal": AnymalTask,
"AnymalTerrain": AnymalTerrainTask,
"BallBalance": BallBalanceTask,
"Cartpole": CartpoleTask,
"CartpoleCamera": CartpoleCameraTask,
"FactoryTaskNutBoltPick": FactoryTaskNutBoltPick,
"FactoryTaskNutBoltPlace": FactoryTaskNutBoltPlace,
"FactoryTaskNutBoltScrew": FactoryTaskNutBoltScrew,
"FrankaCabinet": FrankaCabinetTask,
"FrankaDeformable": FrankaDeformableTask,
"Humanoid": HumanoidLocomotionTask,
"Ingenuity": IngenuityTask,
"Quadcopter": QuadcopterTask,
"Crazyflie": CrazyflieTask,
"ShadowHand": ShadowHandTask,
"ShadowHandOpenAI_FF": ShadowHandTask,
"ShadowHandOpenAI_LSTM": ShadowHandTask,
"DofbotReacher": DofbotReacherTask,
}
task_map_warp = {
"Cartpole": CartpoleTaskWarp,
"Ant":AntLocomotionTaskWarp,
"Humanoid": HumanoidLocomotionTaskWarp
}
return task_map, task_map_warp
def initialize_task(config, env, init_sim=True):
from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig
sim_config = SimConfig(config)
task_map, task_map_warp = import_tasks()
cfg = sim_config.config
if cfg["warp"]:
task_map = task_map_warp
task = task_map[cfg["task_name"]](
name=cfg["task_name"], sim_config=sim_config, env=env
)
backend = "warp" if cfg["warp"] else "torch"
rendering_dt = sim_config.get_physics_params()["rendering_dt"]
env.set_task(
task=task,
sim_params=sim_config.get_physics_params(),
backend=backend,
init_sim=init_sim,
rendering_dt=rendering_dt,
)
return task
| 5,049 | Python | 42.913043 | 105 | 0.75302 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/domain_randomization/randomize.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import copy
import numpy as np
import torch
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.utils.extensions import enable_extension
class Randomizer:
def __init__(self, main_config, task_config):
self._cfg = task_config
self._config = main_config
self.randomize = False
dr_config = self._cfg.get("domain_randomization", None)
self.distributions = dict()
self.active_domain_randomizations = dict()
self._observations_dr_params = None
self._actions_dr_params = None
if dr_config is not None:
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize and randomization_params is not None:
self.randomize = True
self.min_frequency = dr_config.get("min_frequency", 1)
# import DR extensions
enable_extension("omni.replicator.isaac")
import omni.replicator.core as rep
import omni.replicator.isaac as dr
self.rep = rep
self.dr = dr
def apply_on_startup_domain_randomization(self, task):
if self.randomize:
torch.manual_seed(self._config["seed"])
randomization_params = self._cfg["domain_randomization"]["randomization_params"]
for opt in randomization_params.keys():
if opt == "rigid_prim_views":
if randomization_params["rigid_prim_views"] is not None:
for view_name in randomization_params["rigid_prim_views"].keys():
if randomization_params["rigid_prim_views"][view_name] is not None:
for attribute, params in randomization_params["rigid_prim_views"][view_name].items():
params = randomization_params["rigid_prim_views"][view_name][attribute]
if attribute in ["scale", "mass", "density"] and params is not None:
if "on_startup" in params.keys():
if not set(
("operation", "distribution", "distribution_parameters")
).issubset(params["on_startup"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} "
+ "on_startup are provided: operation, distribution, distribution_parameters."
)
view = task._env._world.scene._scene_registry.rigid_prim_views[view_name]
if attribute == "scale":
self.randomize_scale_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
sync_dim_noise=True,
)
elif attribute == "mass":
self.randomize_mass_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
)
elif attribute == "density":
self.randomize_density_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
)
if opt == "articulation_views":
if randomization_params["articulation_views"] is not None:
for view_name in randomization_params["articulation_views"].keys():
if randomization_params["articulation_views"][view_name] is not None:
for attribute, params in randomization_params["articulation_views"][view_name].items():
params = randomization_params["articulation_views"][view_name][attribute]
if attribute in ["scale"] and params is not None:
if "on_startup" in params.keys():
if not set(
("operation", "distribution", "distribution_parameters")
).issubset(params["on_startup"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} "
+ "on_startup are provided: operation, distribution, distribution_parameters."
)
view = task._env._world.scene._scene_registry.articulated_views[view_name]
if attribute == "scale":
self.randomize_scale_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"][
"distribution_parameters"
],
operation=params["on_startup"]["operation"],
sync_dim_noise=True,
)
else:
dr_config = self._cfg.get("domain_randomization", None)
if dr_config is None:
raise ValueError("No domain randomization parameters are specified in the task yaml config file")
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize == False or randomization_params is None:
print("On Startup Domain randomization will not be applied.")
def set_up_domain_randomization(self, task):
if self.randomize:
randomization_params = self._cfg["domain_randomization"]["randomization_params"]
self.rep.set_global_seed(self._config["seed"])
with self.dr.trigger.on_rl_frame(num_envs=self._cfg["env"]["numEnvs"]):
for opt in randomization_params.keys():
if opt == "observations":
self._set_up_observations_randomization(task)
elif opt == "actions":
self._set_up_actions_randomization(task)
elif opt == "simulation":
if randomization_params["simulation"] is not None:
self.distributions["simulation"] = dict()
self.dr.physics_view.register_simulation_context(task._env._world)
for attribute, params in randomization_params["simulation"].items():
self._set_up_simulation_randomization(attribute, params)
elif opt == "rigid_prim_views":
if randomization_params["rigid_prim_views"] is not None:
self.distributions["rigid_prim_views"] = dict()
for view_name in randomization_params["rigid_prim_views"].keys():
if randomization_params["rigid_prim_views"][view_name] is not None:
self.distributions["rigid_prim_views"][view_name] = dict()
self.dr.physics_view.register_rigid_prim_view(
rigid_prim_view=task._env._world.scene._scene_registry.rigid_prim_views[
view_name
],
)
for attribute, params in randomization_params["rigid_prim_views"][
view_name
].items():
if attribute not in ["scale", "density"]:
self._set_up_rigid_prim_view_randomization(view_name, attribute, params)
elif opt == "articulation_views":
if randomization_params["articulation_views"] is not None:
self.distributions["articulation_views"] = dict()
for view_name in randomization_params["articulation_views"].keys():
if randomization_params["articulation_views"][view_name] is not None:
self.distributions["articulation_views"][view_name] = dict()
self.dr.physics_view.register_articulation_view(
articulation_view=task._env._world.scene._scene_registry.articulated_views[
view_name
],
)
for attribute, params in randomization_params["articulation_views"][
view_name
].items():
if attribute not in ["scale"]:
self._set_up_articulation_view_randomization(view_name, attribute, params)
self.rep.orchestrator.run()
else:
dr_config = self._cfg.get("domain_randomization", None)
if dr_config is None:
raise ValueError("No domain randomization parameters are specified in the task yaml config file")
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize == False or randomization_params is None:
print("Domain randomization will not be applied.")
def _set_up_observations_randomization(self, task):
task.randomize_observations = True
self._observations_dr_params = self._cfg["domain_randomization"]["randomization_params"]["observations"]
if self._observations_dr_params is None:
raise ValueError(f"Observations randomization parameters are not provided.")
if "on_reset" in self._observations_dr_params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(
self._observations_dr_params["on_reset"].keys()
):
raise ValueError(
f"Please ensure the following observations on_reset randomization parameters are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("observations", "on_reset")] = np.array(
self._observations_dr_params["on_reset"]["distribution_parameters"]
)
if "on_interval" in self._observations_dr_params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
self._observations_dr_params["on_interval"].keys()
):
raise ValueError(
f"Please ensure the following observations on_interval randomization parameters are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("observations", "on_interval")] = np.array(
self._observations_dr_params["on_interval"]["distribution_parameters"]
)
self._observations_counter_buffer = torch.zeros(
(self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"]
)
self._observations_correlated_noise = torch.zeros(
(self._cfg["env"]["numEnvs"], task.num_observations), device=self._config["rl_device"]
)
def _set_up_actions_randomization(self, task):
task.randomize_actions = True
self._actions_dr_params = self._cfg["domain_randomization"]["randomization_params"]["actions"]
if self._actions_dr_params is None:
raise ValueError(f"Actions randomization parameters are not provided.")
if "on_reset" in self._actions_dr_params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(
self._actions_dr_params["on_reset"].keys()
):
raise ValueError(
f"Please ensure the following actions on_reset randomization parameters are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("actions", "on_reset")] = np.array(
self._actions_dr_params["on_reset"]["distribution_parameters"]
)
if "on_interval" in self._actions_dr_params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
self._actions_dr_params["on_interval"].keys()
):
raise ValueError(
f"Please ensure the following actions on_interval randomization parameters are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("actions", "on_interval")] = np.array(
self._actions_dr_params["on_interval"]["distribution_parameters"]
)
self._actions_counter_buffer = torch.zeros(
(self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"]
)
self._actions_correlated_noise = torch.zeros(
(self._cfg["env"]["numEnvs"], task.num_actions), device=self._config["rl_device"]
)
def apply_observations_randomization(self, observations, reset_buf):
env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1)
self._observations_counter_buffer[env_ids] = 0
self._observations_counter_buffer += 1
if "on_reset" in self._observations_dr_params.keys():
observations[:] = self._apply_correlated_noise(
buffer_type="observations",
buffer=observations,
reset_ids=env_ids,
operation=self._observations_dr_params["on_reset"]["operation"],
distribution=self._observations_dr_params["on_reset"]["distribution"],
distribution_parameters=self._observations_dr_params["on_reset"]["distribution_parameters"],
)
if "on_interval" in self._observations_dr_params.keys():
randomize_ids = (
(self._observations_counter_buffer >= self._observations_dr_params["on_interval"]["frequency_interval"])
.nonzero(as_tuple=False)
.squeeze(-1)
)
self._observations_counter_buffer[randomize_ids] = 0
observations[:] = self._apply_uncorrelated_noise(
buffer=observations,
randomize_ids=randomize_ids,
operation=self._observations_dr_params["on_interval"]["operation"],
distribution=self._observations_dr_params["on_interval"]["distribution"],
distribution_parameters=self._observations_dr_params["on_interval"]["distribution_parameters"],
)
return observations
def apply_actions_randomization(self, actions, reset_buf):
env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1)
self._actions_counter_buffer[env_ids] = 0
self._actions_counter_buffer += 1
if "on_reset" in self._actions_dr_params.keys():
actions[:] = self._apply_correlated_noise(
buffer_type="actions",
buffer=actions,
reset_ids=env_ids,
operation=self._actions_dr_params["on_reset"]["operation"],
distribution=self._actions_dr_params["on_reset"]["distribution"],
distribution_parameters=self._actions_dr_params["on_reset"]["distribution_parameters"],
)
if "on_interval" in self._actions_dr_params.keys():
randomize_ids = (
(self._actions_counter_buffer >= self._actions_dr_params["on_interval"]["frequency_interval"])
.nonzero(as_tuple=False)
.squeeze(-1)
)
self._actions_counter_buffer[randomize_ids] = 0
actions[:] = self._apply_uncorrelated_noise(
buffer=actions,
randomize_ids=randomize_ids,
operation=self._actions_dr_params["on_interval"]["operation"],
distribution=self._actions_dr_params["on_interval"]["distribution"],
distribution_parameters=self._actions_dr_params["on_interval"]["distribution_parameters"],
)
return actions
def _apply_uncorrelated_noise(self, buffer, randomize_ids, operation, distribution, distribution_parameters):
if distribution == "gaussian" or distribution == "normal":
noise = torch.normal(
mean=distribution_parameters[0],
std=distribution_parameters[1],
size=(len(randomize_ids), buffer.shape[1]),
device=self._config["rl_device"],
)
elif distribution == "uniform":
noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand(
(len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"]
) + distribution_parameters[0]
elif distribution == "loguniform" or distribution == "log_uniform":
noise = torch.exp(
(np.log(distribution_parameters[1]) - np.log(distribution_parameters[0]))
* torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"])
+ np.log(distribution_parameters[0])
)
else:
print(f"The specified {distribution} distribution is not supported.")
if operation == "additive":
buffer[randomize_ids] += noise
elif operation == "scaling":
buffer[randomize_ids] *= noise
else:
print(f"The specified {operation} operation type is not supported.")
return buffer
def _apply_correlated_noise(self, buffer_type, buffer, reset_ids, operation, distribution, distribution_parameters):
if buffer_type == "observations":
correlated_noise_buffer = self._observations_correlated_noise
elif buffer_type == "actions":
correlated_noise_buffer = self._actions_correlated_noise
if len(reset_ids) > 0:
if distribution == "gaussian" or distribution == "normal":
correlated_noise_buffer[reset_ids] = torch.normal(
mean=distribution_parameters[0],
std=distribution_parameters[1],
size=(len(reset_ids), buffer.shape[1]),
device=self._config["rl_device"],
)
elif distribution == "uniform":
correlated_noise_buffer[reset_ids] = (
distribution_parameters[1] - distribution_parameters[0]
) * torch.rand(
(len(reset_ids), buffer.shape[1]), device=self._config["rl_device"]
) + distribution_parameters[
0
]
elif distribution == "loguniform" or distribution == "log_uniform":
correlated_noise_buffer[reset_ids] = torch.exp(
(np.log(distribution_parameters[1]) - np.log(distribution_parameters[0]))
* torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["rl_device"])
+ np.log(distribution_parameters[0])
)
else:
print(f"The specified {distribution} distribution is not supported.")
if operation == "additive":
buffer += correlated_noise_buffer
elif operation == "scaling":
buffer *= correlated_noise_buffer
else:
print(f"The specified {operation} operation type is not supported.")
return buffer
def _set_up_simulation_randomization(self, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for simulation {attribute} is not provided.")
if attribute in self.dr.SIMULATION_CONTEXT_ATTRIBUTES:
self.distributions["simulation"][attribute] = dict()
if "on_reset" in params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(params["on_reset"]):
raise ValueError(
f"Please ensure the following randomization parameters for simulation {attribute} on_reset are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("simulation", attribute, "on_reset")] = np.array(
params["on_reset"]["distribution_parameters"]
)
kwargs = {"operation": params["on_reset"]["operation"]}
self.distributions["simulation"][attribute]["on_reset"] = self._generate_distribution(
dimension=self.dr.physics_view._simulation_context_initial_values[attribute].shape[0],
view_name="simulation",
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["simulation"][attribute]["on_reset"]
with self.dr.gate.on_env_reset():
self.dr.physics_view.randomize_simulation_context(**kwargs)
if "on_interval" in params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
params["on_interval"]
):
raise ValueError(
f"Please ensure the following randomization parameters for simulation {attribute} on_interval are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("simulation", attribute, "on_interval")] = np.array(
params["on_interval"]["distribution_parameters"]
)
kwargs = {"operation": params["on_interval"]["operation"]}
self.distributions["simulation"][attribute]["on_interval"] = self._generate_distribution(
dimension=self.dr.physics_view._simulation_context_initial_values[attribute].shape[0],
view_name="simulation",
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["simulation"][attribute]["on_interval"]
with self.dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
self.dr.physics_view.randomize_simulation_context(**kwargs)
def _set_up_rigid_prim_view_randomization(self, view_name, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for rigid prim view {view_name} {attribute} is not provided.")
if attribute in self.dr.RIGID_PRIM_ATTRIBUTES:
self.distributions["rigid_prim_views"][view_name][attribute] = dict()
if "on_reset" in params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(params["on_reset"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_reset")] = np.array(
params["on_reset"]["distribution_parameters"]
)
kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys():
kwargs["num_buckets"] = params["on_reset"]["num_buckets"]
self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"] = self._generate_distribution(
dimension=self.dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"]
with self.dr.gate.on_env_reset():
self.dr.physics_view.randomize_rigid_prim_view(**kwargs)
if "on_interval" in params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
params["on_interval"]
):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_interval")] = np.array(
params["on_interval"]["distribution_parameters"]
)
kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys():
kwargs["num_buckets"] = params["on_interval"]["num_buckets"]
self.distributions["rigid_prim_views"][view_name][attribute][
"on_interval"
] = self._generate_distribution(
dimension=self.dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"]
with self.dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
self.dr.physics_view.randomize_rigid_prim_view(**kwargs)
else:
raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.")
def _set_up_articulation_view_randomization(self, view_name, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for articulation view {view_name} {attribute} is not provided.")
if attribute in self.dr.ARTICULATION_ATTRIBUTES:
self.distributions["articulation_views"][view_name][attribute] = dict()
if "on_reset" in params.keys():
if not set(("operation", "distribution", "distribution_parameters")).issubset(params["on_reset"]):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: "
+ "operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_reset")] = np.array(
params["on_reset"]["distribution_parameters"]
)
kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys():
kwargs["num_buckets"] = params["on_reset"]["num_buckets"]
self.distributions["articulation_views"][view_name][attribute][
"on_reset"
] = self._generate_distribution(
dimension=self.dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_reset"]
with self.dr.gate.on_env_reset():
self.dr.physics_view.randomize_articulation_view(**kwargs)
if "on_interval" in params.keys():
if not set(("frequency_interval", "operation", "distribution", "distribution_parameters")).issubset(
params["on_interval"]
):
raise ValueError(
f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: "
+ "frequency_interval, operation, distribution, distribution_parameters."
)
self.active_domain_randomizations[
("articulation_views", view_name, attribute, "on_interval")
] = np.array(params["on_interval"]["distribution_parameters"])
kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys():
kwargs["num_buckets"] = params["on_interval"]["num_buckets"]
self.distributions["articulation_views"][view_name][attribute][
"on_interval"
] = self._generate_distribution(
dimension=self.dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_interval"]
with self.dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
self.dr.physics_view.randomize_articulation_view(**kwargs)
else:
raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.")
def _generate_distribution(self, view_name, attribute, dimension, params):
dist_params = self._sanitize_distribution_parameters(attribute, dimension, params["distribution_parameters"])
if params["distribution"] == "uniform":
return self.rep.distribution.uniform(tuple(dist_params[0]), tuple(dist_params[1]))
elif params["distribution"] == "gaussian" or params["distribution"] == "normal":
return self.rep.distribution.normal(tuple(dist_params[0]), tuple(dist_params[1]))
elif params["distribution"] == "loguniform" or params["distribution"] == "log_uniform":
return self.rep.distribution.log_uniform(tuple(dist_params[0]), tuple(dist_params[1]))
else:
raise ValueError(
f"The provided distribution for {view_name} {attribute} is not supported. "
+ "Options: uniform, gaussian/normal, loguniform/log_uniform"
)
def _sanitize_distribution_parameters(self, attribute, dimension, params):
distribution_parameters = np.array(params)
if distribution_parameters.shape == (2,):
# if the user does not provide a set of parameters for each dimension
dist_params = [[distribution_parameters[0]] * dimension, [distribution_parameters[1]] * dimension]
elif distribution_parameters.shape == (2, dimension):
# if the user provides a set of parameters for each dimension in the format [[...], [...]]
dist_params = distribution_parameters.tolist()
elif attribute in ["material_properties", "body_inertias"] and distribution_parameters.shape == (2, 3):
# if the user only provides the parameters for one body in the articulation, assume the same parameters for all other links
dist_params = [
[distribution_parameters[0]] * (dimension // 3),
[distribution_parameters[1]] * (dimension // 3),
]
else:
raise ValueError(
f"The provided distribution_parameters for {view_name} {attribute} is invalid due to incorrect dimensions."
)
return dist_params
def set_dr_distribution_parameters(self, distribution_parameters, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(
f"Cannot find a valid domain randomization distribution using the path {distribution_path}."
)
if distribution_path[0] == "observations":
if len(distribution_parameters) == 2:
self._observations_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters
else:
raise ValueError(
f"Please provide distribution_parameters for observations {distribution_path[1]} "
+ "in the form of [dist_param_1, dist_param_2]"
)
elif distribution_path[0] == "actions":
if len(distribution_parameters) == 2:
self._actions_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters
else:
raise ValueError(
f"Please provide distribution_parameters for actions {distribution_path[1]} "
+ "in the form of [dist_param_1, dist_param_2]"
)
else:
replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][
distribution_path[2]
]
if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views":
replicator_distribution = replicator_distribution[distribution_path[3]]
if (
replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform"
or replicator_distribution.node.get_node_type().get_node_type()
== "omni.replicator.core.OgnSampleLogUniform"
):
dimension = len(self.dr.utils.get_distribution_params(replicator_distribution, ["lower"])[0])
dist_params = self._sanitize_distribution_parameters(
distribution_path[-2], dimension, distribution_parameters
)
self.dr.utils.set_distribution_params(
replicator_distribution, {"lower": dist_params[0], "upper": dist_params[1]}
)
elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal":
dimension = len(self.dr.utils.get_distribution_params(replicator_distribution, ["mean"])[0])
dist_params = self._sanitize_distribution_parameters(
distribution_path[-2], dimension, distribution_parameters
)
self.dr.utils.set_distribution_params(
replicator_distribution, {"mean": dist_params[0], "std": dist_params[1]}
)
def get_dr_distribution_parameters(self, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(
f"Cannot find a valid domain randomization distribution using the path {distribution_path}."
)
if distribution_path[0] == "observations":
return self._observations_dr_params[distribution_path[1]]["distribution_parameters"]
elif distribution_path[0] == "actions":
return self._actions_dr_params[distribution_path[1]]["distribution_parameters"]
else:
replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][
distribution_path[2]
]
if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views":
replicator_distribution = replicator_distribution[distribution_path[3]]
if (
replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform"
or replicator_distribution.node.get_node_type().get_node_type()
== "omni.replicator.core.OgnSampleLogUniform"
):
return self.dr.utils.get_distribution_params(replicator_distribution, ["lower", "upper"])
elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal":
return self.dr.utils.get_distribution_params(replicator_distribution, ["mean", "std"])
def get_initial_dr_distribution_parameters(self, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(
f"Cannot find a valid domain randomization distribution using the path {distribution_path}."
)
return self.active_domain_randomizations[distribution_path].copy()
def _generate_noise(self, distribution, distribution_parameters, size, device):
if distribution == "gaussian" or distribution == "normal":
noise = torch.normal(
mean=distribution_parameters[0], std=distribution_parameters[1], size=size, device=device
)
elif distribution == "uniform":
noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand(
size, device=device
) + distribution_parameters[0]
elif distribution == "loguniform" or distribution == "log_uniform":
noise = torch.exp(
(np.log(distribution_parameters[1]) - np.log(distribution_parameters[0]))
* torch.rand(size, device=device)
+ np.log(distribution_parameters[0])
)
else:
print(f"The specified {distribution} distribution is not supported.")
return noise
def randomize_scale_on_startup(self, view, distribution, distribution_parameters, operation, sync_dim_noise=True):
scales = view.get_local_scales()
if sync_dim_noise:
dist_params = np.asarray(
self._sanitize_distribution_parameters(attribute="scale", dimension=1, params=distribution_parameters)
)
noise = (
self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device).repeat(3, 1).T
)
else:
dist_params = np.asarray(
self._sanitize_distribution_parameters(attribute="scale", dimension=3, params=distribution_parameters)
)
noise = torch.zeros((view.count, 3), device=view._device)
for i in range(3):
noise[:, i] = self._generate_noise(distribution, dist_params[:, i], (view.count,), view._device)
if operation == "additive":
scales += noise
elif operation == "scaling":
scales *= noise
elif operation == "direct":
scales = noise
else:
print(f"The specified {operation} operation type is not supported.")
view.set_local_scales(scales=scales)
def randomize_mass_on_startup(self, view, distribution, distribution_parameters, operation):
if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView):
masses = view.get_masses()
dist_params = np.asarray(
self._sanitize_distribution_parameters(
attribute=f"{view.name} mass", dimension=1, params=distribution_parameters
)
)
noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device)
set_masses = view.set_masses
if operation == "additive":
masses += noise
elif operation == "scaling":
masses *= noise
elif operation == "direct":
masses = noise
else:
print(f"The specified {operation} operation type is not supported.")
set_masses(masses)
def randomize_density_on_startup(self, view, distribution, distribution_parameters, operation):
if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView):
densities = view.get_densities()
dist_params = np.asarray(
self._sanitize_distribution_parameters(
attribute=f"{view.name} density", dimension=1, params=distribution_parameters
)
)
noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device)
set_densities = view.set_densities
if operation == "additive":
densities += noise
elif operation == "scaling":
densities *= noise
elif operation == "direct":
densities = noise
else:
print(f"The specified {operation} operation type is not supported.")
set_densities(densities)
| 45,603 | Python | 58.691099 | 136 | 0.555051 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/rlgames/rlgames_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Callable
import numpy as np
import torch
from rl_games.algos_torch import torch_ext
from rl_games.common import env_configurations, vecenv
from rl_games.common.algo_observer import AlgoObserver
class RLGPUAlgoObserver(AlgoObserver):
"""Allows us to log stats from the env along with the algorithm running stats."""
def __init__(self):
pass
def after_init(self, algo):
self.algo = algo
self.mean_scores = torch_ext.AverageMeter(1, self.algo.games_to_track).to(self.algo.ppo_device)
self.ep_infos = []
self.direct_info = {}
self.writer = self.algo.writer
def process_infos(self, infos, done_indices):
assert isinstance(infos, dict), "RLGPUAlgoObserver expects dict info"
if isinstance(infos, dict):
if "episode" in infos:
self.ep_infos.append(infos["episode"])
if len(infos) > 0 and isinstance(infos, dict): # allow direct logging from env
self.direct_info = {}
for k, v in infos.items():
# only log scalars
if (
isinstance(v, float)
or isinstance(v, int)
or (isinstance(v, torch.Tensor) and len(v.shape) == 0)
):
self.direct_info[k] = v
def after_clear_stats(self):
self.mean_scores.clear()
def after_print_stats(self, frame, epoch_num, total_time):
if self.ep_infos:
for key in self.ep_infos[0]:
infotensor = torch.tensor([], device=self.algo.device)
for ep_info in self.ep_infos:
# handle scalar and zero dimensional tensor infos
if not isinstance(ep_info[key], torch.Tensor):
ep_info[key] = torch.Tensor([ep_info[key]])
if len(ep_info[key].shape) == 0:
ep_info[key] = ep_info[key].unsqueeze(0)
infotensor = torch.cat((infotensor, ep_info[key].to(self.algo.device)))
value = torch.mean(infotensor)
self.writer.add_scalar("Episode/" + key, value, epoch_num)
self.ep_infos.clear()
for k, v in self.direct_info.items():
self.writer.add_scalar(f"{k}/frame", v, frame)
self.writer.add_scalar(f"{k}/iter", v, epoch_num)
self.writer.add_scalar(f"{k}/time", v, total_time)
if self.mean_scores.current_size > 0:
mean_scores = self.mean_scores.get_mean()
self.writer.add_scalar("scores/mean", mean_scores, frame)
self.writer.add_scalar("scores/iter", mean_scores, epoch_num)
self.writer.add_scalar("scores/time", mean_scores, total_time)
class RLGPUEnv(vecenv.IVecEnv):
def __init__(self, config_name, num_actors, **kwargs):
self.env = env_configurations.configurations[config_name]["env_creator"](**kwargs)
def step(self, action):
return self.env.step(action)
def reset(self):
return self.env.reset()
def get_number_of_agents(self):
return self.env.get_number_of_agents()
def get_env_info(self):
info = {}
info["action_space"] = self.env.action_space
info["observation_space"] = self.env.observation_space
if self.env.num_states > 0:
info["state_space"] = self.env.state_space
print(info["action_space"], info["observation_space"], info["state_space"])
else:
print(info["action_space"], info["observation_space"])
return info
| 5,201 | Python | 40.951613 | 103 | 0.636801 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/rlgames/rlgames_train_mt.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import copy
import datetime
import os
import queue
import threading
import traceback
import hydra
from omegaconf import DictConfig
from omni.isaac.gym.vec_env.vec_env_mt import TrainerMT
from omniisaacgymenvs.envs.vec_env_rlgames_mt import VecEnvRLGamesMT
from omniisaacgymenvs.utils.config_utils.path_utils import retrieve_checkpoint_path
from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import *
from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from omniisaacgymenvs.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv
from omniisaacgymenvs.utils.task_util import initialize_task
from rl_games.common import env_configurations, vecenv
from rl_games.torch_runner import Runner
class RLGTrainer:
def __init__(self, cfg, cfg_dict):
self.cfg = cfg
self.cfg_dict = cfg_dict
# ensure checkpoints can be specified as relative paths
self._bad_checkpoint = False
if self.cfg.checkpoint:
self.cfg.checkpoint = retrieve_checkpoint_path(self.cfg.checkpoint)
if not self.cfg.checkpoint:
self._bad_checkpoint = True
def launch_rlg_hydra(self, env):
# `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally.
# We use the helper function here to specify the environment config.
self.cfg_dict["task"]["test"] = self.cfg.test
# register the rl-games adapter to use inside the runner
vecenv.register("RLGPU", lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs))
env_configurations.register("rlgpu", {"vecenv_type": "RLGPU", "env_creator": lambda **kwargs: env})
self.rlg_config_dict = omegaconf_to_dict(self.cfg.train)
def run(self):
# create runner and set the settings
runner = Runner(RLGPUAlgoObserver())
# add evaluation parameters
if self.cfg.evaluation:
player_config = self.rlg_config_dict["params"]["config"].get("player", {})
player_config["evaluation"] = True
player_config["update_checkpoint_freq"] = 100
player_config["dir_to_monitor"] = os.path.dirname(self.cfg.checkpoint)
self.rlg_config_dict["params"]["config"]["player"] = player_config
# load config
runner.load(copy.deepcopy(self.rlg_config_dict))
runner.reset()
# dump config dict
experiment_dir = os.path.join("runs", self.cfg.train.params.config.name)
os.makedirs(experiment_dir, exist_ok=True)
with open(os.path.join(experiment_dir, "config.yaml"), "w") as f:
f.write(OmegaConf.to_yaml(self.cfg))
time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if self.cfg.wandb_activate:
# Make sure to install WandB if you actually use this.
import wandb
run_name = f"{self.cfg.wandb_name}_{time_str}"
wandb.init(
project=self.cfg.wandb_project,
group=self.cfg.wandb_group,
entity=self.cfg.wandb_entity,
config=self.cfg_dict,
sync_tensorboard=True,
id=run_name,
resume="allow",
monitor_gym=True,
)
runner.run(
{"train": not self.cfg.test, "play": self.cfg.test, "checkpoint": self.cfg.checkpoint, "sigma": None}
)
if self.cfg.wandb_activate:
wandb.finish()
class Trainer(TrainerMT):
def __init__(self, trainer, env):
self.ppo_thread = None
self.action_queue = None
self.data_queue = None
self.trainer = trainer
self.is_running = False
self.env = env
self.create_task()
self.run()
def create_task(self):
self.trainer.launch_rlg_hydra(self.env)
# task = initialize_task(self.trainer.cfg_dict, self.env, init_sim=False)
self.task = self.env._task
def run(self):
self.is_running = True
self.action_queue = queue.Queue(1)
self.data_queue = queue.Queue(1)
if "mt_timeout" in self.trainer.cfg_dict:
self.env.initialize(self.action_queue, self.data_queue, self.trainer.cfg_dict["mt_timeout"])
else:
self.env.initialize(self.action_queue, self.data_queue)
self.ppo_thread = PPOTrainer(self.env, self.task, self.trainer)
self.ppo_thread.daemon = True
self.ppo_thread.start()
def stop(self):
self.env.stop = True
self.env.clear_queues()
if self.action_queue:
self.action_queue.join()
if self.data_queue:
self.data_queue.join()
if self.ppo_thread:
self.ppo_thread.join()
self.action_queue = None
self.data_queue = None
self.ppo_thread = None
self.is_running = False
class PPOTrainer(threading.Thread):
def __init__(self, env, task, trainer):
super().__init__()
self.env = env
self.task = task
self.trainer = trainer
def run(self):
from omni.isaac.gym.vec_env import TaskStopException
print("starting ppo...")
try:
self.trainer.run()
# trainer finished - send stop signal to main thread
self.env.should_run = False
self.env.send_actions(None, block=False)
except TaskStopException:
print("Task Stopped!")
self.env.should_run = False
self.env.send_actions(None, block=False)
except Exception as e:
# an error occurred on the RL side - signal stop to main thread
print(traceback.format_exc())
self.env.should_run = False
self.env.send_actions(None, block=False)
| 7,402 | Python | 36.770408 | 119 | 0.653337 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/config_utils/sim_config.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import copy
import carb
import numpy as np
import omni.usd
import torch
from omni.isaac.core.utils.extensions import enable_extension
from omniisaacgymenvs.utils.config_utils.default_scene_params import *
class SimConfig:
def __init__(self, config: dict = None):
if config is None:
config = dict()
self._config = config
self._cfg = config.get("task", dict())
self._parse_config()
if self._config["test"] == True:
self._sim_params["enable_scene_query_support"] = True
if (
self._config["headless"] == True
and not self._sim_params["enable_cameras"]
and not self._config["enable_livestream"]
):
self._sim_params["use_fabric"] = False
self._sim_params["enable_viewport"] = False
else:
self._sim_params["enable_viewport"] = True
enable_extension("omni.kit.viewport.bundle")
if self._sim_params["enable_cameras"]:
enable_extension("omni.replicator.isaac")
self._sim_params["warp"] = self._config["warp"]
self._sim_params["sim_device"] = self._config["sim_device"]
self._adjust_dt()
if self._sim_params["disable_contact_processing"]:
carb.settings.get_settings().set_bool("/physics/disableContactProcessing", True)
carb.settings.get_settings().set_bool("/physics/physxDispatcher", True)
# Force the background grid off all the time for RL tasks, to avoid the grid showing up in any RL camera task
carb.settings.get_settings().set("/app/viewport/grid/enabled", False)
# Disable framerate limiting which might cause rendering slowdowns
carb.settings.get_settings().set("/app/runLoops/main/rateLimitEnabled", False)
import omni.ui
# Dock floating UIs this might not be needed anymore as extensions dock themselves
# Method for docking a particular window to a location
def dock_window(space, name, location, ratio=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, ratio=ratio)
return window
# Acquire the main docking station
main_dockspace = omni.ui.Workspace.get_window("DockSpace")
dock_window(main_dockspace, "Content", omni.ui.DockPosition.BOTTOM, 0.3)
window = omni.ui.Workspace.get_window("Content")
if window:
window.visible = False
def _parse_config(self):
# general sim parameter
self._sim_params = copy.deepcopy(default_sim_params)
self._default_physics_material = copy.deepcopy(default_physics_material)
sim_cfg = self._cfg.get("sim", None)
if sim_cfg is not None:
for opt in sim_cfg.keys():
if opt in self._sim_params:
if opt == "default_physics_material":
for material_opt in sim_cfg[opt]:
self._default_physics_material[material_opt] = sim_cfg[opt][material_opt]
else:
self._sim_params[opt] = sim_cfg[opt]
else:
print("Sim params does not have attribute: ", opt)
self._sim_params["default_physics_material"] = self._default_physics_material
# physx parameters
self._physx_params = copy.deepcopy(default_physx_params)
if sim_cfg is not None and "physx" in sim_cfg:
for opt in sim_cfg["physx"].keys():
if opt in self._physx_params:
self._physx_params[opt] = sim_cfg["physx"][opt]
else:
print("Physx sim params does not have attribute: ", opt)
self._sanitize_device()
def _sanitize_device(self):
if self._sim_params["use_gpu_pipeline"]:
self._physx_params["use_gpu"] = True
# device should be in sync with pipeline
if self._sim_params["use_gpu_pipeline"]:
self._config["sim_device"] = f"cuda:{self._config['device_id']}"
else:
self._config["sim_device"] = "cpu"
# also write to physics params for setting sim device
self._physx_params["sim_device"] = self._config["sim_device"]
print("Pipeline: ", "GPU" if self._sim_params["use_gpu_pipeline"] else "CPU")
print("Pipeline Device: ", self._config["sim_device"])
print("Sim Device: ", "GPU" if self._physx_params["use_gpu"] else "CPU")
def parse_actor_config(self, actor_name):
actor_params = copy.deepcopy(default_actor_options)
if "sim" in self._cfg and actor_name in self._cfg["sim"]:
actor_cfg = self._cfg["sim"][actor_name]
for opt in actor_cfg.keys():
if actor_cfg[opt] != -1 and opt in actor_params:
actor_params[opt] = actor_cfg[opt]
elif opt not in actor_params:
print("Actor params does not have attribute: ", opt)
return actor_params
def _get_actor_config_value(self, actor_name, attribute_name, attribute=None):
actor_params = self.parse_actor_config(actor_name)
if attribute is not None:
if attribute_name not in actor_params:
return attribute.Get()
if actor_params[attribute_name] != -1:
return actor_params[attribute_name]
elif actor_params["override_usd_defaults"] and not attribute.IsAuthored():
return self._physx_params[attribute_name]
else:
if actor_params[attribute_name] != -1:
return actor_params[attribute_name]
def _adjust_dt(self):
# re-evaluate rendering dt to simulate physics substeps
physics_dt = self.sim_params["dt"]
rendering_dt = self.sim_params["rendering_dt"]
# by default, rendering dt = physics dt
if rendering_dt <= 0:
rendering_dt = physics_dt
self.task_config["renderingInterval"] = max(round((1/physics_dt) / (1/rendering_dt)), 1)
# we always set rendering dt to be the same as physics dt, stepping is taken care of in VecEnvRLGames
self.sim_params["rendering_dt"] = physics_dt
@property
def sim_params(self):
return self._sim_params
@property
def config(self):
return self._config
@property
def task_config(self):
return self._cfg
@property
def physx_params(self):
return self._physx_params
def get_physics_params(self):
return {**self.sim_params, **self.physx_params}
def _get_physx_collision_api(self, prim):
from pxr import PhysxSchema, UsdPhysics
physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim)
if not physx_collision_api:
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim)
return physx_collision_api
def _get_physx_rigid_body_api(self, prim):
from pxr import PhysxSchema, UsdPhysics
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI(prim)
if not physx_rb_api:
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim)
return physx_rb_api
def _get_physx_articulation_api(self, prim):
from pxr import PhysxSchema, UsdPhysics
arti_api = PhysxSchema.PhysxArticulationAPI(prim)
if not arti_api:
arti_api = PhysxSchema.PhysxArticulationAPI.Apply(prim)
return arti_api
def set_contact_offset(self, name, prim, value=None):
physx_collision_api = self._get_physx_collision_api(prim)
contact_offset = physx_collision_api.GetContactOffsetAttr()
# if not contact_offset:
# contact_offset = physx_collision_api.CreateContactOffsetAttr()
if value is None:
value = self._get_actor_config_value(name, "contact_offset", contact_offset)
if value != -1:
contact_offset.Set(value)
def set_rest_offset(self, name, prim, value=None):
physx_collision_api = self._get_physx_collision_api(prim)
rest_offset = physx_collision_api.GetRestOffsetAttr()
# if not rest_offset:
# rest_offset = physx_collision_api.CreateRestOffsetAttr()
if value is None:
value = self._get_actor_config_value(name, "rest_offset", rest_offset)
if value != -1:
rest_offset.Set(value)
def set_position_iteration(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
solver_position_iteration_count = physx_rb_api.GetSolverPositionIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_position_iteration_count", solver_position_iteration_count
)
if value != -1:
solver_position_iteration_count.Set(value)
def set_velocity_iteration(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
solver_velocity_iteration_count = physx_rb_api.GetSolverVelocityIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_velocity_iteration_count", solver_velocity_iteration_count
)
if value != -1:
solver_velocity_iteration_count.Set(value)
def set_max_depenetration_velocity(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
max_depenetration_velocity = physx_rb_api.GetMaxDepenetrationVelocityAttr()
if value is None:
value = self._get_actor_config_value(name, "max_depenetration_velocity", max_depenetration_velocity)
if value != -1:
max_depenetration_velocity.Set(value)
def set_sleep_threshold(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
sleep_threshold = physx_rb_api.GetSleepThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold)
if value != -1:
sleep_threshold.Set(value)
def set_stabilization_threshold(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
stabilization_threshold = physx_rb_api.GetStabilizationThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold)
if value != -1:
stabilization_threshold.Set(value)
def set_gyroscopic_forces(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
enable_gyroscopic_forces = physx_rb_api.GetEnableGyroscopicForcesAttr()
if value is None:
value = self._get_actor_config_value(name, "enable_gyroscopic_forces", enable_gyroscopic_forces)
if value != -1:
enable_gyroscopic_forces.Set(value)
def set_density(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
density = physx_rb_api.GetDensityAttr()
if value is None:
value = self._get_actor_config_value(name, "density", density)
if value != -1:
density.Set(value)
# auto-compute mass
self.set_mass(prim, 0.0)
def set_mass(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
mass = physx_rb_api.GetMassAttr()
if value is None:
value = self._get_actor_config_value(name, "mass", mass)
if value != -1:
mass.Set(value)
def retain_acceleration(self, prim):
# retain accelerations if running with more than one substep
physx_rb_api = self._get_physx_rigid_body_api(prim)
if self._sim_params["substeps"] > 1:
physx_rb_api.GetRetainAccelerationsAttr().Set(True)
def make_kinematic(self, name, prim, cfg, value=None):
# make rigid body kinematic (fixed base and no collision)
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
if value is None:
value = self._get_actor_config_value(name, "make_kinematic")
if value == True:
# parse through all children prims
prims = [prim]
while len(prims) > 0:
cur_prim = prims.pop(0)
rb = UsdPhysics.RigidBodyAPI.Get(stage, cur_prim.GetPath())
if rb:
rb.CreateKinematicEnabledAttr().Set(True)
children_prims = cur_prim.GetPrim().GetChildren()
prims = prims + children_prims
def set_articulation_position_iteration(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
solver_position_iteration_count = arti_api.GetSolverPositionIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_position_iteration_count", solver_position_iteration_count
)
if value != -1:
solver_position_iteration_count.Set(value)
def set_articulation_velocity_iteration(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
solver_velocity_iteration_count = arti_api.GetSolverVelocityIterationCountAttr()
if value is None:
value = self._get_actor_config_value(
name, "solver_velocity_iteration_count", solver_position_iteration_count
)
if value != -1:
solver_velocity_iteration_count.Set(value)
def set_articulation_sleep_threshold(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
sleep_threshold = arti_api.GetSleepThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold)
if value != -1:
sleep_threshold.Set(value)
def set_articulation_stabilization_threshold(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
stabilization_threshold = arti_api.GetStabilizationThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold)
if value != -1:
stabilization_threshold.Set(value)
def apply_rigid_body_settings(self, name, prim, cfg, is_articulation):
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
rb_api = UsdPhysics.RigidBodyAPI.Get(stage, prim.GetPath())
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Get(stage, prim.GetPath())
if not physx_rb_api:
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim)
# if it's a body in an articulation, it's handled at articulation root
if not is_articulation:
self.make_kinematic(name, prim, cfg, cfg["make_kinematic"])
self.set_position_iteration(name, prim, cfg["solver_position_iteration_count"])
self.set_velocity_iteration(name, prim, cfg["solver_velocity_iteration_count"])
self.set_max_depenetration_velocity(name, prim, cfg["max_depenetration_velocity"])
self.set_sleep_threshold(name, prim, cfg["sleep_threshold"])
self.set_stabilization_threshold(name, prim, cfg["stabilization_threshold"])
self.set_gyroscopic_forces(name, prim, cfg["enable_gyroscopic_forces"])
# density and mass
mass_api = UsdPhysics.MassAPI.Get(stage, prim.GetPath())
if mass_api is None:
mass_api = UsdPhysics.MassAPI.Apply(prim)
mass_attr = mass_api.GetMassAttr()
density_attr = mass_api.GetDensityAttr()
if not mass_attr:
mass_attr = mass_api.CreateMassAttr()
if not density_attr:
density_attr = mass_api.CreateDensityAttr()
if cfg["density"] != -1:
density_attr.Set(cfg["density"])
mass_attr.Set(0.0) # mass is to be computed
elif cfg["override_usd_defaults"] and not density_attr.IsAuthored() and not mass_attr.IsAuthored():
density_attr.Set(self._physx_params["density"])
self.retain_acceleration(prim)
def apply_rigid_shape_settings(self, name, prim, cfg):
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
# collision APIs
collision_api = UsdPhysics.CollisionAPI(prim)
if not collision_api:
collision_api = UsdPhysics.CollisionAPI.Apply(prim)
physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim)
if not physx_collision_api:
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim)
self.set_contact_offset(name, prim, cfg["contact_offset"])
self.set_rest_offset(name, prim, cfg["rest_offset"])
def apply_articulation_settings(self, name, prim, cfg):
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
is_articulation = False
# check if is articulation
prims = [prim]
while len(prims) > 0:
prim_tmp = prims.pop(0)
articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, prim_tmp.GetPath())
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, prim_tmp.GetPath())
if articulation_api or physx_articulation_api:
is_articulation = True
children_prims = prim_tmp.GetPrim().GetChildren()
prims = prims + children_prims
# parse through all children prims
prims = [prim]
while len(prims) > 0:
cur_prim = prims.pop(0)
rb = UsdPhysics.RigidBodyAPI.Get(stage, cur_prim.GetPath())
collision_body = UsdPhysics.CollisionAPI.Get(stage, cur_prim.GetPath())
articulation = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath())
if rb:
self.apply_rigid_body_settings(name, cur_prim, cfg, is_articulation)
if collision_body:
self.apply_rigid_shape_settings(name, cur_prim, cfg)
if articulation:
articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath())
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, cur_prim.GetPath())
# enable self collisions
enable_self_collisions = physx_articulation_api.GetEnabledSelfCollisionsAttr()
if cfg["enable_self_collisions"] != -1:
enable_self_collisions.Set(cfg["enable_self_collisions"])
self.set_articulation_position_iteration(name, cur_prim, cfg["solver_position_iteration_count"])
self.set_articulation_velocity_iteration(name, cur_prim, cfg["solver_velocity_iteration_count"])
self.set_articulation_sleep_threshold(name, cur_prim, cfg["sleep_threshold"])
self.set_articulation_stabilization_threshold(name, cur_prim, cfg["stabilization_threshold"])
children_prims = cur_prim.GetPrim().GetChildren()
prims = prims + children_prims
| 20,932 | Python | 42.792887 | 117 | 0.632429 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/config_utils/default_scene_params.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
default_physx_params = {
### Per-scene settings
"use_gpu": False,
"worker_thread_count": 4,
"solver_type": 1, # 0: PGS, 1:TGS
"bounce_threshold_velocity": 0.2,
"friction_offset_threshold": 0.04, # A threshold of contact separation distance used to decide if a contact
# point will experience friction forces.
"friction_correlation_distance": 0.025, # Contact points can be merged into a single friction anchor if the
# distance between the contacts is smaller than correlation distance.
# disabling these can be useful for debugging
"enable_sleeping": True,
"enable_stabilization": True,
# GPU buffers
"gpu_max_rigid_contact_count": 512 * 1024,
"gpu_max_rigid_patch_count": 80 * 1024,
"gpu_found_lost_pairs_capacity": 1024,
"gpu_found_lost_aggregate_pairs_capacity": 1024,
"gpu_total_aggregate_pairs_capacity": 1024,
"gpu_max_soft_body_contacts": 1024 * 1024,
"gpu_max_particle_contacts": 1024 * 1024,
"gpu_heap_capacity": 64 * 1024 * 1024,
"gpu_temp_buffer_capacity": 16 * 1024 * 1024,
"gpu_max_num_partitions": 8,
"gpu_collision_stack_size": 64 * 1024 * 1024,
### Per-actor settings ( can override in actor_options )
"solver_position_iteration_count": 4,
"solver_velocity_iteration_count": 1,
"sleep_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may go to sleep.
# Allowed range [0, max_float).
"stabilization_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may
# participate in stabilization. Allowed range [0, max_float).
### Per-body settings ( can override in actor_options )
"enable_gyroscopic_forces": False,
"density": 1000.0, # density to be used for bodies that do not specify mass or density
"max_depenetration_velocity": 100.0,
### Per-shape settings ( can override in actor_options )
"contact_offset": 0.02,
"rest_offset": 0.001,
}
default_physics_material = {"static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0}
default_sim_params = {
"gravity": [0.0, 0.0, -9.81],
"dt": 1.0 / 60.0,
"rendering_dt": -1.0, # we don't want to override this if it's set from cfg
"substeps": 1,
"use_gpu_pipeline": True,
"add_ground_plane": True,
"add_distant_light": True,
"use_fabric": True,
"enable_scene_query_support": False,
"enable_cameras": False,
"disable_contact_processing": False,
"default_physics_material": default_physics_material,
}
default_actor_options = {
# -1 means use authored value from USD or default values from default_sim_params if not explicitly authored in USD.
# If an attribute value is not explicitly authored in USD, add one with the value given here,
# which overrides the USD default.
"override_usd_defaults": False,
"make_kinematic": -1,
"enable_self_collisions": -1,
"enable_gyroscopic_forces": -1,
"solver_position_iteration_count": -1,
"solver_velocity_iteration_count": -1,
"sleep_threshold": -1,
"stabilization_threshold": -1,
"max_depenetration_velocity": -1,
"density": -1,
"mass": -1,
"contact_offset": -1,
"rest_offset": -1,
}
| 4,783 | Python | 44.132075 | 119 | 0.703951 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/config_utils/path_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import os
import carb
from hydra.utils import to_absolute_path
def is_valid_local_file(path):
return os.path.isfile(path)
def is_valid_ov_file(path):
import omni.client
result, entry = omni.client.stat(path)
return result == omni.client.Result.OK
def download_ov_file(source_path, target_path):
import omni.client
result = omni.client.copy(source_path, target_path)
if result == omni.client.Result.OK:
return True
return False
def break_ov_path(path):
import omni.client
return omni.client.break_url(path)
def retrieve_checkpoint_path(path):
# check if it's a local path
if is_valid_local_file(path):
return to_absolute_path(path)
# check if it's an OV path
elif is_valid_ov_file(path):
ov_path = break_ov_path(path)
file_name = os.path.basename(ov_path.path)
target_path = f"checkpoints/{file_name}"
copy_to_local = download_ov_file(path, target_path)
return to_absolute_path(target_path)
else:
carb.log_error(f"Invalid checkpoint path: {path}. Does the file exist?")
return None
def get_experience(headless, enable_livestream, enable_viewport, kit_app):
if kit_app == '':
if enable_viewport:
experience = os.path.abspath(os.path.join('../apps', 'omni.isaac.sim.python.gym.camera.kit'))
else:
experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.gym.kit'
if headless and not enable_livestream:
experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.gym.headless.kit'
else:
experience = kit_app
return experience
| 3,226 | Python | 34.855555 | 105 | 0.713887 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/hydra_cfg/hydra_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import hydra
from omegaconf import DictConfig, OmegaConf
## OmegaConf & Hydra Config
# Resolvers used in hydra configs (see https://omegaconf.readthedocs.io/en/2.1_branch/usage.html#resolvers)
if not OmegaConf.has_resolver("eq"):
OmegaConf.register_new_resolver("eq", lambda x, y: x.lower() == y.lower())
if not OmegaConf.has_resolver("contains"):
OmegaConf.register_new_resolver("contains", lambda x, y: x.lower() in y.lower())
if not OmegaConf.has_resolver("if"):
OmegaConf.register_new_resolver("if", lambda pred, a, b: a if pred else b)
# allows us to resolve default arguments which are copied in multiple places in the config. used primarily for
# num_ensv
if not OmegaConf.has_resolver("resolve_default"):
OmegaConf.register_new_resolver("resolve_default", lambda default, arg: default if arg == "" else arg)
| 2,394 | Python | 51.065216 | 110 | 0.767753 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/hydra_cfg/reformat.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Dict
from omegaconf import DictConfig, OmegaConf
def omegaconf_to_dict(d: DictConfig) -> Dict:
"""Converts an omegaconf DictConfig to a python Dict, respecting variable interpolation."""
ret = {}
for k, v in d.items():
if isinstance(v, DictConfig):
ret[k] = omegaconf_to_dict(v)
else:
ret[k] = v
return ret
def print_dict(val, nesting: int = -4, start: bool = True):
"""Outputs a nested dictionory."""
if type(val) == dict:
if not start:
print("")
nesting += 4
for k in val:
print(nesting * " ", end="")
print(k, end=": ")
print_dict(val[k], nesting, start=False)
else:
print(val)
| 2,313 | Python | 38.896551 | 95 | 0.707739 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/terrain_utils/terrain_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from math import sqrt
import numpy as np
from numpy.random import choice
from omni.isaac.core.prims import XFormPrim
from pxr import Gf, PhysxSchema, Sdf, UsdPhysics
from scipy import interpolate
def random_uniform_terrain(
terrain,
min_height,
max_height,
step=1,
downsampled_scale=None,
):
"""
Generate a uniform noise terrain
Parameters
terrain (SubTerrain): the terrain
min_height (float): the minimum height of the terrain [meters]
max_height (float): the maximum height of the terrain [meters]
step (float): minimum height change between two points [meters]
downsampled_scale (float): distance between two randomly sampled points ( musty be larger or equal to terrain.horizontal_scale)
"""
if downsampled_scale is None:
downsampled_scale = terrain.horizontal_scale
# switch parameters to discrete units
min_height = int(min_height / terrain.vertical_scale)
max_height = int(max_height / terrain.vertical_scale)
step = int(step / terrain.vertical_scale)
heights_range = np.arange(min_height, max_height + step, step)
height_field_downsampled = np.random.choice(
heights_range,
(
int(terrain.width * terrain.horizontal_scale / downsampled_scale),
int(terrain.length * terrain.horizontal_scale / downsampled_scale),
),
)
x = np.linspace(0, terrain.width * terrain.horizontal_scale, height_field_downsampled.shape[0])
y = np.linspace(0, terrain.length * terrain.horizontal_scale, height_field_downsampled.shape[1])
f = interpolate.RectBivariateSpline(y, x, height_field_downsampled)
x_upsampled = np.linspace(0, terrain.width * terrain.horizontal_scale, terrain.width)
y_upsampled = np.linspace(0, terrain.length * terrain.horizontal_scale, terrain.length)
z_upsampled = np.rint(f(y_upsampled, x_upsampled))
terrain.height_field_raw += z_upsampled.astype(np.int16)
return terrain
def sloped_terrain(terrain, slope=1):
"""
Generate a sloped terrain
Parameters:
terrain (SubTerrain): the terrain
slope (int): positive or negative slope
Returns:
terrain (SubTerrain): update terrain
"""
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = xx.reshape(terrain.width, 1)
max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * terrain.width)
terrain.height_field_raw[:, np.arange(terrain.length)] += (max_height * xx / terrain.width).astype(
terrain.height_field_raw.dtype
)
return terrain
def pyramid_sloped_terrain(terrain, slope=1, platform_size=1.0):
"""
Generate a sloped terrain
Parameters:
terrain (terrain): the terrain
slope (int): positive or negative slope
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
center_x = int(terrain.width / 2)
center_y = int(terrain.length / 2)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = (center_x - np.abs(center_x - xx)) / center_x
yy = (center_y - np.abs(center_y - yy)) / center_y
xx = xx.reshape(terrain.width, 1)
yy = yy.reshape(1, terrain.length)
max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * (terrain.width / 2))
terrain.height_field_raw += (max_height * xx * yy).astype(terrain.height_field_raw.dtype)
platform_size = int(platform_size / terrain.horizontal_scale / 2)
x1 = terrain.width // 2 - platform_size
x2 = terrain.width // 2 + platform_size
y1 = terrain.length // 2 - platform_size
y2 = terrain.length // 2 + platform_size
min_h = min(terrain.height_field_raw[x1, y1], 0)
max_h = max(terrain.height_field_raw[x1, y1], 0)
terrain.height_field_raw = np.clip(terrain.height_field_raw, min_h, max_h)
return terrain
def discrete_obstacles_terrain(terrain, max_height, min_size, max_size, num_rects, platform_size=1.0):
"""
Generate a terrain with gaps
Parameters:
terrain (terrain): the terrain
max_height (float): maximum height of the obstacles (range=[-max, -max/2, max/2, max]) [meters]
min_size (float): minimum size of a rectangle obstacle [meters]
max_size (float): maximum size of a rectangle obstacle [meters]
num_rects (int): number of randomly generated obstacles
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
max_height = int(max_height / terrain.vertical_scale)
min_size = int(min_size / terrain.horizontal_scale)
max_size = int(max_size / terrain.horizontal_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
(i, j) = terrain.height_field_raw.shape
height_range = [-max_height, -max_height // 2, max_height // 2, max_height]
width_range = range(min_size, max_size, 4)
length_range = range(min_size, max_size, 4)
for _ in range(num_rects):
width = np.random.choice(width_range)
length = np.random.choice(length_range)
start_i = np.random.choice(range(0, i - width, 4))
start_j = np.random.choice(range(0, j - length, 4))
terrain.height_field_raw[start_i : start_i + width, start_j : start_j + length] = np.random.choice(height_range)
x1 = (terrain.width - platform_size) // 2
x2 = (terrain.width + platform_size) // 2
y1 = (terrain.length - platform_size) // 2
y2 = (terrain.length + platform_size) // 2
terrain.height_field_raw[x1:x2, y1:y2] = 0
return terrain
def wave_terrain(terrain, num_waves=1, amplitude=1.0):
"""
Generate a wavy terrain
Parameters:
terrain (terrain): the terrain
num_waves (int): number of sine waves across the terrain length
Returns:
terrain (SubTerrain): update terrain
"""
amplitude = int(0.5 * amplitude / terrain.vertical_scale)
if num_waves > 0:
div = terrain.length / (num_waves * np.pi * 2)
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = xx.reshape(terrain.width, 1)
yy = yy.reshape(1, terrain.length)
terrain.height_field_raw += (amplitude * np.cos(yy / div) + amplitude * np.sin(xx / div)).astype(
terrain.height_field_raw.dtype
)
return terrain
def stairs_terrain(terrain, step_width, step_height):
"""
Generate a stairs
Parameters:
terrain (terrain): the terrain
step_width (float): the width of the step [meters]
step_height (float): the height of the step [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
step_width = int(step_width / terrain.horizontal_scale)
step_height = int(step_height / terrain.vertical_scale)
num_steps = terrain.width // step_width
height = step_height
for i in range(num_steps):
terrain.height_field_raw[i * step_width : (i + 1) * step_width, :] += height
height += step_height
return terrain
def pyramid_stairs_terrain(terrain, step_width, step_height, platform_size=1.0):
"""
Generate stairs
Parameters:
terrain (terrain): the terrain
step_width (float): the width of the step [meters]
step_height (float): the step_height [meters]
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
step_width = int(step_width / terrain.horizontal_scale)
step_height = int(step_height / terrain.vertical_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
height = 0
start_x = 0
stop_x = terrain.width
start_y = 0
stop_y = terrain.length
while (stop_x - start_x) > platform_size and (stop_y - start_y) > platform_size:
start_x += step_width
stop_x -= step_width
start_y += step_width
stop_y -= step_width
height += step_height
terrain.height_field_raw[start_x:stop_x, start_y:stop_y] = height
return terrain
def stepping_stones_terrain(terrain, stone_size, stone_distance, max_height, platform_size=1.0, depth=-10):
"""
Generate a stepping stones terrain
Parameters:
terrain (terrain): the terrain
stone_size (float): horizontal size of the stepping stones [meters]
stone_distance (float): distance between stones (i.e size of the holes) [meters]
max_height (float): maximum height of the stones (positive and negative) [meters]
platform_size (float): size of the flat platform at the center of the terrain [meters]
depth (float): depth of the holes (default=-10.) [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
stone_size = int(stone_size / terrain.horizontal_scale)
stone_distance = int(stone_distance / terrain.horizontal_scale)
max_height = int(max_height / terrain.vertical_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
height_range = np.arange(-max_height - 1, max_height, step=1)
start_x = 0
start_y = 0
terrain.height_field_raw[:, :] = int(depth / terrain.vertical_scale)
if terrain.length >= terrain.width:
while start_y < terrain.length:
stop_y = min(terrain.length, start_y + stone_size)
start_x = np.random.randint(0, stone_size)
# fill first hole
stop_x = max(0, start_x - stone_distance)
terrain.height_field_raw[0:stop_x, start_y:stop_y] = np.random.choice(height_range)
# fill row
while start_x < terrain.width:
stop_x = min(terrain.width, start_x + stone_size)
terrain.height_field_raw[start_x:stop_x, start_y:stop_y] = np.random.choice(height_range)
start_x += stone_size + stone_distance
start_y += stone_size + stone_distance
elif terrain.width > terrain.length:
while start_x < terrain.width:
stop_x = min(terrain.width, start_x + stone_size)
start_y = np.random.randint(0, stone_size)
# fill first hole
stop_y = max(0, start_y - stone_distance)
terrain.height_field_raw[start_x:stop_x, 0:stop_y] = np.random.choice(height_range)
# fill column
while start_y < terrain.length:
stop_y = min(terrain.length, start_y + stone_size)
terrain.height_field_raw[start_x:stop_x, start_y:stop_y] = np.random.choice(height_range)
start_y += stone_size + stone_distance
start_x += stone_size + stone_distance
x1 = (terrain.width - platform_size) // 2
x2 = (terrain.width + platform_size) // 2
y1 = (terrain.length - platform_size) // 2
y2 = (terrain.length + platform_size) // 2
terrain.height_field_raw[x1:x2, y1:y2] = 0
return terrain
def convert_heightfield_to_trimesh(height_field_raw, horizontal_scale, vertical_scale, slope_threshold=None):
"""
Convert a heightfield array to a triangle mesh represented by vertices and triangles.
Optionally, corrects vertical surfaces above the provide slope threshold:
If (y2-y1)/(x2-x1) > slope_threshold -> Move A to A' (set x1 = x2). Do this for all directions.
B(x2,y2)
/|
/ |
/ |
(x1,y1)A---A'(x2',y1)
Parameters:
height_field_raw (np.array): input heightfield
horizontal_scale (float): horizontal scale of the heightfield [meters]
vertical_scale (float): vertical scale of the heightfield [meters]
slope_threshold (float): the slope threshold above which surfaces are made vertical. If None no correction is applied (default: None)
Returns:
vertices (np.array(float)): array of shape (num_vertices, 3). Each row represents the location of each vertex [meters]
triangles (np.array(int)): array of shape (num_triangles, 3). Each row represents the indices of the 3 vertices connected by this triangle.
"""
hf = height_field_raw
num_rows = hf.shape[0]
num_cols = hf.shape[1]
y = np.linspace(0, (num_cols - 1) * horizontal_scale, num_cols)
x = np.linspace(0, (num_rows - 1) * horizontal_scale, num_rows)
yy, xx = np.meshgrid(y, x)
if slope_threshold is not None:
slope_threshold *= horizontal_scale / vertical_scale
move_x = np.zeros((num_rows, num_cols))
move_y = np.zeros((num_rows, num_cols))
move_corners = np.zeros((num_rows, num_cols))
move_x[: num_rows - 1, :] += hf[1:num_rows, :] - hf[: num_rows - 1, :] > slope_threshold
move_x[1:num_rows, :] -= hf[: num_rows - 1, :] - hf[1:num_rows, :] > slope_threshold
move_y[:, : num_cols - 1] += hf[:, 1:num_cols] - hf[:, : num_cols - 1] > slope_threshold
move_y[:, 1:num_cols] -= hf[:, : num_cols - 1] - hf[:, 1:num_cols] > slope_threshold
move_corners[: num_rows - 1, : num_cols - 1] += (
hf[1:num_rows, 1:num_cols] - hf[: num_rows - 1, : num_cols - 1] > slope_threshold
)
move_corners[1:num_rows, 1:num_cols] -= (
hf[: num_rows - 1, : num_cols - 1] - hf[1:num_rows, 1:num_cols] > slope_threshold
)
xx += (move_x + move_corners * (move_x == 0)) * horizontal_scale
yy += (move_y + move_corners * (move_y == 0)) * horizontal_scale
# create triangle mesh vertices and triangles from the heightfield grid
vertices = np.zeros((num_rows * num_cols, 3), dtype=np.float32)
vertices[:, 0] = xx.flatten()
vertices[:, 1] = yy.flatten()
vertices[:, 2] = hf.flatten() * vertical_scale
triangles = -np.ones((2 * (num_rows - 1) * (num_cols - 1), 3), dtype=np.uint32)
for i in range(num_rows - 1):
ind0 = np.arange(0, num_cols - 1) + i * num_cols
ind1 = ind0 + 1
ind2 = ind0 + num_cols
ind3 = ind2 + 1
start = 2 * i * (num_cols - 1)
stop = start + 2 * (num_cols - 1)
triangles[start:stop:2, 0] = ind0
triangles[start:stop:2, 1] = ind3
triangles[start:stop:2, 2] = ind1
triangles[start + 1 : stop : 2, 0] = ind0
triangles[start + 1 : stop : 2, 1] = ind2
triangles[start + 1 : stop : 2, 2] = ind3
return vertices, triangles
def add_terrain_to_stage(stage, vertices, triangles, position=None, orientation=None):
num_faces = triangles.shape[0]
terrain_mesh = stage.DefinePrim("/World/terrain", "Mesh")
terrain_mesh.GetAttribute("points").Set(vertices)
terrain_mesh.GetAttribute("faceVertexIndices").Set(triangles.flatten())
terrain_mesh.GetAttribute("faceVertexCounts").Set(np.asarray([3] * num_faces))
terrain = XFormPrim(prim_path="/World/terrain", name="terrain", position=position, orientation=orientation)
UsdPhysics.CollisionAPI.Apply(terrain.prim)
# collision_api = UsdPhysics.MeshCollisionAPI.Apply(terrain.prim)
# collision_api.CreateApproximationAttr().Set("meshSimplification")
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(terrain.prim)
physx_collision_api.GetContactOffsetAttr().Set(0.02)
physx_collision_api.GetRestOffsetAttr().Set(0.00)
class SubTerrain:
def __init__(self, terrain_name="terrain", width=256, length=256, vertical_scale=1.0, horizontal_scale=1.0):
self.terrain_name = terrain_name
self.vertical_scale = vertical_scale
self.horizontal_scale = horizontal_scale
self.width = width
self.length = length
self.height_field_raw = np.zeros((self.width, self.length), dtype=np.int16)
| 17,645 | Python | 41.215311 | 147 | 0.649306 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/terrain_utils/create_terrain_demo.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import os, sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(SCRIPT_DIR)
import omni
from omni.isaac.kit import SimulationApp
import numpy as np
import torch
simulation_app = SimulationApp({"headless": False})
from abc import abstractmethod
from omni.isaac.core.tasks import BaseTask
from omni.isaac.core.prims import RigidPrimView, RigidPrim, XFormPrim
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import define_prim, get_prim_at_path
from omni.isaac.core.utils.nucleus import find_nucleus_server
from omni.isaac.core.utils.stage import add_reference_to_stage, get_current_stage
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.cloner import GridCloner
from pxr import UsdPhysics, UsdLux, UsdShade, Sdf, Gf, UsdGeom, PhysxSchema
from terrain_utils import *
class TerrainCreation(BaseTask):
def __init__(self, name, num_envs, num_per_row, env_spacing, config=None, offset=None,) -> None:
BaseTask.__init__(self, name=name, offset=offset)
self._num_envs = num_envs
self._num_per_row = num_per_row
self._env_spacing = env_spacing
self._device = "cpu"
self._cloner = GridCloner(self._env_spacing, self._num_per_row)
self._cloner.define_base_env(self.default_base_env_path)
define_prim(self.default_zero_env_path)
@property
def default_base_env_path(self):
return "/World/envs"
@property
def default_zero_env_path(self):
return f"{self.default_base_env_path}/env_0"
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight"))
distantLight.CreateIntensityAttr(2000)
self.get_terrain()
self.get_ball()
super().set_up_scene(scene)
prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs)
print(f"cloning {self._num_envs} environments...")
self._env_pos = self._cloner.clone(
source_prim_path="/World/envs/env_0",
prim_paths=prim_paths
)
return
def get_terrain(self):
# create all available terrain types
num_terains = 8
terrain_width = 12.
terrain_length = 12.
horizontal_scale = 0.25 # [m]
vertical_scale = 0.005 # [m]
num_rows = int(terrain_width/horizontal_scale)
num_cols = int(terrain_length/horizontal_scale)
heightfield = np.zeros((num_terains*num_rows, num_cols), dtype=np.int16)
def new_sub_terrain():
return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale)
heightfield[0:num_rows, :] = random_uniform_terrain(new_sub_terrain(), min_height=-0.2, max_height=0.2, step=0.2, downsampled_scale=0.5).height_field_raw
heightfield[num_rows:2*num_rows, :] = sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw
heightfield[2*num_rows:3*num_rows, :] = pyramid_sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw
heightfield[3*num_rows:4*num_rows, :] = discrete_obstacles_terrain(new_sub_terrain(), max_height=0.5, min_size=1., max_size=5., num_rects=20).height_field_raw
heightfield[4*num_rows:5*num_rows, :] = wave_terrain(new_sub_terrain(), num_waves=2., amplitude=1.).height_field_raw
heightfield[5*num_rows:6*num_rows, :] = stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw
heightfield[6*num_rows:7*num_rows, :] = pyramid_stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw
heightfield[7*num_rows:8*num_rows, :] = stepping_stones_terrain(new_sub_terrain(), stone_size=1.,
stone_distance=1., max_height=0.5, platform_size=0.).height_field_raw
vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5)
position = np.array([-6.0, 48.0, 0])
orientation = np.array([0.70711, 0.0, 0.0, -0.70711])
add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation)
def get_ball(self):
ball = DynamicSphere(prim_path=self.default_zero_env_path + "/ball",
name="ball",
translation=np.array([0.0, 0.0, 1.0]),
mass=0.5,
radius=0.2,)
def post_reset(self):
for i in range(self._num_envs):
ball_prim = self._stage.GetPrimAtPath(f"{self.default_base_env_path}/env_{i}/ball")
color = 0.5 + 0.5 * np.random.random(3)
visual_material = PreviewSurface(prim_path=f"{self.default_base_env_path}/env_{i}/ball/Looks/visual_material", color=color)
binding_api = UsdShade.MaterialBindingAPI(ball_prim)
binding_api.Bind(visual_material.material, bindingStrength=UsdShade.Tokens.strongerThanDescendants)
def get_observations(self):
pass
def calculate_metrics(self) -> None:
pass
def is_done(self) -> None:
pass
if __name__ == "__main__":
world = World(
stage_units_in_meters=1.0,
rendering_dt=1.0/60.0,
backend="torch",
device="cpu",
)
num_envs = 800
num_per_row = 80
env_spacing = 0.56*2
terrain_creation_task = TerrainCreation(name="TerrainCreation",
num_envs=num_envs,
num_per_row=num_per_row,
env_spacing=env_spacing,
)
world.add_task(terrain_creation_task)
world.reset()
while simulation_app.is_running():
if world.is_playing():
if world.current_time_step_index == 0:
world.reset(soft=True)
world.step(render=True)
else:
world.step(render=True)
simulation_app.close() | 7,869 | Python | 43.213483 | 166 | 0.650654 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import omni.client
import omni.usd
from pxr import Sdf, UsdGeom
def update_reference(source_prim_path, source_reference_path, target_reference_path):
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
while len(prims) > 0:
prim = prims.pop(0)
prim_spec = stage.GetRootLayer().GetPrimAtPath(prim.GetPath())
reference_list = prim_spec.referenceList
refs = reference_list.GetAddedOrExplicitItems()
if len(refs) > 0:
for ref in refs:
if ref.assetPath == source_reference_path:
prim.GetReferences().RemoveReference(ref)
prim.GetReferences().AddReference(assetPath=target_reference_path, primPath=prim.GetPath())
prims = prims + prim.GetChildren()
def create_parent_xforms(asset_usd_path, source_prim_path, save_as_path=None):
"""Adds a new UsdGeom.Xform prim for each Mesh/Geometry prim under source_prim_path.
Moves material assignment to new parent prim if any exists on the Mesh/Geometry prim.
Args:
asset_usd_path (str): USD file path for asset
source_prim_path (str): USD path of root prim
save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file.
"""
omni.usd.get_context().open_stage(asset_usd_path)
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
edits = Sdf.BatchNamespaceEdit()
while len(prims) > 0:
prim = prims.pop(0)
print(prim)
if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]:
new_xform = UsdGeom.Xform.Define(stage, str(prim.GetPath()) + "_xform")
print(prim, new_xform)
edits.Add(Sdf.NamespaceEdit.Reparent(prim.GetPath(), new_xform.GetPath(), 0))
continue
children_prims = prim.GetChildren()
prims = prims + children_prims
stage.GetRootLayer().Apply(edits)
if save_as_path is None:
omni.usd.get_context().save_stage()
else:
omni.usd.get_context().save_as_stage(save_as_path)
def convert_asset_instanceable(asset_usd_path, source_prim_path, save_as_path=None, create_xforms=True):
"""Makes all mesh/geometry prims instanceable.
Can optionally add UsdGeom.Xform prim as parent for all mesh/geometry prims.
Makes a copy of the asset USD file, which will be used for referencing.
Updates asset file to convert all parent prims of mesh/geometry prims to reference cloned USD file.
Args:
asset_usd_path (str): USD file path for asset
source_prim_path (str): USD path of root prim
save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file.
create_xforms (bool): Whether to add new UsdGeom.Xform prims to mesh/geometry prims.
"""
if create_xforms:
create_parent_xforms(asset_usd_path, source_prim_path, save_as_path)
asset_usd_path = save_as_path
instance_usd_path = ".".join(asset_usd_path.split(".")[:-1]) + "_meshes.usd"
omni.client.copy(asset_usd_path, instance_usd_path)
omni.usd.get_context().open_stage(asset_usd_path)
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
while len(prims) > 0:
prim = prims.pop(0)
if prim:
if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]:
parent_prim = prim.GetParent()
if parent_prim and not parent_prim.IsInstance():
parent_prim.GetReferences().AddReference(
assetPath=instance_usd_path, primPath=str(parent_prim.GetPath())
)
parent_prim.SetInstanceable(True)
continue
children_prims = prim.GetChildren()
prims = prims + children_prims
if save_as_path is None:
omni.usd.get_context().save_stage()
else:
omni.usd.get_context().save_as_stage(save_as_path)
| 5,627 | Python | 42.627907 | 111 | 0.67727 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/usd_utils/create_instanceable_dofbot.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
import omni.usd
import omni.client
from pxr import UsdGeom, Sdf, UsdPhysics, UsdShade
# Note: this script should be executed in Isaac Sim `Script Editor` window
def create_dofbot(asset_usd_path, dofbot_usd_path):
# Duplicate dofbot.usd file
omni.client.copy(asset_usd_path, dofbot_usd_path)
def create_dofbot_mesh(asset_usd_path, dofbot_mesh_usd_path):
# Create dofbot_mesh.usd file
omni.client.copy(asset_usd_path, dofbot_mesh_usd_path)
omni.usd.get_context().open_stage(dofbot_mesh_usd_path)
stage = omni.usd.get_context().get_stage()
edits = Sdf.BatchNamespaceEdit()
# Reparent joints in link5
for d in ['Left', 'Right']:
# Reparent finger 03 joint
new_parent_path = f'/arm/link5/Finger_{d}_03'
old_parent_path = f'{new_parent_path}/Finger_{d}_03'
joint_path = f'{old_parent_path}/Finger_{d}_03_RevoluteJoint'
edits.Add(Sdf.NamespaceEdit.Reparent(joint_path, new_parent_path, 0))
# Reparent finger 02 joint
new_parent_path = f'/arm/link5/Finger_{d}_02'
old_parent_path = f'{new_parent_path}/Finger_{d}_02'
joint_path = f'{old_parent_path}/Finger_{d}_02_RevoluteJoint'
edits.Add(Sdf.NamespaceEdit.Reparent(joint_path, new_parent_path, 0))
# Create parent Xforms
# Joint 1 & 2 & 3
reparent_tasks = [
# base_link
['/arm/base_link/visuals', 'visuals_xform'],
['/arm/base_link/PCB_01', 'visuals_xform'],
['/arm/base_link/Base01_01', 'visuals_xform'],
['/arm/base_link/Antennas_01', 'visuals_xform'],
['/arm/base_link/collisions', 'collisions_xform'],
# link1
['/arm/link1/visuals', 'visuals_xform'],
['/arm/link1/collisions', 'collisions_xform'],
# link2
['/arm/link2/visuals', 'visuals_xform'],
['/arm/link2/collisions', 'collisions_xform'],
# link3
['/arm/link3/visuals', 'visuals_xform'],
['/arm/link3/collisions', 'collisions_xform'],
# link4
['/arm/link4/Wrist_Lift', 'geoms_xform'],
['/arm/link4/Camera', 'geoms_xform'],
# link5
['/arm/link5/Wrist_Twist/Wrist_Twist', 'geoms_xform'],
['/arm/link5/Finger_Left_01/Finger_Left_01', 'geoms_xform'],
['/arm/link5/Finger_Right_01/Finger_Right_01', 'geoms_xform'],
['/arm/link5/Finger_Left_03/Finger_Left_03', 'geoms_xform'],
['/arm/link5/Finger_Right_03/Finger_Right_03', 'geoms_xform'],
['/arm/link5/Finger_Left_02/Finger_Left_02', 'geoms_xform'],
['/arm/link5/Finger_Right_02/Finger_Right_02', 'geoms_xform'],
] # [prim_path, parent_xform_name]
for task in reparent_tasks:
prim_path, parent_xform_name = task
old_parent_path = '/'.join(prim_path.split('/')[:-1])
new_parent_path = f'{old_parent_path}/{parent_xform_name}'
UsdGeom.Xform.Define(stage, new_parent_path)
edits.Add(Sdf.NamespaceEdit.Reparent(prim_path, new_parent_path, -1))
# Delete redundant materials
edits.Add(Sdf.NamespaceEdit.Remove('/arm/link5/Looks'))
stage.GetRootLayer().Apply(edits)
# Fix link5 joints
for d in ['Left', 'Right']:
# finger 01 revolute joints
joint_path = f'/arm/link5/Finger_{d}_01/Finger_{d}_01_RevoluteJoint'
joint = UsdPhysics.Joint.Get(stage, joint_path)
joint.GetBody1Rel().SetTargets(['/arm/link5/Wrist_Twist/geoms_xform/Wrist_Twist'])
# finger 03 revolute joints
joint_path = f'/arm/link5/Finger_{d}_03/Finger_{d}_03_RevoluteJoint'
joint = UsdPhysics.Joint.Get(stage, joint_path)
joint.GetBody0Rel().SetTargets([f'/arm/link5/Finger_{d}_03'])
joint.GetBody1Rel().SetTargets([f'/arm/link5/Finger_{d}_01/geoms_xform/Finger_{d}_01'])
# finger 02 spherical joints
joint_path = f'/arm/link5/Finger_{d}_02/Finger_{d}_02_SphericalJoint'
joint = UsdPhysics.Joint.Get(stage, joint_path)
joint.GetBody0Rel().SetTargets([f'/arm/link5/Finger_{d}_03/geoms_xform/Finger_{d}_03'])
joint.GetBody1Rel().SetTargets([f'/arm/link5/Finger_{d}_02/geoms_xform/Finger_{d}_02'])
# finger 02 revolute joints
joint_path = f'/arm/link5/Finger_{d}_02/Finger_{d}_02_RevoluteJoint'
joint = UsdPhysics.Joint.Get(stage, joint_path)
joint.GetBody0Rel().SetTargets([f'/arm/link5/Finger_{d}_02/geoms_xform/Finger_{d}_02'])
joint.GetBody1Rel().SetTargets(['/arm/link5/Wrist_Twist/geoms_xform/Wrist_Twist'])
for prim in stage.Traverse():
if prim.GetTypeName() == 'Xform':
# Copy Looks folder into visuals_xform and geoms_xform
path = str(prim.GetPath())
if path.endswith('visuals_xform') or path.endswith('geoms_xform'):
omni.usd.duplicate_prim(stage, '/arm/Looks', f'{path}/Looks')
ref = stage.GetPrimAtPath(f'{path}/Looks').GetReferences()
ref.ClearReferences()
ref.AddReference('./dofbot_materials.usd')
pass
elif prim.GetTypeName() == 'GeomSubset':
# Bind GeomSubset to local materials
path = str(prim.GetPath())
parent_xform_path = path.split('/')
while parent_xform_path[-1] != 'visuals_xform' and parent_xform_path[-1] != 'geoms_xform':
parent_xform_path.pop()
parent_xform_path = '/'.join(parent_xform_path)
name = path.split('/')[-1]
material = UsdShade.Material.Get(stage, f'{parent_xform_path}/Looks/{name}')
UsdShade.MaterialBindingAPI(prim).Bind(material) # , UsdShade.Tokens.strongerThanDescendants)
edits = Sdf.BatchNamespaceEdit()
edits.Add(Sdf.NamespaceEdit.Remove('/arm/Looks'))
stage.GetRootLayer().Apply(edits)
# Save to file
omni.usd.get_context().save_stage()
def create_dofbot_materials(asset_usd_path, dofbot_materials_usd_path):
# Create dofbot_materials.usd file
omni.client.copy(asset_usd_path, dofbot_materials_usd_path)
omni.usd.get_context().open_stage(dofbot_materials_usd_path)
stage = omni.usd.get_context().get_stage()
edits = Sdf.BatchNamespaceEdit()
# Extract Looks folder
edits.Add(Sdf.NamespaceEdit.Reparent('/arm/Looks', '/', 0))
# Remove everything else
edits.Add(Sdf.NamespaceEdit.Remove('/World'))
edits.Add(Sdf.NamespaceEdit.Remove('/arm'))
# Apply & save to file
stage.GetRootLayer().Apply(edits)
prim = stage.GetPrimAtPath('/Looks')
stage.SetDefaultPrim(prim)
omni.usd.get_context().save_stage()
def create_dofbot_instanceable(dofbot_mesh_usd_path, dofbot_instanceable_usd_path):
omni.client.copy(dofbot_mesh_usd_path, dofbot_instanceable_usd_path)
omni.usd.get_context().open_stage(dofbot_instanceable_usd_path)
stage = omni.usd.get_context().get_stage()
# Set up references and instanceables
for prim in stage.Traverse():
if prim.GetTypeName() != 'Xform':
continue
# Add reference to visuals_xform, collisions_xform, geoms_xform, and make them instanceable
path = str(prim.GetPath())
if path.endswith('visuals_xform') or path.endswith('collisions_xform') or path.endswith('geoms_xform'):
ref = prim.GetReferences()
ref.ClearReferences()
ref.AddReference('./dofbot_mesh.usd', path)
prim.SetInstanceable(True)
# Save to file
omni.usd.get_context().save_stage()
def create_block_indicator():
for suffix in ['', '_instanceable']:
asset_usd_path = f'omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Props/Blocks/block{suffix}.usd'
block_usd_path = f'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Props/Blocks/block{suffix}.usd'
omni.client.copy(asset_usd_path, block_usd_path)
omni.usd.get_context().open_stage(block_usd_path)
stage = omni.usd.get_context().get_stage()
edits = Sdf.BatchNamespaceEdit()
edits.Add(Sdf.NamespaceEdit.Remove('/object/object/collisions'))
stage.GetRootLayer().Apply(edits)
omni.usd.get_context().save_stage()
if __name__ == '__main__':
asset_usd_path = 'omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot.usd'
dofbot_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot.usd'
dofbot_materials_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot_materials.usd'
dofbot_mesh_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot_mesh.usd'
dofbot_instanceable_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot_instanceable.usd'
create_dofbot(asset_usd_path, dofbot_usd_path)
create_dofbot_materials(asset_usd_path, dofbot_materials_usd_path)
create_dofbot_mesh(asset_usd_path, dofbot_mesh_usd_path)
create_dofbot_instanceable(dofbot_mesh_usd_path, dofbot_instanceable_usd_path)
create_block_indicator()
print("Done!")
| 10,636 | Python | 49.174528 | 133 | 0.668578 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/utils/usd_utils/create_instanceable_dofbot_from_urdf.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
# Ref: https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_urdf.html#importing-urdf-using-python
import os
import omni.kit.commands
import omni.usd
from omni.importer.urdf import _urdf
from omni.isaac.core.utils.extensions import get_extension_path_from_name
from pxr import Sdf, UsdGeom
def create_dofbot_from_urdf(urdf_path, usd_path, mesh_usd_path, instanceable_usd_path):
# Set the settings in the import config
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.convex_decomp = False
import_config.import_inertia_tensor = False
import_config.fix_base = True
import_config.make_default_prim = True
import_config.self_collision = False
import_config.create_physics_scene = True
# The two values below follows the Dofbot USD file provided by NVIDIA
# Joint 5 should be damping = 10, stiffness = 1000, but we ignore it for now
import_config.default_drive_strength = 1048.0
import_config.default_position_drive_damping = 53.0
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_POSITION
import_config.distance_scale = 1
import_config.density = 0.0
# Finally import the robot & save it as USD
result, prim_path = omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path,
import_config=import_config, dest_path=usd_path,
)
import_config.make_instanceable=True
import_config.instanceable_usd_path=mesh_usd_path
# Finally import the robot & save it as instanceable USD
result, prim_path = omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path,
import_config=import_config, dest_path=instanceable_usd_path,
)
def create_block_indicator():
for suffix in ['', '_instanceable']:
asset_usd_path = f'omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Props/Blocks/block{suffix}.usd'
block_usd_path = f'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Props/Blocks/block{suffix}.usd'
omni.client.copy(asset_usd_path, block_usd_path)
omni.usd.get_context().open_stage(block_usd_path)
stage = omni.usd.get_context().get_stage()
edits = Sdf.BatchNamespaceEdit()
edits.Add(Sdf.NamespaceEdit.Remove('/object/object/collisions'))
stage.GetRootLayer().Apply(edits)
omni.usd.get_context().save_stage()
if __name__ == '__main__':
dofbot_urdf_path = f'{os.path.expanduser("~")}/OmniIsaacGymEnvs-DofbotReacher/thirdparty/dofbot_info/urdf/dofbot.urdf'
dofbot_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot_urdf.usd'
dofbot_mesh_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot_urdf_instanceable_meshes.usd'
dofbot_instanceable_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2023.1.0/Isaac/Robots/Dofbot/dofbot_urdf_instanceable.usd'
create_dofbot_from_urdf(dofbot_urdf_path, dofbot_usd_path, dofbot_mesh_usd_path, dofbot_instanceable_usd_path)
create_block_indicator()
print("Done!")
| 4,749 | Python | 51.197802 | 138 | 0.744999 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/balance_bot.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
class BalanceBot(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "BalanceBot",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/BalanceBot/balance_bot.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
for j in range(3):
# set leg joint properties
joint_path = f"joints/lower_leg{j}"
set_drive(f"{self.prim_path}/{joint_path}", "angular", "position", 0, 400, 40, 1000)
| 2,996 | Python | 40.054794 | 96 | 0.697597 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/allegro_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics
class AllegroHand(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "allegro_hand",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/AllegroHand/allegro_hand_instanceable.usd"
self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation
self._orientation = (
torch.tensor([0.257551, 0.283045, 0.683330, -0.621782]) if orientation is None else orientation
)
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
def set_allegro_hand_properties(self, stage, allegro_hand_prim):
for link_prim in allegro_hand_prim.GetChildren():
if not (
link_prim == stage.GetPrimAtPath("/allegro/Looks")
or link_prim == stage.GetPrimAtPath("/allegro/root_joint")
):
rb = PhysxSchema.PhysxRigidBodyAPI.Apply(link_prim)
rb.GetDisableGravityAttr().Set(True)
rb.GetRetainAccelerationsAttr().Set(False)
rb.GetEnableGyroscopicForcesAttr().Set(False)
rb.GetAngularDampingAttr().Set(0.01)
rb.GetMaxLinearVelocityAttr().Set(1000)
rb.GetMaxAngularVelocityAttr().Set(64 / np.pi * 180)
rb.GetMaxDepenetrationVelocityAttr().Set(1000)
rb.GetMaxContactImpulseAttr().Set(1e32)
def set_motor_control_mode(self, stage, allegro_hand_path):
prim = stage.GetPrimAtPath(allegro_hand_path)
self._set_joint_properties(stage, prim)
def _set_joint_properties(self, stage, prim):
if prim.HasAPI(UsdPhysics.DriveAPI):
drive = UsdPhysics.DriveAPI.Apply(prim, "angular")
drive.GetStiffnessAttr().Set(3 * np.pi / 180)
drive.GetDampingAttr().Set(0.1 * np.pi / 180)
drive.GetMaxForceAttr().Set(0.5)
revolute_joint = PhysxSchema.PhysxJointAPI.Get(stage, prim.GetPath())
revolute_joint.GetJointFrictionAttr().Set(0.01)
for child_prim in prim.GetChildren():
self._set_joint_properties(stage, child_prim)
| 4,627 | Python | 43.5 | 107 | 0.673655 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/shadow_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics
class ShadowHand(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "shadow_hand",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/ShadowHand/shadow_hand_instanceable.usd"
self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation
self._orientation = torch.tensor([1.0, 0.0, 0.0, 0.0]) if orientation is None else orientation
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
def set_shadow_hand_properties(self, stage, shadow_hand_prim):
for link_prim in shadow_hand_prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.GetDisableGravityAttr().Set(True)
rb.GetRetainAccelerationsAttr().Set(True)
def set_motor_control_mode(self, stage, shadow_hand_path):
joints_config = {
"robot0_WRJ1": {"stiffness": 5, "damping": 0.5, "max_force": 4.785},
"robot0_WRJ0": {"stiffness": 5, "damping": 0.5, "max_force": 2.175},
"robot0_FFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_FFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_FFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_MFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_MFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_MFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_RFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_RFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_RFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_LFJ4": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_LFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_LFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9},
"robot0_LFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245},
"robot0_THJ4": {"stiffness": 1, "damping": 0.1, "max_force": 2.3722},
"robot0_THJ3": {"stiffness": 1, "damping": 0.1, "max_force": 1.45},
"robot0_THJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.99},
"robot0_THJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.99},
"robot0_THJ0": {"stiffness": 1, "damping": 0.1, "max_force": 0.81},
}
for joint_name, config in joints_config.items():
set_drive(
f"{self.prim_path}/joints/{joint_name}",
"angular",
"position",
0.0,
config["stiffness"] * np.pi / 180,
config["damping"] * np.pi / 180,
config["max_force"],
)
| 5,517 | Python | 46.982608 | 103 | 0.623527 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/crazyflie.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Crazyflie(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "crazyflie",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Crazyflie/cf2x.usd"
add_reference_to_stage(self._usd_path, prim_path)
scale = torch.tensor([5, 5, 5])
super().__init__(prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale)
| 2,720 | Python | 40.861538 | 119 | 0.718015 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/cabinet.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Cabinet(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "cabinet",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Props/Sektion_Cabinet/sektion_cabinet_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
self._position = torch.tensor([0.0, 0.0, 0.4]) if translation is None else translation
self._orientation = torch.tensor([0.1, 0.0, 0.0, 0.0]) if orientation is None else orientation
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
| 1,819 | Python | 35.399999 | 111 | 0.660803 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/humanoid.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Humanoid(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Humanoid",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Humanoid/humanoid_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,716 | Python | 38.955882 | 98 | 0.71134 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/franka.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import math
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
from pxr import PhysxSchema
class Franka(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "franka",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
self._position = torch.tensor([1.0, 0.0, 0.0]) if translation is None else translation
self._orientation = torch.tensor([0.0, 0.0, 0.0, 1.0]) if orientation is None else orientation
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Franka/franka_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
dof_paths = [
"panda_link0/panda_joint1",
"panda_link1/panda_joint2",
"panda_link2/panda_joint3",
"panda_link3/panda_joint4",
"panda_link4/panda_joint5",
"panda_link5/panda_joint6",
"panda_link6/panda_joint7",
"panda_hand/panda_finger_joint1",
"panda_hand/panda_finger_joint2",
]
drive_type = ["angular"] * 7 + ["linear"] * 2
default_dof_pos = [math.degrees(x) for x in [0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8]] + [0.02, 0.02]
stiffness = [400 * np.pi / 180] * 7 + [10000] * 2
damping = [80 * np.pi / 180] * 7 + [100] * 2
max_force = [87, 87, 87, 87, 12, 12, 12, 200, 200]
max_velocity = [math.degrees(x) for x in [2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]] + [0.2, 0.2]
for i, dof in enumerate(dof_paths):
set_drive(
prim_path=f"{self.prim_path}/{dof}",
drive_type=drive_type[i],
target_type="position",
target_value=default_dof_pos[i],
stiffness=stiffness[i],
damping=damping[i],
max_force=max_force[i],
)
PhysxSchema.PhysxJointAPI(get_prim_at_path(f"{self.prim_path}/{dof}")).CreateMaxJointVelocityAttr().Set(
max_velocity[i]
)
def set_franka_properties(self, stage, prim):
for link_prim in prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.GetDisableGravityAttr().Set(True)
| 3,653 | Python | 37.0625 | 116 | 0.599781 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/ant.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Ant(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Ant",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Ant/ant_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,696 | Python | 38.661764 | 88 | 0.709199 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/cartpole.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Cartpole(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Cartpole",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Cartpole/cartpole.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,703 | Python | 38.764705 | 85 | 0.710322 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/factory_franka.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import math
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
from pxr import PhysxSchema
class FactoryFranka(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "franka",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
self._position = torch.tensor([1.0, 0.0, 0.0]) if translation is None else translation
self._orientation = torch.tensor([0.0, 0.0, 0.0, 1.0]) if orientation is None else orientation
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/FactoryFranka/factory_franka.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
dof_paths = [
"panda_link0/panda_joint1",
"panda_link1/panda_joint2",
"panda_link2/panda_joint3",
"panda_link3/panda_joint4",
"panda_link4/panda_joint5",
"panda_link5/panda_joint6",
"panda_link6/panda_joint7",
"panda_hand/panda_finger_joint1",
"panda_hand/panda_finger_joint2",
]
drive_type = ["angular"] * 7 + ["linear"] * 2
default_dof_pos = [math.degrees(x) for x in [0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8]] + [0.02, 0.02]
stiffness = [40 * np.pi / 180] * 7 + [500] * 2
damping = [80 * np.pi / 180] * 7 + [20] * 2
max_force = [87, 87, 87, 87, 12, 12, 12, 200, 200]
max_velocity = [math.degrees(x) for x in [2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]] + [0.2, 0.2]
for i, dof in enumerate(dof_paths):
set_drive(
prim_path=f"{self.prim_path}/{dof}",
drive_type=drive_type[i],
target_type="position",
target_value=default_dof_pos[i],
stiffness=stiffness[i],
damping=damping[i],
max_force=max_force[i],
)
PhysxSchema.PhysxJointAPI(get_prim_at_path(f"{self.prim_path}/{dof}")).CreateMaxJointVelocityAttr().Set(
max_velocity[i]
)
| 3,356 | Python | 36.719101 | 116 | 0.596544 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/quadcopter.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Quadcopter(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Quadcopter",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = assets_root_path + "/Isaac/Robots/Quadcopter/quadcopter.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
position=translation,
orientation=orientation,
articulation_controller=None,
)
| 2,719 | Python | 39.597014 | 89 | 0.706878 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/dofbot.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
# Ref: /omniisaacgymenvs/robots/articulations/shadow_hand.py
from typing import Optional
import carb
import numpy as np
import torch
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Dofbot(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Dofbot",
usd_path: Optional[str] = None,
translation: Optional[torch.tensor] = None,
orientation: Optional[torch.tensor] = None,
) -> None:
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._position = torch.tensor([0.0, 0.0, 0.0]) if translation is None else translation
self._orientation = torch.tensor([1.0, 0.0, 0.0, 0.0]) if orientation is None else orientation
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=self._position,
orientation=self._orientation,
articulation_controller=None,
)
| 2,926 | Python | 39.09589 | 102 | 0.710526 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/ingenuity.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
class Ingenuity(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "ingenuity",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.array] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self._usd_path = (
assets_root_path + "/Isaac/Robots/Ingenuity/ingenuity.usd"
)
add_reference_to_stage(self._usd_path, prim_path)
scale = torch.tensor([0.01, 0.01, 0.01])
super().__init__(prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale)
| 2,802 | Python | 40.83582 | 119 | 0.711991 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/anymal.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import numpy as np
import torch
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from pxr import PhysxSchema
class Anymal(Robot):
def __init__(
self,
prim_path: str,
name: Optional[str] = "Anymal",
usd_path: Optional[str] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
"""[summary]"""
self._usd_path = usd_path
self._name = name
if self._usd_path is None:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find nucleus server with /Isaac folder")
self._usd_path = assets_root_path + "/Isaac/Robots/ANYbotics/anymal_instanceable.usd"
add_reference_to_stage(self._usd_path, prim_path)
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=orientation,
articulation_controller=None,
)
self._dof_names = [
"LF_HAA",
"LH_HAA",
"RF_HAA",
"RH_HAA",
"LF_HFE",
"LH_HFE",
"RF_HFE",
"RH_HFE",
"LF_KFE",
"LH_KFE",
"RF_KFE",
"RH_KFE",
]
@property
def dof_names(self):
return self._dof_names
def set_anymal_properties(self, stage, prim):
for link_prim in prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.GetDisableGravityAttr().Set(False)
rb.GetRetainAccelerationsAttr().Set(False)
rb.GetLinearDampingAttr().Set(0.0)
rb.GetMaxLinearVelocityAttr().Set(1000.0)
rb.GetAngularDampingAttr().Set(0.0)
rb.GetMaxAngularVelocityAttr().Set(64 / np.pi * 180)
def prepare_contacts(self, stage, prim):
for link_prim in prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
if "_HIP" not in str(link_prim.GetPrimPath()):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.CreateSleepThresholdAttr().Set(0)
cr_api = PhysxSchema.PhysxContactReportAPI.Apply(link_prim)
cr_api.CreateThresholdAttr().Set(0)
| 4,273 | Python | 38.943925 | 97 | 0.648022 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/cabinet_view.py | from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class CabinetView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "CabinetView",
) -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._drawers = RigidPrimView(
prim_paths_expr="/World/envs/.*/cabinet/drawer_top", name="drawers_view", reset_xform_properties=False
)
| 586 | Python | 28.349999 | 114 | 0.653584 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/shadow_hand_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class ShadowHandView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "ShadowHandView",
) -> None:
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._fingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/shadow_hand/robot0.*distal",
name="finger_view",
reset_xform_properties=False,
)
@property
def actuated_dof_indices(self):
return self._actuated_dof_indices
def initialize(self, physics_sim_view):
super().initialize(physics_sim_view)
self.actuated_joint_names = [
"robot0_WRJ1",
"robot0_WRJ0",
"robot0_FFJ3",
"robot0_FFJ2",
"robot0_FFJ1",
"robot0_MFJ3",
"robot0_MFJ2",
"robot0_MFJ1",
"robot0_RFJ3",
"robot0_RFJ2",
"robot0_RFJ1",
"robot0_LFJ4",
"robot0_LFJ3",
"robot0_LFJ2",
"robot0_LFJ1",
"robot0_THJ4",
"robot0_THJ3",
"robot0_THJ2",
"robot0_THJ1",
"robot0_THJ0",
]
self._actuated_dof_indices = list()
for joint_name in self.actuated_joint_names:
self._actuated_dof_indices.append(self.get_dof_index(joint_name))
self._actuated_dof_indices.sort()
limit_stiffness = torch.tensor([30.0] * self.num_fixed_tendons, device=self._device)
damping = torch.tensor([0.1] * self.num_fixed_tendons, device=self._device)
self.set_fixed_tendon_properties(dampings=damping, limit_stiffnesses=limit_stiffness)
fingertips = ["robot0_ffdistal", "robot0_mfdistal", "robot0_rfdistal", "robot0_lfdistal", "robot0_thdistal"]
self._sensor_indices = torch.tensor([self._body_indices[j] for j in fingertips], device=self._device, dtype=torch.long)
| 3,681 | Python | 38.591397 | 127 | 0.669383 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/franka_view.py | from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class FrankaView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "FrankaView",
) -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._hands = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_link7", name="hands_view", reset_xform_properties=False
)
self._lfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_leftfinger", name="lfingers_view", reset_xform_properties=False
)
self._rfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_rightfinger",
name="rfingers_view",
reset_xform_properties=False,
)
def initialize(self, physics_sim_view):
super().initialize(physics_sim_view)
self._gripper_indices = [self.get_dof_index("panda_finger_joint1"), self.get_dof_index("panda_finger_joint2")]
@property
def gripper_indices(self):
return self._gripper_indices
| 1,241 | Python | 32.567567 | 120 | 0.637389 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/dofbot_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
# Ref: /omniisaacgymenvs/robots/articulations/views/shadow_hand_view.py
from typing import Optional
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class DofbotView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
end_effector_prim_paths_expr: str,
name: Optional[str] = "DofbotView",
) -> None:
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
# Use RigidPrimView instead of XFormPrimView, since the XForm is not updated when running
self._end_effectors = RigidPrimView(
prim_paths_expr=end_effector_prim_paths_expr,
name="end_effector_view",
reset_xform_properties=False
)
def initialize(self, physics_sim_view):
super().initialize(physics_sim_view)
| 2,503 | Python | 42.172413 | 98 | 0.744307 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/factory_franka_view.py | from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class FactoryFrankaView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "FactoryFrankaView",
) -> None:
"""Initialize articulation view."""
super().__init__(
prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False
)
self._hands = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_hand",
name="hands_view",
reset_xform_properties=False,
)
self._lfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_leftfinger",
name="lfingers_view",
reset_xform_properties=False,
track_contact_forces=True,
)
self._rfingers = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_rightfinger",
name="rfingers_view",
reset_xform_properties=False,
track_contact_forces=True,
)
self._fingertip_centered = RigidPrimView(
prim_paths_expr="/World/envs/.*/franka/panda_fingertip_centered",
name="fingertips_view",
reset_xform_properties=False,
)
def initialize(self, physics_sim_view):
"""Initialize physics simulation view."""
super().initialize(physics_sim_view)
| 1,488 | Python | 31.369565 | 84 | 0.598118 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/anymal_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class AnymalView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "AnymalView",
track_contact_forces=False,
prepare_contact_sensors=False,
) -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._knees = RigidPrimView(
prim_paths_expr="/World/envs/.*/anymal/.*_THIGH",
name="knees_view",
reset_xform_properties=False,
track_contact_forces=track_contact_forces,
prepare_contact_sensors=prepare_contact_sensors,
)
self._base = RigidPrimView(
prim_paths_expr="/World/envs/.*/anymal/base",
name="base_view",
reset_xform_properties=False,
track_contact_forces=track_contact_forces,
prepare_contact_sensors=prepare_contact_sensors,
)
def get_knee_transforms(self):
return self._knees.get_world_poses()
def is_knee_below_threshold(self, threshold, ground_heights=None):
knee_pos, _ = self._knees.get_world_poses()
knee_heights = knee_pos.view((-1, 4, 3))[:, :, 2]
if ground_heights is not None:
knee_heights -= ground_heights
return (
(knee_heights[:, 0] < threshold)
| (knee_heights[:, 1] < threshold)
| (knee_heights[:, 2] < threshold)
| (knee_heights[:, 3] < threshold)
)
def is_base_below_threshold(self, threshold, ground_heights):
base_pos, _ = self.get_world_poses()
base_heights = base_pos[:, 2]
base_heights -= ground_heights
return base_heights[:] < threshold
| 3,433 | Python | 41.395061 | 98 | 0.678415 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/quadcopter_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class QuadcopterView(ArticulationView):
def __init__(self, prim_paths_expr: str, name: Optional[str] = "QuadcopterView") -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self.rotors = RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Quadcopter/rotor[0-3]", name="rotors_view", reset_xform_properties=False
)
| 2,121 | Python | 47.227272 | 117 | 0.759547 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/allegro_hand_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class AllegroHandView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "AllegroHandView",
) -> None:
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self._actuated_dof_indices = list()
@property
def actuated_dof_indices(self):
return self._actuated_dof_indices
def initialize(self, physics_sim_view):
super().initialize(physics_sim_view)
self._actuated_dof_indices = [i for i in range(self.num_dof)]
| 2,275 | Python | 41.148147 | 98 | 0.74989 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/crazyflie_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class CrazyflieView(ArticulationView):
def __init__(self, prim_paths_expr: str, name: Optional[str] = "CrazyflieView") -> None:
"""[summary]"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
)
self.physics_rotors = [
RigidPrimView(prim_paths_expr=f"/World/envs/.*/Crazyflie/m{i}_prop", name=f"m{i}_prop_view")
for i in range(1, 5)
]
| 2,140 | Python | 42.693877 | 104 | 0.737383 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/omniisaacgymenvs/robots/articulations/views/ingenuity_view.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
class IngenuityView(ArticulationView):
def __init__(self, prim_paths_expr: str, name: Optional[str] = "IngenuityView") -> None:
"""[summary]"""
super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False)
self.physics_rotors = [
RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_physics_{i}",
name=f"physics_rotor_{i}_view",
reset_xform_properties=False,
)
for i in range(2)
]
self.visual_rotors = [
RigidPrimView(
prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_visual_{i}",
name=f"visual_rotor_{i}_view",
reset_xform_properties=False,
)
for i in range(2)
]
| 2,524 | Python | 42.534482 | 98 | 0.70206 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/domain_randomization.md | Domain Randomization
====================
Overview
--------
We sometimes need our reinforcement learning agents to be robust to
different physics than they are trained with, such as when attempting a
sim2real policy transfer. Using domain randomization (DR), we repeatedly
randomize the simulation dynamics during training in order to learn a
good policy under a wide range of physical parameters.
OmniverseIsaacGymEnvs supports "on the fly" domain randomization, allowing
dynamics to be changed without requiring reloading of assets. This allows
us to efficiently apply domain randomizations without common overheads like
re-parsing asset files.
The OmniverseIsaacGymEnvs DR framework utilizes the `omni.replicator.isaac`
extension in its backend to perform "on the fly" randomization. Users can
add domain randomization by either directly using methods provided in
`omni.replicator.isaac` in python, or specifying DR settings in the
task configuration `yaml` file. The following sections will focus on setting
up DR using the `yaml` file interface. For more detailed documentations
regarding methods provided in the `omni.replicator.isaac` extension, please
visit [here](https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.replicator.isaac/docs/index.html).
Domain Randomization Options
-------------------------------
We will first explain what can be randomized in the scene and the sampling
distributions. There are five main parameter groups that support randomization.
They are:
- `observations`: Add noise directly to the agent observations
- `actions`: Add noise directly to the agent actions
- `simulation`: Add noise to physical parameters defined for the entire
scene, such as `gravity`
- `rigid_prim_views`: Add noise to properties belonging to rigid prims,
such as `material_properties`.
- `articulation_views`: Add noise to properties belonging to articulations,
such as `stiffness` of joints.
For each parameter you wish to randomize, you can specify two ways that
determine when the randomization is applied:
- `on_reset`: Adds correlated noise to a parameter of an environment when
that environment gets reset. This correlated noise will remain
with an environment until that environemnt gets reset again, which
will then set a new correlated noise. To trigger `on_reset`,
the indices for the environemnts that need to be reset must be passed in
to `omni.replicator.isaac.physics_view.step_randomization(reset_inds)`.
- `on_interval`: Adds uncorrelated noise to a parameter at a frequency specified
by `frequency_interval`. If a parameter also has `on_reset` randomization,
the `on_interval` noise is combined with the noise applied at `on_reset`.
- `on_startup`: Applies randomization once prior to the start of the simulation. Only available
to rigid prim scale, mass, density and articulation scale parameters.
For `on_reset`, `on_interval`, and `on_startup`, you can specify the following settings:
- `distribution`: The distribution to generate a sample `x` from. The available distributions
are listed below. Note that parameters `a` and `b` are defined by the
`distribution_parameters` setting.
- `uniform`: `x ~ unif(a, b)`
- `loguniform`: `x ~ exp(unif(log(a), log(b)))`
- `gaussian`: `x ~ normal(a, b)`
- `distribution_parameters`: The parameters to the distribution.
- For observations and actions, this setting is specified as a tuple `[a, b]` of
real values.
- For simulation and view parameters, this setting is specified as a nested tuple
in the form of `[[a_1, a_2, ..., a_n], [[b_1, b_2, ..., b_n]]`, where the `n` is
the dimension of the parameter (*i.e.* `n` is 3 for position). It can also be
specified as a tuple in the form of `[a, b]`, which will be broadcasted to the
correct dimensions.
- For `uniform` and `loguniform` distributions, `a` and `b` are the lower and
upper bounds.
- For `gaussian`, `a` is the distribution mean and `b` is the variance.
- `operation`: Defines how the generated sample `x` will be applied to the original
simulation parameter. The options are `additive`, `scaling`, `direct`.
- `additive`:, add the sample to the original value.
- `scaling`: multiply the original value by the sample.
- `direct`: directly sets the sample as the parameter value.
- `frequency_interval`: Specifies the number of steps to apply randomization.
- Only used with `on_interval`.
- Steps of each environemnt are incremented with each
`omni.replicator.isaac.physics_view.step_randomization(reset_inds)` call and
reset if the environment index is in `reset_inds`.
- `num_buckets`: Only used for `material_properties` randomization
- Physx only allows 64000 unique physics materials in the scene at once. If more than
64000 materials are needed, increase `num_buckets` to allow materials to be shared
between prims.
YAML Interface
--------------
Now that we know what options are available for domain randomization,
let's put it all together in the YAML config. In your `omniverseisaacgymenvs/cfg/task`
yaml file, you can specify your domain randomization parameters under the
`domain_randomization` key. First, we turn on domain randomization by setting
`randomize` to `True`:
```yaml
domain_randomization:
randomize: True
randomization_params:
...
```
This can also be set as a command line argument at launch time with `task.domain_randomization.randomize=True`.
Next, we will define our parameters under the `randomization_params`
keys. Here you can see how we used the previous settings to define some
randomization parameters for a ShadowHand cube manipulation task:
```yaml
randomization_params:
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]
simulation:
gravity:
on_reset:
operation: "additive"
distribution: "gaussian"
distribution_parameters: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.4]]
rigid_prim_views:
object_view:
material_properties:
on_reset:
num_buckets: 250
operation: "scaling"
distribution: "uniform"
distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]]
articulation_views:
shadow_hand_view:
stiffness:
on_reset:
operation: "scaling"
distribution: "uniform"
distribution_parameters: [0.75, 1.5]
```
Note how we structured `rigid_prim_views` and `articulation_views`. When creating
a `RigidPrimView` or `ArticulationView` in the task python file, you have the option to
pass in `name` as an argument. **To use domain randomization, the name of the `RigidPrimView` or
`ArticulationView` must match the name provided in the randomization `yaml` file.** In the
example above, `object_view` is the name of a `RigidPrimView` and `shadow_hand_view` is the name
of the `ArticulationView`.
The exact parameters that can be randomized are listed below:
**simulation**:
- gravity (dim=3): The gravity vector of the entire scene.
**rigid\_prim\_views**:
- position (dim=3): The position of the rigid prim. In meters.
- orientation (dim=3): The orientation of the rigid prim, specified with euler angles. In radians.
- linear_velocity (dim=3): The linear velocity of the rigid prim. In m/s. **CPU pipeline only**
- angular_velocity (dim=3): The angular velocity of the rigid prim. In rad/s. **CPU pipeline only**
- velocity (dim=6): The linear + angular velocity of the rigid prim.
- force (dim=3): Apply a force to the rigid prim. In N.
- mass (dim=1): Mass of the rigid prim. In kg. **CPU pipeline only during runtime**.
- inertia (dim=3): The diagonal values of the inertia matrix. **CPU pipeline only**
- material_properties (dim=3): Static friction, Dynamic friction, and Restitution.
- contact_offset (dim=1): A small distance from the surface of the collision geometry at
which contacts start being generated.
- rest_offset (dim=1): A small distance from the surface of the collision geometry at
which the effective contact with the shape takes place.
- scale (dim=1): The scale of the rigid prim. `on_startup` only.
- density (dim=1): Density of the rigid prim. `on_startup` only.
**articulation\_views**:
- position (dim=3): The position of the articulation root. In meters.
- orientation (dim=3): The orientation of the articulation root, specified with euler angles. In radians.
- linear_velocity (dim=3): The linear velocity of the articulation root. In m/s. **CPU pipeline only**
- angular_velocity (dim=3): The angular velocity of the articulation root. In rad/s. **CPU pipeline only**
- velocity (dim=6): The linear + angular velocity of the articulation root.
- stiffness (dim=num_dof): The stiffness of the joints.
- damping (dim=num_dof): The damping of the joints
- joint_friction (dim=num_dof): The friction coefficient of the joints.
- joint_positions (dim=num_dof): The joint positions. In radians or meters.
- joint_velocities (dim=num_dof): The joint velocities. In rad/s or m/s.
- lower_dof_limits (dim=num_dof): The lower limit of the joints. In radians or meters.
- upper_dof_limits (dim=num_dof): The upper limit of the joints. In radians or meters.
- max_efforts (dim=num_dof): The maximum force or torque that the joints can exert. In N or Nm.
- joint_armatures (dim=num_dof): A value added to the diagonal of the joint-space inertia matrix.
Physically, it corresponds to the rotating part of a motor
- joint_max_velocities (dim=num_dof): The maximum velocity allowed on the joints. In rad/s or m/s.
- joint_efforts (dim=num_dof): Applies a force or a torque on the joints. In N or Nm.
- body_masses (dim=num_bodies): The mass of each body in the articulation. In kg. **CPU pipeline only**
- body_inertias (dim=num_bodies×3): The diagonal values of the inertia matrix of each body. **CPU pipeline only**
- material_properties (dim=num_bodies×3): The static friction, dynamic friction, and restitution of each body
in the articulation, specified in the following order:
[body_1_static_friciton, body_1_dynamic_friciton, body_1_restitution,
body_1_static_friciton, body_2_dynamic_friciton, body_2_restitution,
... ]
- tendon_stiffnesses (dim=num_tendons): The stiffness of the fixed tendons in the articulation.
- tendon_dampings (dim=num_tendons): The damping of the fixed tendons in the articulation.
- tendon_limit_stiffnesses (dim=num_tendons): The limit stiffness of the fixed tendons in the articulation.
- tendon_lower_limits (dim=num_tendons): The lower limits of the fixed tendons in the articulation.
- tendon_upper_limits (dim=num_tendons): The upper limits of the fixed tendons in the articulation.
- tendon_rest_lengths (dim=num_tendons): The rest lengths of the fixed tendons in the articulation.
- tendon_offsets (dim=num_tendons): The offsets of the fixed tendons in the articulation.
- scale (dim=1): The scale of the articulation. `on_startup` only.
Applying Domain Randomization
------------------------------
To parse the domain randomization configurations in the task `yaml` file and set up the DR pipeline,
it is necessary to call `self._randomizer.set_up_domain_randomization(self)`, where `self._randomizer`
is the `Randomizer` object created in RLTask's `__init__`.
It is worth noting that the names of the views provided under `rigid_prim_views` or `articulation_views`
in the task `yaml` file must match the names passed into `RigidPrimView` or `ArticulationView` objects
in the python task file. In addition, all `RigidPrimView` and `ArticulationView` that would have domain
randomizaiton applied must be added to the scene in the task's `set_up_scene()` via `scene.add()`.
To trigger `on_startup` randomizations, call `self._randomizer.apply_on_startup_domain_randomization(self)`
in `set_up_scene()` after all views are added to the scene. Note that `on_startup` randomizations
are only availble to rigid prim scale, mass, density and articulation scale parameters since these parameters
cannot be randomized after the simulation begins on GPU pipeline. Therefore, randomizations must be applied
to these parameters in `set_up_scene()` prior to the start of the simulation.
To trigger `on_reset` and `on_interval` randomizations, it is required to step the interal
counter of the DR pipeline in `pre_physics_step()`:
```python
if self._randomizer.randomize:
omni.replicator.isaac.physics_view.step_randomization(reset_inds)
```
`reset_inds` is a list of indices of the environments that need to be reset. For those environments, it will
trigger the randomizations defined with `on_reset`. All other environments will follow randomizations
defined with `on_interval`.
Randomization Scheduling
----------------------------
We provide methods to modify distribution parameters defined in the `yaml` file during training, which
allows custom DR scheduling. There are three methods from the `Randomizer` class
that are relevant to DR scheduling:
- `get_initial_dr_distribution_parameters`: returns a numpy array of the initial parameters (as defined in
the `yaml` file) of a specified distribution
- `get_dr_distribution_parameters`: returns a numpy array of the current parameters of a specified distribution
- `set_dr_distribution_parameters`: sets new parameters to a specified distribution
Using the DR configuration example defined above, we can get the current parameters and set new parameters
to gravity randomization and shadow hand joint stiffness randomization as follows:
```python
current_gravity_dr_params = self._randomizer.get_dr_distribution_parameters(
"simulation",
"gravity",
"on_reset",
)
self._randomizer.set_dr_distribution_parameters(
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.5]],
"simulation",
"gravity",
"on_reset",
)
current_joint_stiffness_dr_params = self._randomizer.get_dr_distribution_parameters(
"articulation_views",
"shadow_hand_view",
"stiffness",
"on_reset",
)
self._randomizer.set_dr_distribution_parameters(
[0.7, 1.55],
"articulation_views",
"shadow_hand_view",
"stiffness",
"on_reset",
)
```
The following is an example of using these methods to perform linear scheduling of gaussian noise
that is added to observations and actions in the above shadow hand example. The following method
linearly adds more noise to observations and actions every epoch up until the `schedule_epoch`.
This method can be added to the Task python class and be called in `pre_physics_step()`.
```python
def apply_observations_actions_noise_linear_scheduling(self, schedule_epoch=100):
current_epoch = self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"] // self._cfg["train"]["params"]["config"]["horizon_length"]
if current_epoch <= schedule_epoch:
if (self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"]) % self._cfg["train"]["params"]["config"]["horizon_length"] == 0:
for distribution_path in [("observations", "on_reset"), ("observations", "on_interval"), ("actions", "on_reset"), ("actions", "on_interval")]:
scheduled_params = self._randomizer.get_initial_dr_distribution_parameters(*distribution_path)
scheduled_params[1] = (1/schedule_epoch) * current_epoch * scheduled_params[1]
self._randomizer.set_dr_distribution_parameters(scheduled_params, *distribution_path)
```
| 16,889 | Markdown | 51.453416 | 156 | 0.68814 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/instanceable_assets.md | ## A Note on Instanceable USD Assets
The following section presents a method that modifies existing USD assets
which allows Isaac Sim to load significantly more environments. This is currently
an experimental method and has thus not been completely integrated into the
framework. As a result, this section is reserved for power users who wish to
maxmimize the performance of the Isaac Sim RL framework.
### Motivation
One common issue in Isaac Sim that occurs when we try to increase
the number of environments `numEnvs` is running out of RAM. This occurs because
the Isaac Sim RL framework uses `omni.isaac.cloner` to duplicate environments.
As a result, there are `numEnvs` number of identical copies of the visual and
collision meshes in the scene, which consumes lots of memory. However, only one
copy of the meshes are needed on stage since prims in all other environments could
merely reference that one copy, thus reducing the amount of memory used for loading
environments. To enable this functionality, USD assets need to be modified to be
`instanceable`.
### Creating Instanceable Assets
Assets can now be directly imported as Instanceable assets through the URDF and MJCF importers provided in Isaac Sim. By selecting this option, imported assets will be split into two separate USD files that follow the above hierarchy definition. Any mesh data will be written to an USD stage to be referenced by the main USD stage, which contains the main robot definition.
To use the Instanceable option in the importers, first check the `Create Instanceable Asset` option. Then, specify a file path to indicate the location for saving the mesh data in the `Instanceable USD Path` textbox. This will default to `./instanceable_meshes.usd`, which will generate a file `instanceable_meshes.usd` that is saved to the current directory.
Once the asset is imported with these options enabled, you will see the robot definition in the stage - we will refer to this stage as the master stage. If we expand the robot hierarchy in the Stage, we will notice that the parent prims that have mesh decendants have been marked as Instanceable and they reference a prim in our `Instanceable USD Path` USD file. We are also no longer able to modify attributes of descendant meshes.
To add the instanced asset into a new stage, we will simply need to add the master USD file.
### Converting Existing Assets
We provide the utility function `convert_asset_instanceable`, which creates an instanceable
version of a given USD asset in `/omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py`.
To run this function, launch Isaac Sim and open the script editor via `Window -> Script Editor`.
Enter the following script and press `Run (Ctrl + Enter)`:
```bash
from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import convert_asset_instanceable
convert_asset_instanceable(
asset_usd_path=ASSET_USD_PATH,
source_prim_path=SOURCE_PRIM_PATH,
save_as_path=SAVE_AS_PATH
)
```
Note that `ASSET_USD_PATH` is the file path to the USD asset (*e.g.* robot_asset.usd).
`SOURCE_PRIM_PATH` is the USD path of the root prim of the asset on stage. `SAVE_AS_PATH`
is the file path of the generated instanceable version of the asset
(*e.g.* robot_asset_instanceable.usd).
Assuming that `SAVE_AS_PATH` is `OUTPUT_NAME.usd`, the above script will generate two files:
`OUTPUT_NAME.usd` and `OUTPUT_NAME_meshes.usd`. `OUTPUT_NAME.usd` is the instanceable version
of the asset that can be imported to stage and used by `omni.isaac.cloner` to create numerous
duplicates without consuming much memory. `OUTPUT_NAME_meshes.usd` contains all the visual
and collision meshes that `OUTPUT_NAME.usd` references.
It is worth noting that any [USD Relationships](https://graphics.pixar.com/usd/dev/api/class_usd_relationship.html)
on the referenced meshes are removed in `OUTPUT_NAME.usd`. This is because those USD Relationships
originally have targets set to prims in `OUTPUT_NAME_meshes.usd` and hence cannot be accessed
from `OUTPUT_NAME.usd`. Common examples of USD Relationships that could exist on the meshes are
visual materials, physics materials, and filtered collision pairs. Therefore, it is recommanded
to set these USD Relationships on the meshes' parent Xforms instead of the meshes themselves.
In a case where we would like to update the main USD file where the instanceable USD file is being referenced from, we also provide a utility method to update all references in the stage that matches a source reference path to a new USD file path.
```bash
from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import update_reference
update_reference(
source_prim_path=SOURCE_PRIM_PATH,
source_reference_path=SOURCE_REFERENCE_PATH,
target_reference_path=TARGET_REFERENCE_PATH
)
```
### Limitations
USD requires a specific structure in the asset tree definition in order for the instanceable flag to take action. To mark any mesh or primitive geometry prim in the asset as instanceable, the mesh prim requires a parent Xform prim to be present, which will be used to add a reference to a master USD file containing definition of the mesh prim.
For example, the following definition:
```
World
|_ Robot
|_ Collisions
|_ Sphere
|_ Box
```
would have to be modified to:
```
World
|_ Robot
|_ Collisions
|_ Sphere_Xform
| |_ Sphere
|_ Box_Xform
|_ Box
```
Any references that exist on the original `Sphere` and `Box` prims would have to be moved to `Sphere_Xform` and `Box_Xform` prims.
To help with the process of creating new parent prims, we provide a utility method `create_parent_xforms()` in `omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py` to automatically insert a new Xform prim as a parent of every mesh prim in the stage. This method can be run on an existing non-instanced USD file for an asset from the script editor:
```bash
from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import create_parent_xforms
create_parent_xforms(
asset_usd_path=ASSET_USD_PATH,
source_prim_path=SOURCE_PRIM_PATH,
save_as_path=SAVE_AS_PATH
)
```
This method can also be run as part of `convert_asset_instanceable()` method, by passing in the argument `create_xforms=True`.
It is also worth noting that once an instanced asset is added to the stage, we can no longer modify USD attributes on the instanceable prims. For example, to modify attributes of collision meshes that are set as instanceable, we have to first modify the attributes on the corresponding prims in the master prim which our instanced asset references from. Then, we can allow the instanced asset to pick up the updated values from the master prim. | 6,846 | Markdown | 56.058333 | 444 | 0.76804 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/reproducibility.md | Reproducibility and Determinism
===============================
Seeds
-----
To achieve deterministic behavior on multiple training runs, a seed
value can be set in the training config file for each task. This will potentially
allow for individual runs of the same task to be deterministic when
executed on the same machine and system setup. Alternatively, a seed can
also be set via command line argument `seed=<seed>` to override any
settings in config files. If no seed is specified in either config files
or command line arguments, we default to generating a random seed. In
this case, individual runs of the same task should not be expected to be
deterministic. For convenience, we also support setting `seed=-1` to
generate a random seed, which will override any seed values set in
config files. By default, we have explicitly set all seed values in
config files to be 42.
PyTorch Deterministic Training
------------------------------
We also include a `torch_deterministic` argument for use when running RL
training. Enabling this flag (by passing `torch_deterministic=True`) will
apply additional settings to PyTorch that can force the usage of deterministic
algorithms in PyTorch, but may also negatively impact runtime performance.
For more details regarding PyTorch reproducibility, refer to
<https://pytorch.org/docs/stable/notes/randomness.html>. If both
`torch_deterministic=True` and `seed=-1` are set, the seed value will be
fixed to 42.
Runtime Simulation Changes / Domain Randomization
-------------------------------------------------
Note that using a fixed seed value will only **potentially** allow for deterministic
behavior. Due to GPU work scheduling, it is possible that runtime changes to
simulation parameters can alter the order in which operations take place, as
environment updates can happen while the GPU is doing other work. Because of the nature
of floating point numeric storage, any alteration of execution ordering can
cause small changes in the least significant bits of output data, leading
to divergent execution over the simulation of thousands of environments and
simulation frames.
As an example of this, runtime domain randomization of object scales
is known to cause both determinancy and simulation issues when running on the GPU
due to the way those parameters are passed from CPU to GPU in lower level APIs. Therefore,
this is only supported at setup time before starting simulation, which is specified by
the `on_startup` condition for Domain Randomization.
At this time, we do not believe that other domain randomizations offered by this
framework cause issues with deterministic execution when running GPU simulation,
but directly manipulating other simulation parameters outside of the omni.isaac.core View
APIs may induce similar issues.
Also 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.
Another known cause of non-determinism is from resetting actors into contact states.
If actors within a scene is reset to a state where contacts are registered
between actors, the simulation may not be able to produce deterministic results.
This is because contacts are not recorded and will be re-computed from scratch for
each reset scenario where actors come into contact, which cannot guarantee
deterministic behavior across different computations.
| 4,017 | Markdown | 53.297297 | 96 | 0.787155 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/training_with_camera.md | ## Reinforcement Learning with Vision in the Loop
Some reinforcement learning tasks can benefit from having image data in the pipeline by collecting sensor data from cameras to use as observations. However, high fidelity rendering can be expensive when scaled up towards thousands of environments during training.
Although Isaac Sim does not currently have the capability to scale towards thousands of environments, we are continually working on improvements to reach the goal. As a starting point, we are providing a simple example showcasing a proof-of-concept for reinforcement learning with vision in the loop.
### CartpoleCamera [cartpole_camera.py](../omniisaacgymenvs/tasks/cartpole_camera.py)
As an example showcasing the possiblity of reinforcmenet learning with vision in the loop, we provide a variation of the Cartpole task, which uses RGB image data as observations. This example
can be launched with command line argument `task=CartpoleCamera`.
Config files used for this task are:
- **Task config**: [CartpoleCamera.yaml](../omniisaacgymenvs/cfg/task/CartpoleCamera.yaml)
- **rl_games training config**: [CartpoleCameraPPO.yaml](../omniisaacgymenvs/cfg/train/CartpoleCameraPPO.yaml)
### Working with Cameras
We have provided an individual app file `apps/omni.isaac.sim.python.gym.camera.kit`, designed specifically towards vision-based RL tasks. This app file provides necessary settings to enable multiple cameras to be rendered each frame. Additional settings are also applied to increase performance when rendering cameras across multiple environments.
In addition, the following settings can be added to the app file to increase performance at a cost of accuracy. By setting these flags to `false`, data collected from the cameras may have a 1 to 2 frame delay.
```
app.renderer.waitIdle=false
app.hydraEngine.waitIdle=false
```
We can also render in white-mode by adding the following line:
```
rtx.debugMaterialType=0
```
### Config Settings
In order for rendering to occur during training, tasks using camera rendering must have the `enable_cameras` flag set to `True` in the task config file. By default, the `omni.isaac.sim.python.gym.camera.kit` app file will be used automatically when `enable_cameras` is set to `True`. This flag is located in the task config file, under the `sim` section.
In addition, the `rendering_dt` parameter can be used to specify the rendering frequency desired. Similar to `dt` for physics simulation frequency, the `rendering_dt` specifies the amount of time in `s` between each rendering step. The `rendering_dt` should be larger or equal to the physics `dt`, and be a multiple of physics `dt`. Note that specifying the `controlFrequencyInv` flag will reduce the control frequency in terms of the physics simulation frequency.
For example, assume control frequency is 30hz, physics simulation frequency is 120 hz, and rendering frequency is 10hz. In the task config file, we can set `dt: 1/120`, `controlFrequencyInv: 4`, such that control is applied every 4 physics steps, and `rendering_dt: 1/10`. In this case, render data will only be updated once every 12 physics steps. Note that both `dt` and `rendering_dt` parameters are under the `sim` section of the config file, while `controlFrequencyInv` is under the `env` section.
### Environment Setup
To set up a task for vision-based RL, we will first need to add a camera to each environment in the scene and wrap it in a Replicator `render_product` to use the vectorized rendering API available in Replicator.
This can be done with the following code in `set_up_scene`:
```python
self.render_products = []
env_pos = self._env_pos.cpu()
for i in range(self._num_envs):
camera = self.rep.create.camera(
position=(-4.2 + env_pos[i][0], env_pos[i][1], 3.0), look_at=(env_pos[i][0], env_pos[i][1], 2.55))
render_product = self.rep.create.render_product(camera, resolution=(self.camera_width, self.camera_height))
self.render_products.append(render_product)
```
Next, we need to initialize Replicator and the PytorchListener, which will be used to collect rendered data.
```python
# start replicator to capture image data
self.rep.orchestrator._orchestrator._is_started = True
# initialize pytorch writer for vectorized collection
self.pytorch_listener = self.PytorchListener()
self.pytorch_writer = self.rep.WriterRegistry.get("PytorchWriter")
self.pytorch_writer.initialize(listener=self.pytorch_listener, device="cuda")
self.pytorch_writer.attach(self.render_products)
```
Then, we can simply collect rendered data from each environment using a single API call:
```python
# retrieve RGB data from all render products
images = self.pytorch_listener.get_rgb_data()
``` | 4,728 | Markdown | 58.860759 | 502 | 0.777496 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/rl_examples.md | ## Reinforcement Learning Examples
We introduce the following reinforcement learning examples that are implemented using
Isaac Sim's RL framework.
Pre-trained checkpoints can be found on the Nucleus server. To set up localhost, please refer to the [Isaac Sim installation guide](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html).
*Note: All commands should be executed from `omniisaacgymenvs/omniisaacgymenvs`.*
- [Reinforcement Learning Examples](#reinforcement-learning-examples)
- [Cartpole cartpole.py](#cartpole-cartpolepy)
- [Ant ant.py](#ant-antpy)
- [Humanoid humanoid.py](#humanoid-humanoidpy)
- [Shadow Hand Object Manipulation shadow_hand.py](#shadow-hand-object-manipulation-shadow_handpy)
- [OpenAI Variant](#openai-variant)
- [LSTM Training Variant](#lstm-training-variant)
- [Allegro Hand Object Manipulation allegro_hand.py](#allegro-hand-object-manipulation-allegro_handpy)
- [ANYmal anymal.py](#anymal-anymalpy)
- [Anymal Rough Terrain anymal_terrain.py](#anymal-rough-terrain-anymal_terrainpy)
- [NASA Ingenuity Helicopter ingenuity.py](#nasa-ingenuity-helicopter-ingenuitypy)
- [Quadcopter quadcopter.py](#quadcopter-quadcopterpy)
- [Crazyflie crazyflie.py](#crazyflie-crazyfliepy)
- [Ball Balance ball_balance.py](#ball-balance-ball_balancepy)
- [Franka Cabinet franka_cabinet.py](#franka-cabinet-franka_cabinetpy)
- [Franka Deformable franka_deformable.py](#franka-deformablepy)
- [Factory: Fast Contact for Robotic Assembly](#factory-fast-contact-for-robotic-assembly)
### Cartpole [cartpole.py](../omniisaacgymenvs/tasks/cartpole.py)
Cartpole is a simple example that demonstrates getting and setting usage of DOF states using
`ArticulationView` from `omni.isaac.core`. The goal of this task is to move a cart horizontally
such that the pole, which is connected to the cart via a revolute joint, stays upright.
Joint positions and joint velocities are retrieved using `get_joint_positions` and
`get_joint_velocities` respectively, which are required in computing observations. Actions are
applied onto the cartpoles via `set_joint_efforts`. Cartpoles are reset by using `set_joint_positions`
and `set_joint_velocities`.
Training can be launched with command line argument `task=Cartpole`.
Training using the Warp backend can be launched with `task=Cartpole warp=True`.
Running inference with pre-trained model can be launched with command line argument `task=Cartpole test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/cartpole.pth`
Config files used for this task are:
- **Task config**: [Cartpole.yaml](../omniisaacgymenvs/cfg/task/Cartpole.yaml)
- **rl_games training config**: [CartpolePPO.yaml](../omniisaacgymenvs/cfg/train/CartpolePPO.yaml)
#### CartpoleCamera [cartpole_camera.py](../omniisaacgymenvs/tasks/cartpole_camera.py)
A variation of the Cartpole task showcases the usage of RGB image data as observations. This example
can be launched with command line argument `task=CartpoleCamera`. Note that to use camera data as
observations, `enable_cameras` must be set to `True` in the task config file. In addition, the example must be run with the `omni.isaac.sim.python.gym.camera.kit` app file provided under `apps`, which applies necessary settings to enable camera training. By default, this app file will be used automatically when `enable_cameras` is set to `True`.
Config files used for this task are:
- **Task config**: [CartpoleCamera.yaml](../omniisaacgymenvs/cfg/task/CartpoleCamera.yaml)
- **rl_games training config**: [CartpoleCameraPPO.yaml](../omniisaacgymenvs/cfg/train/CartpoleCameraPPO.yaml)
For more details on training with camera data, please visit [here](training_with_camera.md).
<img src="https://user-images.githubusercontent.com/34286328/171454189-6afafbff-bb61-4aac-b518-24646007cb9f.gif" width="300" height="150"/>
### Ant [ant.py](../omniisaacgymenvs/tasks/ant.py)
Ant is an example of a simple locomotion task. The goal of this task is to train
quadruped robots (ants) to run forward as fast as possible. This example inherets
from [LocomotionTask](../omniisaacgymenvs/tasks/shared/locomotion.py),
which is a shared class between this example and the humanoid example; this simplifies
implementations for both environemnts since they compute rewards, observations,
and resets in a similar manner. This framework allows us to easily switch between
robots used in the task.
The Ant task includes more examples of utilizing `ArticulationView` from `omni.isaac.core`, which
provides various functions to get and set both DOF states and articulation root states
in a tensorized fashion across all of the actors in the environment. `get_world_poses`,
`get_linear_velocities`, and `get_angular_velocities`, can be used to determine whether the
ants have been moving towards the desired direction and whether they have fallen or flipped over.
Actions are applied onto the ants via `set_joint_efforts`, which moves the ants by setting
torques to the DOFs.
Note that the previously used force sensors and `get_force_sensor_forces` API are now deprecated.
Force sensors can now be retrieved directly using `get_measured_joint_forces` from `ArticulationView`.
Training with PPO can be launched with command line argument `task=Ant`.
Training with SAC with command line arguments `task=AntSAC train=AntSAC`.
Training using the Warp backend can be launched with `task=Ant warp=True`.
Running inference with pre-trained model can be launched with command line argument `task=Ant test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth`
Config files used for this task are:
- **PPO task config**: [Ant.yaml](../omniisaacgymenvs/cfg/task/Ant.yaml)
- **rl_games PPO training config**: [AntPPO.yaml](../omniisaacgymenvs/cfg/train/AntPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/171454182-0be1b830-bceb-4cfd-93fb-e1eb8871ec68.gif" width="300" height="150"/>
### Humanoid [humanoid.py](../omniisaacgymenvs/tasks/humanoid.py)
Humanoid is another environment that uses
[LocomotionTask](../omniisaacgymenvs/tasks/shared/locomotion.py). It is conceptually
very similar to the Ant example, where the goal for the humanoid is to run forward
as fast as possible.
Training can be launched with command line argument `task=Humanoid`.
Training with SAC with command line arguments `task=HumanoidSAC train=HumanoidSAC`.
Training using the Warp backend can be launched with `task=Humanoid warp=True`.
Running inference with pre-trained model can be launched with command line argument `task=Humanoid test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/humanoid.pth`
Config files used for this task are:
- **PPO task config**: [Humanoid.yaml](../omniisaacgymenvs/cfg/task/Humanoid.yaml)
- **rl_games PPO training config**: [HumanoidPPO.yaml](../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/171454193-e027885d-1510-4ef4-b838-06b37f70c1c7.gif" width="300" height="150"/>
### Shadow Hand Object Manipulation [shadow_hand.py](../omniisaacgymenvs/tasks/shadow_hand.py)
The Shadow Hand task is an example of a challenging dexterity manipulation task with complex contact
dynamics. It resembles OpenAI's [Learning Dexterity](https://openai.com/blog/learning-dexterity/)
project and [Robotics Shadow Hand](https://github.com/openai/gym/tree/v0.21.0/gym/envs/robotics)
training environments. The goal of this task is to orient the object in the robot hand to match
a random target orientation, which is visually displayed by a goal object in the scene.
This example inherets from [InHandManipulationTask](../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py),
which is a shared class between this example and the Allegro Hand example. The idea of
this shared [InHandManipulationTask](../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py) class
is similar to that of the [LocomotionTask](../omniisaacgymenvs/tasks/shared/locomotion.py);
since the Shadow Hand example and the Allegro Hand example only differ by the robot hand used
in the task, using this shared class simplifies implementation across the two.
In this example, motion of the hand is controlled using position targets with `set_joint_position_targets`.
The object and the goal object are reset using `set_world_poses`; their states are retrieved via
`get_world_poses` for computing observations. It is worth noting that the Shadow Hand model in
this example also demonstrates the use of tendons, which are imported using the `omni.isaac.mjcf` extension.
Training can be launched with command line argument `task=ShadowHand`.
Training with Domain Randomization can be launched with command line argument `task.domain_randomization.randomize=True`.
For best training results with DR, use `num_envs=16384`.
Running inference with pre-trained model can be launched with command line argument `task=ShadowHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand.pth`
Config files used for this task are:
- **Task config**: [ShadowHand.yaml](../omniisaacgymenvs/cfg/task/ShadowHand.yaml)
- **rl_games training config**: [ShadowHandPPO.yaml](../omniisaacgymenvs/cfg/train/ShadowHandPPO.yaml)
#### OpenAI Variant
In addition to the basic version of this task, there is an additional variant matching OpenAI's
[Learning Dexterity](https://openai.com/blog/learning-dexterity/) project. This variant uses the **openai**
observations in the policy network, but asymmetric observations of the **full_state** in the value network.
This can be launched with command line argument `task=ShadowHandOpenAI_FF`.
Running inference with pre-trained model can be launched with command line argument `task=ShadowHandOpenAI_FF test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand_openai_ff.pth`
Config files used for this are:
- **Task config**: [ShadowHandOpenAI_FF.yaml](../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_FF.yaml)
- **rl_games training config**: [ShadowHandOpenAI_FFPPO.yaml](../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_FFPPO.yaml).
#### LSTM Training Variant
This variant uses LSTM policy and value networks instead of feed forward networks, and also asymmetric
LSTM critic designed for the OpenAI variant of the task. This can be launched with command line argument
`task=ShadowHandOpenAI_LSTM`.
Running inference with pre-trained model can be launched with command line argument `task=ShadowHandOpenAI_LSTM test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand_openai_lstm.pth`
Config files used for this are:
- **Task config**: [ShadowHandOpenAI_LSTM.yaml](../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_LSTM.yaml)
- **rl_games training config**: [ShadowHandOpenAI_LSTMPPO.yaml](../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_LSTMPPO.yaml).
<img src="https://user-images.githubusercontent.com/34286328/171454160-8cb6739d-162a-4c84-922d-cda04382633f.gif" width="300" height="150"/>
### Allegro Hand Object Manipulation [allegro_hand.py](../omniisaacgymenvs/tasks/allegro_hand.py)
This example performs the same object orientation task as the Shadow Hand example,
but using the Allegro hand instead of the Shadow hand.
Training can be launched with command line argument `task=AllegroHand`.
Running inference with pre-trained model can be launched with command line argument `task=AllegroHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/allegro_hand.pth`
Config files used for this task are:
- **Task config**: [AllegroHand.yaml](../omniisaacgymenvs/cfg/task/Allegro.yaml)
- **rl_games training config**: [AllegroHandPPO.yaml](../omniisaacgymenvs/cfg/train/AllegroHandPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/171454176-ce08f6d0-3087-4ecc-9273-7d30d8f73f6d.gif" width="300" height="150"/>
### ANYmal [anymal.py](../omniisaacgymenvs/tasks/anymal.py)
This example trains a model of the ANYmal quadruped robot from ANYbotics
to follow randomly chosen x, y, and yaw target velocities.
Training can be launched with command line argument `task=Anymal`.
Running inference with pre-trained model can be launched with command line argument `task=Anymal test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal.pth`
Config files used for this task are:
- **Task config**: [Anymal.yaml](../omniisaacgymenvs/cfg/task/Anymal.yaml)
- **rl_games training config**: [AnymalPPO.yaml](../omniisaacgymenvs/cfg/train/AnymalPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184168200-152567a8-3354-4947-9ae0-9443a56fee4c.gif" width="300" height="150"/>
### Anymal Rough Terrain [anymal_terrain.py](../omniisaacgymenvs/tasks/anymal_terrain.py)
A more complex version of the above Anymal environment that supports
traversing various forms of rough terrain.
Training can be launched with command line argument `task=AnymalTerrain`.
Running inference with pre-trained model can be launched with command line argument `task=AnymalTerrain test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal_terrain.pth`
- **Task config**: [AnymalTerrain.yaml](../omniisaacgymenvs/cfg/task/AnymalTerrain.yaml)
- **rl_games training config**: [AnymalTerrainPPO.yaml](../omniisaacgymenvs/cfg/train/AnymalTerrainPPO.yaml)
**Note** during test time use the last weights generated, rather than the usual best weights.
Due to curriculum training, the reward goes down as the task gets more challenging, so the best weights
do not typically correspond to the best outcome.
**Note** if you use the ANYmal rough terrain environment in your work, please ensure you cite the following work:
```
@misc{rudin2021learning,
title={Learning to Walk in Minutes Using Massively Parallel Deep Reinforcement Learning},
author={Nikita Rudin and David Hoeller and Philipp Reist and Marco Hutter},
year={2021},
journal = {arXiv preprint arXiv:2109.11978}
```
**Note** The OmniIsaacGymEnvs implementation slightly differs from the implementation used in the paper above, which also
uses a different RL library and PPO implementation. The original implementation is made available [here](https://github.com/leggedrobotics/legged_gym). Results reported in the Isaac Gym technical paper are based on that repository, not this one.
<img src="https://user-images.githubusercontent.com/34286328/184170040-3f76f761-e748-452e-b8c8-3cc1c7c8cb98.gif" width="300" height="150"/>
### NASA Ingenuity Helicopter [ingenuity.py](../omniisaacgymenvs/tasks/ingenuity.py)
This example trains a simplified model of NASA's Ingenuity helicopter to navigate to a moving target.
It showcases the use of velocity tensors and applying force vectors to rigid bodies.
Note that we are applying force directly to the chassis, rather than simulating aerodynamics.
This example also demonstrates using different values for gravitational forces.
Ingenuity Helicopter visual 3D Model courtesy of NASA: https://mars.nasa.gov/resources/25043/mars-ingenuity-helicopter-3d-model/.
Training can be launched with command line argument `task=Ingenuity`.
Running inference with pre-trained model can be launched with command line argument `task=Ingenuity test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ingenuity.pth`
Config files used for this task are:
- **Task config**: [Ingenuity.yaml](../omniisaacgymenvs/cfg/task/Ingenuity.yaml)
- **rl_games training config**: [IngenuityPPO.yaml](../omniisaacgymenvs/cfg/train/IngenuityPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184176312-df7d2727-f043-46e3-b537-48a583d321b9.gif" width="300" height="150"/>
### Quadcopter [quadcopter.py](../omniisaacgymenvs/tasks/quadcopter.py)
This example trains a very simple quadcopter model to reach and hover near a fixed position.
Lift is achieved by applying thrust forces to the "rotor" bodies, which are modeled as flat cylinders.
In addition to thrust, the pitch and roll of each rotor is controlled using DOF position targets.
Training can be launched with command line argument `task=Quadcopter`.
Running inference with pre-trained model can be launched with command line argument `task=Quadcopter test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/quadcopter.pth`
Config files used for this task are:
- **Task config**: [Quadcopter.yaml](../omniisaacgymenvs/cfg/task/Quadcopter.yaml)
- **rl_games training config**: [QuadcopterPPO.yaml](../omniisaacgymenvs/cfg/train/QuadcopterPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184178817-9c4b6b3c-c8a2-41fb-94be-cfc8ece51d5d.gif" width="300" height="150"/>
### Crazyflie [crazyflie.py](../omniisaacgymenvs/tasks/crazyflie.py)
This example trains the Crazyflie drone model to hover near a fixed position. It is achieved by applying thrust forces to the four rotors.
Training can be launched with command line argument `task=Crazyflie`.
Running inference with pre-trained model can be launched with command line argument `task=Crazyflie test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/crazyflie.pth`
Config files used for this task are:
- **Task config**: [Crazyflie.yaml](../omniisaacgymenvs/cfg/task/Crazyflie.yaml)
- **rl_games training config**: [CrazyfliePPO.yaml](../omniisaacgymenvs/cfg/train/CrazyfliePPO.yaml)
<img src="https://user-images.githubusercontent.com/6352136/185715165-b430a0c7-948b-4dce-b3bb-7832be714c37.gif" width="300" height="150"/>
### Ball Balance [ball_balance.py](../omniisaacgymenvs/tasks/ball_balance.py)
This example trains balancing tables to balance a ball on the table top.
This is a great example to showcase the use of force and torque sensors, as well as DOF states for the table and root states for the ball.
In this example, the three-legged table has a force sensor attached to each leg.
We use the force sensor APIs to collect force and torque data on the legs, which guide position target outputs produced by the policy.
Training can be launched with command line argument `task=BallBalance`.
Running inference with pre-trained model can be launched with command line argument `task=BallBalance test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ball_balance.pth`
Config files used for this task are:
- **Task config**: [BallBalance.yaml](../omniisaacgymenvs/cfg/task/BallBalance.yaml)
- **rl_games training config**: [BallBalancePPO.yaml](../omniisaacgymenvs/cfg/train/BallBalancePPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184172037-cdad9ee8-f705-466f-bbde-3caa6c7dea37.gif" width="300" height="150"/>
### Franka Cabinet [franka_cabinet.py](../omniisaacgymenvs/tasks/franka_cabinet.py)
This Franka example demonstrates interaction between Franka arm and cabinet, as well as setting states of objects inside the drawer.
It also showcases control of the Franka arm using position targets.
In this example, we use DOF state tensors to retrieve the state of the Franka arm, as well as the state of the drawer on the cabinet.
Actions are applied as position targets to the Franka arm DOFs.
Training can be launched with command line argument `task=FrankaCabinet`.
Running inference with pre-trained model can be launched with command line argument `task=FrankaCabinet test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/franka_cabinet.pth`
Config files used for this task are:
- **Task config**: [FrankaCabinet.yaml](../omniisaacgymenvs/cfg/task/FrankaCabinet.yaml)
- **rl_games training config**: [FrankaCabinetPPO.yaml](../omniisaacgymenvs/cfg/train/FrankaCabinetPPO.yaml)
<img src="https://user-images.githubusercontent.com/34286328/184174894-03767aa0-936c-4bfe-bbe9-a6865f539bb4.gif" width="300" height="150"/>
### Franka Deformable [franka_deformable.py](../omniisaacgymenvs/tasks/franka_deformable.py)
This Franka example demonstrates interaction between Franka arm and a deformable tube. It demonstrates the manipulation of deformable objects, using nodal positions and velocities of the simulation mesh as observations.
Training can be launched with command line argument `task=FrankaDeformable`.
Running inference with pre-trained model can be launched with command line argument `task=FrankaDeformable test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/franka_deformable.pth`
Config files used for this task are:
- **Task config**: [FrankaDeformable.yaml](../omniisaacgymenvs/cfg/task/FrankaDeformable.yaml)
- **rl_games training config**: [FrankaCabinetFrankaDeformable.yaml](../omniisaacgymenvs/cfg/train/FrankaDeformablePPO.yaml)
### Factory: Fast Contact for Robotic Assembly
We provide a set of Factory example tasks, [**FactoryTaskNutBoltPick**](../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_pick.py), [**FactoryTaskNutBoltPlace**](../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_place.py), and [**FactoryTaskNutBoltScrew**](../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_screw.py),
`FactoryTaskNutBoltPick` can be executed with `python train.py task=FactoryTaskNutBoltPick`. This task trains policy for the Pick task, a simplified version of the corresponding task in the Factory paper. The policy may take ~1 hour to achieve high success rates on a modern GPU.
- The general configuration file for the above task is [FactoryTaskNutBoltPick.yaml](../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltPick.yaml).
- The training configuration file for the above task is [FactoryTaskNutBoltPickPPO.yaml](../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltPickPPO.yaml).
Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltPick test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_pick.pth`
`FactoryTaskNutBoltPlace` can be executed with `python train.py task=FactoryTaskNutBoltPlace`. This task trains policy for the Place task.
- The general configuration file for the above task is [FactoryTaskNutBoltPlace.yaml](../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltPlace.yaml).
- The training configuration file for the above task is [FactoryTaskNutBoltPlacePPO.yaml](../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltPlacePPO.yaml).
Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltPlace test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_place.pth`
`FactoryTaskNutBoltScrew` can be executed with `python train.py task=FactoryTaskNutBoltScrew`. This task trains policy for the Screw task.
- The general configuration file for the above task is [FactoryTaskNutBoltScrew.yaml](../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltScrew.yaml).
- The training configuration file for the above task is [FactoryTaskNutBoltScrewPPO.yaml](../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltScrewPPO.yaml).
Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltScrew test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_screw.pth`
If you use the Factory simulation methods (e.g., SDF collisions, contact reduction) or Factory learning tools (e.g., assets, environments, or controllers) in your work, please cite the following paper:
```
@inproceedings{
narang2022factory,
author = {Yashraj Narang and Kier Storey and Iretiayo Akinola and Miles Macklin and Philipp Reist and Lukasz Wawrzyniak and Yunrong Guo and Adam Moravanszky and Gavriel State and Michelle Lu and Ankur Handa and Dieter Fox},
title = {Factory: Fast contact for robotic assembly},
booktitle = {Robotics: Science and Systems},
year = {2022}
}
```
Also note that our original formulations of SDF collisions and contact reduction were developed by [Macklin, et al.](https://dl.acm.org/doi/abs/10.1145/3384538) and [Moravanszky and Terdiman](https://scholar.google.com/scholar?q=Game+Programming+Gems+4%2C+chapter+Fast+Contact+Reduction+for+Dynamics+Simulation), respectively.
<img src="https://user-images.githubusercontent.com/6352136/205978286-fa2ae714-a3cb-4acd-9f5f-a467338a8bb3.gif"/>
| 25,126 | Markdown | 63.927648 | 347 | 0.792725 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/release_notes.md | Release Notes
=============
2023.1.0a - October 20, 2023
----------------------------
Fixes
-----
- Fix extension loading error in camera app file
2023.1.0 - October 18, 2023
---------------------------
Additions
---------
- Add support for Warp backend task implementation
- Add Warp-based RL examples: Cartpole, Ant, Humanoid
- Add new Factory environments for place and screw: FactoryTaskNutBoltPlace and FactoryTaskNutBoltScrew
- Add new camera-based Cartpole example: CartpoleCamera
- Add new deformable environment showing Franka picking up a deformable tube: FrankaDeformable
- Add support for running OIGE as an extension in Isaac Sim
- Add options to filter collisions between environments and specify global collision filter paths to `RLTask.set_to_scene()`
- Add multinode training support
- Add dockerfile with OIGE
- Add option to select kit app file from command line argument `kit_app`
- Add `rendering_dt` parameter to the task config file for setting rendering dt. Defaults to the same value as the physics dt.
Changes
-------
- `use_flatcache` flag has been renamed to `use_fabric`
- Update hydra-core version to 1.3.2, omegaconf version to 2.3.0
- Update rlgames to version 1.6.1.
- The `get_force_sensor_forces` API for articulations is now deprecated and replaced with `get_measured_joint_forces`
- Remove unnecessary cloning of buffers in VecEnv classes
- Only enable omni.replicator.isaac when domain randomization or cameras are enabled
- The multi-threaded launch script `rlgames_train_mt.py` has been re-designed to support the extension workflow. This script can no longer be used to launch a training run from python. Please use `rlgames_train.py` instead.
- Restructures for environments to support the new extension-based workflow
- Add async workflow to factory pick environment to support extension-based workflow
- Update docker scripts with cache directories
Fixes
-----
- Fix errors related to setting velocities to kinematic markers in Ingenuity and Quadcopter environments
- Fix contact-related issues with quadruped assets
- Fix errors in physics APIs when returning empty tensors
- Fix orientation correctness issues when using some assets with omni.isaac.core. Additional orientations applied to accommodate for the error are no longer required (i.e. ShadowHand)
- Updated the deprecated config name `seq_len` used with RNN networks to `seq_length`
2022.2.1 - March 16, 2023
-------------------------
Additions
---------
- Add FactoryTaskNutBoltPick example
- Add Ant and Humanoid SAC training examples
- Add multi-GPU support for training
- Add utility scripts for launching Isaac Sim docker with OIGE
- Add support for livestream through the Omniverse Streaming Client
Changes
-------
- Change rigid body fixed_base option to make_kinematic, avoiding creation of unnecessary articulations
- Update ShadowHand, Ingenuity, Quadcopter and Crazyflie marker objects to use kinematics
- Update ShadowHand GPU buffer parameters
- Disable PyTorch nvFuser for better performance
- Enable viewport and replicator extensions dynamically to maintain order of extension startup
- Separate app files for headless environments with rendering (requires Isaac Sim update)
- Update rl-games to v1.6.0
Fixes
-----
- Fix material property randomization at run-time, including friction and restitution (requires Isaac Sim update)
- Fix a bug in contact reporting API where incorrect values were being reported (requires Isaac Sim update)
- Enable render flag in Isaac Sim when enable_cameras is set to True
- Add root pose and velocity reset to BallBalance environment
2.0.0 - December 15, 2022
-------------------------
Additions
---------
- Update to Viewport 2.0
- Allow for runtime mass randomization on GPU pipeline
- Add runtime mass randomization to ShadowHand environments
- Introduce `disable_contact_processing` simulation parameter for faster contact processing
- Use physics replication for cloning by default for faster load time
Changes
-------
- Update AnymalTerrain environment to use contact forces
- Update Quadcopter example to apply local forces
- Update training parameters for ShadowHandOpenAI_FF environment
- Rename rlgames_play.py to rlgames_demo.py
Fixes
-----
- Remove fix_base option from articulation configs
- Fix in_hand_manipulation random joint position sampling on reset
- Fix mass and density randomization in MT training script
- Fix actions/observations noise randomization in MT training script
- Fix random seed when domain randomization is enabled
- Check whether simulation is running before executing pre_physics_step logic
1.1.0 - August 22, 2022
-----------------------
Additions
---------
- Additional examples: Anymal, AnymalTerrain, BallBalance, Crazyflie, FrankaCabinet, Ingenuity, Quadcopter
- Add OpenAI variantions for Feed-Forward and LSTM networks for ShadowHand
- Add domain randomization framework `using omni.replicator.isaac`
- Add AnymalTerrain interactable demo
- Automatically disable `omni.kit.window.viewport` and `omni.physx.flatcache` extensions in headless mode to improve start-up load time
- Introduce `reset_xform_properties` flag for initializing Views of cloned environments to reduce load time
- Add WandB support
- Update RL-Games version to 1.5.2
Fixes
-----
- Correctly sets simulation device for GPU simulation
- Fix omni.client import order
- Fix episode length reset condition for ShadowHand and AllegroHand
1.0.0 - June 03, 2022
----------------------
- Initial release for RL examples with Isaac Sim
- Examples provided: AllegroHand, Ant, Cartpole, Humanoid, ShadowHand | 5,592 | Markdown | 41.371212 | 223 | 0.768777 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/CHANGELOG.md | # Changelog
## [0.0.0] - 2023-07-13
### Added
- UI for launching RL trasks
| 76 | Markdown | 11.833331 | 28 | 0.618421 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/transfering_policies_from_isaac_gym.md | ## Transfering Policies from Isaac Gym Preview Releases
This section delineates some of the differences between the standalone
[Isaac Gym Preview Releases](https://developer.nvidia.com/isaac-gym) and
Isaac Sim reinforcement learning extensions, in hopes of facilitating the
process of transferring policies trained in the standalone preview releases
to Isaac Sim.
### Isaac Sim RL Extensions
Unlike the monolithic standalone Isaac Gym Preview Releases, Omniverse is
a highly modular system, with functionality split between various [Extensions](https://docs.omniverse.nvidia.com/extensions/latest/index.html).
The APIs used by typical robotics RL systems are split between a handful of
extensions in Isaac Sim. These include `omni.isaac.core`, which provides
tensorized access to physics simulation state as well as a task management
framework, the `omni.isaac.cloner` extension for creating many copies of
your environments, and the `omni.isaac.gym` extension for interfacing with
external RL training libraries.
For naming clarity, we'll refer collectively to the extensions used for RL
within Isaac Sim as the **Isaac Sim RL extensions**, in contrast with the
older **Isaac Gym Preview Releases**.
### Quaternion Convention
The Isaac Sim RL extensions use various classes and methods in `omni.isaac.core`,
which adopts `wxyz` as the quaternion convention. However, the quaternion
convention used in Isaac Gym Preview Releases is `xyzw`. Therefore, if a policy
trained in one of the Isaac Gym Preview Releases takes in quaternions as part
of its observations, remember to switch all quaternions to use the `xyzw` convention
in the observation buffer `self.obs_buf`. Similarly, please ensure all quaternions
are in `wxyz` before passing them in any of the utility functions in `omni.isaac.core`.
### Assets
Isaac Sim provides [URDF](https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_urdf.html)
and [MJCF](https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_mjcf.html) importers for translating URDF and MJCF assets into USD format.
Any robot or object assets must be in .usd, .usda, or .usdc format for Isaac Sim and Omniverse.
For more details on working with USD, please see https://docs.omniverse.nvidia.com/isaacsim/latest/reference_glossary.html#usd.
Importer tools are also available for other common geometry file formats, such as .obj, .fbx, and more.
Please see [Asset Importer](https://docs.omniverse.nvidia.com/extensions/latest/ext_asset-importer.html) for more details.
### Joint Order
Isaac Sim's `ArticulationView` in `omni.isaac.core` assumes a breadth-first
ordering for the joints in a given kinematic tree. Specifically, for the following
kinematic tree, the method `ArticulationView.get_joint_positions` returns a
tensor of shape `(number of articulations in the view, number of joints in the articulation)`.
Along the second dimension of this tensor, the values represent the articulation's joint positions
in the following order: `[Joint 1, Joint 2, Joint 4, Joint 3, Joint 5]`. On the other hand,
the Isaac Gym Preview Releases assume a depth-first ordering for the joints in the kinematic
tree; In the example below, the joint orders would be the following: `[Joint 1, Joint 2, Joint 3, Joint 4, Joint 5]`.
<img src="./media/KinematicTree.png" height="300"/>
With this in mind, it is important to change the joint order to depth-first in
the observation buffer before feeding it into an existing policy trained in one of the
Isaac Gym Preview Releases. Similarly, you would also need to change the joint order
in the output (the action buffer) of the Isaac Gym Preview Release trained policy
to breadth-first before applying joint actions to articulations via methods in `ArticulationView`.
### Physics Parameters
One factor that could dictate the success of policy transfer from Isaac Gym Preview
Releases to Isaac Sim is to ensure the physics parameters used in both simulations are
identical or very similar. In general, the `sim` parameters specified in the
task configuration `yaml` file overwrite the corresponding parameters in the USD asset.
However, there are additional parameters in the USD asset that are not included
in the task configuration `yaml` file. These additional parameters may sometimes
impact the performance of Isaac Gym Preview Release trained policies and hence need
modifications in the USD asset itself to match the values set in Isaac Gym Preview Releases.
For instance, the following parameters in the `RigidBodyAPI` could be modified in the
USD asset to yield better policy transfer performance:
| RigidBodyAPI Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases |
|:----------------------:|:--------------------------:|:--------------------------:|
| Linear Damping | 0.00 | 0.00 |
| Angular Damping | 0.05 | 0.00 |
| Max Linear Velocity | inf | 1000 |
| Max Angular Velocity | 5729.58008 (deg/s) | 64 (rad/s) |
| Max Contact Impulse | inf | 1e32 |
<img src="./media/RigidBodyAPI.png" width="500"/>
Parameters in the `JointAPI` as well as the `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` paramters in the `DriveAPI` have the unit
of `1/deg` in the Isaac Sim UI but `1/rad` in Isaac Gym Preview Releases.
| Joint Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases |
|:----------------------:|:--------------------------:|:--------------------------:|
| Maximum Joint Velocity | 1000000.0 (deg) | 100.0 (rad) |
<img src="./media/JointAPI.png" width="500"/>
### Differences in APIs
APIs for accessing physics states in Isaac Sim require the creation of an ArticulationView or RigidPrimView
object. Multiple view objects can be initialized for different articulations or bodies in the scene by defining
a regex expression that matches the paths of the desired objects. This approach eliminates the need of retrieving
body handles to slice states for specific bodies in the scene.
We have also removed `acquire` and `refresh` APIs in Isaac Sim. Physics states can be directly applied or retrieved
by using `set`/`get` APIs defined for the views.
New APIs provided in Isaac Sim no longer require explicit wrapping and un-wrapping of underlying buffers.
APIs can now work with tensors directly for reading and writing data. Most APIs in Isaac Sim 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.
Note some naming differences between APIs in Isaac Gym Preview Release and Isaac Sim. Most `dof` related APIs have been
named to `joint` in Isaac Sim. `root_states` is now separated into different APIs for `world_poses` and `velocities`.
Similary, `dof_states` are retrieved individually in Isaac Sim as `joint_positions` and `joint_velocities`.
APIs in Isaac Sim 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.
### Task Configuration Files
There are a few modifications that need to be made to an existing Isaac Gym Preview Release
task `yaml` file in order for it to be compatible with the Isaac Sim RL extensions.
#### Frequencies of Physics Simulation and RL Policy
The way in which physics simulation frequency and RL policy frequency are specified is different
between Isaac Gym Preview Releases and Isaac Sim, dictated by the following three
parameters: `dt`, `substeps`, and `controlFrequencyInv`.
- `dt`: The simulation time difference between each simulation step.
- `substeps`: The number of physics steps within one simulation step. *i.e.* if `dt: 1/60`
and `substeps: 4`, physics is simulated at 240 hz.
- `controlFrequencyInv`: The control decimation of the RL policy, which is the number of
simulation steps between RL actions. *i.e.* if `dt: 1/60` and `controlFrequencyInv: 2`,
RL policy is running at 30 hz.
In Isaac Gym Preview Releases, all three of the above parameters are used to specify
the frequencies of physics simulation and RL policy. However, Isaac Sim only uses `controlFrequencyInv` and `dt` as `substeps` is always fixed at `1`. Note that despite
only using two parameters, Isaac Sim can still achieve the same substeps definition
as Isaac Gym. For example, if in an Isaac Gym Preview Release policy, we set `substeps: 2`,
`dt: 1/60` and `controlFrequencyInv: 1`, we can achieve the equivalent in Isaac Sim
by setting `controlFrequencyInv: 2` and `dt: 1/120`.
In the Isaac Sim RL extensions, `dt` is specified in the task configuration `yaml` file
under `sim`, whereas `controlFrequencyInv` is a parameter under `env`.
#### Physx Parameters
Parameters under `physx` in the task configuration `yaml` file remain mostly unchanged.
In Isaac Gym Preview Releases, `use_gpu` is frequently set to
`${contains:"cuda",${....sim_device}}`. For Isaac Sim, please ensure this is changed
to `${eq:${....sim_device},"gpu"}`.
In Isaac Gym Preview Releases, GPU buffer sizes are specified using the following two parameters:
`default_buffer_size_multiplier` and `max_gpu_contact_pairs`. With the Isaac Sim RL extensions,
these two parameters are no longer used; instead, the various GPU buffer sizes can be
set explicitly.
For instance, in the [Humanoid task configuration file](../omniisaacgymenvs/cfg/task/Humanoid.yaml),
GPU buffer sizes are specified as follows:
```yaml
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 8192
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
```
Please refer to the [Troubleshooting](./troubleshoot.md#simulation) documentation should
you encounter errors related to GPU buffer sizes.
#### Articulation Parameters
The articulation parameters of each actor can now be individually specified tn the Isaac Sim
task configuration `yaml` file. The following is an example template for setting these parameters:
```yaml
ARTICULATION_NAME:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: True
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 10.0
```
These articulation parameters can be parsed using the `parse_actor_config` method in the
[SimConfig](../omniisaacgymenvs/utils/config_utils/sim_config.py) class, which can then be applied
to a prim in simulation via the `apply_articulation_settings` method. A concrete example of this
is the following code snippet from the [HumanoidTask](../omniisaacgymenvs/tasks/humanoid.py#L75):
```python
self._sim_config.apply_articulation_settings("Humanoid", get_prim_at_path(humanoid.prim_path), self._sim_config.parse_actor_config("Humanoid"))
```
#### Additional Simulation Parameters
- `use_fabric`: Setting this paramter to `True` enables [PhysX Fabric](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html#flatcache), which offers a significant increase in simulation speed. However, this parameter must
be set to `False` if soft-body simulation is required because `PhysX Fabric` curently only supports rigid-body simulation.
- `enable_scene_query_support`: Setting this paramter to `True` allows the user to interact with prims in the scene. Keeping this setting to `False` during
training improves simulation speed. Note that this parameter is always set to `True` if in test/inference mode to enable user interaction with trained models.
### Training Configuration Files
The Omniverse Isaac Gym RL Environments are trained using a third-party highly-optimized RL library,
[rl_games](https://github.com/Denys88/rl_games), which is also used to train the Isaac Gym Preview Release examples
in [IsaacGymEnvs](https://github.com/NVIDIA-Omniverse/IsaacGymEnvs). Therefore, the rl_games training
configuration `yaml` files in Isaac Sim are compatible with those from IsaacGymEnvs. However, please
add the following lines under `config` in the training configuration `yaml` files (*i.e.*
line 41-42 in [HumanoidPPO.yaml](../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml#L41)) to ensure
RL training runs on the intended device.
```yaml
device: ${....rl_device}
device_name: ${....rl_device}
``` | 13,250 | Markdown | 55.387234 | 252 | 0.749585 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/framework.md | ## RL Framework
### Overview
Our RL examples are built on top of Isaac Sim's RL framework provided in `omni.isaac.gym`. Tasks are implemented following `omni.isaac.core`'s Task structure. PPO training is performed using the [rl_games](https://github.com/Denys88/rl_games) library, but we provide the flexibility to use other RL libraries for training.
For a list of examples provided, refer to the
[RL List of Examples](rl_examples.md)
### Class Definition
The RL ecosystem can be viewed as three main pieces: the Task, the RL policy, and the Environment wrapper that provides an interface for communication between the task and the RL policy.
#### Task
The Task class is where main task logic is implemented, such as computing observations and rewards. This is where we can collect states of actors in the scene and apply controls or actions to our actors.
For convenience, we provide a base Task class, `RLTask`, which inherits from the `BaseTask` class in `omni.isaac.core`. This class is responsible for dealing with common configuration parsing, buffer initialization, and environment creation. Note that some config parameters and buffers in this class are specific to the rl_games library, and it is not necessary to inherit new tasks from `RLTask`.
A few key methods in `RLTask` include:
* `__init__(self, name: str, env: VecEnvBase, offset: np.ndarray = None)` - Parses config values common to all tasks and initializes action/observation spaces if not defined in the child class. Defines a GridCloner by default and creates a base USD scope for holding all environment prims. Can be called from child class.
* `set_up_scene(self, scene: Scene, replicate_physics=True, collision_filter_global_paths=[], filter_collisions=True)` - Adds ground plane and creates clones of environment 0 based on values specifid in config. Can be called from child class `set_up_scene()`.
* `pre_physics_step(self, actions: torch.Tensor)` - Takes in actions buffer from RL policy. Can be overriden by child class to process actions.
* `post_physics_step(self)` - Controls flow of RL data processing by triggering APIs to compute observations, retrieve states, compute rewards, resets, and extras. Will return observation, reward, reset, and extras buffers.
#### Environment Wrappers
As part of the RL framework in Isaac Sim, we have introduced environment wrapper classes in `omni.isaac.gym` for RL policies to communicate with simulation in Isaac Sim. This class provides a vectorized interface for common RL APIs used by `gym.Env` and can be easily extended towards RL libraries that require additional APIs. We show an example of this extension process in this repository, where we extend `VecEnvBase` as provided in `omni.isaac.gym` to include additional APIs required by the rl_games library.
Commonly used APIs provided by the base wrapper class `VecEnvBase` include:
* `render(self, mode: str = "human")` - renders the current frame
* `close(self)` - closes the simulator
* `seed(self, seed: int = -1)` - sets a seed. Use `-1` for a random seed.
* `step(self, actions: Union[np.ndarray, torch.Tensor])` - triggers task `pre_physics_step` with actions, steps simulation and renderer, computes observations, rewards, dones, and returns state buffers
* `reset(self)` - triggers task `reset()`, steps simulation, and re-computes observations
##### Multi-Threaded Environment Wrapper for Extension Workflows
`VecEnvBase` is a simple interface that’s designed to provide commonly used `gym.Env` APIs required by RL libraries. Users can create an instance of this class, attach your task to the interface, and provide your wrapper instance to the RL policy. Since the RL algorithm maintains the main loop of execution, interaction with the UI and environments in the scene can be limited and may interfere with the training loop.
We also provide another environment wrapper class called `VecEnvMT`, which is designed to isolate the RL policy in a new thread, separate from the main simulation and rendering thread. This class provides the same set of interface as `VecEnvBase`, but also provides threaded queues for sending and receiving actions and states between the RL policy and the task. In order to use this wrapper interface, users have to implement a `TrainerMT` class, which should implement a `run()` method that initiates the RL loop on a new thread. We show an example of this in OmniIsaacGymEnvs under `omniisaacgymenvs/utils/rlgames/rlgames_train_mt.py`. The setup for using `VecEnvMT` is more involved compared to the single-threaded `VecEnvBase` interface, but will allow users to have more control over starting and stopping the training loop through interaction with the UI.
Note that `VecEnvMT` has a timeout variable, which defaults to 90 seconds. If either the RL thread waiting for physics state exceeds the timeout amount or the simulation thread waiting for RL actions exceeds the timeout amount, the threaded queues will throw an exception and terminate training. For larger scenes that require longer simulation or training time, try increasing the timeout variable in `VecEnvMT` to prevent unnecessary timeouts. This can be done by passing in a `timeout` argument when calling `VecEnvMT.initialize()`.
This wrapper is currently only supported with the [extension workflow](extension_workflow.md).
### Creating New Examples
For simplicity, we will focus on using the single-threaded `VecEnvBase` interface in this tutorial.
To run any example, first make sure an instance of `VecEnvBase` or descendant of `VecEnvBase` is initialized.
This will be required as an argumet to our new Task. For example:
``` python
env = VecEnvBase(headless=False)
```
The headless parameter indicates whether a viewer should be created for visualizing results.
Then, create our task class, extending it from `RLTask`:
```python
class MyNewTask(RLTask):
def __init__(
self,
name: str, # name of the Task
sim_config: SimConfig, # SimConfig instance for parsing cfg
env: VecEnvBase, # env instance of VecEnvBase or inherited class
offset=None # transform offset in World
) -> None:
# parse configurations, set task-specific members
...
self._num_observations = 4
self._num_actions = 1
# call parent class’s __init__
RLTask.__init__(self, name, env)
```
The `__init__` method should take 4 arguments:
* `name`: a string for the name of the task (required by BaseTask)
* `sim_config`: an instance of `SimConfig` used for config parsing, can be `None`. This object is created in `omniisaacgymenvs/utils/task_utils.py`.
* `env`: an instance of `VecEnvBase` or an inherited class of `VecEnvBase`
* `offset`: any offset required to place the `Task` in `World` (required by `BaseTask`)
In the `__init__` method of `MyNewTask`, we can populate any task-specific parameters, such as dimension of observations and actions, and retrieve data from config dictionaries. Make sure to make a call to `RLTask`’s `__init__` at the end of the method to perform additional data initialization.
Next, we can implement the methods required by the RL framework. These methods follow APIs defined in `omni.isaac.core` `BaseTask` class. Below is an example of a simple implementation for each method.
```python
def set_up_scene(self, scene: Scene) -> None:
# implement environment setup here
add_prim_to_stage(my_robot) # add a robot actor to the stage
super().set_up_scene(scene) # pass scene to parent class - this method in RLTask also uses GridCloner to clone the robot and adds a ground plane if desired
self._my_robots = ArticulationView(...) # create a view of robots
scene.add(self._my_robots) # add view to scene for initialization
def post_reset(self):
# implement any logic required for simulation on-start here
pass
def pre_physics_step(self, actions: torch.Tensor) -> None:
# implement logic to be performed before physics steps
self.perform_reset()
self.apply_action(actions)
def get_observations(self) -> dict:
# implement logic to retrieve observation states
self.obs_buf = self.compute_observations()
def calculate_metrics(self) -> None:
# implement logic to compute rewards
self.rew_buf = self.compute_rewards()
def is_done(self) -> None:
# implement logic to update dones/reset buffer
self.reset_buf = self.compute_resets()
```
To launch the new example from one of our training scripts, add `MyNewTask` to `omniisaacgymenvs/utils/task_util.py`. In `initialize_task()`, add an import to the `MyNewTask` class and add an instance to the `task_map` dictionary to register it into the command line parsing.
To use the Hydra config parsing system, also add a task and train config files into `omniisaacgymenvs/cfg`. The config files should be named `cfg/task/MyNewTask.yaml` and `cfg/train/MyNewTaskPPO.yaml`.
Finally, we can launch `MyNewTask` with:
```bash
PYTHON_PATH random_policy.py task=MyNewTask
```
### Using a New RL Library
In this repository, we provide an example of extending Isaac Sim's environment wrapper classes to work with the rl_games library, which can be found at `omniisaacgymenvs/envs/vec_env_rlgames.py` and `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`.
The first script, `omniisaacgymenvs/envs/vec_env_rlgames.py`, extends from `VecEnvBase`.
```python
from omni.isaac.gym.vec_env import VecEnvBase
class VecEnvRLGames(VecEnvBase):
```
One of the features in rl_games is the support for asymmetrical actor-critic policies, which requires a `states` buffer in addition to the `observations` buffer. Thus, we have overriden a few of the class in `VecEnvBase` to incorporate this requirement.
```python
def set_task(
self, task, backend="numpy", sim_params=None, init_sim=True
) -> None:
super().set_task(task, backend, sim_params, init_sim) # class VecEnvBase's set_task to register task to the environment instance
# special variables required by rl_games
self.num_states = self._task.num_states
self.state_space = self._task.state_space
def step(self, actions):
# we clamp the actions so that values are within a defined range
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone()
# pass actions buffer to task for processing
self._task.pre_physics_step(actions)
# allow users to specify the control frequency through config
for _ in range(self._task.control_frequency_inv):
self._world.step(render=self._render)
self.sim_frame_count += 1
# compute new buffers
self._obs, self._rew, self._resets, self._extras = self._task.post_physics_step()
self._states = self._task.get_states() # special buffer required by rl_games
# return buffers in format required by rl_games
obs_dict = {"obs": self._obs, "states": self._states}
return obs_dict, self._rew, self._resets, self._extras
```
Similarly, we also have a multi-threaded version of the rl_games environment wrapper implementation, `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`. This class extends from `VecEnvMT` and `VecEnvRLGames`:
```python
from omni.isaac.gym.vec_env import VecEnvMT
from .vec_env_rlgames import VecEnvRLGames
class VecEnvRLGamesMT(VecEnvRLGames, VecEnvMT):
```
In this class, we also have a special method `_parse_data(self, data)`, which is required to be implemented to parse dictionary values passed through queues. Since multiple buffers of data are required by the RL policy, we concatenate all of the buffers in a single dictionary, and send that to the queue to be received by the RL thread.
```python
def _parse_data(self, data):
self._obs = torch.clamp(data["obs"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._rew = data["rew"].to(self._task.rl_device).clone()
self._states = torch.clamp(data["states"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._resets = data["reset"].to(self._task.rl_device).clone()
self._extras = data["extras"].copy()
```
### API Limitations
#### omni.isaac.core Setter APIs
Setter APIs in omni.isaac.core for ArticulationView, RigidPrimView, and RigidContactView should only be called once per simulation step for
each view instance per API. This means that for use cases where multiple calls to the same setter API from the same view instance is required,
users will need to cache the states to be set for intermmediate calls, and make only one call to the setter API prior to stepping physics with
the complete buffer containing all cached states.
If multiple calls to the same setter API from the same view object are made within the simulation step,
subsequent calls will override the states that have been set by prior calls to the same API,
voiding the previous calls to the API. The API can be called again once a simulation step is made.
For example, the below code will override states.
```python
my_view.set_world_poses(positions=[[0, 0, 1]], orientations=[[1, 0, 0, 0]], indices=[0])
# this call will void the previous call
my_view.set_world_poses(positions=[[0, 1, 1]], orientations=[[1, 0, 0, 0]], indices=[1])
my_world.step()
```
Instead, the below code should be used.
```python
my_view.set_world_poses(positions=[[0, 0, 1], [0, 1, 1]], orientations=[[1, 0, 0, 0], [1, 0, 0, 0]], indices=[0, 1])
my_world.step()
```
#### omni.isaac.core Getter APIs
Getter APIs for cloth simulation may return stale states when used with the GPU pipeline. This is because the physics simulation requires a simulation step
to occur in order to refresh the GPU buffers with new states. Therefore, when a getter API is called after a setter API before a
simulation step, the states returned from the getter API may not reflect the values that were set using the setter API.
For example:
```python
my_view.set_world_positions(positions=[[0, 0, 1]], indices=[0])
# Values may be stale when called before step
positions = my_view.get_world_positions() # positions may not match [[0, 0, 1]]
my_world.step()
# Values will be updated when called after step
positions = my_view.get_world_positions() # positions will reflect the new states
```
#### Performing Resets
When resetting the states of actors, impulses generated by previous target or effort controls
will continue to be carried over from the previous states in simulation.
Therefore, depending on the time step, the masses of the objects, and the magnitude of the impulses,
the difference between the desired reset state and the observed first state after reset can be large.
To eliminate this issue, users should also reset any position/velocity targets or effort controllers
to the reset state or zero state when resetting actor states. For setting joint positions and velocities
using the omni.isaac.core ArticulationView APIs, position targets and velocity targets will
automatically be set to the same states as joint positions and velocities.
#### Massless Links
It may be helpful in some scenarios to introduce dummy bodies into articulations for
retrieving transformations at certain locations of the articulation. Although it is possible
to introduce rigid bodies with no mass and colliders APIs and attach them to the articulation
with fixed joints, this can sometimes cause physics instabilities in simulation. To prevent
instabilities from occurring, it is recommended to add a dummy geometry to the rigid body
and include both Mass and Collision APIs. The mass of the geometry can be set to a very
small value, such as 0.0001, to avoid modifying physical behaviors of the articulation.
Similarly, we can also disable collision on the Collision API of the geometry to preserve
contact behavior of the articulation. | 15,846 | Markdown | 58.575188 | 862 | 0.754007 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/README.md | # Usage
To enable this extension, go to the Extension Manager menu and enable omniisaacgymenvs extension | 105 | Markdown | 34.333322 | 96 | 0.828571 |
j3soon/OmniIsaacGymEnvs-DofbotReacher/docs/index.rst | RL Examples [omniisaacgymenvs]
######################################################
| 86 | reStructuredText | 27.999991 | 54 | 0.302326 |
j3soon/nvidia-isaac-summary/README.md | # NVIDIA Isaac Summary
A list of NVIDIA Isaac components. [[link](https://developer.nvidia.com/isaac)]
- (Omniverse) Isaac Sim [[link](https://developer.nvidia.com/isaac-sim)][[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html)][[ngc](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim)][[dli](https://courses.nvidia.com/courses/course-v1:DLI+T-OV-01+V1/)][[dli](https://courses.nvidia.com/courses/course-v1:DLI+S-OV-03+V1/)][[youtube](https://youtu.be/pxPFr58gHmQ?list=PL3jK4xNnlCVf1SzxjCm7ZxDBNl9QYyV8X)]
a robotics simulation toolkit based on Omniverse.
> a scalable robotics simulation application and synthetic data-generation tool that powers photorealistic, physically accurate virtual environments.
>
> -- [NVIDIA Isaac Sim](https://developer.nvidia.com/isaac-sim)
Before starting, please make sure your hardware and software meet the [system requirements](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/requirements.html#system-requirements).
Technically, Isaac Sim is an app built upon Omniverse Kit, which is a SDK for building apps upon the Omniverse platform. The simulation is accelerated by PhysX, while the scene is rendered through RTX rendering.
Isaac Sim can be downloaded through [Omniverse Launcher](https://www.nvidia.com/en-us/omniverse/download/) here:
- [Linux](https://install.launcher.omniverse.nvidia.com/installers/omniverse-launcher-linux.AppImage)
- [Windows](https://install.launcher.omniverse.nvidia.com/installers/omniverse-launcher-win.exe)
The required assets are accessed through [Omniverse Nucleus](https://docs.omniverse.nvidia.com/nucleus/latest/index.html), which requires setting up a (local) Nucleus account. In addition, installing [Omniverse Cache](https://docs.omniverse.nvidia.com/prod_utilities/prod_utilities/cache/overview.html) can speed up the access to Nucleus.
- Isaac Sim Unity3D [[docs](https://docs.nvidia.com/isaac/archive/2020.1/doc/simulation/unity3d.html)]
Unity3D support has been deprecated ([source](https://forums.developer.nvidia.com/t/no-isaac-sim-unity3d-to-download/212951)). The term `Isaac Sim` now refer to the Omniverse-based version.
> allows you to use Unity3D as the simulation environment for Isaac robotics.
>
> -- [NVIDIA Isaac SDK](https://docs.nvidia.com/isaac/archive/2020.1/doc/simulation/unity3d.html)
- ROS & ROS 2 Bridges [[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_ros_turtlebot.html)][[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_ros2_turtlebot.html)]
> tools to facilitate integration with ROS systems.
>
> -- [NVIDIA Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_ros_turtlebot.html)
- Isaac Cortex [[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_cortex_1_overview.html)]
A behavior programming tool.
> enables programming task awareness and adaptive decision making into robots, and easily switching between simulation and reality.
>
> -- [NVIDIA Isaac Cortex](https://www.nvidia.com/en-us/on-demand/session/gtcspring22-s42693/) (slightly rephrased)
- Isaac Core API [[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html#isaac-sim-app-tutorial-core-hello-world)]
A Python abstraction API (for Pixar USD API).
> a set of APIs that are designed to be used in robotics applications, APIs that abstract away the complexity of USD APIs and merge multiple steps into one for frequently performed tasks.
>
> -- [NVIDIA Isaac Core API](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html#isaac-sim-app-tutorial-core-hello-world)
- Isaac Sim Assets [[docs](https://docs.omniverse.nvidia.com/isaacsim/latest/features/environment_setup/assets/usd_assets_overview.html)]
A collection of USD assets including environments, robots, sensors, props, and other featured assets.
- other features such as [OmniGraph](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gui_omnigraph.html), [Importers](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_isaac_extensions.html#asset-conversion-extensions), [etc.](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_isaac_extensions.html)
- (Omniverse) Isaac Gym [[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_isaac_gym.html)][[github](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs)]
a light-weight repository based on Isaac Sim that provides a variety of GPU-accelerated reinforcement learning environments and algorithms.
The repository is named as Omniverse Isaac Gym Environments (OIGE), and is released under the BSD 3-Clause License ([source](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/blob/main/LICENSE.txt)).
> an interface for performing reinforcement learning training and inferencing in Isaac Sim.
>
> -- [NVIDIA Isaac Gym](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_isaac_gym.html)
- Isaac Gym (Preview Release) [[link](https://developer.nvidia.com/isaac-gym)][[github](https://github.com/NVIDIA-Omniverse/IsaacGymEnvs)][[arxiv](https://arxiv.org/abs/2108.10470)][[site](https://sites.google.com/view/isaacgym-nvidia)][[youtube](https://youtu.be/nleDq-oJjGk?list=PLq2Xfjf6QzkrgDkQdtEzlnXeUAbTPEXNH)]
the predecessor of (Omniverse) Isaac Gym that does not base on Isaac Sim (and Omniverse).
The repository is named as Isaac Gym Environments (IGE), and is released under the BSD 3-Clause License ([source](https://github.com/NVIDIA-Omniverse/IsaacGymEnvs/blob/main/LICENSE.txt)). The documentation is provided in an offline form that can be accessed after download.
> NVIDIA’s physics simulation environment for reinforcement learning research.
>
> -- [NVIDIA Isaac Gym](https://developer.nvidia.com/isaac-gym)
The term `Isaac Gym` is ambiguous when viewed from a technical perspective. It's better to specify whether the mentioned Isaac Gym is based on Isaac Sim, or the preview version that does not base on Isaac Sim.
> Until Omniverse Isaac Gym functionality is feature complete, this standalone Isaac Gym Preview release will remain available.
>
> -- [NVIDIA Isaac Gym](https://developer.nvidia.com/isaac-gym)
The latest release of Isaac Gym (Preview Release) is Preview 4, and will not be further updated.
- Isaac Orbit [[docs](https://isaac-orbit.github.io/orbit/)][[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_orbit.html)][[arxiv](https://arxiv.org/abs/2301.04195)][[site](https://isaac-orbit.github.io/)][[github](https://github.com/NVIDIA-Omniverse/Orbit)]
a general repository based on Isaac Sim that features a number of GPU-accelerated simulation environments, a variety of motion generators, integrations with several reinforcement learning libraries, utilities for imitation learning, etc.
Released under the BSD 3-Clause License ([source](https://github.com/NVIDIA-Omniverse/Orbit/blob/main/LICENSE)).
> a unified and modular framework for robot learning powered by NVIDIA Isaac Sim.
>
> -- [NVIDIA Isaac Orbit](https://arxiv.org/abs/2301.04195)
Omniverse Isaac Gym is a light-weight framework focusing on reinforcement learning tasks, while Isaac Orbit is a more general and modular framework that focuses on robotics applications. ([source](https://nvidia.slack.com/archives/C01TGK0GSJG/p1675192628308169?thread_ts=1674981564.933639&cid=C01TGK0GSJG))
- Isaac Robot Operating System (ROS) [[link](https://developer.nvidia.com/isaac-ros)][[github](https://github.com/NVIDIA-ISAAC-ROS)][[docs](https://nvidia-isaac-ros.github.io/getting_started/index.html)]
a collection of GPU-accelerated ROS2 packages (i.e., Isaac GEMs).
> a collection of hardware-accelerated packages that make it easier for ROS developers to build high-performance solutions on NVIDIA hardware.
>
> -- [Isaac ROS](https://developer.nvidia.com/isaac-ros)
The term `Isaac ROS` refer to the packages for ROS 2, instead of Isaac SDK. Isaac ROS should not be confused with the `ROS & ROS 2 Bridges` in Isaac Sim, or the `ROS Bridge` in Isaac SDK.
The packages (i.e., Isaac GEMs) are named as `Isaac ROS <Package_Name>`. Unfortunately, ambiguous terms such as `Isaac Elbrus` still exist ([source](https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_visual_slam)). Since the Elbrus package exist in both Isaac ROS and Isaac SDK, Elbrus should be refered to as `Isaac ROS Elbrus` for preciseness.
Before starting, please make sure your PC/Jetson hardware and software meet the [system requirements](https://nvidia-isaac-ros.github.io/getting_started/index.html#system-requirements). After checking the requirements, I suggest you start from the Nvblox tutorial below.
- (Isaac ROS) Nvblox [[github](https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_nvblox)]
> processes depth and pose to reconstruct a 3D scene in real-time and outputs a 2D costmap for Nav2. The costmap is used in planning during navigation as a vision-based solution to avoid obstacles.
>
> -- [Isaac ROS Nvblox](https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_nvblox)
You can quickly experience the power of Isaac ROS by simply following the [the quick start guide](https://nvidia-isaac-ros.github.io/repositories_and_packages/isaac_ros_nvblox/isaac_ros_nvblox/index.html#quickstart) of Nvblox.
- (Isaac ROS) NVIDIA Isaac for Transport for ROS (NITROS) [[github](https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_nitros)]
> the NVIDIA implementation of type adaption and negotiation for ROS2 that eliminates software/CPU overhead and improves performance of hardware acceleration.
>
> -- [Isaac ROS](https://developer.nvidia.com/isaac-ros) (slightly rephrased)
- [etc.](https://nvidia-isaac-ros.github.io/repositories_and_packages/index.html)
- Isaac SDK [[docs](https://docs.nvidia.com/isaac/archive/2021.1/doc/index.html)]
a toolkit for deploying GPU-accelerated algorithms on physical robots.
> a toolkit that includes building blocks and tools that accelerate robot developments that require the increased perception and navigation features enabled by AI.
>
> -- [NVIDIA Isaac SDK](https://developer.nvidia.com/isaac-sdk)
Personally, I suggest using Isaac ROS instead of Isaac SDK for simplicity. Since researchers/engineers working on robotics tend to be more familiar with the [Robot Operating System (ROS)](https://www.ros.org/) than the `bazel` command used in Isaac SDK. The Isaac GEMs and Isaac Applications included in Isaac SDK are also available in Isaac ROS.
> Isaac includes Isaac GEMs for both NVIDIA’s Isaac SDK Engine and ROS2. Isaac ROS has been more recently updated to contribute hardware acceleration to the growing ROS ecosystem. You can choose whichever one is more suitable for your project.
>
> -- [NVIDIA Forum Moderator](https://forums.developer.nvidia.com/t/is-isaac-depreciated/224402) (slightly rephrased)
The latest release of Isaac SDK is 2021.1, since the future roadmap of Isaac SDK is still under development ([source](https://forums.developer.nvidia.com/t/isaac-sdk-next-release/217841/2), [source](https://forums.developer.nvidia.com/t/is-isaac-depreciated/224402), [source](https://forums.developer.nvidia.com/t/isaac-sdk-is-dead/226267/2), [source](https://nvidia.slack.com/archives/CHG4MCWNQ/p1661260234425319?thread_ts=1658787137.725279&cid=CHG4MCWNQ)).
- Isaac GEMs
> a collection of high-performance algorithms, also called GEMs, to accelerate the development of challenging robotics applications.
>
> -- [NVIDIA Isaac SDK](https://docs.nvidia.com/isaac/archive/2021.1/doc/overview.html#isaac-gems)
- Isaac Applications
> provides various sample applications, which highlight features of Isaac SDK Engine or focus on the functionality of a particular Isaac SDK GEM.
>
> -- [NVIDIA Isaac SDK](https://docs.nvidia.com/isaac/archive/2021.1/doc/overview.html#isaac-applications)
- Isaac (Robotics) Engine
> a feature-rich framework for building modular robotics applications.
>
> -- [NVIDIA Isaac SDK](https://docs.nvidia.com/isaac/archive/2021.1/doc/overview.html#isaac-engine)
- Isaac Perceptor [[link](https://developer.nvidia.com/isaac/perceptor)]
Formerly _Isaac for AMRs_ and _Isaac AMR_.
> a collection of hardware-accelerated packages for visual AI, tailored for Autonomous Mobile Robot (AMR) to perceive, localize, and operate robustly in unstructured environments. Robotics software developers can now easily access turnkey AI-based perception capabilities, ensuring reliable operations and obstacle detection in complex scenarios.
>
> -- [NVIDIA Isaac Perceptor](https://developer.nvidia.com/isaac/perceptor)
- Isaac Nova Orin [[link](https://developer.nvidia.com/isaac/nova-orin)]
a reference architecture for AMRs based on NVIDIA Jetson AGX Orin.
> a state-of-the-art compute and sensor reference architecture to accelerate AMR development and deployment. It features up to two Jetson AGX Orin computers and a full sensor suite for next-gen AMRs that enable surround vision-based perception with lidar-based solutions.
>
> -- [NVIDIA Isaac Nova Orin](https://developer.nvidia.com/isaac/nova-orin)
- Nova Carter [[link](https://robotics.segway.com/nova-carter/)] [[spec](https://docs.nvidia.com/isaac/doc/novacarter.html)]
a reference design robot based on the Isaac Nova Orin architecture.
> a reference design robot that uses the Nova Orin compute and sensor architecture. It’s a complete robotics development platform that accelerates the development and deployment of next-generation Autonomous Mobile Robots (AMRs). You can learn more about it from our partner, Segway Robotics
>
> -- [NVIDIA Isaac Nova Orin](https://developer.nvidia.com/isaac/nova-orin)
- Isaac Manipulator [[link](https://developer.nvidia.com/isaac/manipulator)]
> a collection of foundation models and modular GPU-accelerated libraries that help build scalable and repeatable workflows for dynamic manipulation tasks by accelerating AI model training and task (re)programming. It’s revolutionizing how robotics software developers can leverage customized software components for specific tasks such as machine tending, assembly tasks, etc., enabling manipulation arms to seamlessly perceive and interact with their surroundings.
>
> -- [NVIDIA Isaac Manipulator](https://developer.nvidia.com/isaac/manipulator)
- Isaac Lab [[link](https://developer.nvidia.com/isaac-sim#isaac-lab)]
> a lightweight reference application built on the Isaac Sim platform specifically optimized for robot learning and is pivotal for robot foundation model training. Isaac Lab optimizes for reinforcement, imitation, and transfer learning, and is capable of training all types of robot embodiments including the Project GR00T foundation model for humanoids.
>
> -- [NVIDIA Isaac Lab](https://developer.nvidia.com/isaac-sim#isaac-lab)
- OSMO [[link](https://developer.nvidia.com/osmo)]
> a cloud-native workflow orchestration platform that lets you easily scale your workloads across distributed environments—from on-premises to private and public cloud. It provides a single pane of glass for scheduling complex multi-stage and multi-container heterogeneous computing workflows.
>
> -- [NVIDIA OSMO](https://developer.nvidia.com/osmo)
- Project GR00T [[link](https://developer.nvidia.com/project-GR00T)]
> a general-purpose foundation model that promises to transform humanoid robot learning in simulation and the real world. Trained in NVIDIA GPU-accelerated simulation, GR00T enables humanoid embodiments to learn from a handful of human demonstrations with imitation learning and NVIDIA Isaac Lab for reinforcement learning, as well as generating robot movements from video data. The GR00T model takes multimodal instructions and past interactions as input and produces the actions for the robot to execute.
>
> -- [NVIDIA Project GR00T](https://developer.nvidia.com/project-GR00T)
- cuOpt [[link](https://developer.nvidia.com/cuopt-logistics-optimization)][[docs](https://docs.nvidia.com/cuopt/index.html)][[ngc](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/cuopt/containers/cuopt)][[dli](https://courses.nvidia.com/courses/course-v1:DLI+T-FX-05+V1/)][[github](https://github.com/NVIDIA/cuOpt-Resources)]
a GPU-accelerated solver for [vehicle routing problem](https://en.wikipedia.org/wiki/Vehicle_routing_problem).
Formerly _ReOpt_.
> a GPU-accelerated logistics solver that uses heuristics and optimizations to calculate complex vehicle routing problem variants with a wide range of constraints.
>
> -- [NVIDIA cuOpt](https://courses.nvidia.com/courses/course-v1:DLI+T-FX-05+V1/)
- cuOpt for Isaac Sim [[docs](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/logistics_tutorial_cuopt.html)][[github](https://github.com/NVIDIA/cuOpt-Resources/tree/branch-22.12/cuopt-isaacsim)]
> a reference for the use of NVIDIA cuOpt to solve routing optimization problems in simulation.
>
> -- [NVIDIA Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/logistics_tutorial_cuopt.html)
- (Omniverse) Replicator [[link](https://developer.nvidia.com/nvidia-omniverse-platform/replicator)][[docs](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator.html)][[blog](https://developer.nvidia.com/blog/build-custom-synthetic-data-generation-pipelines-with-omniverse-replicator/)]
a synthetic data generation (SDG) toolkit based on Omniverse.
> an advanced, extensible SDK to generate physically accurate 3D synthetic data, and easily build custom synthetic data generation (SDG) tools to accelerate the training and accuracy of perception networks.
>
> -- [NVIDIA Replicator](https://developer.nvidia.com/nvidia-omniverse-platform/replicator)
- Isaac Sim Replicator [[docs](https://docs.omniverse.nvidia.com/isaacsim/latest/replicator_tutorials/index.html)]
> a collection of extensions, python APIs, workflows, and tools such as Replicator Composer that enable a variety of synthetic data generation tasks.
>
> -- [NVIDIA Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_replicator.html)
- (Omniverse) Replicator Insight [[link](https://developer.nvidia.com/nvidia-omniverse/replicator-insight-eap)]
> an app that enables developers to quickly view, navigate, and inspect their synthetically generated renders.
>
> -- [NVIDIA Replicator Insight](https://developer.nvidia.com/nvidia-omniverse/replicator-insight-eap)
- Omniverse Cloud [[link](https://www.nvidia.com/en-us/omniverse/cloud/)]
> a platform of APIs, SDKs, and services available within a full-stack cloud environment for enterprise developers to easily integrate Universal Scene Description (OpenUSD) and RTX rendering technologies into their 3D industrial digitalization applications.
>
> -- [NVIDIA Omniverse Cloud](https://www.nvidia.com/en-us/omniverse/cloud/)
Please [open an issue](https://github.com/j3soon/nvidia-isaac-summary/issues) if you have spotted any errors.
I have documented some bug fixes and workarounds for Isaac in the [j3soon/isaac-extended](https://github.com/j3soon/isaac-extended) repository. I recommend also checking out that repository for reference.
Last updated on 2024/04/10.
| 19,540 | Markdown | 97.691919 | 508 | 0.770317 |
j3soon/isaac-extended/README.md | # Isaac Extended
Some examples, notes, and patches not yet included in the latest Isaac release.
The description of each Isaac components can be found in the [j3soon/nvidia-isaac-summary](https://github.com/j3soon/nvidia-isaac-summary) repo.
## Set up
```sh
git clone https://github.com/j3soon/isaac-extended.git
cd isaac-extended
```
The following will assume you have cloned the directory and `cd` into it:
## Isaac Sim
### Conda issue on Linux
Reference: <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_python.html#advanced-running-with-anaconda>
Bug reports:
- [#3752249](https://github.com/j3soon/nvbugs/blob/master/3752249.md)
Solutions:
- Isaac Sim 2022.1.1
```sh
export ISAAC_SIM="$HOME/.local/share/ov/pkg/isaac_sim-2022.1.1"
cp $ISAAC_SIM/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh.bak
cp ./isaac_sim-2022.1.1-patch/linux/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh
```
- Isaac Sim 2022.2.0
```sh
export ISAAC_SIM="$HOME/.local/share/ov/pkg/isaac_sim-2022.2.0"
cp $ISAAC_SIM/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh.bak
cp ./isaac_sim-2022.2.0-patch/linux/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh
```
- Isaac Sim 2022.2.1
```sh
export ISAAC_SIM="$HOME/.local/share/ov/pkg/isaac_sim-2022.2.1"
cp $ISAAC_SIM/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh.bak
cp ./isaac_sim-2022.2.1-patch/linux/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh
```
- Isaac Sim 2023.1.0
```sh
export ISAAC_SIM="$HOME/.local/share/ov/pkg/isaac_sim-2023.1.0"
cp $ISAAC_SIM/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh.bak
cp ./isaac_sim-2023.1.0-patch/linux/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh
```
### Conda issue on Windows
Bug reports:
- [#3837533](https://github.com/j3soon/nvbugs/blob/master/3837533.md)
- [#3837573](https://github.com/j3soon/nvbugs/blob/master/3837573.md)
- [#3837658](https://github.com/j3soon/nvbugs/blob/master/3837658.md)
Solutions:
- Isaac Sim 2022.1.1
```sh
set ISAAC_SIM="%LOCALAPPDATA%\ov\pkg\isaac_sim-2022.1.1"
copy .\isaac_sim-2022.1.1-patch\windows\setup_conda_env.bat %ISAAC_SIM%\setup_conda_env.bat
```
and make sure to run the following after activating the conda environment:
```sh
call setup_conda_env.bat
```
- If you need a patch for other Isaac Sim versions, please [open an issue](https://github.com/j3soon/isaac-extended/issues).
- For other package version issues, please refer to the bug reports.
### Docker Container issue
Bug reports:
- [#4063971](https://github.com/j3soon/nvbugs/blob/master/4063971.md)
Solution:
- Run the following command immediately after starting a `nvcr.io/nvidia/isaac-sim:2022.2.1` container:
```sh
rm /etc/vulkan/icd.d/nvidia_icd.json
```
### Docker Container with Display
Reference: <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_container.html>
The original docker command is:
```sh
docker run --name isaac-sim --entrypoint bash -it --gpus all -e "ACCEPT_EULA=Y" --rm --network=host \
-e "PRIVACY_CONSENT=Y" \
-v ~/docker/isaac-sim/cache/kit:/isaac-sim/kit/cache:rw \
-v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \
-v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \
-v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \
-v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \
-v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \
-v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \
-v ~/docker/isaac-sim/documents:/root/Documents:rw \
nvcr.io/nvidia/isaac-sim:2023.1.1
```
The modified docker command with display is:
```sh
xhost +local:docker
docker run --name isaac-sim --entrypoint bash -it --gpus all -e "ACCEPT_EULA=Y" --rm --network=host \
-e "PRIVACY_CONSENT=Y" \
-v ~/docker/isaac-sim/cache/kit:/isaac-sim/kit/cache:rw \
-v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \
-v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \
-v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \
-v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \
-v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \
-v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \
-v ~/docker/isaac-sim/documents:/root/Documents:rw \
-v $(pwd):/workspace \
-v /tmp/.X11-unix:/tmp/.X11-unix \
-e DISPLAY=$DISPLAY \
nvcr.io/nvidia/isaac-sim:2023.1.1
```
and run `/isaac-sim/runapp.sh` inside the container to start Isaac Sim.
### Running on Omniverse Farm
Please refer to <https://github.com/j3soon/omni-farm-isaac>.
### Minors
Bug reports:
- [#4035662](https://github.com/j3soon/nvbugs/blob/master/4035662.md)
## Nucleus
### Installation
Many users often forget to install Nucleus before running Isaac Sim examples.
Please follow [the official installation instructions](https://docs.omniverse.nvidia.com/nucleus/latest/workstation/installation.html#install-using-omniverse-launcher) carefully.
Or follow our installation guide below:
1. Open Omniverse Launcher, go to the `Nucleus` tab, and click `Add Local Nucleus Service`.

2. Use the default `DATA PATH` and click `NEXT`.

3. Create a local admin account for Nucleus by filling out the form and click `COMPLETE SETUP`.

4. Wait for the installation to finish.

5. Confirm that `Local Nucleus Service` is displayed instead of the original `Add Local Nucleus Service`, indicating that the installation is successful.

6. Launch Isaac Sim and click `Content > Omniverse > localhost` in the bottom tab.

7. You should see a hint to login from your web browser.

8. A new tab should be opened in your web browser. Login with the account you created in step 3.

If you have trouble logging in, simply create a new account by clicking `Create Account`.

9. After logging in, you should see the following page. You can close the tab now.

10. Go back to Isaac Sim and click `Content > Omniverse > localhost` again. You should see the built-in folders (`Library`, `NVIDIA`, `Projects`, `Users`).

### Troubleshooting
In some cases, Nucleus may not be running properly. You can check the status of the Nucleus process by visiting the `Settings` page of Nucleus:
1. Go to the Nucleus tab and click `Settings`.

2. A new tab should be opened in your web browser. Visit the `Apps` tab and make sure that all Apps are currently running. If not, click `Restart all` to start them. If your disk is almost full, you may want to visit the `Cache` tab and clear the cache.

3. Open Isaac Sim and click `Content > Omniverse > localhost`, Nucleus may ask you to login. After that, you should see the built-in folders (`Library`, `NVIDIA`, `Projects`, `Users`).

4. As a side note, you may also need to re-login to the Omniverse Launcher after some time.

## Isaac ROS
### isaac_ros_common issue
Bug reports:
- [#4113333](https://github.com/j3soon/nvbugs/blob/master/4113333.md)
Solution:
- Change repo remote to <https://github.com/j3soon/isaac_ros_common> and reset to remote HEAD.
### Jetson Board Setup
- Make sure to flash the supported Jetpack version: <https://github.com/NVIDIA-ISAAC-ROS/.github/blob/main/profile/hardware-setup.md>.
- A large enough MicroSD Card seem to be able to replace the NVMe SSD card mentioned here: <https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_common/blob/main/docs/dev-env-setup_jetson.md>.
| 8,259 | Markdown | 34.913043 | 253 | 0.722848 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/setup.py | """Installation script for the 'isaacgymenvs' python package."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from setuptools import setup, find_packages
import os
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
"protobuf==3.20.1",
"omegaconf==2.1.1",
"hydra-core==1.1.1",
"redis==3.5.3", # needed by Ray on Windows
"rl-games==1.5.2"
]
# Installation operation
setup(
name="omniisaacgymenvs",
author="NVIDIA",
version="1.1.0",
description="RL environments for robot learning in NVIDIA Isaac Sim.",
keywords=["robotics", "rl"],
include_package_data=True,
install_requires=INSTALL_REQUIRES,
packages=find_packages("."),
classifiers=["Natural Language :: English", "Programming Language :: Python :: 3.7, 3.8"],
zip_safe=False,
)
# EOF
| 890 | Python | 24.457142 | 94 | 0.678652 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/README.md | # UR10 Reacher Reinforcement Learning Sim2Real Environment for Omniverse Isaac Gym/Sim
This repository adds a UR10Reacher environment based on [OmniIsaacGymEnvs](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs) (commit [d0eaf2e](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/tree/d0eaf2e7f1e1e901d62e780392ca77843c08eb2c)), and includes Sim2Real code to control a real-world [UR10](https://www.universal-robots.com/products/ur10-robot/) with the policy learned by reinforcement learning in Omniverse Isaac Gym/Sim.
We target Isaac Sim 2022.1.1 and tested the RL code on Windows 10 and Ubuntu 18.04. The Sim2Real code is tested on Linux and a real UR5 CB3 (since we don't have access to a real UR10).
This repo is compatible with [OmniIsaacGymEnvs-DofbotReacher](https://github.com/j3soon/OmniIsaacGymEnvs-DofbotReacher).
## Preview


## Installation
Prerequisites:
- Before starting, please make sure your hardware and software meet the [system requirements](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/requirements.html#system-requirements).
- [Install Omniverse Isaac Sim 2022.1.1](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html) (Must setup Cache and Nucleus)
- You may try out newer versions of Isaac Sim along with [their corresponding patch](https://github.com/j3soon/isaac-extended#conda-issue-on-linux), but it is not guaranteed to work.
- Double check that Nucleus is correctly installed by [following these steps](https://github.com/j3soon/isaac-extended#nucleus).
- Your computer & GPU should be able to run the Cartpole example in [OmniIsaacGymEnvs](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs)
- (Optional) [Set up a UR3/UR5/UR10](https://www.universal-robots.com/products/) in the real world
Make sure to install Isaac Sim in the default directory and clone this repository to the home directory. Otherwise, you will encounter issues if you didn't modify the commands below accordingly.
We will use Anaconda to manage our virtual environment:
1. Clone this repository:
- Linux
```sh
cd ~
git clone https://github.com/j3soon/OmniIsaacGymEnvs-UR10Reacher.git
```
- Windows
```sh
cd %USERPROFILE%
git clone https://github.com/j3soon/OmniIsaacGymEnvs-UR10Reacher.git
```
2. Generate [instanceable](https://docs.omniverse.nvidia.com/isaacsim/latest/isaac_gym_tutorials/tutorial_gym_instanceable_assets.html) UR10 assets for training:
[Launch the Script Editor](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gui_interactive_scripting.html#script-editor) in Isaac Sim. Copy the content in `omniisaacgymenvs/utils/usd_utils/create_instanceable_ur10.py` and execute it inside the Script Editor window. Wait until you see the text `Done!`.
3. (Optional) [Install ROS Melodic for Ubuntu](https://wiki.ros.org/melodic/Installation/Ubuntu) and [Set up a catkin workspace for UR10](https://github.com/UniversalRobots/Universal_Robots_ROS_Driver/blob/master/README.md).
Please change all `catkin_ws` in the commands to `ur_ws`, and make sure you can control the robot with `rqt-joint-trajectory-controller`.
ROS support is not tested on Windows.
4. [Download and Install Anaconda](https://www.anaconda.com/products/distribution#Downloads).
```sh
# For 64-bit Linux (x86_64/x64/amd64/intel64)
wget https://repo.anaconda.com/archive/Anaconda3-2022.10-Linux-x86_64.sh
bash Anaconda3-2022.10-Linux-x86_64.sh
```
For Windows users, make sure to use `Anaconda Prompt` instead of `Anaconda Powershell Prompt`, `Command Prompt`, or `Powershell` for the following commands.
5. Patch Isaac Sim 2022.1.1
- Linux
```sh
export ISAAC_SIM="$HOME/.local/share/ov/pkg/isaac_sim-2022.1.1"
cp $ISAAC_SIM/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh.bak
cp ~/OmniIsaacGymEnvs-UR10Reacher/isaac_sim-2022.1.1-patch/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh
```
- Windows
```sh
set ISAAC_SIM="%LOCALAPPDATA%\ov\pkg\isaac_sim-2022.1.1"
copy %USERPROFILE%\OmniIsaacGymEnvs-UR10Reacher\isaac_sim-2022.1.1-patch\windows\setup_conda_env.bat %ISAAC_SIM%\setup_conda_env.bat
```
6. [Set up conda environment for Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_python.html#advanced-running-with-anaconda)
- Linux
```sh
# conda remove --name isaac-sim --all
export ISAAC_SIM="$HOME/.local/share/ov/pkg/isaac_sim-2022.1.1"
cd $ISAAC_SIM
conda env create -f environment.yml
conda activate isaac-sim
cd ~/OmniIsaacGymEnvs-UR10Reacher
pip install -e .
# Below is optional
pip install pyyaml rospkg
```
- Windows
```sh
# conda remove --name isaac-sim --all
set ISAAC_SIM="%LOCALAPPDATA%\ov\pkg\isaac_sim-2022.1.1"
cd %ISAAC_SIM%
conda env create -f environment.yml
conda activate isaac-sim
:: Fix incorrect importlib-metadata version (isaac-sim 2022.1.1)
pip install importlib-metadata==4.11.4
cd %USERPROFILE%\OmniIsaacGymEnvs-UR10Reacher
pip install -e .
:: Fix incorrect torch version (isaac-sim 2022.1.1)
conda install -y pytorch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0 -c pytorch
```
7. Activate conda & ROS environment
- Linux
```sh
export ISAAC_SIM="$HOME/.local/share/ov/pkg/isaac_sim-2022.1.1"
cd $ISAAC_SIM
conda activate isaac-sim
source setup_conda_env.sh
# Below are optional
cd ~/ur_ws
source devel/setup.bash # or setup.zsh if you're using zsh
```
- Windows
```sh
set ISAAC_SIM="%LOCALAPPDATA%\ov\pkg\isaac_sim-2022.1.1"
cd %ISAAC_SIM%
conda activate isaac-sim
call setup_conda_env.bat
```
Please note that you should execute the commands in Step 7 for every new shell.
For Windows users, replace `~` to `%USERPROFILE%` for all the following commands.
## Dummy Policy
This is a sample to make sure you have setup the environment correctly. You should see a single UR10 in Isaac Sim.
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
python omniisaacgymenvs/scripts/dummy_ur10_policy.py task=UR10Reacher test=True num_envs=1
```
## Training
You can launch the training in `headless` mode as follows:
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
python omniisaacgymenvs/scripts/rlgames_train.py task=UR10Reacher headless=True
```
The number of environments is set to 512 by default. If your GPU has small memory, you can decrease the number of environments by changing the arguments `num_envs` as below:
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
python omniisaacgymenvs/scripts/rlgames_train.py task=UR10Reacher headless=True num_envs=512
```
You can also skip training by downloading the pre-trained model checkpoint by:
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
wget https://github.com/j3soon/OmniIsaacGymEnvs-UR10Reacher/releases/download/v1.0.0/runs.zip
unzip runs.zip
# For Sim2Real only, requires editing config file as mentioned in the Sim2Real section
wget https://github.com/j3soon/OmniIsaacGymEnvs-UR10Reacher/releases/download/v1.0.0/runs_safety.zip
unzip runs_safety.zip
```
The learning curve of the pre-trained model (normal vs. safety):


## Testing
Make sure you have model checkpoints at `~/OmniIsaacGymEnvs-UR10Reacher/runs`, you can check it with the following command:
```sh
ls ~/OmniIsaacGymEnvs-UR10Reacher/runs/UR10Reacher/nn/
```
You can visualize the learned policy by the following command:
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
python omniisaacgymenvs/scripts/rlgames_train.py task=UR10Reacher test=True num_envs=512 checkpoint=./runs/UR10Reacher/nn/UR10Reacher.pth
```
Likewise, you can decrease the number of environments by modifying the parameter `num_envs=512`.
## Sim2Real
It is important to make sure that you know how to safely control your robot by reading the manual. For additional safety, please add the following configurations:
1. Set `General Limits` to `Very restricted`

2. Set `Joint Limits` according to your robot mounting point and the environment.

3. Set `Boundaries` according to the robot's environment.

Play with the robot and make sure it won't hit anything under the current configuration. If anything goes wrong, press the red `EMERGENCY-STOP` button.
In the following, we'll assume you have the same mounting direction and workspace as the preview GIF. If you have a different setup, you need to modify the code. Please [open an issue](https://github.com/j3soon/OmniIsaacGymEnvs-UR10Reacher/issues) if you need more information on where to modify.
We'll use ROS to control the real-world robot. Run the following command in a Terminal: (Replace `192.168.50.50` to your robot's IP address)
```sh
roslaunch ur_robot_driver ur5_bringup.launch robot_ip:=192.168.50.50 headless_mode:=true
```
Edit `omniisaacgymenvs/cfg/task/UR10Reacher.yaml`. Set `sim2real.enabled` and `safety.enabled` to `True`:
```yaml
sim2real:
enabled: True
fail_quietely: False
verbose: False
safety: # Reduce joint limits during both training & testing
enabled: True
```
Now you can control the real-world UR10 in real-time by the following command:
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
python omniisaacgymenvs/scripts/rlgames_train.py task=UR10Reacher test=True num_envs=1 checkpoint=./runs/UR10Reacher/nn/UR10Reacher.pth
# or if you want to use the pre-trained checkpoint
python omniisaacgymenvs/scripts/rlgames_train.py task=UR10Reacher test=True num_envs=1 checkpoint=./runs_safety/UR10Reacher/nn/UR10Reacher.pth
```
## Demo
We provide an interactable demo based on the `UR10Reacher` RL example. In this demo, you can click on any of
the UR10 in the scene to manually control the robot with your keyboard as follows:
- `Q`/`A`: Control Joint 0.
- `W`/`S`: Control Joint 1.
- `E`/`D`: Control Joint 2.
- `R`/`F`: Control Joint 3.
- `T`/`G`: Control Joint 4.
- `Y`/`H`: Control Joint 5.
- `ESC`: Unselect a selected UR10 and yields manual control
Launch this demo with the following command. Note that this demo limits the maximum number of UR10 in the scene to 128.
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
python omniisaacgymenvs/scripts/rlgames_play.py task=UR10Reacher num_envs=64
```
## Running in Docker
If you have a [NVIDIA Enterprise subscription](https://docs.omniverse.nvidia.com/prod_nucleus/prod_nucleus/enterprise/installation/planning.html), you can run all services with Docker Compose.
For users without a subscription, you can pull the [Isaac Docker image](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim), but should still install Omniverse Nucleus beforehand. (only Isaac itself is dockerized)
Follow [this tutorial](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_container.html#isaac-sim-setup-remote-headless-container) to generate your NGC API Key, and make sure you can access Isaac with Omniverse Streaming Client, WebRTC, or WebSocket. After that, exit the Docker container.
Please note that you should generate instanceable assets beforehand as mentioned in the [Installation](#installation) section.
We will now set up the environment inside Docker:
1. Launch an Isaac Container:
```sh
docker run --name isaac-sim --entrypoint bash -it --gpus all -e "ACCEPT_EULA=Y" --rm --network=host \
-v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \
-v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \
-v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \
-v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \
-v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \
-v ~/docker/isaac-sim/config:/root/.nvidia-omniverse/config:rw \
-v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \
-v ~/docker/isaac-sim/documents:/root/Documents:rw \
nvcr.io/nvidia/isaac-sim:2022.1.1
```
2. Install common tools:
```sh
apt update && apt install -y git wget vim
```
3. Clone this repository:
```sh
cd ~
git clone https://github.com/j3soon/OmniIsaacGymEnvs-UR10Reacher.git
```
4. [Download and Install Anaconda](https://www.anaconda.com/products/distribution#Downloads).
```sh
# For 64-bit (x86_64/x64/amd64/intel64)
wget https://repo.anaconda.com/archive/Anaconda3-2022.10-Linux-x86_64.sh
bash Anaconda3-2022.10-Linux-x86_64.sh -b -p $HOME/anaconda3
```
5. Patch Isaac Sim 2022.1.1
```sh
export ISAAC_SIM="/isaac-sim"
cp $ISAAC_SIM/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh.bak
cp ~/OmniIsaacGymEnvs-UR10Reacher/isaac_sim-2022.1.1-patch/setup_python_env.sh $ISAAC_SIM/setup_python_env.sh
```
6. [Set up conda environment for Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_python.html#advanced-running-with-anaconda)
```sh
source ~/anaconda3/etc/profile.d/conda.sh
# conda remove --name isaac-sim --all
export ISAAC_SIM="/isaac-sim"
cd $ISAAC_SIM
conda env create -f environment.yml
conda activate isaac-sim
cd ~/OmniIsaacGymEnvs-UR10Reacher
pip install -e .
```
7. Activate conda environment
```sh
source ~/anaconda3/etc/profile.d/conda.sh
export ISAAC_SIM="/isaac-sim"
cd $ISAAC_SIM
conda activate isaac-sim
source setup_conda_env.sh
./vulkan_check.sh
```
We can now train a RL policy in this container:
```sh
cd ~/OmniIsaacGymEnvs-UR10Reacher
python omniisaacgymenvs/scripts/rlgames_train.py task=UR10Reacher headless=True num_envs=512
```
Make sure to copy the learned weights to a mounted volume before exiting the container, otherwise it will be deleted:
```sh
# In container
cp -r ~/OmniIsaacGymEnvs-UR10Reacher/runs ~/Documents/runs
# In host
ls ~/docker/isaac-sim/documents/
```
You can watch the training progress with:
```sh
docker ps # Observe Container ID
docker exec -it <CONTAINER_ID> /bin/bash
conda activate isaac-sim
cd ~/OmniIsaacGymEnvs-UR10Reacher
tensorboard --logdir=./runs
```
Currently we do not support running commands that requires visualization (Testing, Sim2Real, etc.) in Docker. Since I haven't figured out how to make Vulkan render a Isaac window inside a container yet. Alternatively, it may be possible to add `headless=True` and view them in Omniverse Streaming Client, WebRTC, or WebSocket, but I haven't tested this by myself.
## Acknowledgement
This project has been made possible through the support of [ElsaLab][elsalab] and [NVIDIA AI Technology Center (NVAITC)][nvaitc].
I would also like to express my gratitude to [@tony2guo](https://github.com/tony2guo) for his invaluable assistance in guiding me through the setup process of the real-world UR10.
For a complete list of contributors to the code of this repository, please visit the [contributor list](https://github.com/j3soon/OmniIsaacGymEnvs-UR10Reacher/graphs/contributors).
[][elsalab]
[][nvaitc]
[elsalab]: https://github.com/elsa-lab
[nvaitc]: https://github.com/NVAITC
Disclaimer: this is not an official NVIDIA product.
> **Note**: below are the original README of [OmniIsaacGymEnvs](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs).
# Omniverse Isaac Gym Reinforcement Learning Environments for Isaac Sim
### About this repository
This repository contains Reinforcement Learning examples that can be run with the latest release of [Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html). RL examples are trained using PPO from [rl_games](https://github.com/Denys88/rl_games) library and examples are built on top of Isaac Sim's `omni.isaac.core` and `omni.isaac.gym` frameworks.
<img src="https://user-images.githubusercontent.com/34286328/171454189-6afafbff-bb61-4aac-b518-24646007cb9f.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184172037-cdad9ee8-f705-466f-bbde-3caa6c7dea37.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/171454182-0be1b830-bceb-4cfd-93fb-e1eb8871ec68.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/171454193-e027885d-1510-4ef4-b838-06b37f70c1c7.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184174894-03767aa0-936c-4bfe-bbe9-a6865f539bb4.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184168200-152567a8-3354-4947-9ae0-9443a56fee4c.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184176312-df7d2727-f043-46e3-b537-48a583d321b9.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184178817-9c4b6b3c-c8a2-41fb-94be-cfc8ece51d5d.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/171454160-8cb6739d-162a-4c84-922d-cda04382633f.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/171454176-ce08f6d0-3087-4ecc-9273-7d30d8f73f6d.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184170040-3f76f761-e748-452e-b8c8-3cc1c7c8cb98.gif" width="614" height="307"/>
### Installation
Follow the Isaac Sim [documentation](https://docs.omniverse.nvidia.com/isaacsim/latest/install_workstation.html) to install the latest Isaac Sim release.
*Examples in this repository rely on features from the most recent Isaac Sim release. Please make sure to update any existing Isaac Sim build to the latest release version, 2022.1.1, to ensure examples work as expected.*
Once installed, this repository can be used as a python module, `omniisaacgymenvs`, with the python executable provided in Isaac Sim.
To install `omniisaacgymenvs`, first clone this repository:
```bash
git clone https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs.git
```
Once cloned, locate the [python executable in Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html). By default, this should be `python.sh`. We will refer to this path as `PYTHON_PATH`.
To set a `PYTHON_PATH` variable in the terminal that links to the python executable, we can run a command that resembles the following. Make sure to update the paths to your local path.
```
For Linux: alias PYTHON_PATH=~/.local/share/ov/pkg/isaac_sim-*/python.sh
For Windows: doskey PYTHON_PATH=C:\Users\user\AppData\Local\ov\pkg\isaac_sim-*\python.bat $*
```
Install `omniisaacgymenvs` as a python module for `PYTHON_PATH`:
```bash
PYTHON_PATH -m pip install -e .
```
### Running the examples
*Note: All commands should be executed from `omniisaacgymenvs/omniisaacgymenvs`.*
To train your first policy, run:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Cartpole
```
You should see an Isaac Sim window pop up. Once Isaac Sim initialization completes, the Cartpole scene will be constructed and simulation will start running automatically. The process will terminate once training finishes.
Here's another example - Ant locomotion - using the multi-threaded training script:
```bash
PYTHON_PATH scripts/rlgames_train_mt.py task=Ant
```
Note that by default, we show a Viewport window with rendering, which slows down training. You can choose to close the Viewport window during training for better performance. The Viewport window can be re-enabled by selecting `Window > Viewport` from the top menu bar.
To achieve maximum performance, you can launch training in `headless` mode as follows:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant headless=True
```
#### A Note on the Startup Time of the Simulation
Some of the examples could take a few minutes to load because the startup time scales based on the number of environments. The startup time will continually
be optimized in future releases.
### Loading trained models // Checkpoints
Checkpoints are saved in the folder `runs/EXPERIMENT_NAME/nn` where `EXPERIMENT_NAME`
defaults to the task name, but can also be overridden via the `experiment` argument.
To load a trained checkpoint and continue training, use the `checkpoint` argument:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=runs/Ant/nn/Ant.pth
```
To load a trained checkpoint and only perform inference (no training), pass `test=True`
as an argument, along with the checkpoint name. To avoid rendering overhead, you may
also want to run with fewer environments using `num_envs=64`:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=runs/Ant/nn/Ant.pth test=True num_envs=64
```
Note that if there are special characters such as `[` or `=` in the checkpoint names,
you will need to escape them and put quotes around the string. For example,
`checkpoint="runs/Ant/nn/last_Antep\=501rew\[5981.31\].pth"`
We provide pre-trained checkpoints on the [Nucleus](https://docs.omniverse.nvidia.com/nucleus/latest/index.html) server under `Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints`. Run the following command
to launch inference with pre-trained checkpoint:
Localhost (To set up localhost, please refer to the [Isaac Sim installation guide](https://docs.omniverse.nvidia.com/isaacsim/latest/install_workstation.html)):
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth test=True num_envs=64
```
Production server:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth test=True num_envs=64
```
When running with a pre-trained checkpoint for the first time, we will automatically download the checkpoint file to `omniisaacgymenvs/checkpoints`. For subsequent runs, we will re-use the file that has already been downloaded, and will not overwrite existing checkpoints with the same name in the `checkpoints` folder.
## Training Scripts
All scripts provided in `omniisaacgymenvs/scripts` can be launched directly with `PYTHON_PATH`.
To test out a task without RL in the loop, run the random policy script with:
```bash
PYTHON_PATH scripts/random_policy.py task=Cartpole
```
This script will sample random actions from the action space and apply these actions to your task without running any RL policies. Simulation should start automatically after launching the script, and will run indefinitely until terminated.
To run a simple form of PPO from `rl_games`, use the single-threaded training script:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Cartpole
```
This script creates an instance of the PPO runner in `rl_games` and automatically launches training and simulation. Once training completes (the total number of iterations have been reached), the script will exit. If running inference with `test=True checkpoint=<path/to/checkpoint>`, the script will run indefinitely until terminated. Note that this script will have limitations on interaction with the UI.
Lastly, we provide a multi-threaded training script that executes the RL policy on a separate thread than the main thread used for simulation and rendering:
```bash
PYTHON_PATH scripts/rlgames_train_mt.py task=Cartpole
```
This script uses the same RL Games PPO policy as the above, but runs the RL loop on a new thread. Communication between the RL thread and the main thread happens on threaded Queues. Simulation will start automatically, but the script will **not** exit when training terminates, except when running in headless mode. Simulation will stop when training completes or can be stopped by clicking on the Stop button in the UI. Training can be launched again by clicking on the Play button. Similarly, if running inference with `test=True checkpoint=<path/to/checkpoint>`, simulation will run until the Stop button is clicked, or the script will run indefinitely until the process is terminated.
### Configuration and command line arguments
We use [Hydra](https://hydra.cc/docs/intro/) to manage the config.
Common arguments for the training scripts are:
* `task=TASK` - Selects which task to use. Any of `AllegroHand`, `Ant`, `Anymal`, `AnymalTerrain`, `BallBalance`, `Cartpole`, `Crazyflie`, `FrankaCabinet`, `Humanoid`, `Ingenuity`, `Quadcopter`, `ShadowHand`, `ShadowHandOpenAI_FF`, `ShadowHandOpenAI_LSTM` (these correspond to the config for each environment in the folder `omniisaacgymenvs/cfg/task`)
* `train=TRAIN` - Selects which training config to use. Will automatically default to the correct config for the environment (ie. `<TASK>PPO`).
* `num_envs=NUM_ENVS` - Selects the number of environments to use (overriding the default number of environments set in the task config).
* `seed=SEED` - Sets a seed value for randomization, and overrides the default seed in the task config
* `pipeline=PIPELINE` - Which API pipeline to use. Defaults to `gpu`, can also set to `cpu`. When using the `gpu` pipeline, all data stays on the GPU. When using the `cpu` pipeline, simulation can run on either CPU or GPU, depending on the `sim_device` setting, but a copy of the data is always made on the CPU at every step.
* `sim_device=SIM_DEVICE` - Device used for physics simulation. Set to `gpu` (default) to use GPU and to `cpu` for CPU.
* `device_id=DEVICE_ID` - Device ID for GPU to use for simulation and task. Defaults to `0`. This parameter will only be used if simulation runs on GPU.
* `rl_device=RL_DEVICE` - Which device / ID to use for the RL algorithm. Defaults to `cuda:0`, and follows PyTorch-like device syntax.
* `test=TEST`- If set to `True`, only runs inference on the policy and does not do any training.
* `checkpoint=CHECKPOINT_PATH` - Path to the checkpoint to load for training or testing.
* `headless=HEADLESS` - Whether to run in headless mode.
* `experiment=EXPERIMENT` - Sets the name of the experiment.
* `max_iterations=MAX_ITERATIONS` - Sets how many iterations to run for. Reasonable defaults are provided for the provided environments.
Hydra also allows setting variables inside config files directly as command line arguments. As an example, to set the minibatch size for a rl_games training run, you can use `train.params.config.minibatch_size=64`. Similarly, variables in task configs can also be set. For example, `task.env.episodeLength=100`.
#### Hydra Notes
Default values for each of these are found in the `omniisaacgymenvs/cfg/config.yaml` file.
The way that the `task` and `train` portions of the config works are through the use of config groups.
You can learn more about how these work [here](https://hydra.cc/docs/tutorials/structured_config/config_groups/)
The actual configs for `task` are in `omniisaacgymenvs/cfg/task/<TASK>.yaml` and for `train` in `omniisaacgymenvs/cfg/train/<TASK>PPO.yaml`.
In some places in the config you will find other variables referenced (for example,
`num_actors: ${....task.env.numEnvs}`). Each `.` represents going one level up in the config hierarchy.
This is documented fully [here](https://omegaconf.readthedocs.io/en/latest/usage.html#variable-interpolation).
### Tensorboard
Tensorboard can be launched during training via the following command:
```bash
PYTHON_PATH -m tensorboard.main --logdir runs/EXPERIMENT_NAME/summaries
```
## WandB support
You can run (WandB)[https://wandb.ai/] with OmniIsaacGymEnvs by setting `wandb_activate=True` flag from the command line. You can set the group, name, entity, and project for the run by setting the `wandb_group`, `wandb_name`, `wandb_entity` and `wandb_project` arguments. Make sure you have WandB installed in the Isaac Sim Python executable with `PYTHON_PATH -m pip install wandb` before activating.
## Tasks
Source code for tasks can be found in `omniisaacgymenvs/tasks`.
Each task follows the frameworks provided in `omni.isaac.core` and `omni.isaac.gym` in Isaac Sim.
Refer to [docs/framework.md](docs/framework.md) for how to create your own tasks.
Full details on each of the tasks available can be found in the [RL examples documentation](docs/rl_examples.md).
## Demo
We provide an interactable demo based on the `AnymalTerrain` RL example. In this demo, you can click on any of
the ANYmals in the scene to go into third-person mode and manually control the robot with your keyboard as follows:
- `Up Arrow`: Forward linear velocity command
- `Down Arrow`: Backward linear velocity command
- `Left Arrow`: Leftward linear velocity command
- `Right Arrow`: Rightward linear velocity command
- `Z`: Counterclockwise yaw angular velocity command
- `X`: Clockwise yaw angular velocity command
- `C`: Toggles camera view between third-person and scene view while maintaining manual control
- `ESC`: Unselect a selected ANYmal and yields manual control
Launch this demo with the following command. Note that this demo limits the maximum number of ANYmals in the scene to 128.
```
PYTHON_PATH scripts/rlgames_play.py task=AnymalTerrain num_envs=64 checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal_terrain.pth
```
<img src="https://user-images.githubusercontent.com/34286328/184688654-6e7899b2-5847-4184-8944-2a96b129b1ff.gif" width="600" height="300"/>
## A note about Force Sensors
Force sensors are supported in Isaac Sim and OIGE via the `ArticulationView` class. Sensor readings can be retrieved using `get_force_sensor_forces()` API, as shown in the Ant/Humanoid Locomotion task, as well as in the Ball Balance task. Please note that there is currently a known bug regarding force sensors in Omniverse Physics. Transforms of force sensors (i.e. their local poses) are set in the actor space of the Articulation instead of the body space, which is the expected behaviour. We will be fixing this in the coming release.
| 30,124 | Markdown | 50.672384 | 688 | 0.763478 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/envs/vec_env_rlgames_mt.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omni.isaac.gym.vec_env import VecEnvMT
from omni.isaac.gym.vec_env import TaskStopException
from .vec_env_rlgames import VecEnvRLGames
import torch
import numpy as np
# VecEnv Wrapper for RL training
class VecEnvRLGamesMT(VecEnvRLGames, VecEnvMT):
def _parse_data(self, data):
self._obs = data["obs"].to(self._task.rl_device).clone()
self._rew = data["rew"].to(self._task.rl_device).clone()
self._states = torch.clamp(data["states"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._resets = data["reset"].to(self._task.rl_device).clone()
self._extras = data["extras"].copy()
def step(self, actions):
if self._stop:
raise TaskStopException()
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).clone()
if self._task.randomize_actions:
actions = self._task._dr_randomizer.apply_actions_randomization(actions=actions, reset_buf=self._task.reset_buf)
self.send_actions(actions)
data = self.get_data()
if self._task.randomize_observations:
self._obs = self._task._dr_randomizer.apply_observations_randomization(observations=self._obs, reset_buf=self._task.reset_buf)
self._obs = torch.clamp(self._obs, -self._task.clip_obs, self._task.clip_obs)
obs_dict = {}
obs_dict["obs"] = self._obs
obs_dict["states"] = self._states
return obs_dict, self._rew, self._resets, self._extras
| 3,101 | Python | 42.69014 | 138 | 0.714931 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/envs/vec_env_rlgames.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omni.isaac.gym.vec_env import VecEnvBase
import torch
import numpy as np
from datetime import datetime
# VecEnv Wrapper for RL training
class VecEnvRLGames(VecEnvBase):
def _process_data(self):
self._obs = torch.clamp(self._obs, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._rew = self._rew.to(self._task.rl_device).clone()
self._states = torch.clamp(self._states, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._resets = self._resets.to(self._task.rl_device).clone()
self._extras = self._extras.copy()
def set_task(
self, task, backend="numpy", sim_params=None, init_sim=True
) -> None:
super().set_task(task, backend, sim_params, init_sim)
self.num_states = self._task.num_states
self.state_space = self._task.state_space
def step(self, actions):
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone()
if self._task.randomize_actions:
actions = self._task._dr_randomizer.apply_actions_randomization(actions=actions, reset_buf=self._task.reset_buf)
self._task.pre_physics_step(actions)
for _ in range(self._task.control_frequency_inv):
self._world.step(render=self._render)
self.sim_frame_count += 1
self._obs, self._rew, self._resets, self._extras = self._task.post_physics_step()
if self._task.randomize_observations:
self._obs = self._task._dr_randomizer.apply_observations_randomization(observations=self._obs, reset_buf=self._task.reset_buf)
self._states = self._task.get_states()
self._process_data()
obs_dict = {"obs": self._obs, "states": self._states}
return obs_dict, self._rew, self._resets, self._extras
def reset(self):
""" Resets the task and applies default zero actions to recompute observations and states. """
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{now}] Running RL reset")
self._task.reset()
actions = torch.zeros((self.num_envs, self._task.num_actions), device=self._task.device)
obs_dict, _, _, _ = self.step(actions)
return obs_dict
| 3,881 | Python | 42.133333 | 138 | 0.69312 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/allegro_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.tasks.shared.in_hand_manipulation import InHandManipulationTask
from omniisaacgymenvs.robots.articulations.allegro_hand import AllegroHand
from omniisaacgymenvs.robots.articulations.views.allegro_hand_view import AllegroHandView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch import *
import numpy as np
import torch
import math
class AllegroHandTask(InHandManipulationTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self.object_type = self._task_cfg["env"]["objectType"]
assert self.object_type in ["block"]
self.obs_type = self._task_cfg["env"]["observationType"]
if not (self.obs_type in ["full_no_vel", "full"]):
raise Exception(
"Unknown type of observations!\nobservationType should be one of: [full_no_vel, full]")
print("Obs type:", self.obs_type)
self.num_obs_dict = {
"full_no_vel": 50,
"full": 72,
}
self.object_scale = torch.tensor([1.0, 1.0, 1.0])
self._num_observations = self.num_obs_dict[self.obs_type]
self._num_actions = 16
self._num_states = 0
InHandManipulationTask.__init__(self, name=name, env=env)
return
def get_hand(self):
hand_start_translation = torch.tensor([0.0, 0.0, 0.5], device=self.device)
hand_start_orientation = torch.tensor([0.257551, 0.283045, 0.683330, -0.621782], device=self.device)
allegro_hand = AllegroHand(
prim_path=self.default_zero_env_path + "/allegro_hand",
name="allegro_hand",
translation=hand_start_translation,
orientation=hand_start_orientation,
)
self._sim_config.apply_articulation_settings(
"allegro_hand",
get_prim_at_path(allegro_hand.prim_path),
self._sim_config.parse_actor_config("allegro_hand")
)
allegro_hand_prim = self._stage.GetPrimAtPath(allegro_hand.prim_path)
allegro_hand.set_allegro_hand_properties(stage=self._stage, allegro_hand_prim=allegro_hand_prim)
allegro_hand.set_motor_control_mode(stage=self._stage, allegro_hand_path=self.default_zero_env_path + "/allegro_hand")
pose_dy, pose_dz = -0.2, 0.06
return hand_start_translation, pose_dy, pose_dz
def get_hand_view(self, scene):
return AllegroHandView(prim_paths_expr="/World/envs/.*/allegro_hand", name="allegro_hand_view")
def get_observations(self):
self.get_object_goal_observations()
self.hand_dof_pos = self._hands.get_joint_positions()
self.hand_dof_vel = self._hands.get_joint_velocities()
if self.obs_type == "full_no_vel":
self.compute_full_observations(True)
elif self.obs_type == "full":
self.compute_full_observations()
else:
print("Unkown observations type!")
observations = {
self._hands.name: {
"obs_buf": self.obs_buf
}
}
return observations
def compute_full_observations(self, no_vel=False):
if no_vel:
self.obs_buf[:, 0:self.num_hand_dofs] = unscale(self.hand_dof_pos,
self.hand_dof_lower_limits, self.hand_dof_upper_limits)
self.obs_buf[:, 16:19] = self.object_pos
self.obs_buf[:, 19:23] = self.object_rot
self.obs_buf[:, 23:26] = self.goal_pos
self.obs_buf[:, 26:30] = self.goal_rot
self.obs_buf[:, 30:34] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 34:50] = self.actions
else:
self.obs_buf[:, 0:self.num_hand_dofs] = unscale(self.hand_dof_pos,
self.hand_dof_lower_limits, self.hand_dof_upper_limits)
self.obs_buf[:, self.num_hand_dofs:2*self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
self.obs_buf[:, 32:35] = self.object_pos
self.obs_buf[:, 35:39] = self.object_rot
self.obs_buf[:, 39:42] = self.object_linvel
self.obs_buf[:, 42:45] = self.vel_obs_scale * self.object_angvel
self.obs_buf[:, 45:48] = self.goal_pos
self.obs_buf[:, 48:52] = self.goal_rot
self.obs_buf[:, 52:56] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 56:72] = self.actions | 6,255 | Python | 41.27027 | 126 | 0.646843 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/ball_balance.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.balance_bot import BalanceBot
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.prims import RigidPrimView, RigidPrim
from omni.isaac.core.utils.torch.maths import *
from omni.isaac.core.objects import DynamicSphere
import numpy as np
import torch
import math
from pxr import PhysxSchema
class BallBalanceTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._dt = self._task_cfg["sim"]["dt"]
self._table_position = torch.tensor([0, 0, 0.62])
self._ball_position = torch.tensor([0.0, 0.0, 1.0])
self._ball_radius = 0.1
self._action_speed_scale = self._task_cfg["env"]["actionSpeedScale"]
self._max_episode_length = self._task_cfg["env"]["maxEpisodeLength"]
self._num_observations = 12 + 12
self._num_actions = 3
self.anchored = False
RLTask.__init__(self, name, env)
return
def set_up_scene(self, scene) -> None:
self.get_balance_table()
self.add_ball()
super().set_up_scene(scene)
self._balance_bots = ArticulationView(prim_paths_expr="/World/envs/.*/BalanceBot", name="balance_bot_view", reset_xform_properties=False)
scene.add(self._balance_bots)
self._balls = RigidPrimView(prim_paths_expr="/World/envs/.*/Ball/ball", name="ball_view", reset_xform_properties=False)
scene.add(self._balls)
return
def get_balance_table(self):
balance_table = BalanceBot(prim_path=self.default_zero_env_path + "/BalanceBot", name="BalanceBot", translation=self._table_position)
self._sim_config.apply_articulation_settings("table", get_prim_at_path(balance_table.prim_path), self._sim_config.parse_actor_config("table"))
def add_ball(self):
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/Ball/ball",
translation=self._ball_position,
name="ball_0",
radius=self._ball_radius,
color=torch.tensor([0.9, 0.6, 0.2]),
)
self._sim_config.apply_articulation_settings("ball", get_prim_at_path(ball.prim_path), self._sim_config.parse_actor_config("ball"))
def set_up_table_anchors(self):
from pxr import Gf
height = 0.08
stage = get_current_stage()
for i in range(self._num_envs):
base_path = f"{self.default_base_env_path}/env_{i}/BalanceBot"
for j, leg_offset in enumerate([(0.4, 0, height), (-0.2, 0.34641, height), (-0.2, -0.34641, height)]):
# fix the legs to ground
leg_path = f"{base_path}/lower_leg{j}"
ground_joint_path = leg_path + "_ground"
env_pos = stage.GetPrimAtPath(f"{self.default_base_env_path}/env_{i}").GetAttribute("xformOp:translate").Get()
anchor_pos = env_pos + Gf.Vec3d(*leg_offset)
self.fix_to_ground(stage, ground_joint_path, leg_path, anchor_pos)
def fix_to_ground(self, stage, joint_path, prim_path, anchor_pos):
from pxr import UsdPhysics, Gf
# D6 fixed joint
d6FixedJoint = UsdPhysics.Joint.Define(stage, joint_path)
d6FixedJoint.CreateBody0Rel().SetTargets(["/World/defaultGroundPlane"])
d6FixedJoint.CreateBody1Rel().SetTargets([prim_path])
d6FixedJoint.CreateLocalPos0Attr().Set(anchor_pos)
d6FixedJoint.CreateLocalRot0Attr().Set(Gf.Quatf(1.0, Gf.Vec3f(0, 0, 0)))
d6FixedJoint.CreateLocalPos1Attr().Set(Gf.Vec3f(0, 0, 0.18))
d6FixedJoint.CreateLocalRot1Attr().Set(Gf.Quatf(1.0, Gf.Vec3f(0, 0, 0)))
# lock all DOF (lock - low is greater than high)
d6Prim = stage.GetPrimAtPath(joint_path)
limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transX")
limitAPI.CreateLowAttr(1.0)
limitAPI.CreateHighAttr(-1.0)
limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transY")
limitAPI.CreateLowAttr(1.0)
limitAPI.CreateHighAttr(-1.0)
limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transZ")
limitAPI.CreateLowAttr(1.0)
limitAPI.CreateHighAttr(-1.0)
def get_observations(self) -> dict:
ball_positions, ball_orientations = self._balls.get_world_poses(clone=False)
ball_positions = ball_positions[:, 0:3] - self._env_pos
ball_velocities = self._balls.get_velocities(clone=False)
ball_linvels = ball_velocities[:, 0:3]
ball_angvels = ball_velocities[:, 3:6]
dof_pos = self._balance_bots.get_joint_positions(clone=False)
dof_vel = self._balance_bots.get_joint_velocities(clone=False)
sensor_force_torques = self._balance_bots._physics_view.get_force_sensor_forces() # (num_envs, num_sensors, 6)
self.obs_buf[..., 0:3] = dof_pos[..., self.actuated_dof_indices]
self.obs_buf[..., 3:6] = dof_vel[..., self.actuated_dof_indices]
self.obs_buf[..., 6:9] = ball_positions
self.obs_buf[..., 9:12] = ball_linvels
self.obs_buf[..., 12:15] = sensor_force_torques[..., 0] / 20.0
self.obs_buf[..., 15:18] = sensor_force_torques[..., 3] / 20.0
self.obs_buf[..., 18:21] = sensor_force_torques[..., 4] / 20.0
self.obs_buf[..., 21:24] = sensor_force_torques[..., 5] / 20.0
self.ball_positions = ball_positions
self.ball_linvels = ball_linvels
observations = {
"ball_balance": {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
if not self.anchored:
# Adding extra joints after ArticulationView is initialized
self.set_up_table_anchors()
self.anchored = True
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
# update position targets from actions
self.dof_position_targets[..., self.actuated_dof_indices] += self._dt * self._action_speed_scale * actions.to(self.device)
self.dof_position_targets[:] = tensor_clamp(
self.dof_position_targets, self.bbot_dof_lower_limits, self.bbot_dof_upper_limits
)
# reset position targets for reset envs
self.dof_position_targets[reset_env_ids] = 0
self._balance_bots.set_joint_position_targets(self.dof_position_targets) #.clone())
def reset_idx(self, env_ids):
num_resets = len(env_ids)
env_ids_32 = env_ids.type(torch.int32)
env_ids_64 = env_ids.type(torch.int64)
min_d = 0.001 # min horizontal dist from origin
max_d = 0.5 # max horizontal dist from origin
min_height = 1.0
max_height = 2.0
min_horizontal_speed = 0
max_horizontal_speed = 2
dists = torch_rand_float(min_d, max_d, (num_resets, 1), self._device)
dirs = torch_random_dir_2((num_resets, 1), self._device)
hpos = dists * dirs
speedscales = (dists - min_d) / (max_d - min_d)
hspeeds = torch_rand_float(min_horizontal_speed, max_horizontal_speed, (num_resets, 1), self._device)
hvels = -speedscales * hspeeds * dirs
vspeeds = -torch_rand_float(5.0, 5.0, (num_resets, 1), self._device).squeeze()
ball_pos = self.initial_ball_pos.clone()
ball_rot = self.initial_ball_rot.clone()
# position
ball_pos[env_ids_64, 0:2] += hpos[..., 0:2]
ball_pos[env_ids_64, 2] += torch_rand_float(min_height, max_height, (num_resets, 1), self._device).squeeze()
# rotation
ball_rot[env_ids_64, 0] = 1
ball_rot[env_ids_64, 1:] = 0
ball_velocities = self.initial_ball_velocities.clone()
# linear
ball_velocities[env_ids_64, 0:2] = hvels[..., 0:2]
ball_velocities[env_ids_64, 2] = vspeeds
# angular
ball_velocities[env_ids_64, 3:6] = 0
# reset root state for bbots and balls in selected envs
self._balance_bots.set_world_poses(self.initial_bot_pos[env_ids_64], self.initial_bot_rot[env_ids_64].clone(), indices=env_ids_32)
self._balls.set_world_poses(ball_pos[env_ids_64], ball_rot[env_ids_64], indices=env_ids_32)
self._balls.set_velocities(ball_velocities[env_ids_64], indices=env_ids_32)
# reset DOF states for bbots in selected envs
self._balance_bots.set_joint_positions(self.initial_dof_positions.clone()[env_ids_64], indices=env_ids_32)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def post_reset(self):
dof_limits = self._balance_bots.get_dof_limits()
self.bbot_dof_lower_limits, self.bbot_dof_upper_limits = torch.t(dof_limits[0].to(device=self._device))
self.initial_dof_positions = self._balance_bots.get_joint_positions(clone=False)
self.initial_bot_pos, self.initial_bot_rot = self._balance_bots.get_world_poses(clone=False)
self.initial_bot_pos[..., 2] = 0.559 # tray_height
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses(clone=False)
self.initial_ball_velocities = self._balls.get_velocities().clone()
self.dof_position_targets = torch.zeros(
(self.num_envs, self._balance_bots.num_dof), dtype=torch.float32, device=self._device, requires_grad=False
)
self.actuated_dof_indices = torch.LongTensor([3, 4, 5]).to(self._device)
def calculate_metrics(self) -> None:
ball_dist = torch.sqrt(
self.ball_positions[..., 0] * self.ball_positions[..., 0]
+ (self.ball_positions[..., 2] - 0.7) * (self.ball_positions[..., 2] - 0.7)
+ (self.ball_positions[..., 1]) * self.ball_positions[..., 1]
)
ball_speed = torch.sqrt(
self.ball_linvels[..., 0] * self.ball_linvels[..., 0]
+ self.ball_linvels[..., 1] * self.ball_linvels[..., 1]
+ self.ball_linvels[..., 2] * self.ball_linvels[..., 2]
)
pos_reward = 1.0 / (1.0 + ball_dist)
speed_reward = 1.0 / (1.0 + ball_speed)
self.rew_buf[:] = pos_reward * speed_reward
def is_done(self) -> None:
reset = torch.where(
self.progress_buf >= self._max_episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf
)
reset = torch.where(self.ball_positions[..., 2] < self._ball_radius * 1.5, torch.ones_like(self.reset_buf), reset)
self.reset_buf[:] = reset
| 12,548 | Python | 44.303249 | 150 | 0.634523 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/anymal_terrain.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.anymal import Anymal
from omniisaacgymenvs.robots.articulations.views.anymal_view import AnymalView
from omniisaacgymenvs.tasks.utils.anymal_terrain_generator import *
from omniisaacgymenvs.utils.terrain_utils.terrain_utils import *
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.simulation_context import SimulationContext
import numpy as np
import torch
import math
from pxr import UsdPhysics, UsdLux
class AnymalTerrainTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self.height_samples = None
self.custom_origins = False
self.init_done = False
# normalization
self.lin_vel_scale = self._task_cfg["env"]["learn"]["linearVelocityScale"]
self.ang_vel_scale = self._task_cfg["env"]["learn"]["angularVelocityScale"]
self.dof_pos_scale = self._task_cfg["env"]["learn"]["dofPositionScale"]
self.dof_vel_scale = self._task_cfg["env"]["learn"]["dofVelocityScale"]
self.height_meas_scale = self._task_cfg["env"]["learn"]["heightMeasurementScale"]
self.action_scale = self._task_cfg["env"]["control"]["actionScale"]
# reward scales
self.rew_scales = {}
self.rew_scales["termination"] = self._task_cfg["env"]["learn"]["terminalReward"]
self.rew_scales["lin_vel_xy"] = self._task_cfg["env"]["learn"]["linearVelocityXYRewardScale"]
self.rew_scales["lin_vel_z"] = self._task_cfg["env"]["learn"]["linearVelocityZRewardScale"]
self.rew_scales["ang_vel_z"] = self._task_cfg["env"]["learn"]["angularVelocityZRewardScale"]
self.rew_scales["ang_vel_xy"] = self._task_cfg["env"]["learn"]["angularVelocityXYRewardScale"]
self.rew_scales["orient"] = self._task_cfg["env"]["learn"]["orientationRewardScale"]
self.rew_scales["torque"] = self._task_cfg["env"]["learn"]["torqueRewardScale"]
self.rew_scales["joint_acc"] = self._task_cfg["env"]["learn"]["jointAccRewardScale"]
self.rew_scales["base_height"] = self._task_cfg["env"]["learn"]["baseHeightRewardScale"]
self.rew_scales["action_rate"] = self._task_cfg["env"]["learn"]["actionRateRewardScale"]
self.rew_scales["hip"] = self._task_cfg["env"]["learn"]["hipRewardScale"]
self.rew_scales["fallen_over"] = self._task_cfg["env"]["learn"]["fallenOverRewardScale"]
#command ranges
self.command_x_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_x"]
self.command_y_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_y"]
self.command_yaw_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["yaw"]
# base init state
pos = self._task_cfg["env"]["baseInitState"]["pos"]
rot = self._task_cfg["env"]["baseInitState"]["rot"]
v_lin = self._task_cfg["env"]["baseInitState"]["vLinear"]
v_ang = self._task_cfg["env"]["baseInitState"]["vAngular"]
self.base_init_state = pos + rot + v_lin + v_ang
# default joint positions
self.named_default_joint_angles = self._task_cfg["env"]["defaultJointAngles"]
# other
self.decimation = self._task_cfg["env"]["control"]["decimation"]
self.dt = self.decimation * self._task_cfg["sim"]["dt"]
self.max_episode_length_s = self._task_cfg["env"]["learn"]["episodeLength_s"]
self.max_episode_length = int(self.max_episode_length_s/ self.dt + 0.5)
self.push_interval = int(self._task_cfg["env"]["learn"]["pushInterval_s"] / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
self.curriculum = self._task_cfg["env"]["terrain"]["curriculum"]
self.base_threshold = 0.2
self.knee_threshold = 0.1
for key in self.rew_scales.keys():
self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._num_observations = 188
self._num_actions = 12
self._task_cfg["sim"]["default_physics_material"]["static_friction"] = self._task_cfg["env"]["terrain"]["staticFriction"]
self._task_cfg["sim"]["default_physics_material"]["dynamic_friction"] = self._task_cfg["env"]["terrain"]["dynamicFriction"]
self._task_cfg["sim"]["default_physics_material"]["restitution"] = self._task_cfg["env"]["terrain"]["restitution"]
self._task_cfg["sim"]["add_ground_plane"] = False
self._env_spacing = 0.0
RLTask.__init__(self, name, env)
self.timeout_buf = torch.zeros(self.num_envs, device=self.device, dtype=torch.long)
# initialize some data used later on
self.up_axis_idx = 2
self.common_step_counter = 0
self.extras = {}
self.noise_scale_vec = self._get_noise_scale_vec(self._task_cfg)
self.commands = torch.zeros(self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False) # x vel, y vel, yaw vel, heading
self.commands_scale = torch.tensor([self.lin_vel_scale, self.lin_vel_scale, self.ang_vel_scale], device=self.device, requires_grad=False,)
self.gravity_vec = torch.tensor(get_axis_params(-1., self.up_axis_idx), dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.forward_vec = torch.tensor([1., 0., 0.], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.torques = torch.zeros(self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False)
self.actions = torch.zeros(self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False)
self.last_actions = torch.zeros(self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False)
self.feet_air_time = torch.zeros(self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False)
self.last_dof_vel = torch.zeros((self.num_envs, 12), dtype=torch.float, device=self.device, requires_grad=False)
self.height_points = self.init_height_points()
self.measured_heights = None
# joint positions offsets
self.default_dof_pos = torch.zeros((self.num_envs, 12), dtype=torch.float, device=self.device, requires_grad=False)
# reward episode sums
torch_zeros = lambda : torch.zeros(self.num_envs, dtype=torch.float, device=self.device, requires_grad=False)
self.episode_sums = {"lin_vel_xy": torch_zeros(), "lin_vel_z": torch_zeros(), "ang_vel_z": torch_zeros(), "ang_vel_xy": torch_zeros(),
"orient": torch_zeros(), "torques": torch_zeros(), "joint_acc": torch_zeros(), "base_height": torch_zeros(),
"air_time": torch_zeros(), "collision": torch_zeros(), "stumble": torch_zeros(), "action_rate": torch_zeros(), "hip": torch_zeros()}
return
def _get_noise_scale_vec(self, cfg):
noise_vec = torch.zeros_like(self.obs_buf[0])
self.add_noise = self._task_cfg["env"]["learn"]["addNoise"]
noise_level = self._task_cfg["env"]["learn"]["noiseLevel"]
noise_vec[:3] = self._task_cfg["env"]["learn"]["linearVelocityNoise"] * noise_level * self.lin_vel_scale
noise_vec[3:6] = self._task_cfg["env"]["learn"]["angularVelocityNoise"] * noise_level * self.ang_vel_scale
noise_vec[6:9] = self._task_cfg["env"]["learn"]["gravityNoise"] * noise_level
noise_vec[9:12] = 0. # commands
noise_vec[12:24] = self._task_cfg["env"]["learn"]["dofPositionNoise"] * noise_level * self.dof_pos_scale
noise_vec[24:36] = self._task_cfg["env"]["learn"]["dofVelocityNoise"] * noise_level * self.dof_vel_scale
noise_vec[36:176] = self._task_cfg["env"]["learn"]["heightMeasurementNoise"] * noise_level * self.height_meas_scale
noise_vec[176:188] = 0. # previous actions
return noise_vec
def init_height_points(self):
# 1mx1.6m rectangle (without center line)
y = 0.1 * torch.tensor([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5], device=self.device, requires_grad=False) # 10-50cm on each side
x = 0.1 * torch.tensor([-8, -7, -6, -5, -4, -3, -2, 2, 3, 4, 5, 6, 7, 8], device=self.device, requires_grad=False) # 20-80cm on each side
grid_x, grid_y = torch.meshgrid(x, y)
self.num_height_points = grid_x.numel()
points = torch.zeros(self.num_envs, self.num_height_points, 3, device=self.device, requires_grad=False)
points[:, :, 0] = grid_x.flatten()
points[:, :, 1] = grid_y.flatten()
return points
def _create_trimesh(self):
self.terrain = Terrain(self._task_cfg["env"]["terrain"], num_robots=self.num_envs)
vertices = self.terrain.vertices
triangles = self.terrain.triangles
position = torch.tensor([-self.terrain.border_size , -self.terrain.border_size , 0.0])
add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position)
self.height_samples = torch.tensor(self.terrain.heightsamples).view(self.terrain.tot_rows, self.terrain.tot_cols).to(self.device)
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
self.get_terrain()
self.get_anymal()
super().set_up_scene(scene)
self._anymals = AnymalView(prim_paths_expr="/World/envs/.*/anymal", name="anymal_view")
scene.add(self._anymals)
scene.add(self._anymals._knees)
scene.add(self._anymals._base)
return
def get_terrain(self):
self.env_origins = torch.zeros((self.num_envs, 3), device=self.device, requires_grad=False)
if not self.curriculum: self._task_cfg["env"]["terrain"]["maxInitMapLevel"] = self._task_cfg["env"]["terrain"]["numLevels"] - 1
self.terrain_levels = torch.randint(0, self._task_cfg["env"]["terrain"]["maxInitMapLevel"]+1, (self.num_envs,), device=self.device)
self.terrain_types = torch.randint(0, self._task_cfg["env"]["terrain"]["numTerrains"], (self.num_envs,), device=self.device)
self._create_trimesh()
self.terrain_origins = torch.from_numpy(self.terrain.env_origins).to(self.device).to(torch.float)
def get_anymal(self):
self.base_init_state = torch.tensor(self.base_init_state, dtype=torch.float, device=self.device, requires_grad=False)
anymal_translation = torch.tensor([0.0, 0.0, 0.66])
anymal_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0])
anymal = Anymal(prim_path=self.default_zero_env_path + "/anymal",
name="anymal",
translation=anymal_translation,
orientation=anymal_orientation,)
self._sim_config.apply_articulation_settings("anymal", get_prim_at_path(anymal.prim_path), self._sim_config.parse_actor_config("anymal"))
anymal.set_anymal_properties(self._stage, anymal.prim)
self.dof_names = anymal.dof_names
for i in range(self.num_actions):
name = self.dof_names[i]
angle = self.named_default_joint_angles[name]
self.default_dof_pos[:, i] = angle
def post_reset(self):
for i in range(self.num_envs):
self.env_origins[i] = self.terrain_origins[self.terrain_levels[i], self.terrain_types[i]]
self.num_dof = self._anymals.num_dof
self.dof_pos = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.dof_vel = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.base_pos = torch.zeros((self.num_envs, 3), dtype=torch.float, device=self.device)
self.base_quat = torch.zeros((self.num_envs, 4), dtype=torch.float, device=self.device)
self.base_velocities = torch.zeros((self.num_envs, 6), dtype=torch.float, device=self.device)
self.knee_pos = torch.zeros((self.num_envs*4, 3), dtype=torch.float, device=self.device)
self.knee_quat = torch.zeros((self.num_envs*4, 4), dtype=torch.float, device=self.device)
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
self.init_done = True
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
positions_offset = torch_rand_float(0.5, 1.5, (len(env_ids), self.num_dof), device=self.device)
velocities = torch_rand_float(-0.1, 0.1, (len(env_ids), self.num_dof), device=self.device)
self.dof_pos[env_ids] = self.default_dof_pos[env_ids] * positions_offset
self.dof_vel[env_ids] = velocities
self.update_terrain_level(env_ids)
self.base_pos[env_ids] = self.base_init_state[0:3]
self.base_pos[env_ids, 0:3] += self.env_origins[env_ids]
self.base_pos[env_ids, 0:2] += torch_rand_float(-0.5, 0.5, (len(env_ids), 2), device=self.device)
self.base_quat[env_ids] = self.base_init_state[3:7]
self.base_velocities[env_ids] = self.base_init_state[7:]
self._anymals.set_world_poses(positions=self.base_pos[env_ids].clone(),
orientations=self.base_quat[env_ids].clone(),
indices=indices)
self._anymals.set_velocities(velocities=self.base_velocities[env_ids].clone(),
indices=indices)
self._anymals.set_joint_positions(positions=self.dof_pos[env_ids].clone(),
indices=indices)
self._anymals.set_joint_velocities(velocities=self.dof_vel[env_ids].clone(),
indices=indices)
self.commands[env_ids, 0] = torch_rand_float(self.command_x_range[0], self.command_x_range[1], (len(env_ids), 1), device=self.device).squeeze()
self.commands[env_ids, 1] = torch_rand_float(self.command_y_range[0], self.command_y_range[1], (len(env_ids), 1), device=self.device).squeeze()
self.commands[env_ids, 3] = torch_rand_float(self.command_yaw_range[0], self.command_yaw_range[1], (len(env_ids), 1), device=self.device).squeeze()
self.commands[env_ids] *= (torch.norm(self.commands[env_ids, :2], dim=1) > 0.25).unsqueeze(1) # set small commands to zero
self.last_actions[env_ids] = 0.
self.last_dof_vel[env_ids] = 0.
self.feet_air_time[env_ids] = 0.
self.progress_buf[env_ids] = 0
self.reset_buf[env_ids] = 1
# fill extras
self.extras["episode"] = {}
for key in self.episode_sums.keys():
self.extras["episode"]['rew_' + key] = torch.mean(self.episode_sums[key][env_ids]) / self.max_episode_length_s
self.episode_sums[key][env_ids] = 0.
self.extras["episode"]["terrain_level"] = torch.mean(self.terrain_levels.float())
def update_terrain_level(self, env_ids):
if not self.init_done or not self.curriculum:
# do not change on initial reset
return
root_pos, _ = self._anymals.get_world_poses(clone=False)
distance = torch.norm(root_pos[env_ids, :2] - self.env_origins[env_ids, :2], dim=1)
self.terrain_levels[env_ids] -= 1 * (distance < torch.norm(self.commands[env_ids, :2])*self.max_episode_length_s*0.25)
self.terrain_levels[env_ids] += 1 * (distance > self.terrain.env_length / 2)
self.terrain_levels[env_ids] = torch.clip(self.terrain_levels[env_ids], 0) % self.terrain.env_rows
self.env_origins[env_ids] = self.terrain_origins[self.terrain_levels[env_ids], self.terrain_types[env_ids]]
def refresh_dof_state_tensors(self):
self.dof_pos = self._anymals.get_joint_positions(clone=False)
self.dof_vel = self._anymals.get_joint_velocities(clone=False)
def refresh_body_state_tensors(self):
self.base_pos, self.base_quat = self._anymals.get_world_poses(clone=False)
self.base_velocities = self._anymals.get_velocities(clone=False)
self.knee_pos, self.knee_quat = self._anymals._knees.get_world_poses(clone=False)
def pre_physics_step(self, actions):
self.actions = actions.clone().to(self.device)
for i in range(self.decimation):
torques = torch.clip(self.Kp*(self.action_scale*self.actions + self.default_dof_pos - self.dof_pos) - self.Kd*self.dof_vel, -80., 80.)
self._anymals.set_joint_efforts(torques)
self.torques = torques
SimulationContext.step(self._env._world, render=False)
self.refresh_dof_state_tensors()
def post_physics_step(self):
self.progress_buf[:] += 1
if self._env._world.is_playing():
self.refresh_dof_state_tensors()
self.refresh_body_state_tensors()
self.common_step_counter += 1
if self.common_step_counter % self.push_interval == 0:
self.push_robots()
# prepare quantities
self.base_lin_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 0:3])
self.base_ang_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 3:6])
self.projected_gravity = quat_rotate_inverse(self.base_quat, self.gravity_vec)
forward = quat_apply(self.base_quat, self.forward_vec)
heading = torch.atan2(forward[:, 1], forward[:, 0])
self.commands[:, 2] = torch.clip(0.5*wrap_to_pi(self.commands[:, 3] - heading), -1., 1.)
self.check_termination()
self.get_states()
self.calculate_metrics()
env_ids = self.reset_buf.nonzero(as_tuple=False).flatten()
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.get_observations()
if self.add_noise:
self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec
self.last_actions[:] = self.actions[:]
self.last_dof_vel[:] = self.dof_vel[:]
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
def push_robots(self):
self.base_velocities[:, 0:2] = torch_rand_float(-1., 1., (self.num_envs, 2), device=self.device) # lin vel x/y
self._anymals.set_velocities(self.base_velocities)
def check_termination(self):
self.timeout_buf = torch.where(self.progress_buf >= self.max_episode_length - 1, torch.ones_like(self.timeout_buf), torch.zeros_like(self.timeout_buf))
ground_heights_below_base = self.get_ground_heights_below_base().squeeze()
self.has_base_fallen = self._anymals.is_base_below_threshold(threshold=self.base_threshold, ground_heights=ground_heights_below_base)
ground_heights_below_knees = self.get_ground_heights_below_knees()
self.has_knees_fallen = self._anymals.is_knee_below_threshold(threshold=self.knee_threshold, ground_heights=ground_heights_below_knees)
self.has_fallen = self.has_base_fallen | self.has_knees_fallen
self.reset_buf = self.has_fallen.clone()
self.reset_buf = torch.where(self.timeout_buf.bool(), torch.ones_like(self.reset_buf), self.reset_buf)
def calculate_metrics(self):
# velocity tracking reward
lin_vel_error = torch.sum(torch.square(self.commands[:, :2] - self.base_lin_vel[:, :2]), dim=1)
ang_vel_error = torch.square(self.commands[:, 2] - self.base_ang_vel[:, 2])
rew_lin_vel_xy = torch.exp(-lin_vel_error/0.25) * self.rew_scales["lin_vel_xy"]
rew_ang_vel_z = torch.exp(-ang_vel_error/0.25) * self.rew_scales["ang_vel_z"]
# other base velocity penalties
rew_lin_vel_z = torch.square(self.base_lin_vel[:, 2]) * self.rew_scales["lin_vel_z"]
rew_ang_vel_xy = torch.sum(torch.square(self.base_ang_vel[:, :2]), dim=1) * self.rew_scales["ang_vel_xy"]
# orientation penalty
rew_orient = torch.sum(torch.square(self.projected_gravity[:, :2]), dim=1) * self.rew_scales["orient"]
# base height penalty
rew_base_height = torch.square(self.base_pos[:, 2] - 0.52) * self.rew_scales["base_height"]
# torque penalty
rew_torque = torch.sum(torch.square(self.torques), dim=1) * self.rew_scales["torque"]
# joint acc penalty
rew_joint_acc = torch.sum(torch.square(self.last_dof_vel - self.dof_vel), dim=1) * self.rew_scales["joint_acc"]
# fallen over penalty
rew_fallen_over = self.has_fallen * self.rew_scales["fallen_over"]
# action rate penalty
rew_action_rate = torch.sum(torch.square(self.last_actions - self.actions), dim=1) * self.rew_scales["action_rate"]
# cosmetic penalty for hip motion
rew_hip = torch.sum(torch.abs(self.dof_pos[:, 0:4] - self.default_dof_pos[:, 0:4]), dim=1)* self.rew_scales["hip"]
# total reward
self.rew_buf = rew_lin_vel_xy + rew_ang_vel_z + rew_lin_vel_z + rew_ang_vel_xy + rew_orient + rew_base_height + \
rew_torque + rew_joint_acc + rew_action_rate + rew_hip + rew_fallen_over
self.rew_buf = torch.clip(self.rew_buf, min=0., max=None)
# add termination reward
self.rew_buf += self.rew_scales["termination"] * self.reset_buf * ~self.timeout_buf
# log episode reward sums
self.episode_sums["lin_vel_xy"] += rew_lin_vel_xy
self.episode_sums["ang_vel_z"] += rew_ang_vel_z
self.episode_sums["lin_vel_z"] += rew_lin_vel_z
self.episode_sums["ang_vel_xy"] += rew_ang_vel_xy
self.episode_sums["orient"] += rew_orient
self.episode_sums["torques"] += rew_torque
self.episode_sums["joint_acc"] += rew_joint_acc
self.episode_sums["action_rate"] += rew_action_rate
self.episode_sums["base_height"] += rew_base_height
self.episode_sums["hip"] += rew_hip
def get_observations(self):
self.measured_heights = self.get_heights()
heights = torch.clip(self.base_pos[:, 2].unsqueeze(1) - 0.5 - self.measured_heights, -1, 1.) * self.height_meas_scale
self.obs_buf = torch.cat(( self.base_lin_vel * self.lin_vel_scale,
self.base_ang_vel * self.ang_vel_scale,
self.projected_gravity,
self.commands[:, :3] * self.commands_scale,
self.dof_pos * self.dof_pos_scale,
self.dof_vel * self.dof_vel_scale,
heights,
self.actions
),dim=-1)
def get_ground_heights_below_knees(self):
points = self.knee_pos.reshape(self.num_envs, 4, 3)
points += self.terrain.border_size
points = (points/self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0]-2)
py = torch.clip(py, 0, self.height_samples.shape[1]-2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px+1, py+1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_ground_heights_below_base(self):
points = self.base_pos.reshape(self.num_envs, 1, 3)
points += self.terrain.border_size
points = (points/self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0]-2)
py = torch.clip(py, 0, self.height_samples.shape[1]-2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px+1, py+1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_heights(self, env_ids=None):
if env_ids:
points = quat_apply_yaw(self.base_quat[env_ids].repeat(1, self.num_height_points), self.height_points[env_ids]) + (self.base_pos[env_ids, 0:3]).unsqueeze(1)
else:
points = quat_apply_yaw(self.base_quat.repeat(1, self.num_height_points), self.height_points) + (self.base_pos[:, 0:3]).unsqueeze(1)
points += self.terrain.border_size
points = (points/self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0]-2)
py = torch.clip(py, 0, self.height_samples.shape[1]-2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px+1, py+1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
@torch.jit.script
def quat_apply_yaw(quat, vec):
quat_yaw = quat.clone().view(-1, 4)
quat_yaw[:, 1:3] = 0.
quat_yaw = normalize(quat_yaw)
return quat_apply(quat_yaw, vec)
@torch.jit.script
def wrap_to_pi(angles):
angles %= 2*np.pi
angles -= 2*np.pi * (angles > np.pi)
return angles
def get_axis_params(value, axis_idx, x_value=0., dtype=np.float, n_dims=3):
"""construct arguments to `Vec` according to axis index.
"""
zs = np.zeros((n_dims,))
assert axis_idx < n_dims, "the axis dim should be within the vector dimensions"
zs[axis_idx] = 1.
params = np.where(zs == 1., value, zs)
params[0] = x_value
return list(params.astype(dtype))
| 27,490 | Python | 53.22288 | 168 | 0.627974 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/shadow_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.tasks.shared.in_hand_manipulation import InHandManipulationTask
from omniisaacgymenvs.robots.articulations.shadow_hand import ShadowHand
from omniisaacgymenvs.robots.articulations.views.shadow_hand_view import ShadowHandView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch import *
import numpy as np
import torch
import math
class ShadowHandTask(InHandManipulationTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self.object_type = self._task_cfg["env"]["objectType"]
assert self.object_type in ["block"]
self.obs_type = self._task_cfg["env"]["observationType"]
if not (self.obs_type in ["openai", "full_no_vel", "full", "full_state"]):
raise Exception(
"Unknown type of observations!\nobservationType should be one of: [openai, full_no_vel, full, full_state]")
print("Obs type:", self.obs_type)
self.num_obs_dict = {
"openai": 42,
"full_no_vel": 77,
"full": 157,
"full_state": 187,
}
self.asymmetric_obs = self._task_cfg["env"]["asymmetric_observations"]
self.use_vel_obs = False
self.fingertip_obs = True
self.fingertips = ["robot0:ffdistal", "robot0:mfdistal", "robot0:rfdistal", "robot0:lfdistal", "robot0:thdistal"]
self.num_fingertips = len(self.fingertips)
self.object_scale = torch.tensor([1.0, 1.0, 1.0])
self.force_torque_obs_scale = 10.0
num_states = 0
if self.asymmetric_obs:
num_states = 187
self._num_observations = self.num_obs_dict[self.obs_type]
self._num_actions = 20
self._num_states = num_states
InHandManipulationTask.__init__(self, name=name, env=env)
return
def get_hand(self):
hand_start_translation = torch.tensor([0.0, 0.0, 0.5], device=self.device)
hand_start_orientation = torch.tensor([0.0, 0.0, -0.70711, 0.70711], device=self.device)
shadow_hand = ShadowHand(
prim_path=self.default_zero_env_path + "/shadow_hand",
name="shadow_hand",
translation=hand_start_translation,
orientation=hand_start_orientation,
)
self._sim_config.apply_articulation_settings(
"shadow_hand",
get_prim_at_path(shadow_hand.prim_path),
self._sim_config.parse_actor_config("shadow_hand"),
)
shadow_hand.set_shadow_hand_properties(stage=self._stage, shadow_hand_prim=shadow_hand.prim)
shadow_hand.set_motor_control_mode(stage=self._stage, shadow_hand_path=shadow_hand.prim_path)
pose_dy, pose_dz = -0.39, 0.10
return hand_start_translation, pose_dy, pose_dz
def get_hand_view(self, scene):
hand_view = ShadowHandView(prim_paths_expr="/World/envs/.*/shadow_hand", name="shadow_hand_view")
scene.add(hand_view._fingers)
return hand_view
def get_observations(self):
self.get_object_goal_observations()
self.fingertip_pos, self.fingertip_rot = self._hands._fingers.get_world_poses()
self.fingertip_pos -= self._env_pos.repeat((1, self.num_fingertips)).reshape(self.num_envs * self.num_fingertips, 3)
self.fingertip_velocities = self._hands._fingers.get_velocities()
self.hand_dof_pos = self._hands.get_joint_positions()
self.hand_dof_vel = self._hands.get_joint_velocities()
if self.obs_type == "full_state" or self.asymmetric_obs:
self.vec_sensor_tensor = self._hands._physics_view.get_force_sensor_forces().reshape(self.num_envs, 6*self.num_fingertips)
if self.obs_type == "openai":
self.compute_fingertip_observations(True)
elif self.obs_type == "full_no_vel":
self.compute_full_observations(True)
elif self.obs_type == "full":
self.compute_full_observations()
elif self.obs_type == "full_state":
self.compute_full_state(False)
else:
print("Unkown observations type!")
if self.asymmetric_obs:
self.compute_full_state(True)
observations = {
self._hands.name: {
"obs_buf": self.obs_buf
}
}
return observations
def compute_fingertip_observations(self, no_vel=False):
if no_vel:
# Per https://arxiv.org/pdf/1808.00177.pdf Table 2
# Fingertip positions
# Object Position, but not orientation
# Relative target orientation
# 3*self.num_fingertips = 15
self.obs_buf[:, 0:15] = self.fingertip_pos.reshape(self.num_envs, 15)
self.obs_buf[:, 15:18] = self.object_pos
self.obs_buf[:, 18:22] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 22:42] = self.actions
else:
# 13*self.num_fingertips = 65
self.obs_buf[:, 0:65] = self.fingertip_state.reshape(self.num_envs, 65)
self.obs_buf[:, 0:15] = self.fingertip_pos.reshape(self.num_envs, 3*self.num_fingertips)
self.obs_buf[:, 15:35] = self.fingertip_rot.reshape(self.num_envs, 4*self.num_fingertips)
self.obs_buf[:, 35:65] = self.fingertip_velocities.reshape(self.num_envs, 6*self.num_fingertips)
self.obs_buf[:, 65:68] = self.object_pos
self.obs_buf[:, 68:72] = self.object_rot
self.obs_buf[:, 72:75] = self.object_linvel
self.obs_buf[:, 75:78] = self.vel_obs_scale * self.object_angvel
self.obs_buf[:, 78:81] = self.goal_pos
self.obs_buf[:, 81:85] = self.goal_rot
self.obs_buf[:, 85:89] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 89:109] = self.actions
def compute_full_observations(self, no_vel=False):
if no_vel:
self.obs_buf[:, 0:self.num_hand_dofs] = unscale(self.hand_dof_pos,
self.hand_dof_lower_limits, self.hand_dof_upper_limits)
self.obs_buf[:, 24:37] = self.object_pos
self.obs_buf[:, 27:31] = self.object_rot
self.obs_buf[:, 31:34] = self.goal_pos
self.obs_buf[:, 34:38] = self.goal_rot
self.obs_buf[:, 38:42] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 42:57] = self.fingertip_pos.reshape(self.num_envs, 3*self.num_fingertips)
self.obs_buf[:, 57:77] = self.actions
else:
self.obs_buf[:, 0:self.num_hand_dofs] = unscale(self.hand_dof_pos,
self.hand_dof_lower_limits, self.hand_dof_upper_limits)
self.obs_buf[:, self.num_hand_dofs:2*self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
self.obs_buf[:, 48:51] = self.object_pos
self.obs_buf[:, 51:55] = self.object_rot
self.obs_buf[:, 55:58] = self.object_linvel
self.obs_buf[:, 58:61] = self.vel_obs_scale * self.object_angvel
self.obs_buf[:, 61:64] = self.goal_pos
self.obs_buf[:, 64:68] = self.goal_rot
self.obs_buf[:, 68:72] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
# (7+6)*self.num_fingertips = 65
self.obs_buf[:, 72:87] = self.fingertip_pos.reshape(self.num_envs, 3*self.num_fingertips)
self.obs_buf[:, 87:107] = self.fingertip_rot.reshape(self.num_envs, 4*self.num_fingertips)
self.obs_buf[:, 107:137] = self.fingertip_velocities.reshape(self.num_envs, 6*self.num_fingertips)
self.obs_buf[:, 137:157] = self.actions
def compute_full_state(self, asymm_obs=False):
if asymm_obs:
self.states_buf[:, 0:self.num_hand_dofs] = unscale(self.hand_dof_pos,
self.hand_dof_lower_limits, self.hand_dof_upper_limits)
self.states_buf[:, self.num_hand_dofs:2*self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
# self.states_buf[:, 2*self.num_hand_dofs:3*self.num_hand_dofs] = self.force_torque_obs_scale * self.dof_force_tensor
obj_obs_start = 2*self.num_hand_dofs # 48
self.states_buf[:, obj_obs_start:obj_obs_start + 3] = self.object_pos
self.states_buf[:, obj_obs_start + 3:obj_obs_start + 7] = self.object_rot
self.states_buf[:, obj_obs_start + 7:obj_obs_start + 10] = self.object_linvel
self.states_buf[:, obj_obs_start + 10:obj_obs_start + 13] = self.vel_obs_scale * self.object_angvel
goal_obs_start = obj_obs_start + 13 # 61
self.states_buf[:, goal_obs_start:goal_obs_start + 3] = self.goal_pos
self.states_buf[:, goal_obs_start + 3:goal_obs_start + 7] = self.goal_rot
self.states_buf[:, goal_obs_start + 7:goal_obs_start + 11] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
# fingertip observations, state(pose and vel) + force-torque sensors
num_ft_states = 13 * self.num_fingertips # 65
num_ft_force_torques = 6 * self.num_fingertips # 30
fingertip_obs_start = goal_obs_start + 11 # 72
self.states_buf[:, fingertip_obs_start:fingertip_obs_start + 3*self.num_fingertips] = self.fingertip_pos.reshape(self.num_envs, 3*self.num_fingertips)
self.states_buf[:, fingertip_obs_start + 3*self.num_fingertips:fingertip_obs_start + 7*self.num_fingertips] = self.fingertip_rot.reshape(self.num_envs, 4*self.num_fingertips)
self.states_buf[:, fingertip_obs_start + 7*self.num_fingertips:fingertip_obs_start + 13*self.num_fingertips] = self.fingertip_velocities.reshape(self.num_envs, 6*self.num_fingertips)
self.states_buf[:, fingertip_obs_start + num_ft_states:fingertip_obs_start + num_ft_states + num_ft_force_torques] = self.force_torque_obs_scale * self.vec_sensor_tensor
# obs_end = 72 + 65 + 30 = 167
# obs_total = obs_end + num_actions = 187
obs_end = fingertip_obs_start + num_ft_states + num_ft_force_torques
self.states_buf[:, obs_end:obs_end + self.num_actions] = self.actions
else:
self.obs_buf[:, 0:self.num_hand_dofs] = unscale(self.hand_dof_pos,
self.hand_dof_lower_limits, self.hand_dof_upper_limits)
self.obs_buf[:, self.num_hand_dofs:2*self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
self.obs_buf[:, 2*self.num_hand_dofs:3*self.num_hand_dofs] = self.force_torque_obs_scale * self.dof_force_tensor
obj_obs_start = 3*self.num_hand_dofs # 48
self.obs_buf[:, obj_obs_start:obj_obs_start + 3] = self.object_pos
self.obs_buf[:, obj_obs_start + 3:obj_obs_start + 7] = self.object_rot
self.obs_buf[:, obj_obs_start + 7:obj_obs_start + 10] = self.object_linvel
self.obs_buf[:, obj_obs_start + 10:obj_obs_start + 13] = self.vel_obs_scale * self.object_angvel
goal_obs_start = obj_obs_start + 13 # 61
self.obs_buf[:, goal_obs_start:goal_obs_start + 3] = self.goal_pos
self.obs_buf[:, goal_obs_start + 3:goal_obs_start + 7] = self.goal_rot
self.obs_buf[:, goal_obs_start + 7:goal_obs_start + 11] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
# fingertip observations, state(pose and vel) + force-torque sensors
num_ft_states = 13 * self.num_fingertips # 65
num_ft_force_torques = 6 * self.num_fingertips # 30
fingertip_obs_start = goal_obs_start + 11 # 72
self.obs_buf[:, fingertip_obs_start:fingertip_obs_start + 3*self.num_fingertips] = self.fingertip_pos.reshape(self.num_envs, 3*self.num_fingertips)
self.obs_buf[:, fingertip_obs_start + 3*self.num_fingertips:fingertip_obs_start + 7*self.num_fingertips] = self.fingertip_rot.reshape(self.num_envs, 4*self.num_fingertips)
self.obs_buf[:, fingertip_obs_start + 7*self.num_fingertips:fingertip_obs_start + 13*self.num_fingertips] = self.fingertip_velocities.reshape(self.num_envs, 6*self.num_fingertips)
self.obs_buf[:, fingertip_obs_start + num_ft_states:fingertip_obs_start + num_ft_states + num_ft_force_torques] = self.force_torque_obs_scale * self.vec_sensor_tensor
# obs_end = 96 + 65 + 30 = 167
# obs_total = obs_end + num_actions = 187
obs_end = fingertip_obs_start + num_ft_states + num_ft_force_torques
self.obs_buf[:, obs_end:obs_end + self.num_actions] = self.actions
| 14,430 | Python | 50.355872 | 194 | 0.627997 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/franka_cabinet.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.franka import Franka
from omniisaacgymenvs.robots.articulations.cabinet import Cabinet
from omniisaacgymenvs.robots.articulations.views.franka_view import FrankaView
from omniisaacgymenvs.robots.articulations.views.cabinet_view import CabinetView
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.core.prims import RigidPrim, RigidPrimView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.transformations import *
from omni.isaac.cloner import Cloner
import numpy as np
import torch
import math
from pxr import Usd, UsdGeom
class FrankaCabinetTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["episodeLength"]
self.action_scale = self._task_cfg["env"]["actionScale"]
self.start_position_noise = self._task_cfg["env"]["startPositionNoise"]
self.start_rotation_noise = self._task_cfg["env"]["startRotationNoise"]
self.num_props = self._task_cfg["env"]["numProps"]
self.dof_vel_scale = self._task_cfg["env"]["dofVelocityScale"]
self.dist_reward_scale = self._task_cfg["env"]["distRewardScale"]
self.rot_reward_scale = self._task_cfg["env"]["rotRewardScale"]
self.around_handle_reward_scale = self._task_cfg["env"]["aroundHandleRewardScale"]
self.open_reward_scale = self._task_cfg["env"]["openRewardScale"]
self.finger_dist_reward_scale = self._task_cfg["env"]["fingerDistRewardScale"]
self.action_penalty_scale = self._task_cfg["env"]["actionPenaltyScale"]
self.finger_close_reward_scale = self._task_cfg["env"]["fingerCloseRewardScale"]
self.distX_offset = 0.04
self.dt = 1/60.
self._num_observations = 23
self._num_actions = 9
RLTask.__init__(self, name, env)
return
def set_up_scene(self, scene) -> None:
self.get_franka()
self.get_cabinet()
if self.num_props > 0:
self.get_props()
super().set_up_scene(scene)
self._frankas = FrankaView(prim_paths_expr="/World/envs/.*/franka", name="franka_view")
self._cabinets = CabinetView(prim_paths_expr="/World/envs/.*/cabinet", name="cabinet_view")
scene.add(self._frankas)
scene.add(self._frankas._hands)
scene.add(self._frankas._lfingers)
scene.add(self._frankas._rfingers)
scene.add(self._cabinets)
scene.add(self._cabinets._drawers)
if self.num_props > 0:
self._props = RigidPrimView(prim_paths_expr="/World/envs/.*/prop/.*", name="prop_view", reset_xform_properties=False)
scene.add(self._props)
self.init_data()
return
def get_franka(self):
franka = Franka(prim_path=self.default_zero_env_path + "/franka", name="franka")
self._sim_config.apply_articulation_settings("franka", get_prim_at_path(franka.prim_path), self._sim_config.parse_actor_config("franka"))
def get_cabinet(self):
cabinet = Cabinet(self.default_zero_env_path + "/cabinet", name="cabinet")
self._sim_config.apply_articulation_settings("cabinet", get_prim_at_path(cabinet.prim_path), self._sim_config.parse_actor_config("cabinet"))
def get_props(self):
prop_cloner = Cloner()
drawer_pos = torch.tensor([0.0515, 0.0, 0.7172])
prop_color = torch.tensor([0.2, 0.4, 0.6])
props_per_row = int(math.ceil(math.sqrt(self.num_props)))
prop_size = 0.08
prop_spacing = 0.09
xmin = -0.5 * prop_spacing * (props_per_row - 1)
zmin = -0.5 * prop_spacing * (props_per_row - 1)
prop_count = 0
prop_pos = []
for j in range(props_per_row):
prop_up = zmin + j * prop_spacing
for k in range(props_per_row):
if prop_count >= self.num_props:
break
propx = xmin + k * prop_spacing
prop_pos.append([propx, prop_up, 0.0])
prop_count += 1
prop = DynamicCuboid(
prim_path=self.default_zero_env_path + "/prop/prop_0",
name="prop",
color=prop_color,
size=prop_size,
density=100.0
)
self._sim_config.apply_articulation_settings("prop", get_prim_at_path(prop.prim_path), self._sim_config.parse_actor_config("prop"))
prop_paths = [f"{self.default_zero_env_path}/prop/prop_{j}" for j in range(self.num_props)]
prop_cloner.clone(
source_prim_path=self.default_zero_env_path + "/prop/prop_0",
prim_paths=prop_paths,
positions=np.array(prop_pos)+drawer_pos.numpy()
)
def init_data(self) -> None:
def get_env_local_pose(env_pos, xformable, device):
"""Compute pose in env-local coordinates"""
world_transform = xformable.ComputeLocalToWorldTransform(0)
world_pos = world_transform.ExtractTranslation()
world_quat = world_transform.ExtractRotationQuat()
px = world_pos[0] - env_pos[0]
py = world_pos[1] - env_pos[1]
pz = world_pos[2] - env_pos[2]
qx = world_quat.imaginary[0]
qy = world_quat.imaginary[1]
qz = world_quat.imaginary[2]
qw = world_quat.real
return torch.tensor([px, py, pz, qw, qx, qy, qz], device=device, dtype=torch.float)
stage = get_current_stage()
hand_pose = get_env_local_pose(self._env_pos[0], UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/franka/panda_link7")), self._device)
lfinger_pose = get_env_local_pose(
self._env_pos[0], UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/franka/panda_leftfinger")), self._device
)
rfinger_pose = get_env_local_pose(
self._env_pos[0], UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/franka/panda_rightfinger")), self._device
)
finger_pose = torch.zeros(7, device=self._device)
finger_pose[0:3] = (lfinger_pose[0:3] + rfinger_pose[0:3]) / 2.0
finger_pose[3:7] = lfinger_pose[3:7]
hand_pose_inv_rot, hand_pose_inv_pos = (tf_inverse(hand_pose[3:7], hand_pose[0:3]))
grasp_pose_axis = 1
franka_local_grasp_pose_rot, franka_local_pose_pos = tf_combine(hand_pose_inv_rot, hand_pose_inv_pos, finger_pose[3:7], finger_pose[0:3])
franka_local_pose_pos += torch.tensor([0, 0.04, 0], device=self._device)
self.franka_local_grasp_pos = franka_local_pose_pos.repeat((self._num_envs, 1))
self.franka_local_grasp_rot = franka_local_grasp_pose_rot.repeat((self._num_envs, 1))
drawer_local_grasp_pose = torch.tensor([0.3, 0.01, 0.0, 1.0, 0.0, 0.0, 0.0], device=self._device)
self.drawer_local_grasp_pos = drawer_local_grasp_pose[0:3].repeat((self._num_envs, 1))
self.drawer_local_grasp_rot = drawer_local_grasp_pose[3:7].repeat((self._num_envs, 1))
self.gripper_forward_axis = torch.tensor([0, 0, 1], device=self._device, dtype=torch.float).repeat((self._num_envs, 1))
self.drawer_inward_axis = torch.tensor([-1, 0, 0], device=self._device, dtype=torch.float).repeat((self._num_envs, 1))
self.gripper_up_axis = torch.tensor([0, 1, 0], device=self._device, dtype=torch.float).repeat((self._num_envs, 1))
self.drawer_up_axis = torch.tensor([0, 0, 1], device=self._device, dtype=torch.float).repeat((self._num_envs, 1))
self.franka_default_dof_pos = torch.tensor(
[1.157, -1.066, -0.155, -2.239, -1.841, 1.003, 0.469, 0.035, 0.035], device=self._device
)
self.actions = torch.zeros((self._num_envs, self.num_actions), device=self._device)
def get_observations(self) -> dict:
hand_pos, hand_rot = self._frankas._hands.get_world_poses(clone=False)
drawer_pos, drawer_rot = self._cabinets._drawers.get_world_poses(clone=False)
franka_dof_pos = self._frankas.get_joint_positions(clone=False)
franka_dof_vel = self._frankas.get_joint_velocities(clone=False)
self.cabinet_dof_pos = self._cabinets.get_joint_positions(clone=False)
self.cabinet_dof_vel = self._cabinets.get_joint_velocities(clone=False)
self.franka_dof_pos = franka_dof_pos
self.franka_grasp_rot, self.franka_grasp_pos, self.drawer_grasp_rot, self.drawer_grasp_pos = self.compute_grasp_transforms(
hand_rot,
hand_pos,
self.franka_local_grasp_rot,
self.franka_local_grasp_pos,
drawer_rot,
drawer_pos,
self.drawer_local_grasp_rot,
self.drawer_local_grasp_pos,
)
self.franka_lfinger_pos, self.franka_lfinger_rot = self._frankas._lfingers.get_world_poses(clone=False)
self.franka_rfinger_pos, self.franka_rfinger_rot = self._frankas._lfingers.get_world_poses(clone=False)
dof_pos_scaled = (
2.0
* (franka_dof_pos - self.franka_dof_lower_limits)
/ (self.franka_dof_upper_limits - self.franka_dof_lower_limits)
- 1.0
)
to_target = self.drawer_grasp_pos - self.franka_grasp_pos
self.obs_buf = torch.cat(
(
dof_pos_scaled,
franka_dof_vel * self.dof_vel_scale,
to_target,
self.cabinet_dof_pos[:, 3].unsqueeze(-1),
self.cabinet_dof_vel[:, 3].unsqueeze(-1),
),
dim=-1,
)
observations = {
self._frankas.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
self.actions = actions.clone().to(self._device)
targets = self.franka_dof_targets + self.franka_dof_speed_scales * self.dt * self.actions * self.action_scale
self.franka_dof_targets[:] = torch.clamp(targets, self.franka_dof_lower_limits, self.franka_dof_upper_limits)
env_ids_int32 = torch.arange(self._frankas.count, dtype=torch.int32, device=self._device)
self._frankas.set_joint_position_targets(self.franka_dof_targets, indices=env_ids_int32)
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
num_indices = len(indices)
# reset franka
pos = torch.clamp(
self.franka_default_dof_pos.unsqueeze(0)
+ 0.25 * (torch.rand((len(env_ids), self.num_franka_dofs), device=self._device) - 0.5),
self.franka_dof_lower_limits,
self.franka_dof_upper_limits,
)
dof_pos = torch.zeros((num_indices, self._frankas.num_dof), device=self._device)
dof_vel = torch.zeros((num_indices, self._frankas.num_dof), device=self._device)
dof_pos[:, :] = pos
self.franka_dof_targets[env_ids, :] = pos
self.franka_dof_pos[env_ids, :] = pos
# reset cabinet
self._cabinets.set_joint_positions(torch.zeros_like(self._cabinets.get_joint_positions(clone=False)[env_ids]), indices=indices)
self._cabinets.set_joint_velocities(torch.zeros_like(self._cabinets.get_joint_velocities(clone=False)[env_ids]), indices=indices)
# reset props
if self.num_props > 0:
self._props.set_world_poses(
self.default_prop_pos[self.prop_indices[env_ids].flatten()],
self.default_prop_rot[self.prop_indices[env_ids].flatten()],
self.prop_indices[env_ids].flatten().to(torch.int32)
)
self._frankas.set_joint_position_targets(self.franka_dof_targets[env_ids], indices=indices)
self._frankas.set_joint_positions(dof_pos, indices=indices)
self._frankas.set_joint_velocities(dof_vel, indices=indices)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def post_reset(self):
self.num_franka_dofs = self._frankas.num_dof
self.franka_dof_pos = torch.zeros((self.num_envs, self.num_franka_dofs), device=self._device)
dof_limits = self._frankas.get_dof_limits()
self.franka_dof_lower_limits = dof_limits[0, :, 0].to(device=self._device)
self.franka_dof_upper_limits = dof_limits[0, :, 1].to(device=self._device)
self.franka_dof_speed_scales = torch.ones_like(self.franka_dof_lower_limits)
self.franka_dof_speed_scales[self._frankas.gripper_indices] = 0.1
self.franka_dof_targets = torch.zeros(
(self._num_envs, self.num_franka_dofs), dtype=torch.float, device=self._device
)
if self.num_props > 0:
self.default_prop_pos, self.default_prop_rot = self._props.get_world_poses()
self.prop_indices = torch.arange(self._num_envs * self.num_props, device=self._device).view(
self._num_envs, self.num_props
)
# randomize all envs
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self) -> None:
self.rew_buf[:] = self.compute_franka_reward(
self.reset_buf, self.progress_buf, self.actions, self.cabinet_dof_pos,
self.franka_grasp_pos, self.drawer_grasp_pos, self.franka_grasp_rot, self.drawer_grasp_rot,
self.franka_lfinger_pos, self.franka_rfinger_pos,
self.gripper_forward_axis, self.drawer_inward_axis, self.gripper_up_axis, self.drawer_up_axis,
self._num_envs, self.dist_reward_scale, self.rot_reward_scale, self.around_handle_reward_scale, self.open_reward_scale,
self.finger_dist_reward_scale, self.action_penalty_scale, self.distX_offset, self._max_episode_length, self.franka_dof_pos,
self.finger_close_reward_scale,
)
def is_done(self) -> None:
# reset if drawer is open or max length reached
self.reset_buf = torch.where(self.cabinet_dof_pos[:, 3] > 0.39, torch.ones_like(self.reset_buf), self.reset_buf)
self.reset_buf = torch.where(self.progress_buf >= self._max_episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf)
def compute_grasp_transforms(
self,
hand_rot,
hand_pos,
franka_local_grasp_rot,
franka_local_grasp_pos,
drawer_rot,
drawer_pos,
drawer_local_grasp_rot,
drawer_local_grasp_pos,
):
global_franka_rot, global_franka_pos = tf_combine(
hand_rot, hand_pos, franka_local_grasp_rot, franka_local_grasp_pos
)
global_drawer_rot, global_drawer_pos = tf_combine(
drawer_rot, drawer_pos, drawer_local_grasp_rot, drawer_local_grasp_pos
)
return global_franka_rot, global_franka_pos, global_drawer_rot, global_drawer_pos
def compute_franka_reward(
self, reset_buf, progress_buf, actions, cabinet_dof_pos,
franka_grasp_pos, drawer_grasp_pos, franka_grasp_rot, drawer_grasp_rot,
franka_lfinger_pos, franka_rfinger_pos,
gripper_forward_axis, drawer_inward_axis, gripper_up_axis, drawer_up_axis,
num_envs, dist_reward_scale, rot_reward_scale, around_handle_reward_scale, open_reward_scale,
finger_dist_reward_scale, action_penalty_scale, distX_offset, max_episode_length, joint_positions, finger_close_reward_scale
):
# type: (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, int, float, float, float, float, float, float, float, float, Tensor) -> Tuple[Tensor, Tensor]
# distance from hand to the drawer
d = torch.norm(franka_grasp_pos - drawer_grasp_pos, p=2, dim=-1)
dist_reward = 1.0 / (1.0 + d ** 2)
dist_reward *= dist_reward
dist_reward = torch.where(d <= 0.02, dist_reward * 2, dist_reward)
axis1 = tf_vector(franka_grasp_rot, gripper_forward_axis)
axis2 = tf_vector(drawer_grasp_rot, drawer_inward_axis)
axis3 = tf_vector(franka_grasp_rot, gripper_up_axis)
axis4 = tf_vector(drawer_grasp_rot, drawer_up_axis)
dot1 = torch.bmm(axis1.view(num_envs, 1, 3), axis2.view(num_envs, 3, 1)).squeeze(-1).squeeze(-1) # alignment of forward axis for gripper
dot2 = torch.bmm(axis3.view(num_envs, 1, 3), axis4.view(num_envs, 3, 1)).squeeze(-1).squeeze(-1) # alignment of up axis for gripper
# reward for matching the orientation of the hand to the drawer (fingers wrapped)
rot_reward = 0.5 * (torch.sign(dot1) * dot1 ** 2 + torch.sign(dot2) * dot2 ** 2)
# bonus if left finger is above the drawer handle and right below
around_handle_reward = torch.zeros_like(rot_reward)
around_handle_reward = torch.where(franka_lfinger_pos[:, 2] > drawer_grasp_pos[:, 2],
torch.where(franka_rfinger_pos[:, 2] < drawer_grasp_pos[:, 2],
around_handle_reward + 0.5, around_handle_reward), around_handle_reward)
# reward for distance of each finger from the drawer
finger_dist_reward = torch.zeros_like(rot_reward)
lfinger_dist = torch.abs(franka_lfinger_pos[:, 2] - drawer_grasp_pos[:, 2])
rfinger_dist = torch.abs(franka_rfinger_pos[:, 2] - drawer_grasp_pos[:, 2])
finger_dist_reward = torch.where(franka_lfinger_pos[:, 2] > drawer_grasp_pos[:, 2],
torch.where(franka_rfinger_pos[:, 2] < drawer_grasp_pos[:, 2],
(0.04 - lfinger_dist) + (0.04 - rfinger_dist), finger_dist_reward), finger_dist_reward)
finger_close_reward = torch.zeros_like(rot_reward)
finger_close_reward = torch.where(d <=0.03, (0.04 - joint_positions[:, 7]) + (0.04 - joint_positions[:, 8]), finger_close_reward)
# regularization on the actions (summed for each environment)
action_penalty = torch.sum(actions ** 2, dim=-1)
# how far the cabinet has been opened out
open_reward = cabinet_dof_pos[:, 3] * around_handle_reward + cabinet_dof_pos[:, 3] # drawer_top_joint
rewards = dist_reward_scale * dist_reward + rot_reward_scale * rot_reward \
+ around_handle_reward_scale * around_handle_reward + open_reward_scale * open_reward \
+ finger_dist_reward_scale * finger_dist_reward - action_penalty_scale * action_penalty + finger_close_reward * finger_close_reward_scale
# bonus for opening drawer properly
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.01, rewards + 0.5, rewards)
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.2, rewards + around_handle_reward, rewards)
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.39, rewards + (2.0 * around_handle_reward), rewards)
# # prevent bad style in opening drawer
# rewards = torch.where(franka_lfinger_pos[:, 0] < drawer_grasp_pos[:, 0] - distX_offset,
# torch.ones_like(rewards) * -1, rewards)
# rewards = torch.where(franka_rfinger_pos[:, 0] < drawer_grasp_pos[:, 0] - distX_offset,
# torch.ones_like(rewards) * -1, rewards)
return rewards
| 20,308 | Python | 47.586124 | 222 | 0.621627 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/crazyflie.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.crazyflie import Crazyflie
from omniisaacgymenvs.robots.articulations.views.crazyflie_view import CrazyflieView
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.utils.prims import get_prim_at_path
import numpy as np
import torch
EPS = 1e-6 # small constant to avoid divisions by 0 and log(0)
class CrazyflieTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["maxEpisodeLength"]
self.dt = self._task_cfg["sim"]["dt"]
self._num_observations = 18
self._num_actions = 4
self._crazyflie_position = torch.tensor([0, 0, 1.0])
self._ball_position = torch.tensor([0, 0, 1.0])
RLTask.__init__(self, name=name, env=env)
# parameters for the crazyflie
self.arm_length = 0.05
# parameters for the controller
self.motor_damp_time_up = 0.15
self.motor_damp_time_down = 0.15
# I use the multiplier 4, since 4*T ~ time for a step response to finish, where
# T is a time constant of the first-order filter
self.motor_tau_up = 4 * self.dt / (self.motor_damp_time_up + EPS)
self.motor_tau_down = 4 * self.dt / (self.motor_damp_time_down + EPS)
self.thrusts = torch.zeros((self._num_envs, 4, 3), dtype=torch.float32, device=self._device)
self.thrust_cmds_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
self.thrust_rot_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
# thrust max
self.mass = 0.028
self.thrust_to_weight = 1.9
self.motor_assymetry = np.array([1.0, 1.0, 1.0, 1.0])
# re-normalizing to sum-up to 4
self.motor_assymetry = self.motor_assymetry * 4. / np.sum(self.motor_assymetry)
self.grav_z = -1.0 * self._task_cfg["sim"]["gravity"][2]
thrust_max = self.grav_z * self.mass * self.thrust_to_weight * self.motor_assymetry / 4.0
self.thrust_max = torch.tensor(thrust_max, device=self._device, dtype=torch.float32)
self.motor_linearity = 1.0
self.prop_max_rot = 433.3
self.target_positions = torch.zeros((self._num_envs, 3), device=self._device, dtype=torch.float32)
self.target_positions[:, 2] = 1
self.actions = torch.zeros((self._num_envs, 4), device=self._device, dtype=torch.float32)
self.all_indices = torch.arange(self._num_envs, dtype=torch.int32, device=self._device)
# Extra info
self.extras = {}
torch_zeros = lambda: torch.zeros(self.num_envs, dtype=torch.float, device=self.device, requires_grad=False)
self.episode_sums = {"rew_pos": torch_zeros(), "rew_orient": torch_zeros(), "rew_effort": torch_zeros(),
"rew_spin": torch_zeros(),
"raw_dist": torch_zeros(), "raw_orient": torch_zeros(), "raw_effort": torch_zeros(),
"raw_spin": torch_zeros()}
return
def set_up_scene(self, scene) -> None:
self.get_crazyflie()
self.get_target()
RLTask.set_up_scene(self, scene)
self._copters = CrazyflieView(prim_paths_expr="/World/envs/.*/Crazyflie", name="crazyflie_view")
self._balls = RigidPrimView(prim_paths_expr="/World/envs/.*/ball")
scene.add(self._copters)
scene.add(self._balls)
for i in range(4):
scene.add(self._copters.physics_rotors[i])
return
def get_crazyflie(self):
copter = Crazyflie(prim_path=self.default_zero_env_path + "/Crazyflie", name="crazyflie",
translation=self._crazyflie_position)
self._sim_config.apply_articulation_settings("crazyflie", get_prim_at_path(copter.prim_path),
self._sim_config.parse_actor_config("crazyflie"))
def get_target(self):
radius = 0.2
color = torch.tensor([1, 0, 0])
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/ball",
translation=self._ball_position,
name="target_0",
radius=radius,
color=color)
self._sim_config.apply_articulation_settings("ball", get_prim_at_path(ball.prim_path),
self._sim_config.parse_actor_config("ball"))
ball.set_collision_enabled(False)
def get_observations(self) -> dict:
self.root_pos, self.root_rot = self._copters.get_world_poses(clone=False)
self.root_velocities = self._copters.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
rot_x = quat_axis(root_quats, 0)
rot_y = quat_axis(root_quats, 1)
rot_z = quat_axis(root_quats, 2)
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = self.target_positions - root_positions
self.obs_buf[..., 3:6] = rot_x
self.obs_buf[..., 6:9] = rot_y
self.obs_buf[..., 9:12] = rot_z
self.obs_buf[..., 12:15] = root_linvels
self.obs_buf[..., 15:18] = root_angvels
observations = {
self._copters.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
actions = actions.clone().to(self._device)
self.actions = actions
# clamp to [-1.0, 1.0]
thrust_cmds = torch.clamp(actions, min=-1.0, max=1.0)
# scale to [0.0, 1.0]
thrust_cmds = (thrust_cmds + 1.0) / 2.0
# filtering the thruster and adding noise
motor_tau = self.motor_tau_up * torch.ones((self._num_envs, 4), dtype=torch.float32, device=self._device)
motor_tau[thrust_cmds < self.thrust_cmds_damp] = self.motor_tau_down
motor_tau[motor_tau > 1.0] = 1.0
# Since NN commands thrusts we need to convert to rot vel and back
thrust_rot = thrust_cmds ** 0.5
self.thrust_rot_damp = motor_tau * (thrust_rot - self.thrust_rot_damp) + self.thrust_rot_damp
self.thrust_cmds_damp = self.thrust_rot_damp ** 2
## Adding noise
thrust_noise = 0.01 * torch.randn(4, dtype=torch.float32, device=self._device)
thrust_noise = thrust_cmds * thrust_noise
self.thrust_cmds_damp = torch.clamp(self.thrust_cmds_damp + thrust_noise, min=0.0, max=1.0)
thrusts = self.thrust_max * self.thrust_cmds_damp
# thrusts given rotation
root_quats = self.root_rot
rot_x = quat_axis(root_quats, 0)
rot_y = quat_axis(root_quats, 1)
rot_z = quat_axis(root_quats, 2)
rot_matrix = torch.cat((rot_x, rot_y, rot_z), 1).reshape(-1, 3, 3)
force_x = torch.zeros(self._num_envs, 4, dtype=torch.float32, device=self._device)
force_y = torch.zeros(self._num_envs, 4, dtype=torch.float32, device=self._device)
force_xy = torch.cat((force_x, force_y), 1).reshape(-1, 4, 2)
thrusts = thrusts.reshape(-1, 4, 1)
thrusts = torch.cat((force_xy, thrusts), 2)
thrusts_0 = thrusts[:, 0]
thrusts_0 = thrusts_0[:, :, None]
thrusts_1 = thrusts[:, 1]
thrusts_1 = thrusts_1[:, :, None]
thrusts_2 = thrusts[:, 2]
thrusts_2 = thrusts_2[:, :, None]
thrusts_3 = thrusts[:, 3]
thrusts_3 = thrusts_3[:, :, None]
mod_thrusts_0 = torch.matmul(rot_matrix, thrusts_0)
mod_thrusts_1 = torch.matmul(rot_matrix, thrusts_1)
mod_thrusts_2 = torch.matmul(rot_matrix, thrusts_2)
mod_thrusts_3 = torch.matmul(rot_matrix, thrusts_3)
self.thrusts[:, 0] = torch.squeeze(mod_thrusts_0)
self.thrusts[:, 1] = torch.squeeze(mod_thrusts_1)
self.thrusts[:, 2] = torch.squeeze(mod_thrusts_2)
self.thrusts[:, 3] = torch.squeeze(mod_thrusts_3)
# clear actions for reset envs
self.thrusts[reset_env_ids] = 0
# spin spinning rotors
prop_rot = self.thrust_cmds_damp * self.prop_max_rot
self.dof_vel[:, 0] = prop_rot[:, 0]
self.dof_vel[:, 1] = -1.0 * prop_rot[:, 1]
self.dof_vel[:, 2] = prop_rot[:, 2]
self.dof_vel[:, 3] = -1.0 * prop_rot[:, 3]
self._copters.set_joint_velocities(self.dof_vel, indices=self.all_indices)
# apply actions
for i in range(4):
self._copters.physics_rotors[i].apply_forces(self.thrusts[:, i], indices=self.all_indices)
def post_reset(self):
self.root_pos, self.root_rot = self._copters.get_world_poses(clone=False)
self.root_velocities = self._copters.get_velocities(clone=False)
self.dof_pos = self._copters.get_joint_positions(clone=False)
self.dof_vel = self._copters.get_joint_velocities(clone=False)
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses(clone=False)
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# control parameters
self.thrusts = torch.zeros((self._num_envs, 4, 3), dtype=torch.float32, device=self._device)
self.thrust_cmds_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
self.thrust_rot_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
self.set_targets(self.all_indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (0, 0) and z in (2)
self.target_positions[envs_long, 0:2] = torch.zeros((num_sets, 2), device=self._device)
self.target_positions[envs_long, 2] = torch.ones(num_sets, device=self._device) * 2.0
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
ball_pos[:, 2] += 0.0
self._balls.set_world_poses(ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
self.dof_pos[env_ids, :] = torch_rand_float(-0.0, 0.0, (num_resets, self._copters.num_dof), device=self._device)
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.0, 0.0, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.0, 0.0, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(-0.0, 0.0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._copters.set_joint_positions(self.dof_pos[env_ids], indices=env_ids)
self._copters.set_joint_velocities(self.dof_vel[env_ids], indices=env_ids)
self._copters.set_world_poses(root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._copters.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
self.thrust_cmds_damp[env_ids] = 0
self.thrust_rot_damp[env_ids] = 0
# fill extras
self.extras["episode"] = {}
for key in self.episode_sums.keys():
self.extras["episode"][key] = torch.mean(
self.episode_sums[key][env_ids]) / self._max_episode_length
self.episode_sums[key][env_ids] = 0.
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_angvels = self.root_velocities[:, 3:]
# pos reward
target_dist = torch.sqrt(torch.square(self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
# orient reward
ups = quat_axis(root_quats, 2)
self.orient_z = ups[..., 2]
up_reward = torch.clamp(ups[..., 2], min=0.0, max=1.0)
# effort reward
effort = torch.square(self.actions).sum(-1)
effort_reward = 0.05 * torch.exp(-0.5 * effort)
# spin reward
spin = torch.square(root_angvels).sum(-1)
spin_reward = 0.01 * torch.exp(-1.0 * spin)
# combined reward
self.rew_buf[:] = pos_reward + pos_reward * (up_reward + spin_reward) - effort_reward
# log episode reward sums
self.episode_sums["rew_pos"] += pos_reward
self.episode_sums["rew_orient"] += up_reward
self.episode_sums["rew_effort"] += effort_reward
self.episode_sums["rew_spin"] += spin_reward
# log raw info
self.episode_sums["raw_dist"] += target_dist
self.episode_sums["raw_orient"] += ups[..., 2]
self.episode_sums["raw_effort"] += effort
self.episode_sums["raw_spin"] += spin
def is_done(self) -> None:
# resets due to misbehavior
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 5.0, ones, die)
# z >= 0.5 & z <= 5.0 & up > 0
die = torch.where(self.root_positions[..., 2] < 0.5, ones, die)
die = torch.where(self.root_positions[..., 2] > 5.0, ones, die)
die = torch.where(self.orient_z < 0.0, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(self.progress_buf >= self._max_episode_length - 1, ones, die)
| 16,158 | Python | 41.635884 | 120 | 0.613814 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/humanoid.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.shared.locomotion import LocomotionTask
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.humanoid import Humanoid
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
from omni.isaac.core.utils.torch.maths import torch_rand_float, tensor_clamp, unscale
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
import numpy as np
import torch
import math
from pxr import PhysxSchema
class HumanoidLocomotionTask(LocomotionTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_observations = 87
self._num_actions = 21
self._humanoid_positions = torch.tensor([0, 0, 1.34])
LocomotionTask.__init__(self, name=name, env=env)
return
def set_up_scene(self, scene) -> None:
self.get_humanoid()
RLTask.set_up_scene(self, scene)
self._humanoids = ArticulationView(prim_paths_expr="/World/envs/.*/Humanoid/torso", name="humanoid_view", reset_xform_properties=False)
scene.add(self._humanoids)
return
def get_humanoid(self):
humanoid = Humanoid(prim_path=self.default_zero_env_path + "/Humanoid", name="Humanoid", translation=self._humanoid_positions)
self._sim_config.apply_articulation_settings("Humanoid", get_prim_at_path(humanoid.prim_path),
self._sim_config.parse_actor_config("Humanoid"))
def get_robot(self):
return self._humanoids
def post_reset(self):
self.joint_gears = torch.tensor(
[
67.5000, # lower_waist
67.5000, # lower_waist
67.5000, # right_upper_arm
67.5000, # right_upper_arm
67.5000, # left_upper_arm
67.5000, # left_upper_arm
67.5000, # pelvis
45.0000, # right_lower_arm
45.0000, # left_lower_arm
45.0000, # right_thigh: x
135.0000, # right_thigh: y
45.0000, # right_thigh: z
45.0000, # left_thigh: x
135.0000, # left_thigh: y
45.0000, # left_thigh: z
90.0000, # right_knee
90.0000, # left_knee
22.5, # right_foot
22.5, # right_foot
22.5, # left_foot
22.5, # left_foot
],
device=self._device,
)
self.max_motor_effort = torch.max(self.joint_gears)
self.motor_effort_ratio = self.joint_gears / self.max_motor_effort
dof_limits = self._humanoids.get_dof_limits()
self.dof_limits_lower = dof_limits[0, :, 0].to(self._device)
self.dof_limits_upper = dof_limits[0, :, 1].to(self._device)
LocomotionTask.post_reset(self)
def get_dof_at_limit_cost(self):
return get_dof_at_limit_cost(self.obs_buf, self.motor_effort_ratio, self.joints_at_limit_cost_scale)
@torch.jit.script
def get_dof_at_limit_cost(obs_buf, motor_effort_ratio, joints_at_limit_cost_scale):
# type: (Tensor, Tensor, float) -> Tensor
scaled_cost = joints_at_limit_cost_scale * (torch.abs(obs_buf[:, 12:33]) - 0.98) / 0.02
dof_at_limit_cost = torch.sum(
(torch.abs(obs_buf[:, 12:33]) > 0.98) * scaled_cost * motor_effort_ratio.unsqueeze(0), dim=-1
)
return dof_at_limit_cost
| 5,214 | Python | 39.742187 | 143 | 0.656885 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/ant.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.robots.articulations.ant import Ant
from omniisaacgymenvs.tasks.shared.locomotion import LocomotionTask
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
from omni.isaac.core.utils.torch.maths import torch_rand_float, tensor_clamp, unscale
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
from pxr import PhysxSchema
import numpy as np
import torch
import math
class AntLocomotionTask(LocomotionTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_observations = 60
self._num_actions = 8
self._ant_positions = torch.tensor([0, 0, 0.5])
LocomotionTask.__init__(self, name=name, env=env)
return
def set_up_scene(self, scene) -> None:
self.get_ant()
RLTask.set_up_scene(self, scene)
self._ants = ArticulationView(prim_paths_expr="/World/envs/.*/Ant/torso", name="ant_view", reset_xform_properties=False)
scene.add(self._ants)
return
def get_ant(self):
ant = Ant(prim_path=self.default_zero_env_path + "/Ant", name="Ant", translation=self._ant_positions)
self._sim_config.apply_articulation_settings("Ant", get_prim_at_path(ant.prim_path), self._sim_config.parse_actor_config("Ant"))
def get_robot(self):
return self._ants
def post_reset(self):
self.joint_gears = torch.tensor([15, 15, 15, 15, 15, 15, 15, 15], dtype=torch.float32, device=self._device)
dof_limits = self._ants.get_dof_limits()
self.dof_limits_lower = dof_limits[0, :, 0].to(self._device)
self.dof_limits_upper = dof_limits[0, :, 1].to(self._device)
self.motor_effort_ratio = torch.ones_like(self.joint_gears, device=self._device)
LocomotionTask.post_reset(self)
def get_dof_at_limit_cost(self):
return get_dof_at_limit_cost(self.obs_buf, self._ants.num_dof)
@torch.jit.script
def get_dof_at_limit_cost(obs_buf, num_dof):
# type: (Tensor, int) -> Tensor
return torch.sum(obs_buf[:, 12:12+num_dof] > 0.99, dim=-1) | 3,939 | Python | 40.473684 | 136 | 0.711348 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/cartpole.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.cartpole import Cartpole
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
import numpy as np
import torch
import math
class CartpoleTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
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"]
self._max_episode_length = 500
self._num_observations = 4
self._num_actions = 1
RLTask.__init__(self, name, env)
return
def set_up_scene(self, scene) -> None:
self.get_cartpole()
super().set_up_scene(scene)
self._cartpoles = ArticulationView(prim_paths_expr="/World/envs/.*/Cartpole", name="cartpole_view", reset_xform_properties=False)
scene.add(self._cartpoles)
return
def get_cartpole(self):
cartpole = Cartpole(prim_path=self.default_zero_env_path + "/Cartpole", name="Cartpole", translation=self._cartpole_positions)
# 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"))
def get_observations(self) -> dict:
dof_pos = self._cartpoles.get_joint_positions(clone=False)
dof_vel = self._cartpoles.get_joint_velocities(clone=False)
cart_pos = dof_pos[:, self._cart_dof_idx]
cart_vel = dof_vel[:, self._cart_dof_idx]
pole_pos = dof_pos[:, self._pole_dof_idx]
pole_vel = dof_vel[:, self._pole_dof_idx]
self.obs_buf[:, 0] = cart_pos
self.obs_buf[:, 1] = cart_vel
self.obs_buf[:, 2] = pole_pos
self.obs_buf[:, 3] = pole_vel
observations = {
self._cartpoles.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
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)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
# randomize DOF positions
dof_pos = torch.zeros((num_resets, self._cartpoles.num_dof), device=self._device)
dof_pos[:, self._cart_dof_idx] = 1.0 * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
dof_pos[:, self._pole_dof_idx] = 0.125 * math.pi * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
# randomize DOF velocities
dof_vel = torch.zeros((num_resets, self._cartpoles.num_dof), device=self._device)
dof_vel[:, self._cart_dof_idx] = 0.5 * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
dof_vel[:, self._pole_dof_idx] = 0.25 * math.pi * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
# apply resets
indices = env_ids.to(dtype=torch.int32)
self._cartpoles.set_joint_positions(dof_pos, indices=indices)
self._cartpoles.set_joint_velocities(dof_vel, indices=indices)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
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)
def calculate_metrics(self) -> None:
cart_pos = self.obs_buf[:, 0]
cart_vel = self.obs_buf[:, 1]
pole_angle = self.obs_buf[:, 2]
pole_vel = self.obs_buf[:, 3]
reward = 1.0 - pole_angle * pole_angle - 0.01 * torch.abs(cart_vel) - 0.005 * torch.abs(pole_vel)
reward = torch.where(torch.abs(cart_pos) > self._reset_dist, torch.ones_like(reward) * -2.0, reward)
reward = torch.where(torch.abs(pole_angle) > np.pi / 2, torch.ones_like(reward) * -2.0, reward)
self.rew_buf[:] = reward
def is_done(self) -> None:
cart_pos = self.obs_buf[:, 0]
pole_pos = self.obs_buf[:, 2]
resets = torch.where(torch.abs(cart_pos) > self._reset_dist, 1, 0)
resets = torch.where(torch.abs(pole_pos) > math.pi / 2, 1, resets)
resets = torch.where(self.progress_buf >= self._max_episode_length, 1, resets)
self.reset_buf[:] = resets
| 6,907 | Python | 41.380368 | 151 | 0.651658 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/ur10_reacher.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
from omniisaacgymenvs.sim2real.ur10 import RealWorldUR10
from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig
from omniisaacgymenvs.tasks.shared.reacher import ReacherTask
from omniisaacgymenvs.robots.articulations.views.ur10_view import UR10View
from omniisaacgymenvs.robots.articulations.ur10 import UR10
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch import *
from omni.isaac.gym.vec_env import VecEnvBase
import numpy as np
import torch
import math
class UR10ReacherTask(ReacherTask):
def __init__(
self,
name: str,
sim_config: SimConfig,
env: VecEnvBase,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self.obs_type = self._task_cfg["env"]["observationType"]
if not (self.obs_type in ["full"]):
raise Exception(
"Unknown type of observations!\nobservationType should be one of: [full]")
print("Obs type:", self.obs_type)
self.num_obs_dict = {
"full": 29,
# 6: UR10 joints position (action space)
# 6: UR10 joints velocity
# 3: goal position
# 4: goal rotation
# 4: goal relative rotation
# 6: previous action
}
self.object_scale = torch.tensor([1.0] * 3)
self.goal_scale = torch.tensor([2.0] * 3)
self._num_observations = self.num_obs_dict[self.obs_type]
self._num_actions = 6
self._num_states = 0
pi = math.pi
if self._task_cfg['safety']['enabled']:
# Depends on your real robot setup
self._dof_limits = torch.tensor([[
[np.deg2rad(-135), np.deg2rad(135)],
[np.deg2rad(-180), np.deg2rad(-60)],
[np.deg2rad(0), np.deg2rad(180)],
[np.deg2rad(-180), np.deg2rad(0)],
[np.deg2rad(-180), np.deg2rad(0)],
[np.deg2rad(-180), np.deg2rad(180)],
]], dtype=torch.float32, device=self._cfg["sim_device"])
else:
# For actions
self._dof_limits = torch.tensor([[
[-2*pi, 2*pi], # [-2*pi, 2*pi],
[-pi + pi/8, 0 - pi/8], # [-2*pi, 2*pi],
[-pi + pi/8, pi - pi/8], # [-2*pi, 2*pi],
[-pi, 0], # [-2*pi, 2*pi],
[-pi, pi], # [-2*pi, 2*pi],
[-2*pi, 2*pi], # [-2*pi, 2*pi],
]], dtype=torch.float32, device=self._cfg["sim_device"])
# The last action space cannot be [0, 0]
# It will introduce the following error:
# ValueError: Expected parameter loc (Tensor of shape (2048, 6)) of distribution Normal(loc: torch.Size([2048, 6]), scale: torch.Size([2048, 6])) to satisfy the constraint Real(), but found invalid values
ReacherTask.__init__(self, name=name, env=env)
# Setup Sim2Real
sim2real_config = self._task_cfg['sim2real']
if sim2real_config['enabled'] and self.test and self.num_envs == 1:
self.act_moving_average /= 5 # Reduce moving speed
self.real_world_ur10 = RealWorldUR10(
sim2real_config['fail_quietely'],
sim2real_config['verbose']
)
return
def get_num_dof(self):
return self._arms.num_dof
def get_arm(self):
ur10 = UR10(prim_path=self.default_zero_env_path + "/ur10", name="UR10")
self._sim_config.apply_articulation_settings(
"ur10",
get_prim_at_path(ur10.prim_path),
self._sim_config.parse_actor_config("ur10"),
)
def get_arm_view(self, scene):
arm_view = UR10View(prim_paths_expr="/World/envs/.*/ur10", name="ur10_view")
scene.add(arm_view._end_effectors)
return arm_view
def get_object_displacement_tensor(self):
return torch.tensor([0.0, 0.05, 0.0], device=self.device).repeat((self.num_envs, 1))
def get_observations(self):
self.arm_dof_pos = self._arms.get_joint_positions()
self.arm_dof_vel = self._arms.get_joint_velocities()
if self.obs_type == "full_no_vel":
self.compute_full_observations(True)
elif self.obs_type == "full":
self.compute_full_observations()
else:
print("Unkown observations type!")
observations = {
self._arms.name: {
"obs_buf": self.obs_buf
}
}
return observations
def get_reset_target_new_pos(self, n_reset_envs):
# Randomly generate goal positions, although the resulting goal may still not be reachable.
new_pos = torch_rand_float(-1, 1, (n_reset_envs, 3), device=self.device)
if self._task_cfg['sim2real']['enabled'] and self.test and self.num_envs == 1:
# Depends on your real robot setup
new_pos[:, 0] = torch.abs(new_pos[:, 0] * 0.1) + 0.35
new_pos[:, 1] = torch.abs(new_pos[:, 1] * 0.1) + 0.35
new_pos[:, 2] = torch.abs(new_pos[:, 2] * 0.5) + 0.3
else:
new_pos[:, 0] = new_pos[:, 0] * 0.4 + 0.5 * torch.sign(new_pos[:, 0])
new_pos[:, 1] = new_pos[:, 1] * 0.4 + 0.5 * torch.sign(new_pos[:, 1])
new_pos[:, 2] = torch.abs(new_pos[:, 2] * 0.8) + 0.1
if self._task_cfg['safety']['enabled']:
new_pos[:, 0] = torch.abs(new_pos[:, 0]) / 1.25
new_pos[:, 1] = torch.abs(new_pos[:, 1]) / 1.25
return new_pos
def compute_full_observations(self, no_vel=False):
if no_vel:
raise NotImplementedError()
else:
# There are many redundant information for the simple Reacher task, but we'll keep them for now.
self.obs_buf[:, 0:self.num_arm_dofs] = unscale(self.arm_dof_pos[:, :self.num_arm_dofs],
self.arm_dof_lower_limits, self.arm_dof_upper_limits)
self.obs_buf[:, self.num_arm_dofs:2*self.num_arm_dofs] = self.vel_obs_scale * self.arm_dof_vel[:, :self.num_arm_dofs]
base = 2 * self.num_arm_dofs
self.obs_buf[:, base+0:base+3] = self.goal_pos
self.obs_buf[:, base+3:base+7] = self.goal_rot
self.obs_buf[:, base+7:base+11] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, base+11:base+17] = self.actions
def send_joint_pos(self, joint_pos):
self.real_world_ur10.send_joint_pos(joint_pos)
| 8,205 | Python | 42.882353 | 216 | 0.599878 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/quadcopter.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.quadcopter import Quadcopter
from omniisaacgymenvs.robots.articulations.views.quadcopter_view import QuadcopterView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.prims import RigidPrimView
import numpy as np
import torch
import math
class QuadcopterTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["maxEpisodeLength"]
self.dt = self._task_cfg["sim"]["dt"]
self._num_observations = 21
self._num_actions = 12
self._copter_position = torch.tensor([0, 0, 1.0])
RLTask.__init__(self, name=name, env=env)
max_thrust = 2.0
self.thrust_lower_limits = -max_thrust * torch.ones(4, device=self._device, dtype=torch.float32)
self.thrust_upper_limits = max_thrust * torch.ones(4, device=self._device, dtype=torch.float32)
self.all_indices = torch.arange(self._num_envs, dtype=torch.int32, device=self._device)
return
def set_up_scene(self, scene) -> None:
self.get_copter()
self.get_target()
RLTask.set_up_scene(self, scene)
self._copters = QuadcopterView(prim_paths_expr="/World/envs/.*/Quadcopter", name="quadcopter_view")
self._balls = RigidPrimView(prim_paths_expr="/World/envs/.*/ball", name="targets_view", reset_xform_properties=False)
scene.add(self._copters)
scene.add(self._copters.rotors)
scene.add(self._balls)
return
def get_copter(self):
copter = Quadcopter(prim_path=self.default_zero_env_path + "/Quadcopter", name="quadcopter", translation=self._copter_position)
self._sim_config.apply_articulation_settings("copter", get_prim_at_path(copter.prim_path), self._sim_config.parse_actor_config("copter"))
def get_target(self):
radius = 0.05
color = torch.tensor([1, 0, 0])
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/ball",
name="target_0",
radius=radius,
color=color,
)
self._sim_config.apply_articulation_settings("ball", get_prim_at_path(ball.prim_path), self._sim_config.parse_actor_config("ball"))
ball.set_collision_enabled(False)
def get_observations(self) -> dict:
self.root_pos, self.root_rot = self._copters.get_world_poses(clone=False)
self.root_velocities = self._copters.get_velocities(clone=False)
self.dof_pos = self._copters.get_joint_positions(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 3:7] = root_quats
self.obs_buf[..., 7:10] = root_linvels / 2
self.obs_buf[..., 10:13] = root_angvels / math.pi
self.obs_buf[..., 13:21] = self.dof_pos
observations = {
self._copters.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
actions = actions.clone().to(self._device)
dof_action_speed_scale = 8 * math.pi
self.dof_position_targets += self.dt * dof_action_speed_scale * actions[:, 0:8]
self.dof_position_targets[:] = tensor_clamp(self.dof_position_targets, self.dof_lower_limits, self.dof_upper_limits)
thrust_action_speed_scale = 100
self.thrusts += self.dt * thrust_action_speed_scale * actions[:, 8:12]
self.thrusts[:] = tensor_clamp(self.thrusts, self.thrust_lower_limits, self.thrust_upper_limits)
self.forces[:, 0, 2] = self.thrusts[:, 0]
self.forces[:, 1, 2] = self.thrusts[:, 1]
self.forces[:, 2, 2] = self.thrusts[:, 2]
self.forces[:, 3, 2] = self.thrusts[:, 3]
# clear actions for reset envs
self.thrusts[reset_env_ids] = 0.0
self.forces[reset_env_ids] = 0.0
self.dof_position_targets[reset_env_ids] = self.dof_pos[reset_env_ids]
_, rotors_quat = self._copters.rotors.get_world_poses(clone=False)
rotors_quat = rotors_quat.reshape(self._num_envs, 4, 4)
for i in range(4):
self.forces_world_frame[:, i, :] = quat_apply(rotors_quat[:, i, :], self.forces[:, i, :])
# apply actions
self._copters.set_joint_position_targets(self.dof_position_targets)
self._copters.rotors.apply_forces(self.forces_world_frame)
def post_reset(self):
# control tensors
self.dof_position_targets = torch.zeros((self._num_envs, self._copters.num_dof), dtype=torch.float32, device=self._device, requires_grad=False)
self.thrusts = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device, requires_grad=False)
self.forces = torch.zeros((self._num_envs, self._copters.rotors.count // self._num_envs, 3), dtype=torch.float32, device=self._device, requires_grad=False)
self.forces_world_frame = torch.zeros((self._num_envs, self._copters.rotors.count // self._num_envs, 3), dtype=torch.float32, device=self._device, requires_grad=False)
self.target_positions = torch.zeros((self._num_envs, 3), device=self._device)
self.target_positions[:, 2] = 1.0
self.root_pos, self.root_rot = self._copters.get_world_poses(clone=False)
self.root_velocities = self._copters.get_velocities(clone=False)
self.dof_pos = self._copters.get_joint_positions(clone=False)
self.dof_vel = self._copters.get_joint_velocities(clone=False)
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
dof_limits = self._copters.get_dof_limits()
self.dof_lower_limits = torch.tensor(dof_limits[0][:, 0], device=self._device)
self.dof_upper_limits = torch.tensor(dof_limits[0][:, 1], device=self._device)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
self.dof_pos[env_ids, :] = torch_rand_float(-0.2, 0.2, (num_resets, self._copters.num_dof), device=self._device)
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-1.5, 1.5, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-1.5, 1.5, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(-0.2, 1.5, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._copters.set_joint_positions(self.dof_pos[env_ids], indices=env_ids)
self._copters.set_joint_velocities(self.dof_vel[env_ids], indices=env_ids)
self._copters.set_world_poses(root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._copters.set_velocities(root_velocities[env_ids], indices=env_ids)
self._balls.set_world_poses(positions=self.target_positions[:, 0:3] + self._env_pos)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_angvels = self.root_velocities[:, 3:]
# distance to target
target_dist = torch.sqrt(torch.square(self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + 3*target_dist * target_dist) # 2
self.target_dist = target_dist
self.root_positions = root_positions
# uprightness
ups = quat_axis(root_quats, 2)
tiltage = torch.abs(1 - ups[..., 2])
up_reward = 1.0 / (1.0 + 10 * tiltage * tiltage)
# spinning
spinnage = torch.abs(root_angvels[..., 2])
spinnage_reward = 1.0 / (1.0 + 0.001 * spinnage * spinnage)
rew = pos_reward + pos_reward * (up_reward + spinnage_reward + spinnage * spinnage * (-1/400))
rew = torch.clip(rew, 0.0, None)
self.rew_buf[:] = rew
def is_done(self) -> None:
# resets due to misbehavior
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 3.0, ones, die)
die = torch.where(self.root_positions[..., 2] < 0.3, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(self.progress_buf >= self._max_episode_length - 1, ones, die)
| 10,862 | Python | 44.2625 | 175 | 0.646474 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/ingenuity.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.ingenuity import Ingenuity
from omniisaacgymenvs.robots.articulations.views.ingenuity_view import IngenuityView
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.utils.prims import get_prim_at_path
import numpy as np
import torch
import math
class IngenuityTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["maxEpisodeLength"]
self.thrust_limit = 2000
self.thrust_lateral_component = 0.2
self.dt = self._task_cfg["sim"]["dt"]
self._num_observations = 13
self._num_actions = 6
self._ingenuity_position = torch.tensor([0, 0, 1.0])
self._ball_position = torch.tensor([0, 0, 1.0])
RLTask.__init__(self, name=name, env=env)
self.force_indices = torch.tensor([0, 2], device=self._device)
self.spinning_indices = torch.tensor([1, 3], device=self._device)
self.target_positions = torch.zeros((self._num_envs, 3), device=self._device, dtype=torch.float32)
self.target_positions[:, 2] = 1
self.all_indices = torch.arange(self._num_envs, dtype=torch.int32, device=self._device)
return
def set_up_scene(self, scene) -> None:
self.get_ingenuity()
self.get_target()
RLTask.set_up_scene(self, scene)
self._copters = IngenuityView(prim_paths_expr="/World/envs/.*/Ingenuity", name="ingenuity_view")
self._balls = RigidPrimView(prim_paths_expr="/World/envs/.*/ball", name="targets_view", reset_xform_properties=False)
scene.add(self._copters)
scene.add(self._balls)
for i in range(2):
scene.add(self._copters.physics_rotors[i])
scene.add(self._copters.visual_rotors[i])
return
def get_ingenuity(self):
copter = Ingenuity(prim_path=self.default_zero_env_path + "/Ingenuity", name="ingenuity", translation=self._ingenuity_position)
self._sim_config.apply_articulation_settings("ingenuity", get_prim_at_path(copter.prim_path), self._sim_config.parse_actor_config("ingenuity"))
def get_target(self):
radius = 0.1
color = torch.tensor([1, 0, 0])
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/ball",
translation=self._ball_position,
name="target_0",
radius=radius,
color=color,
)
self._sim_config.apply_articulation_settings("ball", get_prim_at_path(ball.prim_path), self._sim_config.parse_actor_config("ball"))
ball.set_collision_enabled(False)
def get_observations(self) -> dict:
self.root_pos, self.root_rot = self._copters.get_world_poses(clone=False)
self.root_velocities = self._copters.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 3:7] = root_quats
self.obs_buf[..., 7:10] = root_linvels / 2
self.obs_buf[..., 10:13] = root_angvels / math.pi
observations = {
self._copters.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
actions = actions.clone().to(self._device)
vertical_thrust_prop_0 = torch.clamp(actions[:, 2] * self.thrust_limit, -self.thrust_limit, self.thrust_limit)
vertical_thrust_prop_1 = torch.clamp(actions[:, 5] * self.thrust_limit, -self.thrust_limit, self.thrust_limit)
lateral_fraction_prop_0 = torch.clamp(
actions[:, 0:2] * self.thrust_lateral_component,
-self.thrust_lateral_component,
self.thrust_lateral_component,
)
lateral_fraction_prop_1 = torch.clamp(
actions[:, 3:5] * self.thrust_lateral_component,
-self.thrust_lateral_component,
self.thrust_lateral_component,
)
self.thrusts[:, 0, 2] = self.dt * vertical_thrust_prop_0
self.thrusts[:, 0, 0:2] = self.thrusts[:, 0, 2, None] * lateral_fraction_prop_0
self.thrusts[:, 1, 2] = self.dt * vertical_thrust_prop_1
self.thrusts[:, 1, 0:2] = self.thrusts[:, 1, 2, None] * lateral_fraction_prop_1
# clear actions for reset envs
self.thrusts[reset_env_ids] = 0
# spin spinning rotors
self.dof_vel[:, self.spinning_indices[0]] = 50
self.dof_vel[:, self.spinning_indices[1]] = -50
self._copters.set_joint_velocities(self.dof_vel, indices=self.all_indices)
# apply actions
for i in range(2):
self._copters.physics_rotors[i].apply_forces(self.thrusts[:, i], indices=self.all_indices)
def post_reset(self):
self.root_pos, self.root_rot = self._copters.get_world_poses(clone=False)
self.root_velocities = self._copters.get_velocities(clone=False)
self.dof_pos = self._copters.get_joint_positions(clone=False)
self.dof_vel = self._copters.get_joint_velocities(clone=False)
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses()
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# control tensors
self.thrusts = torch.zeros((self._num_envs, 2, 3), dtype=torch.float32, device=self._device)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-1, 1) and z in (1, 2)
self.target_positions[envs_long, 0:2] = torch.rand((num_sets, 2), device=self._device) * 2 - 1
self.target_positions[envs_long, 2] = torch.rand(num_sets, device=self._device) + 1
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
ball_pos[:, 2] += 0.4
self._balls.set_world_poses(ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
self.dof_pos[env_ids, :] = torch_rand_float(-0.2, 0.2, (num_resets, self._copters.num_dof), device=self._device)
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(-0.5, 0.5, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._copters.set_joint_positions(self.dof_pos[env_ids], indices=env_ids)
self._copters.set_joint_velocities(self.dof_vel[env_ids], indices=env_ids)
self._copters.set_world_poses(root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._copters.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_angvels = self.root_velocities[:, 3:]
# distance to target
target_dist = torch.sqrt(torch.square(self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
# uprightness
ups = quat_axis(root_quats, 2)
tiltage = torch.abs(1 - ups[..., 2])
up_reward = 1.0 / (1.0 + 30 * tiltage * tiltage)
# spinning
spinnage = torch.abs(root_angvels[..., 2])
spinnage_reward = 1.0 / (1.0 + 10 * spinnage * spinnage)
# combined reward
# uprightness and spinning only matter when close to the target
self.rew_buf[:] = pos_reward + pos_reward * (up_reward + spinnage_reward)
def is_done(self) -> None:
# resets due to misbehavior
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] < 0.5, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(self.progress_buf >= self._max_episode_length - 1, ones, die)
| 11,136 | Python | 42.33463 | 151 | 0.639098 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/anymal.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.anymal import Anymal
from omniisaacgymenvs.robots.articulations.views.anymal_view import AnymalView
from omniisaacgymenvs.tasks.utils.usd_utils import set_drive
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
import numpy as np
import torch
import math
class AnymalTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# normalization
self.lin_vel_scale = self._task_cfg["env"]["learn"]["linearVelocityScale"]
self.ang_vel_scale = self._task_cfg["env"]["learn"]["angularVelocityScale"]
self.dof_pos_scale = self._task_cfg["env"]["learn"]["dofPositionScale"]
self.dof_vel_scale = self._task_cfg["env"]["learn"]["dofVelocityScale"]
self.action_scale = self._task_cfg["env"]["control"]["actionScale"]
# reward scales
self.rew_scales = {}
self.rew_scales["lin_vel_xy"] = self._task_cfg["env"]["learn"]["linearVelocityXYRewardScale"]
self.rew_scales["ang_vel_z"] = self._task_cfg["env"]["learn"]["angularVelocityZRewardScale"]
self.rew_scales["lin_vel_z"] = self._task_cfg["env"]["learn"]["linearVelocityZRewardScale"]
self.rew_scales["joint_acc"] = self._task_cfg["env"]["learn"]["jointAccRewardScale"]
self.rew_scales["action_rate"] = self._task_cfg["env"]["learn"]["actionRateRewardScale"]
self.rew_scales["cosmetic"] = self._task_cfg["env"]["learn"]["cosmeticRewardScale"]
# command ranges
self.command_x_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_x"]
self.command_y_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_y"]
self.command_yaw_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["yaw"]
# base init state
pos = self._task_cfg["env"]["baseInitState"]["pos"]
rot = self._task_cfg["env"]["baseInitState"]["rot"]
v_lin = self._task_cfg["env"]["baseInitState"]["vLinear"]
v_ang = self._task_cfg["env"]["baseInitState"]["vAngular"]
state = pos + rot + v_lin + v_ang
self.base_init_state = state
# default joint positions
self.named_default_joint_angles = self._task_cfg["env"]["defaultJointAngles"]
# other
self.dt = 1 / 60
self.max_episode_length_s = self._task_cfg["env"]["learn"]["episodeLength_s"]
self.max_episode_length = int(self.max_episode_length_s / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
for key in self.rew_scales.keys():
self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._anymal_translation = torch.tensor([0.0, 0.0, 0.62])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._num_observations = 48
self._num_actions = 12
RLTask.__init__(self, name, env)
return
def set_up_scene(self, scene) -> None:
self.get_anymal()
super().set_up_scene(scene)
self._anymals = AnymalView(prim_paths_expr="/World/envs/.*/anymal", name="anymalview")
scene.add(self._anymals)
scene.add(self._anymals._knees)
scene.add(self._anymals._base)
return
def get_anymal(self):
anymal = Anymal(prim_path=self.default_zero_env_path + "/anymal", name="Anymal", translation=self._anymal_translation)
self._sim_config.apply_articulation_settings("Anymal", get_prim_at_path(anymal.prim_path), self._sim_config.parse_actor_config("Anymal"))
# Configure joint properties
joint_paths = []
for quadrant in ["LF", "LH", "RF", "RH"]:
for component, abbrev in [("HIP", "H"), ("THIGH", "K")]:
joint_paths.append(f"{quadrant}_{component}/{quadrant}_{abbrev}FE")
joint_paths.append(f"base/{quadrant}_HAA")
for joint_path in joint_paths:
set_drive(f"{anymal.prim_path}/{joint_path}", "angular", "position", 0, 400, 40, 1000)
self.default_dof_pos = torch.zeros((self.num_envs, 12), dtype=torch.float, device=self.device, requires_grad=False)
dof_names = anymal.dof_names
for i in range(self.num_actions):
name = dof_names[i]
angle = self.named_default_joint_angles[name]
self.default_dof_pos[:, i] = angle
def get_observations(self) -> dict:
torso_position, torso_rotation = self._anymals.get_world_poses(clone=False)
root_velocities = self._anymals.get_velocities(clone=False)
dof_pos = self._anymals.get_joint_positions(clone=False)
dof_vel = self._anymals.get_joint_velocities(clone=False)
velocity = root_velocities[:, 0:3]
ang_velocity = root_velocities[:, 3:6]
base_lin_vel = quat_rotate_inverse(torso_rotation, velocity) * self.lin_vel_scale
base_ang_vel = quat_rotate_inverse(torso_rotation, ang_velocity) * self.ang_vel_scale
projected_gravity = quat_rotate(torso_rotation, self.gravity_vec)
dof_pos_scaled = (dof_pos - self.default_dof_pos) * self.dof_pos_scale
commands_scaled = self.commands * torch.tensor(
[self.lin_vel_scale, self.lin_vel_scale, self.ang_vel_scale],
requires_grad=False,
device=self.commands.device,
)
obs = torch.cat(
(
base_lin_vel,
base_ang_vel,
projected_gravity,
commands_scaled,
dof_pos_scaled,
dof_vel * self.dof_vel_scale,
self.actions,
),
dim=-1,
)
self.obs_buf[:] = obs
observations = {
self._anymals.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
indices = torch.arange(self._anymals.count, dtype=torch.int32, device=self._device)
self.actions[:] = actions.clone().to(self._device)
current_targets = self.current_targets + self.action_scale * self.actions * self.dt
self.current_targets[:] = torch.clamp(current_targets, self.anymal_dof_lower_limits, self.anymal_dof_upper_limits)
self._anymals.set_joint_position_targets(self.current_targets, indices)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
# randomize DOF velocities
velocities = torch_rand_float(-0.1, 0.1, (num_resets, self._anymals.num_dof), device=self._device)
dof_pos = self.default_dof_pos[env_ids]
dof_vel = velocities
self.current_targets[env_ids] = dof_pos[:]
root_vel = torch.zeros((num_resets, 6), device=self._device)
# apply resets
indices = env_ids.to(dtype=torch.int32)
self._anymals.set_joint_positions(dof_pos, indices)
self._anymals.set_joint_velocities(dof_vel, indices)
self._anymals.set_world_poses(self.initial_root_pos[env_ids].clone(), self.initial_root_rot[env_ids].clone(), indices)
self._anymals.set_velocities(root_vel, indices)
self.commands_x[env_ids] = torch_rand_float(
self.command_x_range[0], self.command_x_range[1], (num_resets, 1), device=self._device
).squeeze()
self.commands_y[env_ids] = torch_rand_float(
self.command_y_range[0], self.command_y_range[1], (num_resets, 1), device=self._device
).squeeze()
self.commands_yaw[env_ids] = torch_rand_float(
self.command_yaw_range[0], self.command_yaw_range[1], (num_resets, 1), device=self._device
).squeeze()
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
self.last_actions[env_ids] = 0.
self.last_dof_vel[env_ids] = 0.
def post_reset(self):
self.initial_root_pos, self.initial_root_rot = self._anymals.get_world_poses()
self.current_targets = self.default_dof_pos.clone()
dof_limits = self._anymals.get_dof_limits()
self.anymal_dof_lower_limits = dof_limits[0, :, 0].to(device=self._device)
self.anymal_dof_upper_limits = dof_limits[0, :, 1].to(device=self._device)
self.commands = torch.zeros(self._num_envs, 3, dtype=torch.float, device=self._device, requires_grad=False)
self.commands_y = self.commands.view(self._num_envs, 3)[..., 1]
self.commands_x = self.commands.view(self._num_envs, 3)[..., 0]
self.commands_yaw = self.commands.view(self._num_envs, 3)[..., 2]
# initialize some data used later on
self.extras = {}
self.gravity_vec = torch.tensor([0.0, 0.0, -1.0], device=self._device).repeat(
(self._num_envs, 1)
)
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros((self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(self._anymals.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self) -> None:
torso_position, torso_rotation = self._anymals.get_world_poses(clone=False)
root_velocities = self._anymals.get_velocities(clone=False)
dof_pos = self._anymals.get_joint_positions(clone=False)
dof_vel = self._anymals.get_joint_velocities(clone=False)
velocity = root_velocities[:, 0:3]
ang_velocity = root_velocities[:, 3:6]
base_lin_vel = quat_rotate_inverse(torso_rotation, velocity)
base_ang_vel = quat_rotate_inverse(torso_rotation, ang_velocity)
# velocity tracking reward
lin_vel_error = torch.sum(torch.square(self.commands[:, :2] - base_lin_vel[:, :2]), dim=1)
ang_vel_error = torch.square(self.commands[:, 2] - base_ang_vel[:, 2])
rew_lin_vel_xy = torch.exp(-lin_vel_error / 0.25) * self.rew_scales["lin_vel_xy"]
rew_ang_vel_z = torch.exp(-ang_vel_error / 0.25) * self.rew_scales["ang_vel_z"]
rew_lin_vel_z = torch.square(base_lin_vel[:, 2]) * self.rew_scales["lin_vel_z"]
rew_joint_acc = torch.sum(torch.square(self.last_dof_vel - dof_vel), dim=1) * self.rew_scales["joint_acc"]
rew_action_rate = torch.sum(torch.square(self.last_actions - self.actions), dim=1) * self.rew_scales["action_rate"]
rew_cosmetic = torch.sum(torch.abs(dof_pos[:, 0:4] - self.default_dof_pos[:, 0:4]), dim=1) * self.rew_scales["cosmetic"]
total_reward = rew_lin_vel_xy + rew_ang_vel_z + rew_joint_acc + rew_action_rate + rew_cosmetic + rew_lin_vel_z
total_reward = torch.clip(total_reward, 0.0, None)
self.last_actions[:] = self.actions[:]
self.last_dof_vel[:] = dof_vel[:]
self.fallen_over = self._anymals.is_base_below_threshold(threshold=0.51, ground_heights=0.0)
total_reward[torch.nonzero(self.fallen_over)] = -1
self.rew_buf[:] = total_reward.detach()
def is_done(self) -> None:
# reset agents
time_out = self.progress_buf >= self.max_episode_length - 1
self.reset_buf[:] = time_out | self.fallen_over
| 13,495 | Python | 45.061433 | 145 | 0.63505 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/base/rl_task.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from abc import abstractmethod
import numpy as np
import torch
from gym import spaces
from omni.isaac.core.tasks import BaseTask
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.prims import define_prim
from omni.isaac.cloner import GridCloner
from omniisaacgymenvs.tasks.utils.usd_utils import create_distant_light
from omniisaacgymenvs.utils.domain_randomization.randomize import Randomizer
import omni.kit
class RLTask(BaseTask):
""" This class provides a PyTorch RL-specific interface for setting up RL tasks.
It includes utilities for setting up RL task related parameters,
cloning environments, and data collection for RL algorithms.
"""
def __init__(self, name, env, offset=None) -> None:
""" Initializes RL parameters, cloner object, and buffers.
Args:
name (str): name of the task.
env (VecEnvBase): an instance of the environment wrapper class to register task.
offset (Optional[np.ndarray], optional): offset applied to all assets of the task. Defaults to None.
"""
super().__init__(name=name, offset=offset)
self.test = self._cfg["test"]
self._device = self._cfg["sim_device"]
self._dr_randomizer = Randomizer(self._sim_config)
print("Task Device:", self._device)
self.randomize_actions = False
self.randomize_observations = False
self.clip_obs = self._cfg["task"]["env"].get("clipObservations", np.Inf)
self.clip_actions = self._cfg["task"]["env"].get("clipActions", np.Inf)
self.rl_device = self._cfg.get("rl_device", "cuda:0")
self.control_frequency_inv = self._cfg["task"]["env"].get("controlFrequencyInv", 1)
print("RL device: ", self.rl_device)
self._env = env
if not hasattr(self, "_num_agents"):
self._num_agents = 1 # used for multi-agent environments
if not hasattr(self, "_num_states"):
self._num_states = 0
# initialize data spaces (defaults to gym.Box)
if not hasattr(self, "action_space"):
self.action_space = spaces.Box(np.ones(self.num_actions) * -1.0, np.ones(self.num_actions) * 1.0)
if not hasattr(self, "observation_space"):
self.observation_space = spaces.Box(np.ones(self.num_observations) * -np.Inf, np.ones(self.num_observations) * np.Inf)
if not hasattr(self, "state_space"):
self.state_space = spaces.Box(np.ones(self.num_states) * -np.Inf, np.ones(self.num_states) * np.Inf)
self._cloner = GridCloner(spacing=self._env_spacing)
self._cloner.define_base_env(self.default_base_env_path)
define_prim(self.default_zero_env_path)
self.cleanup()
def cleanup(self) -> None:
""" Prepares torch buffers for RL data collection."""
# prepare tensors
self.obs_buf = torch.zeros((self._num_envs, self.num_observations), device=self._device, dtype=torch.float)
self.states_buf = torch.zeros((self._num_envs, self.num_states), device=self._device, dtype=torch.float)
self.rew_buf = torch.zeros(self._num_envs, device=self._device, dtype=torch.float)
self.reset_buf = torch.ones(self._num_envs, device=self._device, dtype=torch.long)
self.progress_buf = torch.zeros(self._num_envs, device=self._device, dtype=torch.long)
self.extras = {}
def set_up_scene(self, scene) -> None:
""" Clones environments based on value provided in task config and applies collision filters to mask
collisions across environments.
Args:
scene (Scene): Scene to add objects to.
"""
super().set_up_scene(scene)
collision_filter_global_paths = list()
if self._sim_config.task_config["sim"].get("add_ground_plane", True):
self._ground_plane_path = "/World/defaultGroundPlane"
collision_filter_global_paths.append(self._ground_plane_path)
scene.add_default_ground_plane(prim_path=self._ground_plane_path)
prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs)
self._env_pos = self._cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=prim_paths)
self._env_pos = torch.tensor(np.array(self._env_pos), device=self._device, dtype=torch.float)
self._cloner.filter_collisions(
self._env._world.get_physics_context().prim_path, "/World/collisions", prim_paths, collision_filter_global_paths)
self.set_initial_camera_params(camera_position=[10, 10, 3], camera_target=[0, 0, 0])
if self._sim_config.task_config["sim"].get("add_distant_light", True):
create_distant_light()
def set_initial_camera_params(self, camera_position=[10, 10, 3], camera_target=[0, 0, 0]):
if self._env._render:
viewport = omni.kit.viewport_legacy.get_default_viewport_window()
viewport.set_camera_position("/OmniverseKit_Persp", camera_position[0], camera_position[1], camera_position[2], True)
viewport.set_camera_target("/OmniverseKit_Persp", camera_target[0], camera_target[1], camera_target[2], True)
@property
def default_base_env_path(self):
""" Retrieves default path to the parent of all env prims.
Returns:
default_base_env_path(str): Defaults to "/World/envs".
"""
return "/World/envs"
@property
def default_zero_env_path(self):
""" Retrieves default path to the first env prim (index 0).
Returns:
default_zero_env_path(str): Defaults to "/World/envs/env_0".
"""
return f"{self.default_base_env_path}/env_0"
@property
def num_envs(self):
""" Retrieves number of environments for task.
Returns:
num_envs(int): Number of environments.
"""
return self._num_envs
@property
def num_actions(self):
""" Retrieves dimension of actions.
Returns:
num_actions(int): Dimension of actions.
"""
return self._num_actions
@property
def num_observations(self):
""" Retrieves dimension of observations.
Returns:
num_observations(int): Dimension of observations.
"""
return self._num_observations
@property
def num_states(self):
""" Retrieves dimesion of states.
Returns:
num_states(int): Dimension of states.
"""
return self._num_states
@property
def num_agents(self):
""" Retrieves number of agents for multi-agent environments.
Returns:
num_agents(int): Dimension of states.
"""
return self._num_agents
def get_states(self):
""" API for retrieving states buffer, used for asymmetric AC training.
Returns:
states_buf(torch.Tensor): States buffer.
"""
return self.states_buf
def get_extras(self):
""" API for retrieving extras data for RL.
Returns:
extras(dict): Dictionary containing extras data.
"""
return self.extras
def reset(self):
""" Flags all environments for reset.
"""
self.reset_buf = torch.ones_like(self.reset_buf)
def pre_physics_step(self, actions):
""" Optionally implemented by individual task classes to process actions.
Args:
actions (torch.Tensor): Actions generated by RL policy.
"""
pass
def post_physics_step(self):
""" Processes RL required computations for observations, states, rewards, resets, and extras.
Also maintains progress buffer for tracking step count per environment.
Returns:
obs_buf(torch.Tensor): Tensor of observation data.
rew_buf(torch.Tensor): Tensor of rewards data.
reset_buf(torch.Tensor): Tensor of resets/dones data.
extras(dict): Dictionary of extras data.
"""
self.progress_buf[:] += 1
if self._env._world.is_playing():
self.get_observations()
self.get_states()
self.calculate_metrics()
self.is_done()
self.get_extras()
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
| 9,915 | Python | 38.349206 | 130 | 0.649723 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/utils/anymal_terrain_generator.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
import numpy as np
import torch
import math
from omniisaacgymenvs.utils.terrain_utils.terrain_utils import *
# terrain generator
class Terrain:
def __init__(self, cfg, num_robots) -> None:
self.horizontal_scale = 0.1
self.vertical_scale = 0.005
self.border_size = 20
self.num_per_env = 2
self.env_length = cfg["mapLength"]
self.env_width = cfg["mapWidth"]
self.proportions = [np.sum(cfg["terrainProportions"][:i+1]) for i in range(len(cfg["terrainProportions"]))]
self.env_rows = cfg["numLevels"]
self.env_cols = cfg["numTerrains"]
self.num_maps = self.env_rows * self.env_cols
self.num_per_env = int(num_robots / self.num_maps)
self.env_origins = np.zeros((self.env_rows, self.env_cols, 3))
self.width_per_env_pixels = int(self.env_width / self.horizontal_scale)
self.length_per_env_pixels = int(self.env_length / self.horizontal_scale)
self.border = int(self.border_size/self.horizontal_scale)
self.tot_cols = int(self.env_cols * self.width_per_env_pixels) + 2 * self.border
self.tot_rows = int(self.env_rows * self.length_per_env_pixels) + 2 * self.border
self.height_field_raw = np.zeros((self.tot_rows , self.tot_cols), dtype=np.int16)
if cfg["curriculum"]:
self.curiculum(num_robots, num_terrains=self.env_cols, num_levels=self.env_rows)
else:
self.randomized_terrain()
self.heightsamples = self.height_field_raw
self.vertices, self.triangles = convert_heightfield_to_trimesh(self.height_field_raw, self.horizontal_scale, self.vertical_scale, cfg["slopeTreshold"])
def randomized_terrain(self):
for k in range(self.num_maps):
# Env coordinates in the world
(i, j) = np.unravel_index(k, (self.env_rows, self.env_cols))
# Heightfield coordinate system from now on
start_x = self.border + i * self.length_per_env_pixels
end_x = self.border + (i + 1) * self.length_per_env_pixels
start_y = self.border + j * self.width_per_env_pixels
end_y = self.border + (j + 1) * self.width_per_env_pixels
terrain = SubTerrain("terrain",
width=self.width_per_env_pixels,
length=self.width_per_env_pixels,
vertical_scale=self.vertical_scale,
horizontal_scale=self.horizontal_scale)
choice = np.random.uniform(0, 1)
if choice < 0.1:
if np.random.choice([0, 1]):
pyramid_sloped_terrain(terrain, np.random.choice([-0.3, -0.2, 0, 0.2, 0.3]))
random_uniform_terrain(terrain, min_height=-0.1, max_height=0.1, step=0.05, downsampled_scale=0.2)
else:
pyramid_sloped_terrain(terrain, np.random.choice([-0.3, -0.2, 0, 0.2, 0.3]))
elif choice < 0.6:
# step_height = np.random.choice([-0.18, -0.15, -0.1, -0.05, 0.05, 0.1, 0.15, 0.18])
step_height = np.random.choice([-0.15, 0.15])
pyramid_stairs_terrain(terrain, step_width=0.31, step_height=step_height, platform_size=3.)
elif choice < 1.:
discrete_obstacles_terrain(terrain, 0.15, 1., 2., 40, platform_size=3.)
self.height_field_raw[start_x: end_x, start_y:end_y] = terrain.height_field_raw
env_origin_x = (i + 0.5) * self.env_length
env_origin_y = (j + 0.5) * self.env_width
x1 = int((self.env_length/2. - 1) / self.horizontal_scale)
x2 = int((self.env_length/2. + 1) / self.horizontal_scale)
y1 = int((self.env_width/2. - 1) / self.horizontal_scale)
y2 = int((self.env_width/2. + 1) / self.horizontal_scale)
env_origin_z = np.max(terrain.height_field_raw[x1:x2, y1:y2])*self.vertical_scale
self.env_origins[i, j] = [env_origin_x, env_origin_y, env_origin_z]
def curiculum(self, num_robots, num_terrains, num_levels):
num_robots_per_map = int(num_robots / num_terrains)
left_over = num_robots % num_terrains
idx = 0
for j in range(num_terrains):
for i in range(num_levels):
terrain = SubTerrain("terrain",
width=self.width_per_env_pixels,
length=self.width_per_env_pixels,
vertical_scale=self.vertical_scale,
horizontal_scale=self.horizontal_scale)
difficulty = i / num_levels
choice = j / num_terrains
slope = difficulty * 0.4
step_height = 0.05 + 0.175 * difficulty
discrete_obstacles_height = 0.025 + difficulty * 0.15
stepping_stones_size = 2 - 1.8 * difficulty
if choice < self.proportions[0]:
if choice < 0.05:
slope *= -1
pyramid_sloped_terrain(terrain, slope=slope, platform_size=3.)
elif choice < self.proportions[1]:
if choice < 0.15:
slope *= -1
pyramid_sloped_terrain(terrain, slope=slope, platform_size=3.)
random_uniform_terrain(terrain, min_height=-0.1, max_height=0.1, step=0.025, downsampled_scale=0.2)
elif choice < self.proportions[3]:
if choice<self.proportions[2]:
step_height *= -1
pyramid_stairs_terrain(terrain, step_width=0.31, step_height=step_height, platform_size=3.)
elif choice < self.proportions[4]:
discrete_obstacles_terrain(terrain, discrete_obstacles_height, 1., 2., 40, platform_size=3.)
else:
stepping_stones_terrain(terrain, stone_size=stepping_stones_size, stone_distance=0.1, max_height=0., platform_size=3.)
# Heightfield coordinate system
start_x = self.border + i * self.length_per_env_pixels
end_x = self.border + (i + 1) * self.length_per_env_pixels
start_y = self.border + j * self.width_per_env_pixels
end_y = self.border + (j + 1) * self.width_per_env_pixels
self.height_field_raw[start_x: end_x, start_y:end_y] = terrain.height_field_raw
robots_in_map = num_robots_per_map
if j < left_over:
robots_in_map +=1
env_origin_x = (i + 0.5) * self.env_length
env_origin_y = (j + 0.5) * self.env_width
x1 = int((self.env_length/2. - 1) / self.horizontal_scale)
x2 = int((self.env_length/2. + 1) / self.horizontal_scale)
y1 = int((self.env_width/2. - 1) / self.horizontal_scale)
y2 = int((self.env_width/2. + 1) / self.horizontal_scale)
env_origin_z = np.max(terrain.height_field_raw[x1:x2, y1:y2])*self.vertical_scale
self.env_origins[i, j] = [env_origin_x, env_origin_y, env_origin_z]
| 8,795 | Python | 52.634146 | 159 | 0.593064 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/utils/usd_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from pxr import UsdPhysics, UsdLux
def set_drive_type(prim_path, drive_type):
joint_prim = get_prim_at_path(prim_path)
# set drive type ("angular" or "linear")
drive = UsdPhysics.DriveAPI.Apply(joint_prim, drive_type)
return drive
def set_drive_target_position(drive, target_value):
if not drive.GetTargetPositionAttr():
drive.CreateTargetPositionAttr(target_value)
else:
drive.GetTargetPositionAttr().Set(target_value)
def set_drive_target_velocity(drive, target_value):
if not drive.GetTargetVelocityAttr():
drive.CreateTargetVelocityAttr(target_value)
else:
drive.GetTargetVelocityAttr().Set(target_value)
def set_drive_stiffness(drive, stiffness):
if not drive.GetStiffnessAttr():
drive.CreateStiffnessAttr(stiffness)
else:
drive.GetStiffnessAttr().Set(stiffness)
def set_drive_damping(drive, damping):
if not drive.GetDampingAttr():
drive.CreateDampingAttr(damping)
else:
drive.GetDampingAttr().Set(damping)
def set_drive_max_force(drive, max_force):
if not drive.GetMaxForceAttr():
drive.CreateMaxForceAttr(max_force)
else:
drive.GetMaxForceAttr().Set(max_force)
def set_drive(prim_path, drive_type, target_type, target_value, stiffness, damping, max_force) -> None:
drive = set_drive_type(prim_path, drive_type)
# set target type ("position" or "velocity")
if target_type == "position":
set_drive_target_position(drive, target_value)
elif target_type == "velocity":
set_drive_target_velocity(drive, target_value)
set_drive_stiffness(drive, stiffness)
set_drive_damping(drive, damping)
set_drive_max_force(drive, max_force)
def create_distant_light(prim_path="/World/defaultDistantLight", intensity=5000):
stage = get_current_stage()
light = UsdLux.DistantLight.Define(stage, prim_path)
light.GetPrim().GetAttribute("intensity").Set(intensity)
| 3,628 | Python | 40.238636 | 103 | 0.742007 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/shared/reacher.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
from abc import abstractmethod
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omni.isaac.core.prims import RigidPrimView, XFormPrim
from omni.isaac.core.scenes.scene import Scene
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage, add_reference_to_stage
from omni.isaac.core.utils.torch import *
# `scale` maps [-1, 1] to [L, U]; `unscale` maps [L, U] to [-1, 1]
from omni.isaac.core.utils.torch import scale, unscale
from omni.isaac.gym.vec_env import VecEnvBase
import numpy as np
import torch
class ReacherTask(RLTask):
def __init__(
self,
name: str,
env: VecEnvBase,
offset=None
) -> None:
"""[summary]
"""
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self.dist_reward_scale = self._task_cfg["env"]["distRewardScale"]
self.rot_reward_scale = self._task_cfg["env"]["rotRewardScale"]
self.action_penalty_scale = self._task_cfg["env"]["actionPenaltyScale"]
self.success_tolerance = self._task_cfg["env"]["successTolerance"]
self.reach_goal_bonus = self._task_cfg["env"]["reachGoalBonus"]
self.rot_eps = self._task_cfg["env"]["rotEps"]
self.vel_obs_scale = self._task_cfg["env"]["velObsScale"]
self.reset_position_noise = self._task_cfg["env"]["resetPositionNoise"]
self.reset_rotation_noise = self._task_cfg["env"]["resetRotationNoise"]
self.reset_dof_pos_noise = self._task_cfg["env"]["resetDofPosRandomInterval"]
self.reset_dof_vel_noise = self._task_cfg["env"]["resetDofVelRandomInterval"]
self.arm_dof_speed_scale = self._task_cfg["env"]["dofSpeedScale"]
self.use_relative_control = self._task_cfg["env"]["useRelativeControl"]
self.act_moving_average = self._task_cfg["env"]["actionsMovingAverage"]
self.max_episode_length = self._task_cfg["env"]["episodeLength"]
self.reset_time = self._task_cfg["env"].get("resetTime", -1.0)
self.print_success_stat = self._task_cfg["env"]["printNumSuccesses"]
self.max_consecutive_successes = self._task_cfg["env"]["maxConsecutiveSuccesses"]
self.av_factor = self._task_cfg["env"].get("averFactor", 0.1)
self.dt = 1.0 / 60
control_freq_inv = self._task_cfg["env"].get("controlFrequencyInv", 1)
if self.reset_time > 0.0:
self.max_episode_length = int(round(self.reset_time/(control_freq_inv * self.dt)))
print("Reset time: ", self.reset_time)
print("New episode length: ", self.max_episode_length)
RLTask.__init__(self, name, env)
self.x_unit_tensor = torch.tensor([1, 0, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.y_unit_tensor = torch.tensor([0, 1, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.z_unit_tensor = torch.tensor([0, 0, 1], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
# Indicates which environments should be reset
self.reset_goal_buf = self.reset_buf.clone()
self.successes = torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
self.consecutive_successes = torch.zeros(1, dtype=torch.float, device=self.device)
self.av_factor = torch.tensor(self.av_factor, dtype=torch.float, device=self.device)
self.total_successes = 0
self.total_resets = 0
return
def set_up_scene(self, scene: Scene) -> None:
self._stage = get_current_stage()
self._assets_root_path = 'omniverse://localhost/Projects/J3soon/Isaac/2022.1'
self.get_arm()
self.get_object()
self.get_goal()
super().set_up_scene(scene)
self._arms = self.get_arm_view(scene)
scene.add(self._arms)
self._objects = RigidPrimView(
prim_paths_expr="/World/envs/env_.*/object/object",
name="object_view",
reset_xform_properties=False,
)
scene.add(self._objects)
self._goals = RigidPrimView(
prim_paths_expr="/World/envs/env_.*/goal/object",
name="goal_view",
reset_xform_properties=False,
)
scene.add(self._goals)
@abstractmethod
def get_num_dof(self):
pass
@abstractmethod
def get_arm(self):
pass
@abstractmethod
def get_arm_view(self):
pass
@abstractmethod
def get_observations(self):
pass
@abstractmethod
def get_reset_target_new_pos(self, n_reset_envs):
pass
@abstractmethod
def send_joint_pos(self, joint_pos):
pass
def get_object(self):
self.object_start_translation = torch.tensor([0.0, 0.0, 0.0], device=self.device)
self.object_start_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.device)
self.object_usd_path = f"{self._assets_root_path}/Isaac/Props/Blocks/block_instanceable.usd"
add_reference_to_stage(self.object_usd_path, self.default_zero_env_path + "/object")
obj = XFormPrim(
prim_path=self.default_zero_env_path + "/object/object",
name="object",
translation=self.object_start_translation,
orientation=self.object_start_orientation,
scale=self.object_scale
)
self._sim_config.apply_articulation_settings("object", get_prim_at_path(obj.prim_path), self._sim_config.parse_actor_config("object"))
def get_goal(self):
self.goal_displacement_tensor = torch.tensor([0.0, 0.0, 0.0], device=self.device)
self.goal_start_translation = torch.tensor([0.0, 0.0, 0.0], device=self.device) + self.goal_displacement_tensor
self.goal_start_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.device)
self.goal_usd_path = f"{self._assets_root_path}/Isaac/Props/Blocks/block_instanceable.usd"
add_reference_to_stage(self.goal_usd_path, self.default_zero_env_path + "/goal")
goal = XFormPrim(
prim_path=self.default_zero_env_path + "/goal/object",
name="goal",
translation=self.goal_start_translation,
orientation=self.goal_start_orientation,
scale=self.goal_scale
)
self._sim_config.apply_articulation_settings("goal", get_prim_at_path(goal.prim_path), self._sim_config.parse_actor_config("goal_object"))
def post_reset(self):
self.num_arm_dofs = self.get_num_dof()
self.actuated_dof_indices = torch.arange(self.num_arm_dofs, dtype=torch.long, device=self.device)
self.arm_dof_targets = torch.zeros((self.num_envs, self._arms.num_dof), dtype=torch.float, device=self.device)
self.prev_targets = torch.zeros((self.num_envs, self.num_arm_dofs), dtype=torch.float, device=self.device)
self.cur_targets = torch.zeros((self.num_envs, self.num_arm_dofs), dtype=torch.float, device=self.device)
dof_limits = self._dof_limits
self.arm_dof_lower_limits, self.arm_dof_upper_limits = torch.t(dof_limits[0].to(self.device))
self.arm_dof_default_pos = torch.zeros(self.num_arm_dofs, dtype=torch.float, device=self.device)
self.arm_dof_default_vel = torch.zeros(self.num_arm_dofs, dtype=torch.float, device=self.device)
self.end_effectors_init_pos, self.end_effectors_init_rot = self._arms._end_effectors.get_world_poses()
self.goal_pos, self.goal_rot = self._goals.get_world_poses()
self.goal_pos -= self._env_pos
# randomize all envs
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self):
self.fall_dist = 0
self.fall_penalty = 0
self.rew_buf[:], self.reset_buf[:], self.reset_goal_buf[:], self.progress_buf[:], self.successes[:], self.consecutive_successes[:] = compute_arm_reward(
self.rew_buf, self.reset_buf, self.reset_goal_buf, self.progress_buf, self.successes, self.consecutive_successes,
self.max_episode_length, self.object_pos, self.object_rot, self.goal_pos, self.goal_rot,
self.dist_reward_scale, self.rot_reward_scale, self.rot_eps, self.actions, self.action_penalty_scale,
self.success_tolerance, self.reach_goal_bonus, self.fall_dist, self.fall_penalty,
self.max_consecutive_successes, self.av_factor,
)
self.extras['consecutive_successes'] = self.consecutive_successes.mean()
if self.print_success_stat:
self.total_resets = self.total_resets + self.reset_buf.sum()
direct_average_successes = self.total_successes + self.successes.sum()
self.total_successes = self.total_successes + (self.successes * self.reset_buf).sum()
# The direct average shows the overall result more quickly, but slightly undershoots long term policy performance.
print("Direct average consecutive successes = {:.1f}".format(direct_average_successes/(self.total_resets + self.num_envs)))
if self.total_resets > 0:
print("Post-Reset average consecutive successes = {:.1f}".format(self.total_successes/self.total_resets))
def pre_physics_step(self, actions):
env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
goal_env_ids = self.reset_goal_buf.nonzero(as_tuple=False).squeeze(-1)
end_effectors_pos, end_effectors_rot = self._arms._end_effectors.get_world_poses()
# Reverse the default rotation and rotate the displacement tensor according to the current rotation
self.object_pos = end_effectors_pos + quat_rotate(end_effectors_rot, quat_rotate_inverse(self.end_effectors_init_rot, self.get_object_displacement_tensor()))
self.object_pos -= self._env_pos # subtract world env pos
self.object_rot = end_effectors_rot
object_pos = self.object_pos + self._env_pos
object_rot = self.object_rot
self._objects.set_world_poses(object_pos, object_rot)
# if only goals need reset, then call set API
if len(goal_env_ids) > 0 and len(env_ids) == 0:
self.reset_target_pose(goal_env_ids)
elif len(goal_env_ids) > 0:
self.reset_target_pose(goal_env_ids)
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.actions = actions.clone().to(self.device)
# Reacher tasks don't require gripper actions, disable it.
self.actions[:, 5] = 0.0
if self.use_relative_control:
targets = self.prev_targets[:, self.actuated_dof_indices] + self.arm_dof_speed_scale * self.dt * self.actions
self.cur_targets[:, self.actuated_dof_indices] = tensor_clamp(targets,
self.arm_dof_lower_limits[self.actuated_dof_indices], self.arm_dof_upper_limits[self.actuated_dof_indices])
else:
self.cur_targets[:, self.actuated_dof_indices] = scale(self.actions,
self.arm_dof_lower_limits[self.actuated_dof_indices], self.arm_dof_upper_limits[self.actuated_dof_indices])
self.cur_targets[:, self.actuated_dof_indices] = self.act_moving_average * self.cur_targets[:, self.actuated_dof_indices] + \
(1.0 - self.act_moving_average) * self.prev_targets[:, self.actuated_dof_indices]
self.cur_targets[:, self.actuated_dof_indices] = tensor_clamp(self.cur_targets[:, self.actuated_dof_indices],
self.arm_dof_lower_limits[self.actuated_dof_indices], self.arm_dof_upper_limits[self.actuated_dof_indices])
self.prev_targets[:, self.actuated_dof_indices] = self.cur_targets[:, self.actuated_dof_indices]
self._arms.set_joint_position_targets(
self.cur_targets[:, self.actuated_dof_indices], indices=None, joint_indices=self.actuated_dof_indices
)
if self._task_cfg['sim2real']['enabled'] and self.test and self.num_envs == 1:
# Only retrieve the 0-th joint position even when multiple envs are used
cur_joint_pos = self._arms.get_joint_positions(indices=[0], joint_indices=self.actuated_dof_indices)
# Send the current joint positions to the real robot
joint_pos = cur_joint_pos[0]
if torch.any(joint_pos < self.arm_dof_lower_limits) or torch.any(joint_pos > self.arm_dof_upper_limits):
print("get_joint_positions out of bound, send_joint_pos skipped")
else:
self.send_joint_pos(joint_pos)
def is_done(self):
pass
def reset_target_pose(self, env_ids):
# reset goal
indices = env_ids.to(dtype=torch.int32)
rand_floats = torch_rand_float(-1.0, 1.0, (len(env_ids), 4), device=self.device)
new_pos = self.get_reset_target_new_pos(len(env_ids))
new_rot = randomize_rotation(rand_floats[:, 0], rand_floats[:, 1], self.x_unit_tensor[env_ids], self.y_unit_tensor[env_ids])
self.goal_pos[env_ids] = new_pos
self.goal_rot[env_ids] = new_rot
goal_pos, goal_rot = self.goal_pos.clone(), self.goal_rot.clone()
goal_pos[env_ids] = self.goal_pos[env_ids] + self._env_pos[env_ids] # add world env pos
self._goals.set_world_poses(goal_pos[env_ids], goal_rot[env_ids], indices)
self.reset_goal_buf[env_ids] = 0
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
rand_floats = torch_rand_float(-1.0, 1.0, (len(env_ids), self.num_arm_dofs * 2 + 5), device=self.device)
self.reset_target_pose(env_ids)
# reset arm
delta_max = self.arm_dof_upper_limits - self.arm_dof_default_pos
delta_min = self.arm_dof_lower_limits - self.arm_dof_default_pos
rand_delta = delta_min + (delta_max - delta_min) * (rand_floats[:, 5:5+self.num_arm_dofs] + 1.0) * 0.5
pos = self.arm_dof_default_pos + self.reset_dof_pos_noise * rand_delta
dof_pos = torch.zeros((self.num_envs, self._arms.num_dof), device=self.device)
dof_pos[env_ids, :self.num_arm_dofs] = pos
dof_vel = torch.zeros((self.num_envs, self._arms.num_dof), device=self.device)
dof_vel[env_ids, :self.num_arm_dofs] = self.arm_dof_default_vel + \
self.reset_dof_vel_noise * rand_floats[:, 5+self.num_arm_dofs:5+self.num_arm_dofs*2]
self.prev_targets[env_ids, :self.num_arm_dofs] = pos
self.cur_targets[env_ids, :self.num_arm_dofs] = pos
self.arm_dof_targets[env_ids, :self.num_arm_dofs] = pos
self._arms.set_joint_position_targets(self.arm_dof_targets[env_ids], indices)
# set_joint_positions doesn't seem to apply immediately.
self._arms.set_joint_positions(dof_pos[env_ids], indices)
self._arms.set_joint_velocities(dof_vel[env_ids], indices)
self.progress_buf[env_ids] = 0
self.reset_buf[env_ids] = 0
self.successes[env_ids] = 0
#####################################################################
###=========================jit functions=========================###
#####################################################################
@torch.jit.script
def randomize_rotation(rand0, rand1, x_unit_tensor, y_unit_tensor):
return quat_mul(quat_from_angle_axis(rand0 * np.pi, x_unit_tensor), quat_from_angle_axis(rand1 * np.pi, y_unit_tensor))
@torch.jit.script
def compute_arm_reward(
rew_buf, reset_buf, reset_goal_buf, progress_buf, successes, consecutive_successes,
max_episode_length: float, object_pos, object_rot, target_pos, target_rot,
dist_reward_scale: float, rot_reward_scale: float, rot_eps: float,
actions, action_penalty_scale: float,
success_tolerance: float, reach_goal_bonus: float, fall_dist: float,
fall_penalty: float, max_consecutive_successes: int, av_factor: float
):
goal_dist = torch.norm(object_pos - target_pos, p=2, dim=-1)
# Orientation alignment for the cube in hand and goal cube
quat_diff = quat_mul(object_rot, quat_conjugate(target_rot))
rot_dist = 2.0 * torch.asin(torch.clamp(torch.norm(quat_diff[:, 1:4], p=2, dim=-1), max=1.0)) # changed quat convention
dist_rew = goal_dist * dist_reward_scale
rot_rew = 1.0/(torch.abs(rot_dist) + rot_eps) * rot_reward_scale
action_penalty = torch.sum(actions ** 2, dim=-1)
# Total reward is: position distance + orientation alignment + action regularization + success bonus + fall penalty
reward = dist_rew + action_penalty * action_penalty_scale
# Find out which envs hit the goal and update successes count
goal_resets = torch.where(torch.abs(goal_dist) <= success_tolerance, torch.ones_like(reset_goal_buf), reset_goal_buf)
successes = successes + goal_resets
# Success bonus: orientation is within `success_tolerance` of goal orientation
reward = torch.where(goal_resets == 1, reward + reach_goal_bonus, reward)
resets = reset_buf
if max_consecutive_successes > 0:
# Reset progress buffer on goal envs if max_consecutive_successes > 0
progress_buf = torch.where(torch.abs(rot_dist) <= success_tolerance, torch.zeros_like(progress_buf), progress_buf)
resets = torch.where(successes >= max_consecutive_successes, torch.ones_like(resets), resets)
resets = torch.where(progress_buf >= max_episode_length, torch.ones_like(resets), resets)
num_resets = torch.sum(resets)
finished_cons_successes = torch.sum(successes * resets.float())
cons_successes = torch.where(num_resets > 0, av_factor*finished_cons_successes/num_resets + (1.0 - av_factor)*consecutive_successes, consecutive_successes)
return reward, resets, goal_resets, progress_buf, successes, cons_successes
| 19,342 | Python | 48.853093 | 165 | 0.655723 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/shared/in_hand_manipulation.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from abc import abstractmethod
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omni.isaac.core.prims import RigidPrimView, XFormPrim
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage, add_reference_to_stage
from omni.isaac.core.utils.torch import *
import numpy as np
import torch
import math
import omni.replicator.isaac as dr
class InHandManipulationTask(RLTask):
def __init__(
self,
name,
env,
offset=None
) -> None:
"""[summary]
"""
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self.dist_reward_scale = self._task_cfg["env"]["distRewardScale"]
self.rot_reward_scale = self._task_cfg["env"]["rotRewardScale"]
self.action_penalty_scale = self._task_cfg["env"]["actionPenaltyScale"]
self.success_tolerance = self._task_cfg["env"]["successTolerance"]
self.reach_goal_bonus = self._task_cfg["env"]["reachGoalBonus"]
self.fall_dist = self._task_cfg["env"]["fallDistance"]
self.fall_penalty = self._task_cfg["env"]["fallPenalty"]
self.rot_eps = self._task_cfg["env"]["rotEps"]
self.vel_obs_scale = self._task_cfg["env"]["velObsScale"]
self.reset_position_noise = self._task_cfg["env"]["resetPositionNoise"]
self.reset_rotation_noise = self._task_cfg["env"]["resetRotationNoise"]
self.reset_dof_pos_noise = self._task_cfg["env"]["resetDofPosRandomInterval"]
self.reset_dof_vel_noise = self._task_cfg["env"]["resetDofVelRandomInterval"]
self.hand_dof_speed_scale = self._task_cfg["env"]["dofSpeedScale"]
self.use_relative_control = self._task_cfg["env"]["useRelativeControl"]
self.act_moving_average = self._task_cfg["env"]["actionsMovingAverage"]
self.max_episode_length = self._task_cfg["env"]["episodeLength"]
self.reset_time = self._task_cfg["env"].get("resetTime", -1.0)
self.print_success_stat = self._task_cfg["env"]["printNumSuccesses"]
self.max_consecutive_successes = self._task_cfg["env"]["maxConsecutiveSuccesses"]
self.av_factor = self._task_cfg["env"].get("averFactor", 0.1)
self.dt = 1.0 / 60
control_freq_inv = self._task_cfg["env"].get("controlFrequencyInv", 1)
if self.reset_time > 0.0:
self.max_episode_length = int(round(self.reset_time/(control_freq_inv * self.dt)))
print("Reset time: ", self.reset_time)
print("New episode length: ", self.max_episode_length)
RLTask.__init__(self, name, env)
self.x_unit_tensor = torch.tensor([1, 0, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.y_unit_tensor = torch.tensor([0, 1, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.z_unit_tensor = torch.tensor([0, 0, 1], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.reset_goal_buf = self.reset_buf.clone()
self.successes = torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
self.consecutive_successes = torch.zeros(1, dtype=torch.float, device=self.device)
self.randomization_buf = torch.zeros(self.num_envs, dtype=torch.long, device=self.device)
self.av_factor = torch.tensor(self.av_factor, dtype=torch.float, device=self.device)
self.total_successes = 0
self.total_resets = 0
return
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
self._assets_root_path = get_assets_root_path()
hand_start_translation, pose_dy, pose_dz = self.get_hand()
self.get_object(hand_start_translation, pose_dy, pose_dz)
self.get_goal()
super().set_up_scene(scene)
self._hands = self.get_hand_view(scene)
scene.add(self._hands)
self._objects = RigidPrimView(
prim_paths_expr="/World/envs/env_.*/object/object",
name="object_view",
reset_xform_properties=False,
masses=torch.tensor([0.07087]*self._num_envs, device=self.device),
)
scene.add(self._objects)
self._goals = RigidPrimView(
prim_paths_expr="/World/envs/env_.*/goal/object",
name="goal_view",
reset_xform_properties=False
)
scene.add(self._goals)
if self._dr_randomizer.randomize:
self._dr_randomizer.apply_on_startup_domain_randomization(self)
@abstractmethod
def get_hand(self):
pass
@abstractmethod
def get_hand_view(self):
pass
@abstractmethod
def get_observations(self):
pass
def get_object(self, hand_start_translation, pose_dy, pose_dz):
self.object_start_translation = hand_start_translation.clone()
self.object_start_translation[1] += pose_dy
self.object_start_translation[2] += pose_dz
self.object_start_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.device)
self.object_usd_path = f"{self._assets_root_path}/Isaac/Props/Blocks/block_instanceable.usd"
add_reference_to_stage(self.object_usd_path, self.default_zero_env_path + "/object")
obj = XFormPrim(
prim_path=self.default_zero_env_path + "/object/object",
name="object",
translation=self.object_start_translation,
orientation=self.object_start_orientation,
scale=self.object_scale,
)
self._sim_config.apply_articulation_settings("object", get_prim_at_path(obj.prim_path), self._sim_config.parse_actor_config("object"))
def get_goal(self):
self.goal_displacement_tensor = torch.tensor([-0.2, -0.06, 0.12], device=self.device)
self.goal_start_translation = self.object_start_translation + self.goal_displacement_tensor
self.goal_start_translation[2] -= 0.04
self.goal_start_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.device)
add_reference_to_stage(self.object_usd_path, self.default_zero_env_path + "/goal")
goal = XFormPrim(
prim_path=self.default_zero_env_path + "/goal",
name="goal",
translation=self.goal_start_translation,
orientation=self.goal_start_orientation,
scale=self.object_scale
)
self._sim_config.apply_articulation_settings("goal", get_prim_at_path(goal.prim_path), self._sim_config.parse_actor_config("goal_object"))
def post_reset(self):
self.num_hand_dofs = self._hands.num_dof
self.actuated_dof_indices = self._hands.actuated_dof_indices
self.hand_dof_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
self.prev_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
self.cur_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
dof_limits = self._hands.get_dof_limits()
self.hand_dof_lower_limits, self.hand_dof_upper_limits = torch.t(dof_limits[0].to(self.device))
self.hand_dof_default_pos = torch.zeros(self.num_hand_dofs, dtype=torch.float, device=self.device)
self.hand_dof_default_vel = torch.zeros(self.num_hand_dofs, dtype=torch.float, device=self.device)
self.object_init_pos, self.object_init_rot = self._objects.get_world_poses()
self.object_init_pos -= self._env_pos
self.object_init_velocities = torch.zeros_like(self._objects.get_velocities(), dtype=torch.float, device=self.device)
self.goal_pos = self.object_init_pos.clone()
self.goal_pos[:, 2] -= 0.04
self.goal_rot = self.object_init_rot.clone()
self.goal_init_pos = self.goal_pos.clone()
self.goal_init_rot = self.goal_rot.clone()
# randomize all envs
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
if self._dr_randomizer.randomize:
self._dr_randomizer.set_up_domain_randomization(self)
def get_object_goal_observations(self):
self.object_pos, self.object_rot = self._objects.get_world_poses(clone=False)
self.object_pos -= self._env_pos
self.object_velocities = self._objects.get_velocities(clone=False)
self.object_linvel = self.object_velocities[:, 0:3]
self.object_angvel = self.object_velocities[:, 3:6]
def calculate_metrics(self):
self.rew_buf[:], self.reset_buf[:], self.reset_goal_buf[:], self.progress_buf[:], self.successes[:], self.consecutive_successes[:] = compute_hand_reward(
self.rew_buf, self.reset_buf, self.reset_goal_buf, self.progress_buf, self.successes, self.consecutive_successes,
self.max_episode_length, self.object_pos, self.object_rot, self.goal_pos, self.goal_rot,
self.dist_reward_scale, self.rot_reward_scale, self.rot_eps, self.actions, self.action_penalty_scale,
self.success_tolerance, self.reach_goal_bonus, self.fall_dist, self.fall_penalty,
self.max_consecutive_successes, self.av_factor,
)
self.extras['consecutive_successes'] = self.consecutive_successes.mean()
self.randomization_buf += 1
if self.print_success_stat:
self.total_resets = self.total_resets + self.reset_buf.sum()
direct_average_successes = self.total_successes + self.successes.sum()
self.total_successes = self.total_successes + (self.successes * self.reset_buf).sum()
# The direct average shows the overall result more quickly, but slightly undershoots long term policy performance.
print("Direct average consecutive successes = {:.1f}".format(direct_average_successes/(self.total_resets + self.num_envs)))
if self.total_resets > 0:
print("Post-Reset average consecutive successes = {:.1f}".format(self.total_successes/self.total_resets))
def pre_physics_step(self, actions):
env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
goal_env_ids = self.reset_goal_buf.nonzero(as_tuple=False).squeeze(-1)
reset_buf = self.reset_buf.clone()
# if only goals need reset, then call set API
if len(goal_env_ids) > 0 and len(env_ids) == 0:
self.reset_target_pose(goal_env_ids)
elif len(goal_env_ids) > 0:
self.reset_target_pose(goal_env_ids)
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.actions = actions.clone().to(self.device)
if self.use_relative_control:
targets = self.prev_targets[:, self.actuated_dof_indices] + self.hand_dof_speed_scale * self.dt * self.actions
self.cur_targets[:, self.actuated_dof_indices] = tensor_clamp(targets,
self.hand_dof_lower_limits[self.actuated_dof_indices], self.hand_dof_upper_limits[self.actuated_dof_indices])
else:
self.cur_targets[:, self.actuated_dof_indices] = scale(self.actions,
self.hand_dof_lower_limits[self.actuated_dof_indices], self.hand_dof_upper_limits[self.actuated_dof_indices])
self.cur_targets[:, self.actuated_dof_indices] = self.act_moving_average * self.cur_targets[:, self.actuated_dof_indices] + \
(1.0 - self.act_moving_average) * self.prev_targets[:, self.actuated_dof_indices]
self.cur_targets[:, self.actuated_dof_indices] = tensor_clamp(self.cur_targets[:, self.actuated_dof_indices],
self.hand_dof_lower_limits[self.actuated_dof_indices], self.hand_dof_upper_limits[self.actuated_dof_indices])
self.prev_targets[:, self.actuated_dof_indices] = self.cur_targets[:, self.actuated_dof_indices]
self._hands.set_joint_position_targets(
self.cur_targets[:, self.actuated_dof_indices], indices=None, joint_indices=self.actuated_dof_indices
)
if self._dr_randomizer.randomize:
rand_envs = torch.where(self.randomization_buf >= self._dr_randomizer.min_frequency, torch.ones_like(self.randomization_buf), torch.zeros_like(self.randomization_buf))
rand_env_ids = torch.nonzero(torch.logical_and(rand_envs, reset_buf))
dr.physics_view.step_randomization(rand_env_ids)
self.randomization_buf[rand_env_ids] = 0
def is_done(self):
pass
def reset_target_pose(self, env_ids):
# reset goal
indices = env_ids.to(dtype=torch.int32)
rand_floats = torch_rand_float(-1.0, 1.0, (len(env_ids), 4), device=self.device)
new_rot = randomize_rotation(rand_floats[:, 0], rand_floats[:, 1], self.x_unit_tensor[env_ids], self.y_unit_tensor[env_ids])
self.goal_pos[env_ids] = self.goal_init_pos[env_ids, 0:3]
self.goal_rot[env_ids] = new_rot
goal_pos, goal_rot = self.goal_pos.clone(), self.goal_rot.clone()
goal_pos[env_ids] = self.goal_pos[env_ids] + self.goal_displacement_tensor + self._env_pos[env_ids] # add world env pos
self._goals.set_world_poses(goal_pos[env_ids], goal_rot[env_ids], indices)
self.reset_goal_buf[env_ids] = 0
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
rand_floats = torch_rand_float(-1.0, 1.0, (len(env_ids), self.num_hand_dofs * 2 + 5), device=self.device)
self.reset_target_pose(env_ids)
# reset object
new_object_pos = self.object_init_pos[env_ids] + \
self.reset_position_noise * rand_floats[:, 0:3] + self._env_pos[env_ids] # add world env pos
new_object_rot = randomize_rotation(rand_floats[:, 3], rand_floats[:, 4], self.x_unit_tensor[env_ids], self.y_unit_tensor[env_ids])
object_velocities = torch.zeros_like(self.object_init_velocities, dtype=torch.float, device=self.device)
self._objects.set_velocities(object_velocities[env_ids], indices)
self._objects.set_world_poses(new_object_pos, new_object_rot, indices)
# reset hand
delta_max = self.hand_dof_upper_limits - self.hand_dof_default_pos
delta_min = self.hand_dof_lower_limits - self.hand_dof_default_pos
rand_delta = delta_min + (delta_max - delta_min) * rand_floats[:, 5:5+self.num_hand_dofs]
pos = self.hand_dof_default_pos + self.reset_dof_pos_noise * rand_delta
dof_pos = torch.zeros((self.num_envs, self.num_hand_dofs), device=self.device)
dof_pos[env_ids, :] = pos
dof_vel = torch.zeros((self.num_envs, self.num_hand_dofs), device=self.device)
dof_vel[env_ids, :] = self.hand_dof_default_vel + \
self.reset_dof_vel_noise * rand_floats[:, 5+self.num_hand_dofs:5+self.num_hand_dofs*2]
self.prev_targets[env_ids, :self.num_hand_dofs] = pos
self.cur_targets[env_ids, :self.num_hand_dofs] = pos
self.hand_dof_targets[env_ids, :] = pos
self._hands.set_joint_position_targets(self.hand_dof_targets[env_ids], indices)
self._hands.set_joint_positions(dof_pos[env_ids], indices)
self._hands.set_joint_velocities(dof_vel[env_ids], indices)
self.progress_buf[env_ids] = 0
self.reset_buf[env_ids] = 0
self.successes[env_ids] = 0
#####################################################################
###=========================jit functions=========================###
#####################################################################
@torch.jit.script
def randomize_rotation(rand0, rand1, x_unit_tensor, y_unit_tensor):
return quat_mul(quat_from_angle_axis(rand0 * np.pi, x_unit_tensor), quat_from_angle_axis(rand1 * np.pi, y_unit_tensor))
@torch.jit.script
def compute_hand_reward(
rew_buf, reset_buf, reset_goal_buf, progress_buf, successes, consecutive_successes,
max_episode_length: float, object_pos, object_rot, target_pos, target_rot,
dist_reward_scale: float, rot_reward_scale: float, rot_eps: float,
actions, action_penalty_scale: float,
success_tolerance: float, reach_goal_bonus: float, fall_dist: float,
fall_penalty: float, max_consecutive_successes: int, av_factor: float
):
goal_dist = torch.norm(object_pos - target_pos, p=2, dim=-1)
# Orientation alignment for the cube in hand and goal cube
quat_diff = quat_mul(object_rot, quat_conjugate(target_rot))
rot_dist = 2.0 * torch.asin(torch.clamp(torch.norm(quat_diff[:, 1:4], p=2, dim=-1), max=1.0)) # changed quat convention
dist_rew = goal_dist * dist_reward_scale
rot_rew = 1.0/(torch.abs(rot_dist) + rot_eps) * rot_reward_scale
action_penalty = torch.sum(actions ** 2, dim=-1)
# Total reward is: position distance + orientation alignment + action regularization + success bonus + fall penalty
reward = dist_rew + rot_rew + action_penalty * action_penalty_scale
# Find out which envs hit the goal and update successes count
goal_resets = torch.where(torch.abs(rot_dist) <= success_tolerance, torch.ones_like(reset_goal_buf), reset_goal_buf)
successes = successes + goal_resets
# Success bonus: orientation is within `success_tolerance` of goal orientation
reward = torch.where(goal_resets == 1, reward + reach_goal_bonus, reward)
# Fall penalty: distance to the goal is larger than a threashold
reward = torch.where(goal_dist >= fall_dist, reward + fall_penalty, reward)
# Check env termination conditions, including maximum success number
resets = torch.where(goal_dist >= fall_dist, torch.ones_like(reset_buf), reset_buf)
if max_consecutive_successes > 0:
# Reset progress buffer on goal envs if max_consecutive_successes > 0
progress_buf = torch.where(torch.abs(rot_dist) <= success_tolerance, torch.zeros_like(progress_buf), progress_buf)
resets = torch.where(successes >= max_consecutive_successes, torch.ones_like(resets), resets)
resets = torch.where(progress_buf >= max_episode_length - 1, torch.ones_like(resets), resets)
# Apply penalty for not reaching the goal
if max_consecutive_successes > 0:
reward = torch.where(progress_buf >= max_episode_length - 1, reward + 0.5 * fall_penalty, reward)
num_resets = torch.sum(resets)
finished_cons_successes = torch.sum(successes * resets.float())
cons_successes = torch.where(num_resets > 0, av_factor*finished_cons_successes/num_resets + (1.0 - av_factor)*consecutive_successes, consecutive_successes)
return reward, resets, goal_resets, progress_buf, successes, cons_successes
| 20,302 | Python | 49.007389 | 179 | 0.657226 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/tasks/shared/locomotion.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# 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.
from abc import abstractmethod
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
from omni.isaac.core.utils.torch.maths import torch_rand_float, tensor_clamp, unscale
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
import numpy as np
import torch
import math
class LocomotionTask(RLTask):
def __init__(
self,
name,
env,
offset=None
) -> None:
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["episodeLength"]
self.dof_vel_scale = self._task_cfg["env"]["dofVelocityScale"]
self.angular_velocity_scale = self._task_cfg["env"]["angularVelocityScale"]
self.contact_force_scale = self._task_cfg["env"]["contactForceScale"]
self.power_scale = self._task_cfg["env"]["powerScale"]
self.heading_weight = self._task_cfg["env"]["headingWeight"]
self.up_weight = self._task_cfg["env"]["upWeight"]
self.actions_cost_scale = self._task_cfg["env"]["actionsCost"]
self.energy_cost_scale = self._task_cfg["env"]["energyCost"]
self.joints_at_limit_cost_scale = self._task_cfg["env"]["jointsAtLimitCost"]
self.death_cost = self._task_cfg["env"]["deathCost"]
self.termination_height = self._task_cfg["env"]["terminationHeight"]
self.alive_reward_scale = self._task_cfg["env"]["alive_reward_scale"]
RLTask.__init__(self, name, env)
return
@abstractmethod
def set_up_scene(self, scene) -> None:
pass
@abstractmethod
def get_robot(self):
pass
def get_observations(self) -> dict:
torso_position, torso_rotation = self._robots.get_world_poses(clone=False)
velocities = self._robots.get_velocities(clone=False)
velocity = velocities[:, 0:3]
ang_velocity = velocities[:, 3:6]
dof_pos = self._robots.get_joint_positions(clone=False)
dof_vel = self._robots.get_joint_velocities(clone=False)
# force sensors attached to the feet
sensor_force_torques = self._robots._physics_view.get_force_sensor_forces() # (num_envs, num_sensors, 6)
self.obs_buf[:], self.potentials[:], self.prev_potentials[:], self.up_vec[:], self.heading_vec[:] = get_observations(
torso_position, torso_rotation, velocity, ang_velocity, dof_pos, dof_vel, self.targets, self.potentials, self.dt,
self.inv_start_rot, self.basis_vec0, self.basis_vec1, self.dof_limits_lower, self.dof_limits_upper, self.dof_vel_scale,
sensor_force_torques, self._num_envs, self.contact_force_scale, self.actions, self.angular_velocity_scale
)
observations = {
self._robots.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
self.actions = actions.clone().to(self._device)
forces = self.actions * self.joint_gears * self.power_scale
indices = torch.arange(self._robots.count, dtype=torch.int32, device=self._device)
# applies joint torques
self._robots.set_joint_efforts(forces, indices=indices)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
# randomize DOF positions and velocities
dof_pos = torch_rand_float(-0.2, 0.2, (num_resets, self._robots.num_dof), device=self._device)
dof_pos[:] = tensor_clamp(
self.initial_dof_pos[env_ids] + dof_pos, self.dof_limits_lower, self.dof_limits_upper
)
dof_vel = torch_rand_float(-0.1, 0.1, (num_resets, self._robots.num_dof), device=self._device)
root_pos, root_rot = self.initial_root_pos[env_ids], self.initial_root_rot[env_ids]
root_vel = torch.zeros((num_resets, 6), device=self._device)
# apply resets
self._robots.set_joint_positions(dof_pos, indices=env_ids)
self._robots.set_joint_velocities(dof_vel, indices=env_ids)
self._robots.set_world_poses(root_pos, root_rot, indices=env_ids)
self._robots.set_velocities(root_vel, indices=env_ids)
to_target = self.targets[env_ids] - self.initial_root_pos[env_ids]
to_target[:, 2] = 0.0
self.prev_potentials[env_ids] = -torch.norm(to_target, p=2, dim=-1) / self.dt
self.potentials[env_ids] = self.prev_potentials[env_ids].clone()
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
num_resets = len(env_ids)
def post_reset(self):
self._robots = self.get_robot()
self.initial_root_pos, self.initial_root_rot = self._robots.get_world_poses()
self.initial_dof_pos = self._robots.get_joint_positions()
# initialize some data used later on
self.start_rotation = torch.tensor([1, 0, 0, 0], device=self._device, dtype=torch.float32)
self.up_vec = torch.tensor([0, 0, 1], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.heading_vec = torch.tensor([1, 0, 0], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.inv_start_rot = quat_conjugate(self.start_rotation).repeat((self.num_envs, 1))
self.basis_vec0 = self.heading_vec.clone()
self.basis_vec1 = self.up_vec.clone()
self.targets = torch.tensor([1000, 0, 0], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.target_dirs = torch.tensor([1, 0, 0], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.dt = 1.0 / 60.0
self.potentials = torch.tensor([-1000.0 / self.dt], dtype=torch.float32, device=self._device).repeat(self.num_envs)
self.prev_potentials = self.potentials.clone()
self.actions = torch.zeros((self.num_envs, self.num_actions), device=self._device)
# randomize all envs
indices = torch.arange(self._robots.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self) -> None:
self.rew_buf[:] = calculate_metrics(
self.obs_buf, self.actions, self.up_weight, self.heading_weight, self.potentials, self.prev_potentials,
self.actions_cost_scale, self.energy_cost_scale, self.termination_height,
self.death_cost, self._robots.num_dof, self.get_dof_at_limit_cost(), self.alive_reward_scale, self.motor_effort_ratio
)
def is_done(self) -> None:
self.reset_buf[:] = is_done(
self.obs_buf, self.termination_height, self.reset_buf, self.progress_buf, self._max_episode_length
)
#####################################################################
###=========================jit functions=========================###
#####################################################################
@torch.jit.script
def normalize_angle(x):
return torch.atan2(torch.sin(x), torch.cos(x))
@torch.jit.script
def get_observations(
torso_position,
torso_rotation,
velocity,
ang_velocity,
dof_pos,
dof_vel,
targets,
potentials,
dt,
inv_start_rot,
basis_vec0,
basis_vec1,
dof_limits_lower,
dof_limits_upper,
dof_vel_scale,
sensor_force_torques,
num_envs,
contact_force_scale,
actions,
angular_velocity_scale
):
# type: (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, float, Tensor, Tensor, Tensor, Tensor, Tensor, float, Tensor, int, float, Tensor, float) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]
to_target = targets - torso_position
to_target[:, 2] = 0.0
prev_potentials = potentials.clone()
potentials = -torch.norm(to_target, p=2, dim=-1) / dt
torso_quat, up_proj, heading_proj, up_vec, heading_vec = compute_heading_and_up(
torso_rotation, inv_start_rot, to_target, basis_vec0, basis_vec1, 2
)
vel_loc, angvel_loc, roll, pitch, yaw, angle_to_target = compute_rot(
torso_quat, velocity, ang_velocity, targets, torso_position
)
dof_pos_scaled = unscale(dof_pos, dof_limits_lower, dof_limits_upper)
# obs_buf shapes: 1, 3, 3, 1, 1, 1, 1, 1, num_dofs, num_dofs, num_sensors * 6, num_dofs
obs = torch.cat(
(
torso_position[:, 2].view(-1, 1),
vel_loc,
angvel_loc * angular_velocity_scale,
normalize_angle(yaw).unsqueeze(-1),
normalize_angle(roll).unsqueeze(-1),
normalize_angle(angle_to_target).unsqueeze(-1),
up_proj.unsqueeze(-1),
heading_proj.unsqueeze(-1),
dof_pos_scaled,
dof_vel * dof_vel_scale,
sensor_force_torques.reshape(num_envs, -1) * contact_force_scale,
actions,
),
dim=-1,
)
return obs, potentials, prev_potentials, up_vec, heading_vec
@torch.jit.script
def is_done(
obs_buf,
termination_height,
reset_buf,
progress_buf,
max_episode_length
):
# type: (Tensor, float, Tensor, Tensor, float) -> Tensor
reset = torch.where(obs_buf[:, 0] < termination_height, torch.ones_like(reset_buf), reset_buf)
reset = torch.where(progress_buf >= max_episode_length - 1, torch.ones_like(reset_buf), reset)
return reset
@torch.jit.script
def calculate_metrics(
obs_buf,
actions,
up_weight,
heading_weight,
potentials,
prev_potentials,
actions_cost_scale,
energy_cost_scale,
termination_height,
death_cost,
num_dof,
dof_at_limit_cost,
alive_reward_scale,
motor_effort_ratio
):
# type: (Tensor, Tensor, float, float, Tensor, Tensor, float, float, float, float, int, Tensor, float, Tensor) -> Tensor
heading_weight_tensor = torch.ones_like(obs_buf[:, 11]) * heading_weight
heading_reward = torch.where(
obs_buf[:, 11] > 0.8, heading_weight_tensor, heading_weight * obs_buf[:, 11] / 0.8
)
# aligning up axis of robot and environment
up_reward = torch.zeros_like(heading_reward)
up_reward = torch.where(obs_buf[:, 10] > 0.93, up_reward + up_weight, up_reward)
# energy penalty for movement
actions_cost = torch.sum(actions ** 2, dim=-1)
electricity_cost = torch.sum(torch.abs(actions * obs_buf[:, 12+num_dof:12+num_dof*2])* motor_effort_ratio.unsqueeze(0), dim=-1)
# reward for duration of staying alive
alive_reward = torch.ones_like(potentials) * alive_reward_scale
progress_reward = potentials - prev_potentials
total_reward = (
progress_reward
+ alive_reward
+ up_reward
+ heading_reward
- actions_cost_scale * actions_cost
- energy_cost_scale * electricity_cost
- dof_at_limit_cost
)
# adjust reward for fallen agents
total_reward = torch.where(
obs_buf[:, 0] < termination_height, torch.ones_like(total_reward) * death_cost, total_reward
)
return total_reward | 12,809 | Python | 38.906542 | 214 | 0.643922 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/sim2real/ur10.py | # Copyright (c) 2022-2023, Johnson Sun
# All rights reserved.
#
# 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.
import asyncio
import math
import numpy as np
try:
import rospy
# Ref: https://github.com/ros-controls/ros_controllers/blob/melodic-devel/rqt_joint_trajectory_controller/src/rqt_joint_trajectory_controller/joint_trajectory_controller.py
from control_msgs.msg import JointTrajectoryControllerState
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
except ImportError:
rospy = None
class RealWorldUR10():
# Defined in ur10.usd
sim_dof_angle_limits = [
(-360, 360, False),
(-360, 360, False),
(-360, 360, False),
(-360, 360, False),
(-360, 360, False),
(-360, 360, False),
] # _sim_dof_limits[:,2] == True indicates inversed joint angle compared to real
# Ref: https://github.com/ros-industrial/universal_robot/issues/112
pi = math.pi
servo_angle_limits = [
(-2*pi, 2*pi),
(-2*pi, 2*pi),
(-2*pi, 2*pi),
(-2*pi, 2*pi),
(-2*pi, 2*pi),
(-2*pi, 2*pi),
]
# ROS-related strings
state_topic = '/scaled_pos_joint_traj_controller/state'
cmd_topic = '/scaled_pos_joint_traj_controller/command'
joint_names = [
'elbow_joint',
'shoulder_lift_joint',
'shoulder_pan_joint',
'wrist_1_joint',
'wrist_2_joint',
'wrist_3_joint'
]
# Joint name mapping to simulation action index
joint_name_to_idx = {
'elbow_joint': 2,
'shoulder_lift_joint': 1,
'shoulder_pan_joint': 0,
'wrist_1_joint': 3,
'wrist_2_joint': 4,
'wrist_3_joint': 5
}
def __init__(self, fail_quietely=False, verbose=False) -> None:
print("Connecting to real-world UR10")
self.fail_quietely = fail_quietely
self.verbose = verbose
self.pub_freq = 10 # Hz
# Not really sure if current_pos and target_pos require mutex here.
self.current_pos = None
self.target_pos = None
if rospy is None:
if not self.fail_quietely:
raise ValueError("ROS is not installed!")
print("ROS is not installed!")
return
try:
rospy.init_node("custom_controller", anonymous=True, disable_signals=True, log_level=rospy.ERROR)
except rospy.exceptions.ROSException as e:
print("Node has already been initialized, do nothing")
if self.verbose:
print("Receiving real-world UR10 joint angles...")
print("If you didn't see any outputs, you may have set up UR5 or ROS incorrectly.")
self.sub = rospy.Subscriber(
self.state_topic,
JointTrajectoryControllerState,
self.sub_callback,
queue_size=1
)
self.pub = rospy.Publisher(
self.cmd_topic,
JointTrajectory,
queue_size=1
)
# self.min_traj_dur = 5.0 / self.pub_freq # Minimum trajectory duration
self.min_traj_dur = 0 # Minimum trajectory duration
# For catching exceptions in asyncio
def custom_exception_handler(loop, context):
print(context)
# Ref: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.set_exception_handler
asyncio.get_event_loop().set_exception_handler(custom_exception_handler)
# Ref: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_ros_custom_message.html
asyncio.ensure_future(self.pub_task())
def sub_callback(self, msg):
# msg has type: JointTrajectoryControllerState
actual_pos = {}
for i in range(len(msg.joint_names)):
joint_name = msg.joint_names[i]
joint_pos = msg.actual.positions[i]
actual_pos[joint_name] = joint_pos
self.current_pos = actual_pos
if self.verbose:
print(f'(sub) {actual_pos}')
async def pub_task(self):
while not rospy.is_shutdown():
await asyncio.sleep(1.0 / self.pub_freq)
if self.current_pos is None:
# Not ready (recieved UR state) yet
continue
if self.target_pos is None:
# No command yet
continue
# Construct message
dur = [] # move duration of each joints
traj = JointTrajectory()
traj.joint_names = self.joint_names
point = JointTrajectoryPoint()
moving_average = 1
for name in traj.joint_names:
pos = self.current_pos[name]
cmd = pos * (1-moving_average) + self.target_pos[self.joint_name_to_idx[name]] * moving_average
max_vel = 3.15 # from ur5.urdf (or ur5.urdf.xacro)
duration = abs(cmd - pos) / max_vel # time = distance / velocity
dur.append(max(duration, self.min_traj_dur))
point.positions.append(cmd)
point.time_from_start = rospy.Duration(max(dur))
traj.points.append(point)
self.pub.publish(traj)
print(f'(pub) {point.positions}')
def send_joint_pos(self, joint_pos):
if len(joint_pos) != 6:
raise Exception("The length of UR10 joint_pos is {}, but should be 6!".format(len(joint_pos)))
# Convert Sim angles to Real angles
target_pos = [0] * 6
for i, pos in enumerate(joint_pos):
if i == 5:
# Ignore the gripper joints for Reacher task
continue
# Map [L, U] to [A, B]
L, U, inversed = self.sim_dof_angle_limits[i]
A, B = self.servo_angle_limits[i]
angle = np.rad2deg(float(pos))
if not L <= angle <= U:
print("The {}-th simulation joint angle ({}) is out of range! Should be in [{}, {}]".format(i, angle, L, U))
angle = np.clip(angle, L, U)
target_pos[i] = (angle - L) * ((B-A)/(U-L)) + A # Map [L, U] to [A, B]
if inversed:
target_pos[i] = (B-A) - (target_pos[i] - A) + A # Map [A, B] to [B, A]
if not A <= target_pos[i] <= B:
raise Exception("(Should Not Happen) The {}-th real world joint angle ({}) is out of range! hould be in [{}, {}]".format(i, target_pos[i], A, B))
self.target_pos = target_pos
if __name__ == "__main__":
print("Make sure you are running `roslaunch ur_robot_driver`.")
print("If the machine running Isaac is not the ROS master node, " + \
"make sure you have set the environment variables: " + \
"`ROS_MASTER_URI` and `ROS_HOSTNAME`/`ROS_IP` correctly.")
ur10 = RealWorldUR10(verbose=True)
rospy.spin()
| 8,268 | Python | 41.405128 | 176 | 0.608128 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/config.yaml |
# Task name - used to pick the class to load
task_name: ${task.name}
# experiment name. defaults to name of training config
experiment: ''
# if set to positive integer, overrides the default number of environments
num_envs: ''
# seed - set to -1 to choose random seed
seed: 42
# set to True for deterministic performance
torch_deterministic: False
# set the maximum number of learning iterations to train for. overrides default per-environment setting
max_iterations: ''
## Device config
physics_engine: 'physx'
# whether to use cpu or gpu pipeline
pipeline: 'gpu'
# whether to use cpu or gpu physx
sim_device: 'gpu'
# used for gpu simulation only - device id for running sim and task if pipeline=gpu
device_id: 0
# device to run RL
rl_device: 'cuda:0'
## PhysX arguments
num_threads: 4 # Number of worker threads per scene used by PhysX - for CPU PhysX only.
solver_type: 1 # 0: pgs, 1: tgs
# RLGames Arguments
# test - if set, run policy in inference mode (requires setting checkpoint to load)
test: False
# used to set checkpoint path
checkpoint: ''
# disables rendering
headless: False
wandb_activate: False
wandb_group: ''
wandb_name: ${train.params.config.name}
wandb_entity: ''
wandb_project: 'omniisaacgymenvs'
# set default task and default training config based on task
defaults:
- task: Cartpole
- train: ${task}PPO
- hydra/job_logging: disabled
# set the directory where the output files get saved
hydra:
output_subdir: null
run:
dir: .
| 1,475 | YAML | 23.6 | 103 | 0.738305 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/FrankaCabinet.yaml | # used to create the object
name: FrankaCabinet
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 3.0
episodeLength: 500
enableDebugVis: False
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 2 # 60 Hz
startPositionNoise: 0.0
startRotationNoise: 0.0
numProps: 4
aggregateMode: 3
actionScale: 7.5
dofVelocityScale: 0.1
distRewardScale: 2.0
rotRewardScale: 0.5
aroundHandleRewardScale: 10.0
openRewardScale: 7.5
fingerDistRewardScale: 100.0
actionPenaltyScale: 0.01
fingerCloseRewardScale: 10.0
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 12
solver_velocity_iteration_count: 1
contact_offset: 0.005
rest_offset: 0.0
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 1000.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 33554432
gpu_found_lost_pairs_capacity: 524288
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1048576
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 33554432
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
franka:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 12
solver_velocity_iteration_count: 1
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0
# per-shape
contact_offset: 0.005
rest_offset: 0.0
cabinet:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 12
solver_velocity_iteration_count: 1
sleep_threshold: 0.0
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0
# per-shape
contact_offset: 0.005
rest_offset: 0.0
prop:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 12
solver_velocity_iteration_count: 1
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: 100
max_depenetration_velocity: 1000.0
# per-shape
contact_offset: 0.005
rest_offset: 0.0
| 3,393 | YAML | 24.908397 | 71 | 0.689066 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Ant.yaml | # used to create the object
name: Ant
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
# numEnvs: ${...num_envs}
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 5
episodeLength: 1000
enableDebugVis: False
clipActions: 1.0
powerScale: 0.5
controlFrequencyInv: 2 # 60 Hz
# reward parameters
headingWeight: 0.5
upWeight: 0.1
# cost parameters
actionsCost: 0.005
energyCost: 0.05
dofVelocityScale: 0.2
angularVelocityScale: 1.0
contactForceScale: 0.1
jointsAtLimitCost: 0.1
deathCost: -2.0
terminationHeight: 0.31
alive_reward_scale: 0.5
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.0
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 10.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 8192
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
Ant:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 10.0 | 2,358 | YAML | 24.641304 | 71 | 0.688719 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/AnymalTerrain.yaml | name: AnymalTerrain
physics_engine: ${..physics_engine}
env:
numEnvs: ${resolve_default:2048,${...num_envs}}
numObservations: 188
numActions: 12
envSpacing: 3. # [m]
terrain:
staticFriction: 1.0 # [-]
dynamicFriction: 1.0 # [-]
restitution: 0. # [-]
# rough terrain only:
curriculum: true
maxInitMapLevel: 0
mapLength: 8.
mapWidth: 8.
numLevels: 10
numTerrains: 20
# terrain types: [smooth slope, rough slope, stairs up, stairs down, discrete]
terrainProportions: [0.1, 0.1, 0.35, 0.25, 0.2]
# tri mesh only:
slopeTreshold: 0.5
baseInitState:
pos: [0.0, 0.0, 0.62] # x,y,z [m]
rot: [1.0, 0.0, 0.0, 0.0] # w,x,y,z [quat]
vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s]
vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s]
randomCommandVelocityRanges:
# train
linear_x: [-1., 1.] # min max [m/s]
linear_y: [-1., 1.] # min max [m/s]
yaw: [-3.14, 3.14] # min max [rad/s]
control:
# PD Drive parameters:
stiffness: 80.0 # [N*m/rad]
damping: 2.0 # [N*m*s/rad]
# action scale: target angle = actionScale * action + defaultAngle
actionScale: 0.5
# decimation: Number of control action updates @ sim DT per policy DT
decimation: 4
defaultJointAngles: # = target angles when action = 0.0
LF_HAA: 0.03 # [rad]
LH_HAA: 0.03 # [rad]
RF_HAA: -0.03 # [rad]
RH_HAA: -0.03 # [rad]
LF_HFE: 0.4 # [rad]
LH_HFE: -0.4 # [rad]
RF_HFE: 0.4 # [rad]
RH_HFE: -0.4 # [rad]
LF_KFE: -0.8 # [rad]
LH_KFE: 0.8 # [rad]
RF_KFE: -0.8 # [rad]
RH_KFE: 0.8 # [rad]
learn:
# rewards
terminalReward: 0.0
linearVelocityXYRewardScale: 1.0
linearVelocityZRewardScale: -4.0
angularVelocityXYRewardScale: -0.05
angularVelocityZRewardScale: 0.5
orientationRewardScale: -0.
torqueRewardScale: -0.00002
jointAccRewardScale: -0.0005
baseHeightRewardScale: -0.0
actionRateRewardScale: -0.01
fallenOverRewardScale: -1.0
# cosmetics
hipRewardScale: -0. #25
# normalization
linearVelocityScale: 2.0
angularVelocityScale: 0.25
dofPositionScale: 1.0
dofVelocityScale: 0.05
heightMeasurementScale: 5.0
# noise
addNoise: true
noiseLevel: 1.0 # scales other values
dofPositionNoise: 0.01
dofVelocityNoise: 1.5
linearVelocityNoise: 0.1
angularVelocityNoise: 0.2
gravityNoise: 0.05
heightMeasurementNoise: 0.06
#randomization
pushInterval_s: 15
# episode length in seconds
episodeLength_s: 20
sim:
dt: 0.005
up_axis: "z"
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: False
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.0
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 163840
gpu_found_lost_pairs_capacity: 4194304
gpu_found_lost_aggregate_pairs_capacity: 33554432
gpu_total_aggregate_pairs_capacity: 4194304
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 134217728
gpu_temp_buffer_capacity: 33554432
gpu_max_num_partitions: 8
anymal:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: False
# also in stage params
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0 | 4,323 | YAML | 25.365854 | 82 | 0.631737 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/BallBalance.yaml | # used to create the object
name: BallBalance
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 2.0
maxEpisodeLength: 500
actionSpeedScale: 20
clipObservations: 5.0
clipActions: 1.0
sim:
dt: 0.01
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 1000.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 8192
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
table:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0
ball:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: 200
max_depenetration_velocity: 1000.0
| 2,438 | YAML | 25.510869 | 71 | 0.687859 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Humanoid.yaml | # used to create the object
name: Humanoid
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
# numEnvs: ${...num_envs}
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 5
episodeLength: 1000
enableDebugVis: False
clipActions: 1.0
powerScale: 1.0
controlFrequencyInv: 2 # 60 Hz
# reward parameters
headingWeight: 0.5
upWeight: 0.1
# cost parameters
actionsCost: 0.01
energyCost: 0.05
dofVelocityScale: 0.1
angularVelocityScale: 0.25
contactForceScale: 0.01
jointsAtLimitCost: 0.25
deathCost: -1.0
terminationHeight: 0.8
alive_reward_scale: 2.0
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 10.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 8192
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
Humanoid:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 10.0
| 2,323 | YAML | 24.538461 | 71 | 0.691347 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/AllegroHand.yaml | # used to create the object
name: AllegroHand
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:8192,${...num_envs}}
envSpacing: 0.75
episodeLength: 600
clipObservations: 5.0
clipActions: 1.0
useRelativeControl: False
dofSpeedScale: 20.0
actionsMovingAverage: 1.0
controlFrequencyInv: 4 # 30 Hz
startPositionNoise: 0.01
startRotationNoise: 0.0
resetPositionNoise: 0.01
resetRotationNoise: 0.0
resetDofPosRandomInterval: 0.2
resetDofVelRandomInterval: 0.0
# reward -> dictionary
distRewardScale: -10.0
rotRewardScale: 1.0
rotEps: 0.1
actionPenaltyScale: -0.0002
reachGoalBonus: 250
fallDistance: 0.24
fallPenalty: 0.0
velObsScale: 0.2
objectType: "block"
observationType: "full" # can be "full_no_vel", "full"
successTolerance: 0.1
printNumSuccesses: False
maxConsecutiveSuccesses: 0
sim:
dt: 0.0083 # 1/120 s
add_ground_plane: True
add_distant_light: True
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
# per-scene
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type} # 0: PGS, 1: TGS
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 33554432
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1048576
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 33554432
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
allegro_hand:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: False
# also in stage params
# per-actor
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.0005
# per-body
density: -1
max_depenetration_velocity: 1000.0
object:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.0025
# per-body
density: 400.0
max_depenetration_velocity: 1000.0
goal_object:
# -1 to use default values
override_usd_defaults: False
fixed_base: True
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
sleep_threshold: 0.000
stabilization_threshold: 0.0025
# per-body
density: -1
max_depenetration_velocity: 1000.0
| 3,338 | YAML | 25.291338 | 71 | 0.696525 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Ingenuity.yaml | # used to create the object
name: Ingenuity
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 2.5
maxEpisodeLength: 2000
enableDebugVis: False
clipObservations: 5.0
clipActions: 1.0
sim:
dt: 0.01
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -3.721]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
physx:
num_threads: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 6
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
max_depenetration_velocity: 1000.0
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: False
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 4194304
gpu_found_lost_aggregate_pairs_capacity: 33554432
gpu_total_aggregate_pairs_capacity: 4194304
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
ingenuity:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 6
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0
ball:
# -1 to use default values
override_usd_defaults: False
fixed_base: True
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 6
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0 | 2,335 | YAML | 26.809523 | 71 | 0.690792 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Quadcopter.yaml | # used to create the object
name: Quadcopter
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 1.25
maxEpisodeLength: 500
enableDebugVis: False
clipObservations: 5.0
clipActions: 1.0
sim:
dt: 0.01
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 1000.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 8192
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 8192
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
copter:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0
| 2,019 | YAML | 25.933333 | 71 | 0.690441 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Crazyflie.yaml | # used to create the object
name: Crazyflie
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 2.5
maxEpisodeLength: 700
enableDebugVis: False
clipObservations: 5.0
clipActions: 1.0
sim:
dt: 0.01
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
physx:
num_threads: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 6
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
max_depenetration_velocity: 1000.0
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: False
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 4194304
gpu_found_lost_aggregate_pairs_capacity: 33554432
gpu_total_aggregate_pairs_capacity: 4194304
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
crazyflie:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: True
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 6
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0
ball:
# -1 to use default values
override_usd_defaults: False
fixed_base: True
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 6
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 1000.0
| 2,334 | YAML | 26.470588 | 71 | 0.690231 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/UR10Reacher.yaml | # used to create the object
name: UR10Reacher
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:512,${...num_envs}}
envSpacing: 3
episodeLength: 600
clipObservations: 5.0
clipActions: 1.0
useRelativeControl: False
dofSpeedScale: 20.0
actionsMovingAverage: 0.1
controlFrequencyInv: 2 # 60 Hz
startPositionNoise: 0.01
startRotationNoise: 0.0
resetPositionNoise: 0.01
resetRotationNoise: 0.0
resetDofPosRandomInterval: 0.2
resetDofVelRandomInterval: 0.0
# Random forces applied to the object
forceScale: 0.0
forceProbRange: [0.001, 0.1]
forceDecay: 0.99
forceDecayInterval: 0.08
# reward -> dictionary
distRewardScale: -2.0
rotRewardScale: 1.0
rotEps: 0.1
actionPenaltyScale: -0.0002
reachGoalBonus: 250
velObsScale: 0.2
observationType: "full" # can only be "full"
successTolerance: 0.1
printNumSuccesses: False
maxConsecutiveSuccesses: 0
sim:
dt: 0.0083 # 1/120 s
add_ground_plane: True
add_distant_light: True
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
# per-scene
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type} # 0: PGS, 1: TGS
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 33554432
gpu_found_lost_pairs_capacity: 19771
gpu_found_lost_aggregate_pairs_capacity: 524288
gpu_total_aggregate_pairs_capacity: 1048576
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 33554432
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
ur10:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
object:
# -1 to use default values
override_usd_defaults: False
fixed_base: True
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
sleep_threshold: 0.000
stabilization_threshold: 0.0025
# per-body
density: -1
max_depenetration_velocity: 1000.0
goal_object:
# -1 to use default values
override_usd_defaults: False
fixed_base: True
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 8
solver_velocity_iteration_count: 0
sleep_threshold: 0.000
stabilization_threshold: 0.0025
# per-body
density: -1
max_depenetration_velocity: 1000.0
sim2real:
enabled: False
fail_quietely: False
verbose: False
safety: # Reduce joint limits during both training & testing
enabled: False
| 3,240 | YAML | 24.722222 | 71 | 0.700617 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Cartpole.yaml | # used to create the object
name: Cartpole
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: ${resolve_default:512,${...num_envs}}
envSpacing: 4.0
resetDist: 3.0
maxEffort: 400.0
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 2 # 60 Hz
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 1024
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1024
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
Cartpole:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 0
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.001 | 2,112 | YAML | 26.089743 | 71 | 0.684659 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Anymal.yaml | # used to create the object
name: Anymal
physics_engine: ${..physics_engine}
env:
numEnvs: ${resolve_default:4096,${...num_envs}}
envSpacing: 4. # [m]
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 2
baseInitState:
pos: [0.0, 0.0, 0.62] # x,y,z [m]
rot: [0.0, 0.0, 0.0, 1.0] # x,y,z,w [quat]
vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s]
vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s]
randomCommandVelocityRanges:
linear_x: [-2., 2.] # min max [m/s]
linear_y: [-1., 1.] # min max [m/s]
yaw: [-1., 1.] # min max [rad/s]
control:
# PD Drive parameters:
stiffness: 85.0 # [N*m/rad]
damping: 2.0 # [N*m*s/rad]
actionScale: 13.5
defaultJointAngles: # = target angles when action = 0.0
LF_HAA: 0.03 # [rad]
LH_HAA: 0.03 # [rad]
RF_HAA: -0.03 # [rad]
RH_HAA: -0.03 # [rad]
LF_HFE: 0.4 # [rad]
LH_HFE: -0.4 # [rad]
RF_HFE: 0.4 # [rad]
RH_HFE: -0.4 # [rad]
LF_KFE: -0.8 # [rad]
LH_KFE: 0.8 # [rad]
RF_KFE: -0.8 # [rad]
RH_KFE: 0.8 # [rad]
learn:
# rewards
linearVelocityXYRewardScale: 1.0
angularVelocityZRewardScale: 0.5
linearVelocityZRewardScale: -0.03
jointAccRewardScale: -0.0003
actionRateRewardScale: -0.006
cosmeticRewardScale: -0.06
# normalization
linearVelocityScale: 2.0
angularVelocityScale: 0.25
dofPositionScale: 1.0
dofVelocityScale: 0.05
# episode length in seconds
episodeLength_s: 50
sim:
dt: 0.01
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
enable_cameras: False
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 1
contact_offset: 0.02
rest_offset: 0.0
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 163840
gpu_found_lost_pairs_capacity: 4194304
gpu_found_lost_aggregate_pairs_capacity: 33554432
gpu_total_aggregate_pairs_capacity: 4194304
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 134217728
gpu_temp_buffer_capacity: 33554432
gpu_max_num_partitions: 8
Anymal:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_position_iteration_count: 4
solver_velocity_iteration_count: 1
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.0
| 3,293 | YAML | 24.937008 | 71 | 0.623747 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/ShadowHandOpenAI_LSTM.yaml | # specifies what the config is when running `ShadowHandOpenAI` in LSTM mode
defaults:
- ShadowHandOpenAI_FF
- _self_
env:
numEnvs: ${resolve_default:8192,${...num_envs}}
| 178 | YAML | 18.888887 | 75 | 0.707865 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/ShadowHandOpenAI_FFPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [400, 400, 200, 100]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False}
load_path: ${...checkpoint}
config:
name: ${resolve_default:ShadowHandOpenAI_FF,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
schedule_type: standard
kl_threshold: 0.016
score_to_win: 100000
max_epochs: ${resolve_default:10000,${....max_iterations}}
save_best_after: 100
save_frequency: 200
print_stats: True
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 16384
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001
central_value_config:
minibatch_size: 8192
mini_epochs: 8
learning_rate: 5e-4
lr_schedule: adaptive
schedule_type: standard
kl_threshold: 0.016
clip_value: True
normalize_input: True
truncate_grads: True
network:
name: actor_critic
central_value: True
mlp:
units: [512, 512, 256, 128]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
player:
deterministic: True
games_num: 100000
print_stats: True
| 2,199 | YAML | 20.782178 | 66 | 0.57799 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/AnymalTerrainPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: True
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0. # std = 1.
fixed_sigma: True
mlp:
units: [512, 256, 128]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
# rnn:
# name: lstm
# units: 128
# layers: 1
# before_mlp: True
# concat_input: True
# layer_norm: False
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:AnymalTerrain,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
ppo: True
mixed_precision: False # True
normalize_input: True
normalize_value: True
normalize_advantage: True
value_bootstrap: True
clip_actions: False
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 1.0
gamma: 0.99
tau: 0.95
e_clip: 0.2
entropy_coef: 0.001
learning_rate: 3.e-4 # overwritten by adaptive lr_schedule
lr_schedule: adaptive
kl_threshold: 0.008 # target kl for adaptive lr
truncate_grads: True
grad_norm: 1.
horizon_length: 48
minibatch_size: 16384
mini_epochs: 5
critic_coef: 2
clip_value: True
seq_len: 4 # only for rnn
bounds_loss_coef: 0.
max_epochs: ${resolve_default:2000,${....max_iterations}}
save_best_after: 100
score_to_win: 20000
save_frequency: 50
print_stats: True
| 1,893 | YAML | 21.547619 | 101 | 0.593767 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/HumanoidPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [400, 200, 100]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:Humanoid,${....experiment}}
full_experiment_name: ${.name}
env_name: rlgpu
device: ${....rl_device}
device_name: ${....rl_device}
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: ${resolve_default:1000,${....max_iterations}}
save_best_after: 100
save_frequency: 100
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 32
minibatch_size: 32768
mini_epochs: 5
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001
| 1,625 | YAML | 21.273972 | 101 | 0.596308 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/CrazyfliePPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 256, 128]
activation: tanh
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:Crazyflie,${....experiment}}
full_experiment_name: ${.name}
env_name: rlgpu
device: ${....rl_device}
device_name: ${....rl_device}
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 1e-4
lr_schedule: adaptive
kl_threshold: 0.016
score_to_win: 20000
max_epochs: ${resolve_default:1000,${....max_iterations}}
save_best_after: 50
save_frequency: 50
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 16384
mini_epochs: 8
critic_coef: 2
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001
| 1,579 | YAML | 21.253521 | 101 | 0.59468 |
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/ShadowHandPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [512, 512, 256, 128]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False}
load_path: ${...checkpoint}
config:
name: ${resolve_default:ShadowHand,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
schedule_type: standard
kl_threshold: 0.016
score_to_win: 100000
max_epochs: ${resolve_default:10000,${....max_iterations}}
save_best_after: 100
save_frequency: 200
print_stats: True
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 32768
mini_epochs: 5
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001
player:
deterministic: True
games_num: 100000
print_stats: True
| 1,689 | YAML | 20.392405 | 62 | 0.590882 |
Subsets and Splits