file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
2.5
98.5
max_line_length
int64
5
993
alphanum_fraction
float64
0.27
0.91
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/utils/generate_cuboids.py
import os from os.path import join from jinja2 import Environment, select_autoescape, FileSystemLoader def generate_assets(scales, min_volume, max_volume, generated_assets_dir, base_mesh): template_dir = join(os.path.dirname(os.path.abspath(__file__)), "../../../assets/asset_templates") print(f'Assets template dir: {template_dir}') env = Environment( loader=FileSystemLoader(template_dir), autoescape=select_autoescape(), ) template = env.get_template("cube_multicolor.urdf.template") cube_size_m = 0.05 idx = 0 for x_scale in scales: for y_scale in scales: for z_scale in scales: volume = x_scale * y_scale * z_scale / (100 * 100 * 100) if volume > max_volume: continue if volume < min_volume: continue curr_scales = [x_scale, y_scale, z_scale] curr_scales.sort() if curr_scales[0] * 3 <= curr_scales[1]: # skip thin "plates" continue asset = template.render(base_mesh=base_mesh, x_scale=cube_size_m * (x_scale / 100), y_scale=cube_size_m * (y_scale / 100), z_scale=cube_size_m * (z_scale / 100)) fname = f"{idx:03d}_cube_{x_scale}_{y_scale}_{z_scale}.urdf" idx += 1 with open(join(generated_assets_dir, fname), "w") as fobj: fobj.write(asset) def generate_small_cuboids(assets_dir, base_mesh): scales = [100, 50, 66, 75, 125, 150, 175, 200, 250, 300] min_volume = 0.75 max_volume = 1.5 generate_assets(scales, min_volume, max_volume, assets_dir, base_mesh) def generate_big_cuboids(assets_dir, base_mesh): scales = [100, 125, 150, 200, 250, 300, 350] min_volume = 2.5 max_volume = 15.0 generate_assets(scales, min_volume, max_volume, assets_dir, base_mesh)
2,053
Python
35.035087
102
0.541646
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/__init__.py
# Copyright (c) 2018-2023, 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.
1,558
Python
54.678569
80
0.784339
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/humanoid_amp_base.py
# Copyright (c) 2018-2023, 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 os import torch from isaacgym import gymtorch from isaacgym import gymapi from isaacgymenvs.utils.torch_jit_utils import quat_mul, to_torch, get_axis_params, calc_heading_quat_inv, \ exp_map_to_quat, quat_to_tan_norm, my_quat_rotate, calc_heading_quat_inv from ..base.vec_task import VecTask DOF_BODY_IDS = [1, 2, 3, 4, 6, 7, 9, 10, 11, 12, 13, 14] DOF_OFFSETS = [0, 3, 6, 9, 10, 13, 14, 17, 18, 21, 24, 25, 28] NUM_OBS = 13 + 52 + 28 + 12 # [root_h, root_rot, root_vel, root_ang_vel, dof_pos, dof_vel, key_body_pos] NUM_ACTIONS = 28 KEY_BODY_NAMES = ["right_hand", "left_hand", "right_foot", "left_foot"] class HumanoidAMPBase(VecTask): def __init__(self, config, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render): self.cfg = config self._pd_control = self.cfg["env"]["pdControl"] self.power_scale = self.cfg["env"]["powerScale"] self.randomize = self.cfg["task"]["randomize"] self.debug_viz = self.cfg["env"]["enableDebugVis"] self.camera_follow = self.cfg["env"].get("cameraFollow", False) self.plane_static_friction = self.cfg["env"]["plane"]["staticFriction"] self.plane_dynamic_friction = self.cfg["env"]["plane"]["dynamicFriction"] self.plane_restitution = self.cfg["env"]["plane"]["restitution"] self.max_episode_length = self.cfg["env"]["episodeLength"] self._local_root_obs = self.cfg["env"]["localRootObs"] self._contact_bodies = self.cfg["env"]["contactBodies"] self._termination_height = self.cfg["env"]["terminationHeight"] self._enable_early_termination = self.cfg["env"]["enableEarlyTermination"] self.cfg["env"]["numObservations"] = self.get_obs_size() self.cfg["env"]["numActions"] = self.get_action_size() super().__init__(config=self.cfg, rl_device=rl_device, sim_device=sim_device, graphics_device_id=graphics_device_id, headless=headless, virtual_screen_capture=virtual_screen_capture, force_render=force_render) dt = self.cfg["sim"]["dt"] self.dt = self.control_freq_inv * dt # get gym GPU state tensors actor_root_state = self.gym.acquire_actor_root_state_tensor(self.sim) dof_state_tensor = self.gym.acquire_dof_state_tensor(self.sim) sensor_tensor = self.gym.acquire_force_sensor_tensor(self.sim) rigid_body_state = self.gym.acquire_rigid_body_state_tensor(self.sim) contact_force_tensor = self.gym.acquire_net_contact_force_tensor(self.sim) sensors_per_env = 2 self.vec_sensor_tensor = gymtorch.wrap_tensor(sensor_tensor).view(self.num_envs, sensors_per_env * 6) dof_force_tensor = self.gym.acquire_dof_force_tensor(self.sim) self.dof_force_tensor = gymtorch.wrap_tensor(dof_force_tensor).view(self.num_envs, self.num_dof) self.gym.refresh_dof_state_tensor(self.sim) self.gym.refresh_actor_root_state_tensor(self.sim) self.gym.refresh_rigid_body_state_tensor(self.sim) self.gym.refresh_net_contact_force_tensor(self.sim) self._root_states = gymtorch.wrap_tensor(actor_root_state) self._initial_root_states = self._root_states.clone() self._initial_root_states[:, 7:13] = 0 # create some wrapper tensors for different slices self._dof_state = gymtorch.wrap_tensor(dof_state_tensor) self._dof_pos = self._dof_state.view(self.num_envs, self.num_dof, 2)[..., 0] self._dof_vel = self._dof_state.view(self.num_envs, self.num_dof, 2)[..., 1] self._initial_dof_pos = torch.zeros_like(self._dof_pos, device=self.device, dtype=torch.float) right_shoulder_x_handle = self.gym.find_actor_dof_handle(self.envs[0], self.humanoid_handles[0], "right_shoulder_x") left_shoulder_x_handle = self.gym.find_actor_dof_handle(self.envs[0], self.humanoid_handles[0], "left_shoulder_x") self._initial_dof_pos[:, right_shoulder_x_handle] = 0.5 * np.pi self._initial_dof_pos[:, left_shoulder_x_handle] = -0.5 * np.pi self._initial_dof_vel = torch.zeros_like(self._dof_vel, device=self.device, dtype=torch.float) self._rigid_body_state = gymtorch.wrap_tensor(rigid_body_state) self._rigid_body_pos = self._rigid_body_state.view(self.num_envs, self.num_bodies, 13)[..., 0:3] self._rigid_body_rot = self._rigid_body_state.view(self.num_envs, self.num_bodies, 13)[..., 3:7] self._rigid_body_vel = self._rigid_body_state.view(self.num_envs, self.num_bodies, 13)[..., 7:10] self._rigid_body_ang_vel = self._rigid_body_state.view(self.num_envs, self.num_bodies, 13)[..., 10:13] self._contact_forces = gymtorch.wrap_tensor(contact_force_tensor).view(self.num_envs, self.num_bodies, 3) self._terminate_buf = torch.ones(self.num_envs, device=self.device, dtype=torch.long) if self.viewer != None: self._init_camera() return def get_obs_size(self): return NUM_OBS def get_action_size(self): return NUM_ACTIONS def create_sim(self): self.up_axis_idx = 2 # index of up axis: Y=1, Z=2 self.sim = super().create_sim(self.device_id, self.graphics_device_id, self.physics_engine, self.sim_params) self._create_ground_plane() self._create_envs(self.num_envs, self.cfg["env"]['envSpacing'], int(np.sqrt(self.num_envs))) # If randomizing, apply once immediately on startup before the fist sim step if self.randomize: self.apply_randomizations(self.randomization_params) return def reset_idx(self, env_ids): self._reset_actors(env_ids) self._refresh_sim_tensors() self._compute_observations(env_ids) return def set_char_color(self, col): for i in range(self.num_envs): env_ptr = self.envs[i] handle = self.humanoid_handles[i] for j in range(self.num_bodies): self.gym.set_rigid_body_color(env_ptr, handle, j, gymapi.MESH_VISUAL, gymapi.Vec3(col[0], col[1], col[2])) return def _create_ground_plane(self): plane_params = gymapi.PlaneParams() plane_params.normal = gymapi.Vec3(0.0, 0.0, 1.0) plane_params.static_friction = self.plane_static_friction plane_params.dynamic_friction = self.plane_dynamic_friction plane_params.restitution = self.plane_restitution self.gym.add_ground(self.sim, plane_params) return def _create_envs(self, num_envs, spacing, num_per_row): lower = gymapi.Vec3(-spacing, -spacing, 0.0) upper = gymapi.Vec3(spacing, spacing, spacing) asset_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../assets') asset_file = "mjcf/amp_humanoid.xml" if "asset" in self.cfg["env"]: #asset_root = self.cfg["env"]["asset"].get("assetRoot", asset_root) asset_file = self.cfg["env"]["asset"].get("assetFileName", asset_file) asset_options = gymapi.AssetOptions() asset_options.angular_damping = 0.01 asset_options.max_angular_velocity = 100.0 asset_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE humanoid_asset = self.gym.load_asset(self.sim, asset_root, asset_file, asset_options) actuator_props = self.gym.get_asset_actuator_properties(humanoid_asset) motor_efforts = [prop.motor_effort for prop in actuator_props] # create force sensors at the feet right_foot_idx = self.gym.find_asset_rigid_body_index(humanoid_asset, "right_foot") left_foot_idx = self.gym.find_asset_rigid_body_index(humanoid_asset, "left_foot") sensor_pose = gymapi.Transform() self.gym.create_asset_force_sensor(humanoid_asset, right_foot_idx, sensor_pose) self.gym.create_asset_force_sensor(humanoid_asset, left_foot_idx, sensor_pose) self.max_motor_effort = max(motor_efforts) self.motor_efforts = to_torch(motor_efforts, device=self.device) self.torso_index = 0 self.num_bodies = self.gym.get_asset_rigid_body_count(humanoid_asset) self.num_dof = self.gym.get_asset_dof_count(humanoid_asset) self.num_joints = self.gym.get_asset_joint_count(humanoid_asset) start_pose = gymapi.Transform() start_pose.p = gymapi.Vec3(*get_axis_params(0.89, self.up_axis_idx)) start_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) self.start_rotation = torch.tensor([start_pose.r.x, start_pose.r.y, start_pose.r.z, start_pose.r.w], device=self.device) self.humanoid_handles = [] self.envs = [] self.dof_limits_lower = [] self.dof_limits_upper = [] for i in range(self.num_envs): # create env instance env_ptr = self.gym.create_env( self.sim, lower, upper, num_per_row ) contact_filter = 0 handle = self.gym.create_actor(env_ptr, humanoid_asset, start_pose, "humanoid", i, contact_filter, 0) self.gym.enable_actor_dof_force_sensors(env_ptr, handle) for j in range(self.num_bodies): self.gym.set_rigid_body_color( env_ptr, handle, j, gymapi.MESH_VISUAL, gymapi.Vec3(0.4706, 0.549, 0.6863)) self.envs.append(env_ptr) self.humanoid_handles.append(handle) if (self._pd_control): dof_prop = self.gym.get_asset_dof_properties(humanoid_asset) dof_prop["driveMode"] = gymapi.DOF_MODE_POS self.gym.set_actor_dof_properties(env_ptr, handle, dof_prop) dof_prop = self.gym.get_actor_dof_properties(env_ptr, handle) for j in range(self.num_dof): if dof_prop['lower'][j] > dof_prop['upper'][j]: self.dof_limits_lower.append(dof_prop['upper'][j]) self.dof_limits_upper.append(dof_prop['lower'][j]) else: self.dof_limits_lower.append(dof_prop['lower'][j]) self.dof_limits_upper.append(dof_prop['upper'][j]) self.dof_limits_lower = to_torch(self.dof_limits_lower, device=self.device) self.dof_limits_upper = to_torch(self.dof_limits_upper, device=self.device) self._key_body_ids = self._build_key_body_ids_tensor(env_ptr, handle) self._contact_body_ids = self._build_contact_body_ids_tensor(env_ptr, handle) if (self._pd_control): self._build_pd_action_offset_scale() return def _build_pd_action_offset_scale(self): num_joints = len(DOF_OFFSETS) - 1 lim_low = self.dof_limits_lower.cpu().numpy() lim_high = self.dof_limits_upper.cpu().numpy() for j in range(num_joints): dof_offset = DOF_OFFSETS[j] dof_size = DOF_OFFSETS[j + 1] - DOF_OFFSETS[j] if (dof_size == 3): lim_low[dof_offset:(dof_offset + dof_size)] = -np.pi lim_high[dof_offset:(dof_offset + dof_size)] = np.pi elif (dof_size == 1): curr_low = lim_low[dof_offset] curr_high = lim_high[dof_offset] curr_mid = 0.5 * (curr_high + curr_low) # extend the action range to be a bit beyond the joint limits so that the motors # don't lose their strength as they approach the joint limits curr_scale = 0.7 * (curr_high - curr_low) curr_low = curr_mid - curr_scale curr_high = curr_mid + curr_scale lim_low[dof_offset] = curr_low lim_high[dof_offset] = curr_high self._pd_action_offset = 0.5 * (lim_high + lim_low) self._pd_action_scale = 0.5 * (lim_high - lim_low) self._pd_action_offset = to_torch(self._pd_action_offset, device=self.device) self._pd_action_scale = to_torch(self._pd_action_scale, device=self.device) return def _compute_reward(self, actions): self.rew_buf[:] = compute_humanoid_reward(self.obs_buf) return def _compute_reset(self): self.reset_buf[:], self._terminate_buf[:] = compute_humanoid_reset(self.reset_buf, self.progress_buf, self._contact_forces, self._contact_body_ids, self._rigid_body_pos, self.max_episode_length, self._enable_early_termination, self._termination_height) return def _refresh_sim_tensors(self): self.gym.refresh_dof_state_tensor(self.sim) self.gym.refresh_actor_root_state_tensor(self.sim) self.gym.refresh_rigid_body_state_tensor(self.sim) self.gym.refresh_force_sensor_tensor(self.sim) self.gym.refresh_dof_force_tensor(self.sim) self.gym.refresh_net_contact_force_tensor(self.sim) return def _compute_observations(self, env_ids=None): obs = self._compute_humanoid_obs(env_ids) if (env_ids is None): self.obs_buf[:] = obs else: self.obs_buf[env_ids] = obs return def _compute_humanoid_obs(self, env_ids=None): if (env_ids is None): root_states = self._root_states dof_pos = self._dof_pos dof_vel = self._dof_vel key_body_pos = self._rigid_body_pos[:, self._key_body_ids, :] else: root_states = self._root_states[env_ids] dof_pos = self._dof_pos[env_ids] dof_vel = self._dof_vel[env_ids] key_body_pos = self._rigid_body_pos[env_ids][:, self._key_body_ids, :] obs = compute_humanoid_observations(root_states, dof_pos, dof_vel, key_body_pos, self._local_root_obs) return obs def _reset_actors(self, env_ids): self._dof_pos[env_ids] = self._initial_dof_pos[env_ids] self._dof_vel[env_ids] = self._initial_dof_vel[env_ids] env_ids_int32 = env_ids.to(dtype=torch.int32) self.gym.set_actor_root_state_tensor_indexed(self.sim, gymtorch.unwrap_tensor(self._initial_root_states), gymtorch.unwrap_tensor(env_ids_int32), len(env_ids_int32)) self.gym.set_dof_state_tensor_indexed(self.sim, gymtorch.unwrap_tensor(self._dof_state), gymtorch.unwrap_tensor(env_ids_int32), len(env_ids_int32)) self.progress_buf[env_ids] = 0 self.reset_buf[env_ids] = 0 self._terminate_buf[env_ids] = 0 return def pre_physics_step(self, actions): self.actions = actions.to(self.device).clone() if (self._pd_control): pd_tar = self._action_to_pd_targets(self.actions) pd_tar_tensor = gymtorch.unwrap_tensor(pd_tar) self.gym.set_dof_position_target_tensor(self.sim, pd_tar_tensor) else: forces = self.actions * self.motor_efforts.unsqueeze(0) * self.power_scale force_tensor = gymtorch.unwrap_tensor(forces) self.gym.set_dof_actuation_force_tensor(self.sim, force_tensor) return def post_physics_step(self): self.progress_buf += 1 self._refresh_sim_tensors() self._compute_observations() self._compute_reward(self.actions) self._compute_reset() self.extras["terminate"] = self._terminate_buf # debug viz if self.viewer and self.debug_viz: self._update_debug_viz() return def render(self): if self.viewer and self.camera_follow: self._update_camera() super().render() return def _build_key_body_ids_tensor(self, env_ptr, actor_handle): body_ids = [] for body_name in KEY_BODY_NAMES: body_id = self.gym.find_actor_rigid_body_handle(env_ptr, actor_handle, body_name) assert(body_id != -1) body_ids.append(body_id) body_ids = to_torch(body_ids, device=self.device, dtype=torch.long) return body_ids def _build_contact_body_ids_tensor(self, env_ptr, actor_handle): body_ids = [] for body_name in self._contact_bodies: body_id = self.gym.find_actor_rigid_body_handle(env_ptr, actor_handle, body_name) assert(body_id != -1) body_ids.append(body_id) body_ids = to_torch(body_ids, device=self.device, dtype=torch.long) return body_ids def _action_to_pd_targets(self, action): pd_tar = self._pd_action_offset + self._pd_action_scale * action return pd_tar def _init_camera(self): self.gym.refresh_actor_root_state_tensor(self.sim) self._cam_prev_char_pos = self._root_states[0, 0:3].cpu().numpy() cam_pos = gymapi.Vec3(self._cam_prev_char_pos[0], self._cam_prev_char_pos[1] - 3.0, 1.0) cam_target = gymapi.Vec3(self._cam_prev_char_pos[0], self._cam_prev_char_pos[1], 1.0) self.gym.viewer_camera_look_at(self.viewer, None, cam_pos, cam_target) return def _update_camera(self): self.gym.refresh_actor_root_state_tensor(self.sim) char_root_pos = self._root_states[0, 0:3].cpu().numpy() cam_trans = self.gym.get_viewer_camera_transform(self.viewer, None) cam_pos = np.array([cam_trans.p.x, cam_trans.p.y, cam_trans.p.z]) cam_delta = cam_pos - self._cam_prev_char_pos new_cam_target = gymapi.Vec3(char_root_pos[0], char_root_pos[1], 1.0) new_cam_pos = gymapi.Vec3(char_root_pos[0] + cam_delta[0], char_root_pos[1] + cam_delta[1], cam_pos[2]) self.gym.viewer_camera_look_at(self.viewer, None, new_cam_pos, new_cam_target) self._cam_prev_char_pos[:] = char_root_pos return def _update_debug_viz(self): self.gym.clear_lines(self.viewer) return ##################################################################### ###=========================jit functions=========================### ##################################################################### @torch.jit.script def dof_to_obs(pose): # type: (Tensor) -> Tensor #dof_obs_size = 64 #dof_offsets = [0, 3, 6, 9, 12, 13, 16, 19, 20, 23, 24, 27, 30, 31, 34] dof_obs_size = 52 dof_offsets = [0, 3, 6, 9, 10, 13, 14, 17, 18, 21, 24, 25, 28] num_joints = len(dof_offsets) - 1 dof_obs_shape = pose.shape[:-1] + (dof_obs_size,) dof_obs = torch.zeros(dof_obs_shape, device=pose.device) dof_obs_offset = 0 for j in range(num_joints): dof_offset = dof_offsets[j] dof_size = dof_offsets[j + 1] - dof_offsets[j] joint_pose = pose[:, dof_offset:(dof_offset + dof_size)] # assume this is a spherical joint if (dof_size == 3): joint_pose_q = exp_map_to_quat(joint_pose) joint_dof_obs = quat_to_tan_norm(joint_pose_q) dof_obs_size = 6 else: joint_dof_obs = joint_pose dof_obs_size = 1 dof_obs[:, dof_obs_offset:(dof_obs_offset + dof_obs_size)] = joint_dof_obs dof_obs_offset += dof_obs_size return dof_obs @torch.jit.script def compute_humanoid_observations(root_states, dof_pos, dof_vel, key_body_pos, local_root_obs): # type: (Tensor, Tensor, Tensor, Tensor, bool) -> Tensor root_pos = root_states[:, 0:3] root_rot = root_states[:, 3:7] root_vel = root_states[:, 7:10] root_ang_vel = root_states[:, 10:13] root_h = root_pos[:, 2:3] heading_rot = calc_heading_quat_inv(root_rot) if (local_root_obs): root_rot_obs = quat_mul(heading_rot, root_rot) else: root_rot_obs = root_rot root_rot_obs = quat_to_tan_norm(root_rot_obs) local_root_vel = my_quat_rotate(heading_rot, root_vel) local_root_ang_vel = my_quat_rotate(heading_rot, root_ang_vel) root_pos_expand = root_pos.unsqueeze(-2) local_key_body_pos = key_body_pos - root_pos_expand heading_rot_expand = heading_rot.unsqueeze(-2) heading_rot_expand = heading_rot_expand.repeat((1, local_key_body_pos.shape[1], 1)) flat_end_pos = local_key_body_pos.view(local_key_body_pos.shape[0] * local_key_body_pos.shape[1], local_key_body_pos.shape[2]) flat_heading_rot = heading_rot_expand.view(heading_rot_expand.shape[0] * heading_rot_expand.shape[1], heading_rot_expand.shape[2]) local_end_pos = my_quat_rotate(flat_heading_rot, flat_end_pos) flat_local_key_pos = local_end_pos.view(local_key_body_pos.shape[0], local_key_body_pos.shape[1] * local_key_body_pos.shape[2]) dof_obs = dof_to_obs(dof_pos) obs = torch.cat((root_h, root_rot_obs, local_root_vel, local_root_ang_vel, dof_obs, dof_vel, flat_local_key_pos), dim=-1) return obs @torch.jit.script def compute_humanoid_reward(obs_buf): # type: (Tensor) -> Tensor reward = torch.ones_like(obs_buf[:, 0]) return reward @torch.jit.script def compute_humanoid_reset(reset_buf, progress_buf, contact_buf, contact_body_ids, rigid_body_pos, max_episode_length, enable_early_termination, termination_height): # type: (Tensor, Tensor, Tensor, Tensor, Tensor, float, bool, float) -> Tuple[Tensor, Tensor] terminated = torch.zeros_like(reset_buf) if (enable_early_termination): masked_contact_buf = contact_buf.clone() masked_contact_buf[:, contact_body_ids, :] = 0 fall_contact = torch.any(masked_contact_buf > 0.1, dim=-1) fall_contact = torch.any(fall_contact, dim=-1) body_height = rigid_body_pos[..., 2] fall_height = body_height < termination_height fall_height[:, contact_body_ids] = False fall_height = torch.any(fall_height, dim=-1) has_fallen = torch.logical_and(fall_contact, fall_height) # first timestep can sometimes still have nonzero contact forces # so only check after first couple of steps has_fallen *= (progress_buf > 1) terminated = torch.where(has_fallen, torch.ones_like(reset_buf), terminated) reset = torch.where(progress_buf >= max_episode_length - 1, torch.ones_like(reset_buf), terminated) return reset, terminated
24,339
Python
42.309608
217
0.606147
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/utils_amp/amp_torch_utils.py
# Copyright (c) 2018-2023, 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 torch import numpy as np from isaacgymenvs.utils.torch_jit_utils import quat_mul, quat_conjugate, quat_from_angle_axis, \ to_torch, get_axis_params, torch_rand_float, tensor_clamp @torch.jit.script def my_quat_rotate(q, v): shape = q.shape q_w = q[:, -1] q_vec = q[:, :3] a = v * (2.0 * q_w ** 2 - 1.0).unsqueeze(-1) b = torch.cross(q_vec, v, dim=-1) * q_w.unsqueeze(-1) * 2.0 c = q_vec * \ torch.bmm(q_vec.view(shape[0], 1, 3), v.view( shape[0], 3, 1)).squeeze(-1) * 2.0 return a + b + c @torch.jit.script def quat_to_angle_axis(q): # type: (Tensor) -> Tuple[Tensor, Tensor] # computes axis-angle representation from quaternion q # q must be normalized min_theta = 1e-5 qx, qy, qz, qw = 0, 1, 2, 3 sin_theta = torch.sqrt(1 - q[..., qw] * q[..., qw]) angle = 2 * torch.acos(q[..., qw]) angle = normalize_angle(angle) sin_theta_expand = sin_theta.unsqueeze(-1) axis = q[..., qx:qw] / sin_theta_expand mask = sin_theta > min_theta default_axis = torch.zeros_like(axis) default_axis[..., -1] = 1 angle = torch.where(mask, angle, torch.zeros_like(angle)) mask_expand = mask.unsqueeze(-1) axis = torch.where(mask_expand, axis, default_axis) return angle, axis @torch.jit.script def angle_axis_to_exp_map(angle, axis): # type: (Tensor, Tensor) -> Tensor # compute exponential map from axis-angle angle_expand = angle.unsqueeze(-1) exp_map = angle_expand * axis return exp_map @torch.jit.script def quat_to_exp_map(q): # type: (Tensor) -> Tensor # compute exponential map from quaternion # q must be normalized angle, axis = quat_to_angle_axis(q) exp_map = angle_axis_to_exp_map(angle, axis) return exp_map @torch.jit.script def quat_to_tan_norm(q): # type: (Tensor) -> Tensor # represents a rotation using the tangent and normal vectors ref_tan = torch.zeros_like(q[..., 0:3]) ref_tan[..., 0] = 1 tan = my_quat_rotate(q, ref_tan) ref_norm = torch.zeros_like(q[..., 0:3]) ref_norm[..., -1] = 1 norm = my_quat_rotate(q, ref_norm) norm_tan = torch.cat([tan, norm], dim=len(tan.shape) - 1) return norm_tan @torch.jit.script def euler_xyz_to_exp_map(roll, pitch, yaw): # type: (Tensor, Tensor, Tensor) -> Tensor q = quat_from_euler_xyz(roll, pitch, yaw) exp_map = quat_to_exp_map(q) return exp_map @torch.jit.script def exp_map_to_angle_axis(exp_map): min_theta = 1e-5 angle = torch.norm(exp_map, dim=-1) angle_exp = torch.unsqueeze(angle, dim=-1) axis = exp_map / angle_exp angle = normalize_angle(angle) default_axis = torch.zeros_like(exp_map) default_axis[..., -1] = 1 mask = angle > min_theta angle = torch.where(mask, angle, torch.zeros_like(angle)) mask_expand = mask.unsqueeze(-1) axis = torch.where(mask_expand, axis, default_axis) return angle, axis @torch.jit.script def exp_map_to_quat(exp_map): angle, axis = exp_map_to_angle_axis(exp_map) q = quat_from_angle_axis(angle, axis) return q @torch.jit.script def slerp(q0, q1, t): # type: (Tensor, Tensor, Tensor) -> Tensor qx, qy, qz, qw = 0, 1, 2, 3 cos_half_theta = q0[..., qw] * q1[..., qw] \ + q0[..., qx] * q1[..., qx] \ + q0[..., qy] * q1[..., qy] \ + q0[..., qz] * q1[..., qz] neg_mask = cos_half_theta < 0 q1 = q1.clone() q1[neg_mask] = -q1[neg_mask] cos_half_theta = torch.abs(cos_half_theta) cos_half_theta = torch.unsqueeze(cos_half_theta, dim=-1) half_theta = torch.acos(cos_half_theta); sin_half_theta = torch.sqrt(1.0 - cos_half_theta * cos_half_theta); ratioA = torch.sin((1 - t) * half_theta) / sin_half_theta; ratioB = torch.sin(t * half_theta) / sin_half_theta; new_q_x = ratioA * q0[..., qx:qx+1] + ratioB * q1[..., qx:qx+1] new_q_y = ratioA * q0[..., qy:qy+1] + ratioB * q1[..., qy:qy+1] new_q_z = ratioA * q0[..., qz:qz+1] + ratioB * q1[..., qz:qz+1] new_q_w = ratioA * q0[..., qw:qw+1] + ratioB * q1[..., qw:qw+1] cat_dim = len(new_q_w.shape) - 1 new_q = torch.cat([new_q_x, new_q_y, new_q_z, new_q_w], dim=cat_dim) new_q = torch.where(torch.abs(sin_half_theta) < 0.001, 0.5 * q0 + 0.5 * q1, new_q) new_q = torch.where(torch.abs(cos_half_theta) >= 1, q0, new_q) return new_q @torch.jit.script def calc_heading(q): # type: (Tensor) -> Tensor # calculate heading direction from quaternion # the heading is the direction on the xy plane # q must be normalized ref_dir = torch.zeros_like(q[..., 0:3]) ref_dir[..., 0] = 1 rot_dir = my_quat_rotate(q, ref_dir) heading = torch.atan2(rot_dir[..., 1], rot_dir[..., 0]) return heading @torch.jit.script def calc_heading_quat(q): # type: (Tensor) -> Tensor # calculate heading rotation from quaternion # the heading is the direction on the xy plane # q must be normalized heading = calc_heading(q) axis = torch.zeros_like(q[..., 0:3]) axis[..., 2] = 1 heading_q = quat_from_angle_axis(heading, axis) return heading_q @torch.jit.script def calc_heading_quat_inv(q): # type: (Tensor) -> Tensor # calculate heading rotation from quaternion # the heading is the direction on the xy plane # q must be normalized heading = calc_heading(q) axis = torch.zeros_like(q[..., 0:3]) axis[..., 2] = 1 heading_q = quat_from_angle_axis(-heading, axis) return heading_q
7,111
Python
33.192308
96
0.63451
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/utils_amp/data_tree.py
# Copyright (c) 2018-2023, 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 json import copy import os from collections import OrderedDict class data_tree(object): def __init__(self, name): self._name = name self._children, self._children_names, self._picked, self._depleted = \ [], [], [], [] self._data, self._length = [], [] self._total_length, self._num_leaf, self._is_leaf = 0, 0, 0 self._assigned_prob = 0.0 def add_node(self, dict_hierachy, mocap_data): # data_hierachy -> 'behavior' 'direction' 'type' 'style' # behavior, direction, mocap_type, style = mocap_data[2:] self._num_leaf += 1 if len(dict_hierachy) == 0: # leaf node self._data.append(mocap_data[0]) self._length.append(mocap_data[1]) self._picked.append(0) self._depleted.append(0) self._is_leaf = 1 else: children_name = dict_hierachy[0].replace('\n', '') if children_name not in self._children_names: self._children_names.append(children_name) self._children.append(data_tree(children_name)) self._picked.append(0) self._depleted.append(0) # add the data index = self._children_names.index(children_name) self._children[index].add_node(dict_hierachy[1:], mocap_data) def summarize_length(self): if self._is_leaf: self._total_length = np.sum(self._length) else: self._total_length = 0 for i_child in self._children: self._total_length += i_child.summarize_length() return self._total_length def to_dict(self, verbose=False): if self._is_leaf: self._data_dict = copy.deepcopy(self._data) else: self._data_dict = OrderedDict() for i_child in self._children: self._data_dict[i_child.name] = i_child.to_dict(verbose) if verbose: if self._is_leaf: verbose_data_dict = [] for ii, i_key in enumerate(self._data_dict): new_key = i_key + ' (picked {} / {})'.format( str(self._picked[ii]), self._length[ii] ) verbose_data_dict.append(new_key) else: verbose_data_dict = OrderedDict() for ii, i_key in enumerate(self._data_dict): new_key = i_key + ' (picked {} / {})'.format( str(self._picked[ii]), self._children[ii].total_length ) verbose_data_dict[new_key] = self._data_dict[i_key] self._data_dict = verbose_data_dict return self._data_dict @property def name(self): return self._name @property def picked(self): return self._picked @property def total_length(self): return self._total_length def water_floating_algorithm(self): # find the sub class with the minimum picked assert not np.all(self._depleted) for ii in np.where(np.array(self._children_names) == 'mix')[0]: self._depleted[ii] = np.inf chosen_child = np.argmin(np.array(self._picked) + np.array(self._depleted)) if self._is_leaf: self._picked[chosen_child] = self._length[chosen_child] self._depleted[chosen_child] = np.inf chosen_data = self._data[chosen_child] data_info = {'name': [self._name], 'length': self._length[chosen_child], 'all_depleted': np.all(self._depleted)} else: chosen_data, data_info = \ self._children[chosen_child].water_floating_algorithm() self._picked[chosen_child] += data_info['length'] data_info['name'].insert(0, self._name) if data_info['all_depleted']: self._depleted[chosen_child] = np.inf data_info['all_depleted'] = np.all(self._depleted) return chosen_data, data_info def assign_probability(self, total_prob): # find the sub class with the minimum picked leaves, probs = [], [] if self._is_leaf: self._assigned_prob = total_prob leaves.extend(self._data) per_traj_prob = total_prob / float(len(self._data)) probs.extend([per_traj_prob] * len(self._data)) else: per_child_prob = total_prob / float(len(self._children)) for i_child in self._children: i_leave, i_prob = i_child.assign_probability(per_child_prob) leaves.extend(i_leave) probs.extend(i_prob) return leaves, probs def parse_dataset(env, args): """ @brief: get the training set and test set """ TRAIN_PERCENTAGE = args.parse_dataset_train info, motion = env.motion_info, env.motion lengths = env.get_all_motion_length() train_size = np.sum(motion.get_all_motion_length()) * TRAIN_PERCENTAGE data_structure = data_tree('root') shuffle_id = list(range(len(info['mocap_data_list']))) np.random.shuffle(shuffle_id) info['mocap_data_list'] = [info['mocap_data_list'][ii] for ii in shuffle_id] for mocap_data, length in zip(info['mocap_data_list'], lengths[shuffle_id]): node_data = [mocap_data[0]] + [length] data_structure.add_node(mocap_data[2:], node_data) raw_data_dict = data_structure.to_dict() print(json.dumps(raw_data_dict, indent=4)) total_length = 0 chosen_data = [] while True: i_data, i_info = data_structure.water_floating_algorithm() print('Current length:', total_length, i_data, i_info) total_length += i_info['length'] chosen_data.append(i_data) if total_length > train_size: break data_structure.summarize_length() data_dict = data_structure.to_dict(verbose=True) print(json.dumps(data_dict, indent=4)) # save the training and test sets train_data, test_data = [], [] for i_data in info['mocap_data_list']: if i_data[0] in chosen_data: train_data.append(i_data[1:]) else: test_data.append(i_data[1:]) train_tsv_name = args.mocap_list_file.split('.')[0] + '_' + \ str(int(args.parse_dataset_train * 100)) + '_train' + '.tsv' test_tsv_name = train_tsv_name.replace('train', 'test') info_name = test_tsv_name.replace('test', 'info').replace('.tsv', '.json') save_tsv_files(env._base_dir, train_tsv_name, train_data) save_tsv_files(env._base_dir, test_tsv_name, test_data) info_file = open(os.path.join(env._base_dir, 'experiments', 'mocap_files', info_name), 'w') json.dump(data_dict, info_file, indent=4) def save_tsv_files(base_dir, name, data_dict): file_name = os.path.join(base_dir, 'experiments', 'mocap_files', name) recorder = open(file_name, "w") for i_data in data_dict: line = '{}\t{}\t{}\t{}\t{}\n'.format(*i_data) recorder.write(line) recorder.close()
8,773
Python
38.522522
80
0.596489
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/utils_amp/gym_util.py
# Copyright (c) 2018-2023, 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 . import logger from isaacgym import gymapi import numpy as np import torch from isaacgymenvs.utils.torch_jit_utils import scale, unscale, quat_mul, quat_conjugate, quat_from_angle_axis, \ to_torch, get_axis_params, torch_rand_float, tensor_clamp from isaacgym import gymtorch def setup_gym_viewer(config): gym = initialize_gym(config) sim, viewer = configure_gym(gym, config) return gym, sim, viewer def initialize_gym(config): gym = gymapi.acquire_gym() if not gym.initialize(): logger.warn("*** Failed to initialize gym") quit() return gym def configure_gym(gym, config): engine, render = config['engine'], config['render'] # physics engine settings if(engine == 'FLEX'): sim_engine = gymapi.SIM_FLEX elif(engine == 'PHYSX'): sim_engine = gymapi.SIM_PHYSX else: logger.warn("Unknown physics engine. defaulting to FLEX") sim_engine = gymapi.SIM_FLEX # gym viewer if render: # create viewer sim = gym.create_sim(0, 0, sim_type=sim_engine) viewer = gym.create_viewer( sim, int(gymapi.DEFAULT_VIEWER_WIDTH / 1.25), int(gymapi.DEFAULT_VIEWER_HEIGHT / 1.25) ) if viewer is None: logger.warn("*** Failed to create viewer") quit() # enable left mouse click or space bar for throwing projectiles if config['add_projectiles']: gym.subscribe_viewer_mouse_event(viewer, gymapi.MOUSE_LEFT_BUTTON, "shoot") gym.subscribe_viewer_keyboard_event(viewer, gymapi.KEY_SPACE, "shoot") else: sim = gym.create_sim(0, -1) viewer = None # simulation params scene_config = config['env']['scene'] sim_params = gymapi.SimParams() sim_params.solver_type = scene_config['SolverType'] sim_params.num_outer_iterations = scene_config['NumIterations'] sim_params.num_inner_iterations = scene_config['NumInnerIterations'] sim_params.relaxation = scene_config.get('Relaxation', 0.75) sim_params.warm_start = scene_config.get('WarmStart', 0.25) sim_params.geometric_stiffness = scene_config.get('GeometricStiffness', 1.0) sim_params.shape_collision_margin = 0.01 sim_params.gravity = gymapi.Vec3(0.0, -9.8, 0.0) gym.set_sim_params(sim, sim_params) return sim, viewer def parse_states_from_reference_states(reference_states, progress): # parse reference states from DeepMimicState global_quats_ref = torch.tensor( reference_states._global_rotation[(progress,)].numpy(), dtype=torch.double ).cuda() ts_ref = torch.tensor( reference_states._translation[(progress,)].numpy(), dtype=torch.double ).cuda() vels_ref = torch.tensor( reference_states._velocity[(progress,)].numpy(), dtype=torch.double ).cuda() avels_ref = torch.tensor( reference_states._angular_velocity[(progress,)].numpy(), dtype=torch.double ).cuda() return global_quats_ref, ts_ref, vels_ref, avels_ref def parse_states_from_reference_states_with_motion_id(precomputed_state, progress, motion_id): assert len(progress) == len(motion_id) # get the global id global_id = precomputed_state['motion_offset'][motion_id] + progress global_id = np.minimum(global_id, precomputed_state['global_quats_ref'].shape[0] - 1) # parse reference states from DeepMimicState global_quats_ref = precomputed_state['global_quats_ref'][global_id] ts_ref = precomputed_state['ts_ref'][global_id] vels_ref = precomputed_state['vels_ref'][global_id] avels_ref = precomputed_state['avels_ref'][global_id] return global_quats_ref, ts_ref, vels_ref, avels_ref def parse_dof_state_with_motion_id(precomputed_state, dof_state, progress, motion_id): assert len(progress) == len(motion_id) # get the global id global_id = precomputed_state['motion_offset'][motion_id] + progress # NOTE: it should never reach the dof_state.shape, cause the episode is # terminated 2 steps before global_id = np.minimum(global_id, dof_state.shape[0] - 1) # parse reference states from DeepMimicState return dof_state[global_id] def get_flatten_ids(precomputed_state): motion_offsets = precomputed_state['motion_offset'] init_state_id, init_motion_id, global_id = [], [], [] for i_motion in range(len(motion_offsets) - 1): i_length = motion_offsets[i_motion + 1] - motion_offsets[i_motion] init_state_id.extend(range(i_length)) init_motion_id.extend([i_motion] * i_length) if len(global_id) == 0: global_id.extend(range(0, i_length)) else: global_id.extend(range(global_id[-1] + 1, global_id[-1] + i_length + 1)) return np.array(init_state_id), np.array(init_motion_id), \ np.array(global_id) def parse_states_from_reference_states_with_global_id(precomputed_state, global_id): # get the global id global_id = global_id % precomputed_state['global_quats_ref'].shape[0] # parse reference states from DeepMimicState global_quats_ref = precomputed_state['global_quats_ref'][global_id] ts_ref = precomputed_state['ts_ref'][global_id] vels_ref = precomputed_state['vels_ref'][global_id] avels_ref = precomputed_state['avels_ref'][global_id] return global_quats_ref, ts_ref, vels_ref, avels_ref def get_robot_states_from_torch_tensor(config, ts, global_quats, vels, avels, init_rot, progress, motion_length=-1, actions=None, relative_rot=None, motion_id=None, num_motion=None, motion_onehot_matrix=None): info = {} # the observation with quaternion-based representation torso_height = ts[..., 0, 1].cpu().numpy() gttrny, gqny, vny, avny, info['root_yaw_inv'] = \ quaternion_math.compute_observation_return_info(global_quats, ts, vels, avels) joint_obs = np.concatenate([gttrny.cpu().numpy(), gqny.cpu().numpy(), vny.cpu().numpy(), avny.cpu().numpy()], axis=-1) joint_obs = joint_obs.reshape(joint_obs.shape[0], -1) num_envs = joint_obs.shape[0] obs = np.concatenate([torso_height[:, np.newaxis], joint_obs], -1) # the previous action if config['env_action_ob']: obs = np.concatenate([obs, actions], axis=-1) # the orientation if config['env_orientation_ob']: if relative_rot is not None: obs = np.concatenate([obs, relative_rot], axis=-1) else: curr_rot = global_quats[np.arange(num_envs)][:, 0] curr_rot = curr_rot.reshape(num_envs, -1, 4) relative_rot = quaternion_math.compute_orientation_drift( init_rot, curr_rot ).cpu().numpy() obs = np.concatenate([obs, relative_rot], axis=-1) if config['env_frame_ob']: if type(motion_length) == np.ndarray: motion_length = motion_length.astype(float) progress_ob = np.expand_dims(progress.astype(float) / motion_length, axis=-1) else: progress_ob = np.expand_dims(progress.astype(float) / float(motion_length), axis=-1) obs = np.concatenate([obs, progress_ob], axis=-1) if config['env_motion_ob'] and not config['env_motion_ob_onehot']: motion_id_ob = np.expand_dims(motion_id.astype(float) / float(num_motion), axis=-1) obs = np.concatenate([obs, motion_id_ob], axis=-1) elif config['env_motion_ob'] and config['env_motion_ob_onehot']: motion_id_ob = motion_onehot_matrix[motion_id] obs = np.concatenate([obs, motion_id_ob], axis=-1) return obs, info def get_xyzoffset(start_ts, end_ts, root_yaw_inv): xyoffset = (end_ts - start_ts)[:, [0], :].reshape(1, -1, 1, 3) ryinv = root_yaw_inv.reshape(1, -1, 1, 4) calibrated_xyz_offset = quaternion_math.quat_apply(ryinv, xyoffset)[0, :, 0, :] return calibrated_xyz_offset
9,996
Python
39.971311
112
0.632753
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/utils_amp/__init__.py
# Copyright (c) 2018-2023, 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.
1,558
Python
54.678569
80
0.784339
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/utils_amp/motion_lib.py
# Copyright (c) 2018-2023, 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 os import yaml from ..poselib.poselib.skeleton.skeleton3d import SkeletonMotion from ..poselib.poselib.core.rotation3d import * from isaacgymenvs.utils.torch_jit_utils import to_torch, slerp, quat_to_exp_map, quat_to_angle_axis, normalize_angle from isaacgymenvs.tasks.amp.humanoid_amp_base import DOF_BODY_IDS, DOF_OFFSETS class MotionLib(): def __init__(self, motion_file, num_dofs, key_body_ids, device): self._num_dof = num_dofs self._key_body_ids = key_body_ids self._device = device self._load_motions(motion_file) self.motion_ids = torch.arange(len(self._motions), dtype=torch.long, device=self._device) return def num_motions(self): return len(self._motions) def get_total_length(self): return sum(self._motion_lengths) def get_motion(self, motion_id): return self._motions[motion_id] def sample_motions(self, n): m = self.num_motions() motion_ids = np.random.choice(m, size=n, replace=True, p=self._motion_weights) return motion_ids def sample_time(self, motion_ids, truncate_time=None): n = len(motion_ids) phase = np.random.uniform(low=0.0, high=1.0, size=motion_ids.shape) motion_len = self._motion_lengths[motion_ids] if (truncate_time is not None): assert(truncate_time >= 0.0) motion_len -= truncate_time motion_time = phase * motion_len return motion_time def get_motion_length(self, motion_ids): return self._motion_lengths[motion_ids] def get_motion_state(self, motion_ids, motion_times): n = len(motion_ids) num_bodies = self._get_num_bodies() num_key_bodies = self._key_body_ids.shape[0] root_pos0 = np.empty([n, 3]) root_pos1 = np.empty([n, 3]) root_rot = np.empty([n, 4]) root_rot0 = np.empty([n, 4]) root_rot1 = np.empty([n, 4]) root_vel = np.empty([n, 3]) root_ang_vel = np.empty([n, 3]) local_rot0 = np.empty([n, num_bodies, 4]) local_rot1 = np.empty([n, num_bodies, 4]) dof_vel = np.empty([n, self._num_dof]) key_pos0 = np.empty([n, num_key_bodies, 3]) key_pos1 = np.empty([n, num_key_bodies, 3]) motion_len = self._motion_lengths[motion_ids] num_frames = self._motion_num_frames[motion_ids] dt = self._motion_dt[motion_ids] frame_idx0, frame_idx1, blend = self._calc_frame_blend(motion_times, motion_len, num_frames, dt) unique_ids = np.unique(motion_ids) for uid in unique_ids: ids = np.where(motion_ids == uid) curr_motion = self._motions[uid] root_pos0[ids, :] = curr_motion.global_translation[frame_idx0[ids], 0].numpy() root_pos1[ids, :] = curr_motion.global_translation[frame_idx1[ids], 0].numpy() root_rot0[ids, :] = curr_motion.global_rotation[frame_idx0[ids], 0].numpy() root_rot1[ids, :] = curr_motion.global_rotation[frame_idx1[ids], 0].numpy() local_rot0[ids, :, :]= curr_motion.local_rotation[frame_idx0[ids]].numpy() local_rot1[ids, :, :] = curr_motion.local_rotation[frame_idx1[ids]].numpy() root_vel[ids, :] = curr_motion.global_root_velocity[frame_idx0[ids]].numpy() root_ang_vel[ids, :] = curr_motion.global_root_angular_velocity[frame_idx0[ids]].numpy() key_pos0[ids, :, :] = curr_motion.global_translation[frame_idx0[ids][:, np.newaxis], self._key_body_ids[np.newaxis, :]].numpy() key_pos1[ids, :, :] = curr_motion.global_translation[frame_idx1[ids][:, np.newaxis], self._key_body_ids[np.newaxis, :]].numpy() dof_vel[ids, :] = curr_motion.dof_vels[frame_idx0[ids]] blend = to_torch(np.expand_dims(blend, axis=-1), device=self._device) root_pos0 = to_torch(root_pos0, device=self._device) root_pos1 = to_torch(root_pos1, device=self._device) root_rot0 = to_torch(root_rot0, device=self._device) root_rot1 = to_torch(root_rot1, device=self._device) root_vel = to_torch(root_vel, device=self._device) root_ang_vel = to_torch(root_ang_vel, device=self._device) local_rot0 = to_torch(local_rot0, device=self._device) local_rot1 = to_torch(local_rot1, device=self._device) key_pos0 = to_torch(key_pos0, device=self._device) key_pos1 = to_torch(key_pos1, device=self._device) dof_vel = to_torch(dof_vel, device=self._device) root_pos = (1.0 - blend) * root_pos0 + blend * root_pos1 root_rot = slerp(root_rot0, root_rot1, blend) blend_exp = blend.unsqueeze(-1) key_pos = (1.0 - blend_exp) * key_pos0 + blend_exp * key_pos1 local_rot = slerp(local_rot0, local_rot1, torch.unsqueeze(blend, axis=-1)) dof_pos = self._local_rotation_to_dof(local_rot) return root_pos, root_rot, dof_pos, root_vel, root_ang_vel, dof_vel, key_pos def _load_motions(self, motion_file): self._motions = [] self._motion_lengths = [] self._motion_weights = [] self._motion_fps = [] self._motion_dt = [] self._motion_num_frames = [] self._motion_files = [] total_len = 0.0 motion_files, motion_weights = self._fetch_motion_files(motion_file) num_motion_files = len(motion_files) for f in range(num_motion_files): curr_file = motion_files[f] print("Loading {:d}/{:d} motion files: {:s}".format(f + 1, num_motion_files, curr_file)) curr_motion = SkeletonMotion.from_file(curr_file) motion_fps = curr_motion.fps curr_dt = 1.0 / motion_fps num_frames = curr_motion.tensor.shape[0] curr_len = 1.0 / motion_fps * (num_frames - 1) self._motion_fps.append(motion_fps) self._motion_dt.append(curr_dt) self._motion_num_frames.append(num_frames) curr_dof_vels = self._compute_motion_dof_vels(curr_motion) curr_motion.dof_vels = curr_dof_vels self._motions.append(curr_motion) self._motion_lengths.append(curr_len) curr_weight = motion_weights[f] self._motion_weights.append(curr_weight) self._motion_files.append(curr_file) self._motion_lengths = np.array(self._motion_lengths) self._motion_weights = np.array(self._motion_weights) self._motion_weights /= np.sum(self._motion_weights) self._motion_fps = np.array(self._motion_fps) self._motion_dt = np.array(self._motion_dt) self._motion_num_frames = np.array(self._motion_num_frames) num_motions = self.num_motions() total_len = self.get_total_length() print("Loaded {:d} motions with a total length of {:.3f}s.".format(num_motions, total_len)) return def _fetch_motion_files(self, motion_file): ext = os.path.splitext(motion_file)[1] if (ext == ".yaml"): dir_name = os.path.dirname(motion_file) motion_files = [] motion_weights = [] with open(os.path.join(os.getcwd(), motion_file), 'r') as f: motion_config = yaml.load(f, Loader=yaml.SafeLoader) motion_list = motion_config['motions'] for motion_entry in motion_list: curr_file = motion_entry['file'] curr_weight = motion_entry['weight'] assert(curr_weight >= 0) curr_file = os.path.join(dir_name, curr_file) motion_weights.append(curr_weight) motion_files.append(curr_file) else: motion_files = [motion_file] motion_weights = [1.0] return motion_files, motion_weights def _calc_frame_blend(self, time, len, num_frames, dt): phase = time / len phase = np.clip(phase, 0.0, 1.0) frame_idx0 = (phase * (num_frames - 1)).astype(int) frame_idx1 = np.minimum(frame_idx0 + 1, num_frames - 1) blend = (time - frame_idx0 * dt) / dt return frame_idx0, frame_idx1, blend def _get_num_bodies(self): motion = self.get_motion(0) num_bodies = motion.num_joints return num_bodies def _compute_motion_dof_vels(self, motion): num_frames = motion.tensor.shape[0] dt = 1.0 / motion.fps dof_vels = [] for f in range(num_frames - 1): local_rot0 = motion.local_rotation[f] local_rot1 = motion.local_rotation[f + 1] frame_dof_vel = self._local_rotation_to_dof_vel(local_rot0, local_rot1, dt) frame_dof_vel = frame_dof_vel dof_vels.append(frame_dof_vel) dof_vels.append(dof_vels[-1]) dof_vels = np.array(dof_vels) return dof_vels def _local_rotation_to_dof(self, local_rot): body_ids = DOF_BODY_IDS dof_offsets = DOF_OFFSETS n = local_rot.shape[0] dof_pos = torch.zeros((n, self._num_dof), dtype=torch.float, device=self._device) for j in range(len(body_ids)): body_id = body_ids[j] joint_offset = dof_offsets[j] joint_size = dof_offsets[j + 1] - joint_offset if (joint_size == 3): joint_q = local_rot[:, body_id] joint_exp_map = quat_to_exp_map(joint_q) dof_pos[:, joint_offset:(joint_offset + joint_size)] = joint_exp_map elif (joint_size == 1): joint_q = local_rot[:, body_id] joint_theta, joint_axis = quat_to_angle_axis(joint_q) joint_theta = joint_theta * joint_axis[..., 1] # assume joint is always along y axis joint_theta = normalize_angle(joint_theta) dof_pos[:, joint_offset] = joint_theta else: print("Unsupported joint type") assert(False) return dof_pos def _local_rotation_to_dof_vel(self, local_rot0, local_rot1, dt): body_ids = DOF_BODY_IDS dof_offsets = DOF_OFFSETS dof_vel = np.zeros([self._num_dof]) diff_quat_data = quat_mul_norm(quat_inverse(local_rot0), local_rot1) diff_angle, diff_axis = quat_angle_axis(diff_quat_data) local_vel = diff_axis * diff_angle.unsqueeze(-1) / dt local_vel = local_vel.numpy() for j in range(len(body_ids)): body_id = body_ids[j] joint_offset = dof_offsets[j] joint_size = dof_offsets[j + 1] - joint_offset if (joint_size == 3): joint_vel = local_vel[body_id] dof_vel[joint_offset:(joint_offset + joint_size)] = joint_vel elif (joint_size == 1): assert(joint_size == 1) joint_vel = local_vel[body_id] dof_vel[joint_offset] = joint_vel[1] # assume joint is always along y axis else: print("Unsupported joint type") assert(False) return dof_vel
12,738
Python
38.317901
139
0.600879
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/utils_amp/logger.py
# ----------------------------------------------------------------------------- # @brief: # The logger here will be called all across the project. It is inspired # by Yuxin Wu ([email protected]) # # @author: # Tingwu Wang, 2017, Feb, 20th # ----------------------------------------------------------------------------- import logging import sys import os import datetime __all__ = ['set_file_handler'] # the actual worker is the '_logger' color2id = {"grey": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37} def colored(text, color): return f"\033[{color2id[color]}m{text}\033[0m" class _MyFormatter(logging.Formatter): ''' @brief: a class to make sure the format could be used ''' def format(self, record): date = colored('[%(asctime)s @%(filename)s:%(lineno)d]', 'green') msg = '%(message)s' if record.levelno == logging.WARNING: fmt = date + ' ' + \ colored('WRN', 'red', attrs=[]) + ' ' + msg elif record.levelno == logging.ERROR or \ record.levelno == logging.CRITICAL: fmt = date + ' ' + \ colored('ERR', 'red', attrs=['underline']) + ' ' + msg else: fmt = date + ' ' + msg if hasattr(self, '_style'): # Python3 compatibility self._style._fmt = fmt self._fmt = fmt return super(self.__class__, self).format(record) _logger = logging.getLogger('joint_embedding') _logger.propagate = False _logger.setLevel(logging.INFO) # set the console output handler con_handler = logging.StreamHandler(sys.stdout) con_handler.setFormatter(_MyFormatter(datefmt='%m%d %H:%M:%S')) _logger.addHandler(con_handler) class GLOBAL_PATH(object): def __init__(self, path=None): if path is None: path = os.getcwd() self.path = path def _set_path(self, path): self.path = path def _get_path(self): return self.path PATH = GLOBAL_PATH() def set_file_handler(path=None, prefix='', time_str=''): # set the file output handler if time_str == '': file_name = prefix + \ datetime.datetime.now().strftime("%A_%d_%B_%Y_%I:%M%p") + '.log' else: file_name = prefix + time_str + '.log' if path is None: mod = sys.modules['__main__'] path = os.path.join(os.path.abspath(mod.__file__), '..', '..', 'log') else: path = os.path.join(path, 'log') path = os.path.abspath(path) path = os.path.join(path, file_name) if not os.path.exists(path): os.makedirs(path) PATH._set_path(path) path = os.path.join(path, file_name) from tensorboard_logger import configure configure(path) file_handler = logging.FileHandler( filename=os.path.join(path, 'logger'), encoding='utf-8', mode='w') file_handler.setFormatter(_MyFormatter(datefmt='%m%d %H:%M:%S')) _logger.addHandler(file_handler) _logger.info('Log file set to {}'.format(path)) return path def _get_path(): return PATH._get_path() _LOGGING_METHOD = ['info', 'warning', 'error', 'critical', 'warn', 'exception', 'debug'] # export logger functions for func in _LOGGING_METHOD: locals()[func] = getattr(_logger, func)
3,351
Python
26.47541
113
0.549388
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/mjcf_importer.py
# Copyright (c) 2018-2023, 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 poselib.skeleton.skeleton3d import SkeletonTree, SkeletonState from poselib.visualization.common import plot_skeleton_state # load in XML mjcf file and save zero rotation pose in npy format xml_path = "../../../../assets/mjcf/nv_humanoid.xml" skeleton = SkeletonTree.from_mjcf(xml_path) zero_pose = SkeletonState.zero_pose(skeleton) zero_pose.to_file("data/nv_humanoid.npy") # visualize zero rotation pose plot_skeleton_state(zero_pose)
2,003
Python
49.099999
80
0.783325
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/generate_amp_humanoid_tpose.py
# Copyright (c) 2018-2023, 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 torch from poselib.core.rotation3d import * from poselib.skeleton.skeleton3d import SkeletonTree, SkeletonState from poselib.visualization.common import plot_skeleton_state """ This scripts imports a MJCF XML file and converts the skeleton into a SkeletonTree format. It then generates a zero rotation pose, and adjusts the pose into a T-Pose. """ # import MJCF file xml_path = "../../../../assets/mjcf/amp_humanoid.xml" skeleton = SkeletonTree.from_mjcf(xml_path) # generate zero rotation pose zero_pose = SkeletonState.zero_pose(skeleton) # adjust pose into a T Pose local_rotation = zero_pose.local_rotation local_rotation[skeleton.index("left_upper_arm")] = quat_mul( quat_from_angle_axis(angle=torch.tensor([90.0]), axis=torch.tensor([1.0, 0.0, 0.0]), degree=True), local_rotation[skeleton.index("left_upper_arm")] ) local_rotation[skeleton.index("right_upper_arm")] = quat_mul( quat_from_angle_axis(angle=torch.tensor([-90.0]), axis=torch.tensor([1.0, 0.0, 0.0]), degree=True), local_rotation[skeleton.index("right_upper_arm")] ) translation = zero_pose.root_translation translation += torch.tensor([0, 0, 0.9]) # save and visualize T-pose zero_pose.to_file("data/amp_humanoid_tpose.npy") plot_skeleton_state(zero_pose)
2,816
Python
43.714285
104
0.763849
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/fbx_importer.py
# Copyright (c) 2018-2023, 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 json from poselib.skeleton.skeleton3d import SkeletonTree, SkeletonState, SkeletonMotion from poselib.visualization.common import plot_skeleton_state, plot_skeleton_motion_interactive # source fbx file path fbx_file = "data/01_01_cmu.fbx" # import fbx file - make sure to provide a valid joint name for root_joint motion = SkeletonMotion.from_fbx( fbx_file_path=fbx_file, root_joint="Hips", fps=60 ) # save motion in npy format motion.to_file("data/01_01_cmu.npy") # visualize motion plot_skeleton_motion_interactive(motion)
2,119
Python
40.568627
94
0.779141
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/README.md
# poselib `poselib` is a library for loading, manipulating, and retargeting skeleton poses and motions. It is separated into three modules: `poselib.core` for basic data loading and tensor operations, `poselib.skeleton` for higher-level skeleton operations, and `poselib.visualization` for displaying skeleton poses. This library is built on top of the PyTorch framework and requires data to be in PyTorch tensors. ## poselib.core - `poselib.core.rotation3d`: A set of Torch JIT functions for computing quaternions, transforms, and rotation/transformation matrices. - `quat_*` manipulate and create quaternions in [x, y, z, w] format (where w is the real component). - `transform_*` handle 7D transforms in [quat, pos] format. - `rot_matrix_*` handle 3x3 rotation matrices. - `euclidean_*` handle 4x4 Euclidean transformation matrices. - `poselib.core.tensor_utils`: Provides loading and saving functions for PyTorch tensors. ## poselib.skeleton - `poselib.skeleton.skeleton3d`: Utilities for loading and manipulating skeleton poses, and retargeting poses to different skeletons. - `SkeletonTree` is a class that stores a skeleton as a tree structure. This describes the skeleton topology and joints. - `SkeletonState` describes the static state of a skeleton, and provides both global and local joint angles. - `SkeletonMotion` describes a time-series of skeleton states and provides utilities for computing joint velocities. ## poselib.visualization - `poselib.visualization.common`: Functions used for visualizing skeletons interactively in `matplotlib`. - In SkeletonState visualization, use key `q` to quit window. - In interactive SkeletonMotion visualization, you can use the following key commands: - `w` - loop animation - `x` - play/pause animation - `z` - previous frame - `c` - next frame - `n` - quit window ## Key Features Poselib provides several key features for working with animation data. We list some of the frequently used ones here, and provide instructions and examples on their usage. ### Importing from FBX Poselib supports importing skeletal animation sequences from .fbx format into a SkeletonMotion representation. To use this functionality, you will need to first set up the Python FBX SDK on your machine using the following instructions. This package is necessary to read data from fbx files, which is a proprietary file format owned by Autodesk. The latest FBX SDK tested was FBX SDK 2020.2.1 for Python 3.7, which can be found on the Autodesk website: https://www.autodesk.com/developer-network/platform-technologies/fbx-sdk-2020-2-1. Follow the instructions at https://help.autodesk.com/view/FBX/2020/ENU/?guid=FBX_Developer_Help_scripting_with_python_fbx_installing_python_fbx_html for download, install, and copy/paste instructions for the FBX Python SDK. This repo provides an example script `fbx_importer.py` that shows usage of importing a .fbx file. Note that `SkeletonMotion.from_fbx()` takes in an optional parameter `root_joint`, which can be used to specify a joint in the skeleton tree as the root joint. If `root_joint` is not specified, we will default to using the first node in the FBX scene that contains animation data. ### Importing from MJCF MJCF is a robotics file format supported by Isaac Gym. For convenience, we provide an API for importing MJCF assets into SkeletonTree definitions to represent the skeleton topology. An example script `mjcf_importer.py` is provided to show usage of this. This can be helpful if motion sequences need to be retargeted to your simulation skeleton that's been created in MJCF format. Importing the file to SkeletonTree format will allow you to generate T-poses or other retargeting poses that can be used for retargeting. We also show an example of creating a T-Pose for our AMP Humanoid asset in `generate_amp_humanoid_tpose.py`. ### Retargeting Motions Retargeting motions is important when your source data uses skeletons that have different morphologies than your target skeletons. We provide APIs for performing retarget of motion sequences in our SkeletonState and SkeletonMotion classes. To use the retargeting API, users must provide the following information: - source_motion: a SkeletonMotion npy representation of a motion sequence. The motion clip should use the same skeleton as the source T-Pose skeleton. - target_motion_path: path to save the retargeted motion to - source_tpose: a SkeletonState npy representation of the source skeleton in it's T-Pose state - target_tpose: a SkeletonState npy representation of the target skeleton in it's T-Pose state (pose should match source T-Pose) - joint_mapping: mapping of joint names from source to target - rotation: root rotation offset from source to target skeleton (for transforming across different orientation axes), represented as a quaternion in XYZW order. - scale: scale offset from source to target skeleton We provide an example script `retarget_motion.py` to demonstrate usage of the retargeting API for the CMU Motion Capture Database. Note that the retargeting data for this script is stored in `data/configs/retarget_cmu_to_amp.json`. Additionally, a SkeletonState T-Pose file and retargeting config file are also provided for the SFU Motion Capture Database. These can be found at `data/sfu_tpose.npy` and `data/configs/retarget_sfu_to_amp.json`. ### Documentation We provide a description of the functions and classes available in poselib in the comments of the APIs. Please check them out for more details.
5,585
Markdown
86.281249
404
0.78299
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/retarget_motion.py
# Copyright (c) 2018-2023, 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 isaacgymenvs.utils.torch_jit_utils import quat_mul, quat_from_angle_axis import torch import json import numpy as np from poselib.core.rotation3d import * from poselib.skeleton.skeleton3d import SkeletonTree, SkeletonState, SkeletonMotion from poselib.visualization.common import plot_skeleton_state, plot_skeleton_motion_interactive """ This scripts shows how to retarget a motion clip from the source skeleton to a target skeleton. Data required for retargeting are stored in a retarget config dictionary as a json file. This file contains: - source_motion: a SkeletonMotion npy format representation of a motion sequence. The motion clip should use the same skeleton as the source T-Pose skeleton. - target_motion_path: path to save the retargeted motion to - source_tpose: a SkeletonState npy format representation of the source skeleton in it's T-Pose state - target_tpose: a SkeletonState npy format representation of the target skeleton in it's T-Pose state (pose should match source T-Pose) - joint_mapping: mapping of joint names from source to target - rotation: root rotation offset from source to target skeleton (for transforming across different orientation axes), represented as a quaternion in XYZW order. - scale: scale offset from source to target skeleton """ VISUALIZE = False def project_joints(motion): right_upper_arm_id = motion.skeleton_tree._node_indices["right_upper_arm"] right_lower_arm_id = motion.skeleton_tree._node_indices["right_lower_arm"] right_hand_id = motion.skeleton_tree._node_indices["right_hand"] left_upper_arm_id = motion.skeleton_tree._node_indices["left_upper_arm"] left_lower_arm_id = motion.skeleton_tree._node_indices["left_lower_arm"] left_hand_id = motion.skeleton_tree._node_indices["left_hand"] right_thigh_id = motion.skeleton_tree._node_indices["right_thigh"] right_shin_id = motion.skeleton_tree._node_indices["right_shin"] right_foot_id = motion.skeleton_tree._node_indices["right_foot"] left_thigh_id = motion.skeleton_tree._node_indices["left_thigh"] left_shin_id = motion.skeleton_tree._node_indices["left_shin"] left_foot_id = motion.skeleton_tree._node_indices["left_foot"] device = motion.global_translation.device # right arm right_upper_arm_pos = motion.global_translation[..., right_upper_arm_id, :] right_lower_arm_pos = motion.global_translation[..., right_lower_arm_id, :] right_hand_pos = motion.global_translation[..., right_hand_id, :] right_shoulder_rot = motion.local_rotation[..., right_upper_arm_id, :] right_elbow_rot = motion.local_rotation[..., right_lower_arm_id, :] right_arm_delta0 = right_upper_arm_pos - right_lower_arm_pos right_arm_delta1 = right_hand_pos - right_lower_arm_pos right_arm_delta0 = right_arm_delta0 / torch.norm(right_arm_delta0, dim=-1, keepdim=True) right_arm_delta1 = right_arm_delta1 / torch.norm(right_arm_delta1, dim=-1, keepdim=True) right_elbow_dot = torch.sum(-right_arm_delta0 * right_arm_delta1, dim=-1) right_elbow_dot = torch.clamp(right_elbow_dot, -1.0, 1.0) right_elbow_theta = torch.acos(right_elbow_dot) right_elbow_q = quat_from_angle_axis(-torch.abs(right_elbow_theta), torch.tensor(np.array([[0.0, 1.0, 0.0]]), device=device, dtype=torch.float32)) right_elbow_local_dir = motion.skeleton_tree.local_translation[right_hand_id] right_elbow_local_dir = right_elbow_local_dir / torch.norm(right_elbow_local_dir) right_elbow_local_dir_tile = torch.tile(right_elbow_local_dir.unsqueeze(0), [right_elbow_rot.shape[0], 1]) right_elbow_local_dir0 = quat_rotate(right_elbow_rot, right_elbow_local_dir_tile) right_elbow_local_dir1 = quat_rotate(right_elbow_q, right_elbow_local_dir_tile) right_arm_dot = torch.sum(right_elbow_local_dir0 * right_elbow_local_dir1, dim=-1) right_arm_dot = torch.clamp(right_arm_dot, -1.0, 1.0) right_arm_theta = torch.acos(right_arm_dot) right_arm_theta = torch.where(right_elbow_local_dir0[..., 1] <= 0, right_arm_theta, -right_arm_theta) right_arm_q = quat_from_angle_axis(right_arm_theta, right_elbow_local_dir.unsqueeze(0)) right_shoulder_rot = quat_mul(right_shoulder_rot, right_arm_q) # left arm left_upper_arm_pos = motion.global_translation[..., left_upper_arm_id, :] left_lower_arm_pos = motion.global_translation[..., left_lower_arm_id, :] left_hand_pos = motion.global_translation[..., left_hand_id, :] left_shoulder_rot = motion.local_rotation[..., left_upper_arm_id, :] left_elbow_rot = motion.local_rotation[..., left_lower_arm_id, :] left_arm_delta0 = left_upper_arm_pos - left_lower_arm_pos left_arm_delta1 = left_hand_pos - left_lower_arm_pos left_arm_delta0 = left_arm_delta0 / torch.norm(left_arm_delta0, dim=-1, keepdim=True) left_arm_delta1 = left_arm_delta1 / torch.norm(left_arm_delta1, dim=-1, keepdim=True) left_elbow_dot = torch.sum(-left_arm_delta0 * left_arm_delta1, dim=-1) left_elbow_dot = torch.clamp(left_elbow_dot, -1.0, 1.0) left_elbow_theta = torch.acos(left_elbow_dot) left_elbow_q = quat_from_angle_axis(-torch.abs(left_elbow_theta), torch.tensor(np.array([[0.0, 1.0, 0.0]]), device=device, dtype=torch.float32)) left_elbow_local_dir = motion.skeleton_tree.local_translation[left_hand_id] left_elbow_local_dir = left_elbow_local_dir / torch.norm(left_elbow_local_dir) left_elbow_local_dir_tile = torch.tile(left_elbow_local_dir.unsqueeze(0), [left_elbow_rot.shape[0], 1]) left_elbow_local_dir0 = quat_rotate(left_elbow_rot, left_elbow_local_dir_tile) left_elbow_local_dir1 = quat_rotate(left_elbow_q, left_elbow_local_dir_tile) left_arm_dot = torch.sum(left_elbow_local_dir0 * left_elbow_local_dir1, dim=-1) left_arm_dot = torch.clamp(left_arm_dot, -1.0, 1.0) left_arm_theta = torch.acos(left_arm_dot) left_arm_theta = torch.where(left_elbow_local_dir0[..., 1] <= 0, left_arm_theta, -left_arm_theta) left_arm_q = quat_from_angle_axis(left_arm_theta, left_elbow_local_dir.unsqueeze(0)) left_shoulder_rot = quat_mul(left_shoulder_rot, left_arm_q) # right leg right_thigh_pos = motion.global_translation[..., right_thigh_id, :] right_shin_pos = motion.global_translation[..., right_shin_id, :] right_foot_pos = motion.global_translation[..., right_foot_id, :] right_hip_rot = motion.local_rotation[..., right_thigh_id, :] right_knee_rot = motion.local_rotation[..., right_shin_id, :] right_leg_delta0 = right_thigh_pos - right_shin_pos right_leg_delta1 = right_foot_pos - right_shin_pos right_leg_delta0 = right_leg_delta0 / torch.norm(right_leg_delta0, dim=-1, keepdim=True) right_leg_delta1 = right_leg_delta1 / torch.norm(right_leg_delta1, dim=-1, keepdim=True) right_knee_dot = torch.sum(-right_leg_delta0 * right_leg_delta1, dim=-1) right_knee_dot = torch.clamp(right_knee_dot, -1.0, 1.0) right_knee_theta = torch.acos(right_knee_dot) right_knee_q = quat_from_angle_axis(torch.abs(right_knee_theta), torch.tensor(np.array([[0.0, 1.0, 0.0]]), device=device, dtype=torch.float32)) right_knee_local_dir = motion.skeleton_tree.local_translation[right_foot_id] right_knee_local_dir = right_knee_local_dir / torch.norm(right_knee_local_dir) right_knee_local_dir_tile = torch.tile(right_knee_local_dir.unsqueeze(0), [right_knee_rot.shape[0], 1]) right_knee_local_dir0 = quat_rotate(right_knee_rot, right_knee_local_dir_tile) right_knee_local_dir1 = quat_rotate(right_knee_q, right_knee_local_dir_tile) right_leg_dot = torch.sum(right_knee_local_dir0 * right_knee_local_dir1, dim=-1) right_leg_dot = torch.clamp(right_leg_dot, -1.0, 1.0) right_leg_theta = torch.acos(right_leg_dot) right_leg_theta = torch.where(right_knee_local_dir0[..., 1] >= 0, right_leg_theta, -right_leg_theta) right_leg_q = quat_from_angle_axis(right_leg_theta, right_knee_local_dir.unsqueeze(0)) right_hip_rot = quat_mul(right_hip_rot, right_leg_q) # left leg left_thigh_pos = motion.global_translation[..., left_thigh_id, :] left_shin_pos = motion.global_translation[..., left_shin_id, :] left_foot_pos = motion.global_translation[..., left_foot_id, :] left_hip_rot = motion.local_rotation[..., left_thigh_id, :] left_knee_rot = motion.local_rotation[..., left_shin_id, :] left_leg_delta0 = left_thigh_pos - left_shin_pos left_leg_delta1 = left_foot_pos - left_shin_pos left_leg_delta0 = left_leg_delta0 / torch.norm(left_leg_delta0, dim=-1, keepdim=True) left_leg_delta1 = left_leg_delta1 / torch.norm(left_leg_delta1, dim=-1, keepdim=True) left_knee_dot = torch.sum(-left_leg_delta0 * left_leg_delta1, dim=-1) left_knee_dot = torch.clamp(left_knee_dot, -1.0, 1.0) left_knee_theta = torch.acos(left_knee_dot) left_knee_q = quat_from_angle_axis(torch.abs(left_knee_theta), torch.tensor(np.array([[0.0, 1.0, 0.0]]), device=device, dtype=torch.float32)) left_knee_local_dir = motion.skeleton_tree.local_translation[left_foot_id] left_knee_local_dir = left_knee_local_dir / torch.norm(left_knee_local_dir) left_knee_local_dir_tile = torch.tile(left_knee_local_dir.unsqueeze(0), [left_knee_rot.shape[0], 1]) left_knee_local_dir0 = quat_rotate(left_knee_rot, left_knee_local_dir_tile) left_knee_local_dir1 = quat_rotate(left_knee_q, left_knee_local_dir_tile) left_leg_dot = torch.sum(left_knee_local_dir0 * left_knee_local_dir1, dim=-1) left_leg_dot = torch.clamp(left_leg_dot, -1.0, 1.0) left_leg_theta = torch.acos(left_leg_dot) left_leg_theta = torch.where(left_knee_local_dir0[..., 1] >= 0, left_leg_theta, -left_leg_theta) left_leg_q = quat_from_angle_axis(left_leg_theta, left_knee_local_dir.unsqueeze(0)) left_hip_rot = quat_mul(left_hip_rot, left_leg_q) new_local_rotation = motion.local_rotation.clone() new_local_rotation[..., right_upper_arm_id, :] = right_shoulder_rot new_local_rotation[..., right_lower_arm_id, :] = right_elbow_q new_local_rotation[..., left_upper_arm_id, :] = left_shoulder_rot new_local_rotation[..., left_lower_arm_id, :] = left_elbow_q new_local_rotation[..., right_thigh_id, :] = right_hip_rot new_local_rotation[..., right_shin_id, :] = right_knee_q new_local_rotation[..., left_thigh_id, :] = left_hip_rot new_local_rotation[..., left_shin_id, :] = left_knee_q new_local_rotation[..., left_hand_id, :] = quat_identity([1]) new_local_rotation[..., right_hand_id, :] = quat_identity([1]) new_sk_state = SkeletonState.from_rotation_and_root_translation(motion.skeleton_tree, new_local_rotation, motion.root_translation, is_local=True) new_motion = SkeletonMotion.from_skeleton_state(new_sk_state, fps=motion.fps) return new_motion def main(): # load retarget config retarget_data_path = "data/configs/retarget_cmu_to_amp.json" with open(retarget_data_path) as f: retarget_data = json.load(f) # load and visualize t-pose files source_tpose = SkeletonState.from_file(retarget_data["source_tpose"]) if VISUALIZE: plot_skeleton_state(source_tpose) target_tpose = SkeletonState.from_file(retarget_data["target_tpose"]) if VISUALIZE: plot_skeleton_state(target_tpose) # load and visualize source motion sequence source_motion = SkeletonMotion.from_file(retarget_data["source_motion"]) if VISUALIZE: plot_skeleton_motion_interactive(source_motion) # parse data from retarget config joint_mapping = retarget_data["joint_mapping"] rotation_to_target_skeleton = torch.tensor(retarget_data["rotation"]) # run retargeting target_motion = source_motion.retarget_to_by_tpose( joint_mapping=retarget_data["joint_mapping"], source_tpose=source_tpose, target_tpose=target_tpose, rotation_to_target_skeleton=rotation_to_target_skeleton, scale_to_target_skeleton=retarget_data["scale"] ) # keep frames between [trim_frame_beg, trim_frame_end - 1] frame_beg = retarget_data["trim_frame_beg"] frame_end = retarget_data["trim_frame_end"] if (frame_beg == -1): frame_beg = 0 if (frame_end == -1): frame_end = target_motion.local_rotation.shape[0] local_rotation = target_motion.local_rotation root_translation = target_motion.root_translation local_rotation = local_rotation[frame_beg:frame_end, ...] root_translation = root_translation[frame_beg:frame_end, ...] new_sk_state = SkeletonState.from_rotation_and_root_translation(target_motion.skeleton_tree, local_rotation, root_translation, is_local=True) target_motion = SkeletonMotion.from_skeleton_state(new_sk_state, fps=target_motion.fps) # need to convert some joints from 3D to 1D (e.g. elbows and knees) target_motion = project_joints(target_motion) # move the root so that the feet are on the ground local_rotation = target_motion.local_rotation root_translation = target_motion.root_translation tar_global_pos = target_motion.global_translation min_h = torch.min(tar_global_pos[..., 2]) root_translation[:, 2] += -min_h # adjust the height of the root to avoid ground penetration root_height_offset = retarget_data["root_height_offset"] root_translation[:, 2] += root_height_offset new_sk_state = SkeletonState.from_rotation_and_root_translation(target_motion.skeleton_tree, local_rotation, root_translation, is_local=True) target_motion = SkeletonMotion.from_skeleton_state(new_sk_state, fps=target_motion.fps) # save retargeted motion target_motion.to_file(retarget_data["target_motion_path"]) # visualize retargeted motion plot_skeleton_motion_interactive(target_motion) return if __name__ == '__main__': main()
15,589
Python
54.283688
162
0.696196
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/__init__.py
# Copyright (c) 2018-2023, 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. __version__ = "0.0.1" from .core import *
1,603
Python
47.606059
80
0.777293
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/common.py
# Copyright (c) 2018-2023, 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 from ..core import logger from .plt_plotter import Matplotlib3DPlotter from .skeleton_plotter_tasks import Draw3DSkeletonMotion, Draw3DSkeletonState def plot_skeleton_state(skeleton_state, task_name=""): """ Visualize a skeleton state :param skeleton_state: :param task_name: :type skeleton_state: SkeletonState :type task_name: string, optional """ logger.info("plotting {}".format(task_name)) task = Draw3DSkeletonState(task_name=task_name, skeleton_state=skeleton_state) plotter = Matplotlib3DPlotter(task) plotter.show() def plot_skeleton_states(skeleton_state, skip_n=1, task_name=""): """ Visualize a sequence of skeleton state. The dimension of the skeleton state must be 1 :param skeleton_state: :param task_name: :type skeleton_state: SkeletonState :type task_name: string, optional """ logger.info("plotting {} motion".format(task_name)) assert len(skeleton_state.shape) == 1, "the state must have only one dimension" task = Draw3DSkeletonState(task_name=task_name, skeleton_state=skeleton_state[0]) plotter = Matplotlib3DPlotter(task) for frame_id in range(skeleton_state.shape[0]): if frame_id % skip_n != 0: continue task.update(skeleton_state[frame_id]) plotter.update() plotter.show() def plot_skeleton_motion(skeleton_motion, skip_n=1, task_name=""): """ Visualize a skeleton motion along its first dimension. :param skeleton_motion: :param task_name: :type skeleton_motion: SkeletonMotion :type task_name: string, optional """ logger.info("plotting {} motion".format(task_name)) task = Draw3DSkeletonMotion( task_name=task_name, skeleton_motion=skeleton_motion, frame_index=0 ) plotter = Matplotlib3DPlotter(task) for frame_id in range(len(skeleton_motion)): if frame_id % skip_n != 0: continue task.update(frame_id) plotter.update() plotter.show() def plot_skeleton_motion_interactive_base(skeleton_motion, task_name=""): class PlotParams: def __init__(self, total_num_frames): self.current_frame = 0 self.playing = False self.looping = False self.confirmed = False self.playback_speed = 4 self.total_num_frames = total_num_frames def sync(self, other): self.current_frame = other.current_frame self.playing = other.playing self.looping = other.current_frame self.confirmed = other.confirmed self.playback_speed = other.playback_speed self.total_num_frames = other.total_num_frames task = Draw3DSkeletonMotion( task_name=task_name, skeleton_motion=skeleton_motion, frame_index=0 ) plotter = Matplotlib3DPlotter(task) plot_params = PlotParams(total_num_frames=len(skeleton_motion)) print("Entered interactive plot - press 'n' to quit, 'h' for a list of commands") def press(event): if event.key == "x": plot_params.playing = not plot_params.playing elif event.key == "z": plot_params.current_frame = plot_params.current_frame - 1 elif event.key == "c": plot_params.current_frame = plot_params.current_frame + 1 elif event.key == "a": plot_params.current_frame = plot_params.current_frame - 20 elif event.key == "d": plot_params.current_frame = plot_params.current_frame + 20 elif event.key == "w": plot_params.looping = not plot_params.looping print("Looping: {}".format(plot_params.looping)) elif event.key == "v": plot_params.playback_speed *= 2 print("playback speed: {}".format(plot_params.playback_speed)) elif event.key == "b": if plot_params.playback_speed != 1: plot_params.playback_speed //= 2 print("playback speed: {}".format(plot_params.playback_speed)) elif event.key == "n": plot_params.confirmed = True elif event.key == "h": rows, columns = os.popen("stty size", "r").read().split() columns = int(columns) print("=" * columns) print("x: play/pause") print("z: previous frame") print("c: next frame") print("a: jump 10 frames back") print("d: jump 10 frames forward") print("w: looping/non-looping") print("v: double speed (this can be applied multiple times)") print("b: half speed (this can be applied multiple times)") print("n: quit") print("h: help") print("=" * columns) print( 'current frame index: {}/{} (press "n" to quit)'.format( plot_params.current_frame, plot_params.total_num_frames - 1 ) ) plotter.fig.canvas.mpl_connect("key_press_event", press) while True: reset_trail = False if plot_params.confirmed: break if plot_params.playing: plot_params.current_frame += plot_params.playback_speed if plot_params.current_frame >= plot_params.total_num_frames: if plot_params.looping: plot_params.current_frame %= plot_params.total_num_frames reset_trail = True else: plot_params.current_frame = plot_params.total_num_frames - 1 if plot_params.current_frame < 0: if plot_params.looping: plot_params.current_frame %= plot_params.total_num_frames reset_trail = True else: plot_params.current_frame = 0 yield plot_params task.update(plot_params.current_frame, reset_trail) plotter.update() def plot_skeleton_motion_interactive(skeleton_motion, task_name=""): """ Visualize a skeleton motion along its first dimension interactively. :param skeleton_motion: :param task_name: :type skeleton_motion: SkeletonMotion :type task_name: string, optional """ for _ in plot_skeleton_motion_interactive_base(skeleton_motion, task_name): pass def plot_skeleton_motion_interactive_multiple(*callables, sync=True): for _ in zip(*callables): if sync: for p1, p2 in zip(_[:-1], _[1:]): p2.sync(p1) # def plot_skeleton_motion_interactive_multiple_same(skeleton_motions, task_name=""):
8,107
Python
37.42654
89
0.642654
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/simple_plotter_tasks.py
# Copyright (c) 2018-2023, 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. """ This is where all the task primitives are defined """ import numpy as np from .core import BasePlotterTask class DrawXDLines(BasePlotterTask): _lines: np.ndarray _color: str _line_width: int _alpha: float _influence_lim: bool def __init__( self, task_name: str, lines: np.ndarray, color: str = "blue", line_width: int = 2, alpha: float = 1.0, influence_lim: bool = True, ) -> None: super().__init__(task_name=task_name, task_type=self.__class__.__name__) self._color = color self._line_width = line_width self._alpha = alpha self._influence_lim = influence_lim self.update(lines) @property def influence_lim(self) -> bool: return self._influence_lim @property def raw_data(self): return self._lines @property def color(self): return self._color @property def line_width(self): return self._line_width @property def alpha(self): return self._alpha @property def dim(self): raise NotImplementedError @property def name(self): return "{}DLines".format(self.dim) def update(self, lines): self._lines = np.array(lines) shape = self._lines.shape assert shape[-1] == self.dim and shape[-2] == 2 and len(shape) == 3 def __getitem__(self, index): return self._lines[index] def __len__(self): return self._lines.shape[0] def __iter__(self): yield self class DrawXDDots(BasePlotterTask): _dots: np.ndarray _color: str _marker_size: int _alpha: float _influence_lim: bool def __init__( self, task_name: str, dots: np.ndarray, color: str = "blue", marker_size: int = 10, alpha: float = 1.0, influence_lim: bool = True, ) -> None: super().__init__(task_name=task_name, task_type=self.__class__.__name__) self._color = color self._marker_size = marker_size self._alpha = alpha self._influence_lim = influence_lim self.update(dots) def update(self, dots): self._dots = np.array(dots) shape = self._dots.shape assert shape[-1] == self.dim and len(shape) == 2 def __getitem__(self, index): return self._dots[index] def __len__(self): return self._dots.shape[0] def __iter__(self): yield self @property def influence_lim(self) -> bool: return self._influence_lim @property def raw_data(self): return self._dots @property def color(self): return self._color @property def marker_size(self): return self._marker_size @property def alpha(self): return self._alpha @property def dim(self): raise NotImplementedError @property def name(self): return "{}DDots".format(self.dim) class DrawXDTrail(DrawXDDots): @property def line_width(self): return self.marker_size @property def name(self): return "{}DTrail".format(self.dim) class Draw2DLines(DrawXDLines): @property def dim(self): return 2 class Draw3DLines(DrawXDLines): @property def dim(self): return 3 class Draw2DDots(DrawXDDots): @property def dim(self): return 2 class Draw3DDots(DrawXDDots): @property def dim(self): return 3 class Draw2DTrail(DrawXDTrail): @property def dim(self): return 2 class Draw3DTrail(DrawXDTrail): @property def dim(self): return 3
5,246
Python
23.404651
80
0.633626
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/__init__.py
# Copyright (c) 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.
423
Python
69.666655
76
0.817967
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/core.py
# Copyright (c) 2018-2023, 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. """ The base abstract classes for plotter and the plotting tasks. It describes how the plotter deals with the tasks in the general cases """ from typing import List class BasePlotterTask(object): _task_name: str # unique name of the task _task_type: str # type of the task is used to identify which callable def __init__(self, task_name: str, task_type: str) -> None: self._task_name = task_name self._task_type = task_type @property def task_name(self): return self._task_name @property def task_type(self): return self._task_type def get_scoped_name(self, name): return self._task_name + "/" + name def __iter__(self): """Should override this function to return a list of task primitives """ raise NotImplementedError class BasePlotterTasks(object): def __init__(self, tasks) -> None: self._tasks = tasks def __iter__(self): for task in self._tasks: yield from task class BasePlotter(object): """An abstract plotter which deals with a plotting task. The children class needs to implement the functions to create/update the objects according to the task given """ _task_primitives: List[BasePlotterTask] def __init__(self, task: BasePlotterTask) -> None: self._task_primitives = [] self.create(task) @property def task_primitives(self): return self._task_primitives def create(self, task: BasePlotterTask) -> None: """Create more task primitives from a task for the plotter""" new_task_primitives = list(task) # get all task primitives self._task_primitives += new_task_primitives # append them self._create_impl(new_task_primitives) def update(self) -> None: """Update the plotter for any updates in the task primitives""" self._update_impl(self._task_primitives) def _update_impl(self, task_list: List[BasePlotterTask]) -> None: raise NotImplementedError def _create_impl(self, task_list: List[BasePlotterTask]) -> None: raise NotImplementedError
3,700
Python
36.01
98
0.705676
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/plt_plotter.py
# Copyright (c) 2018-2023, 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. """ The matplotlib plotter implementation for all the primitive tasks (in our case: lines and dots) """ from typing import Any, Callable, Dict, List import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import numpy as np from .core import BasePlotter, BasePlotterTask class Matplotlib2DPlotter(BasePlotter): _fig: plt.figure # plt figure _ax: plt.axis # plt axis # stores artist objects for each task (task name as the key) _artist_cache: Dict[str, Any] # callables for each task primitives _create_impl_callables: Dict[str, Callable] _update_impl_callables: Dict[str, Callable] def __init__(self, task: "BasePlotterTask") -> None: fig, ax = plt.subplots() self._fig = fig self._ax = ax self._artist_cache = {} self._create_impl_callables = { "Draw2DLines": self._lines_create_impl, "Draw2DDots": self._dots_create_impl, "Draw2DTrail": self._trail_create_impl, } self._update_impl_callables = { "Draw2DLines": self._lines_update_impl, "Draw2DDots": self._dots_update_impl, "Draw2DTrail": self._trail_update_impl, } self._init_lim() super().__init__(task) @property def ax(self): return self._ax @property def fig(self): return self._fig def show(self): plt.show() def _min(self, x, y): if x is None: return y if y is None: return x return min(x, y) def _max(self, x, y): if x is None: return y if y is None: return x return max(x, y) def _init_lim(self): self._curr_x_min = None self._curr_y_min = None self._curr_x_max = None self._curr_y_max = None def _update_lim(self, xs, ys): self._curr_x_min = self._min(np.min(xs), self._curr_x_min) self._curr_y_min = self._min(np.min(ys), self._curr_y_min) self._curr_x_max = self._max(np.max(xs), self._curr_x_max) self._curr_y_max = self._max(np.max(ys), self._curr_y_max) def _set_lim(self): if not ( self._curr_x_min is None or self._curr_x_max is None or self._curr_y_min is None or self._curr_y_max is None ): self._ax.set_xlim(self._curr_x_min, self._curr_x_max) self._ax.set_ylim(self._curr_y_min, self._curr_y_max) self._init_lim() @staticmethod def _lines_extract_xy_impl(index, lines_task): return lines_task[index, :, 0], lines_task[index, :, 1] @staticmethod def _trail_extract_xy_impl(index, trail_task): return (trail_task[index : index + 2, 0], trail_task[index : index + 2, 1]) def _lines_create_impl(self, lines_task): color = lines_task.color self._artist_cache[lines_task.task_name] = [ self._ax.plot( *Matplotlib2DPlotter._lines_extract_xy_impl(i, lines_task), color=color, linewidth=lines_task.line_width, alpha=lines_task.alpha )[0] for i in range(len(lines_task)) ] def _lines_update_impl(self, lines_task): lines_artists = self._artist_cache[lines_task.task_name] for i in range(len(lines_task)): artist = lines_artists[i] xs, ys = Matplotlib2DPlotter._lines_extract_xy_impl(i, lines_task) artist.set_data(xs, ys) if lines_task.influence_lim: self._update_lim(xs, ys) def _dots_create_impl(self, dots_task): color = dots_task.color self._artist_cache[dots_task.task_name] = self._ax.plot( dots_task[:, 0], dots_task[:, 1], c=color, linestyle="", marker=".", markersize=dots_task.marker_size, alpha=dots_task.alpha, )[0] def _dots_update_impl(self, dots_task): dots_artist = self._artist_cache[dots_task.task_name] dots_artist.set_data(dots_task[:, 0], dots_task[:, 1]) if dots_task.influence_lim: self._update_lim(dots_task[:, 0], dots_task[:, 1]) def _trail_create_impl(self, trail_task): color = trail_task.color trail_length = len(trail_task) - 1 self._artist_cache[trail_task.task_name] = [ self._ax.plot( *Matplotlib2DPlotter._trail_extract_xy_impl(i, trail_task), color=trail_task.color, linewidth=trail_task.line_width, alpha=trail_task.alpha * (1.0 - i / (trail_length - 1)) )[0] for i in range(trail_length) ] def _trail_update_impl(self, trail_task): trails_artists = self._artist_cache[trail_task.task_name] for i in range(len(trail_task) - 1): artist = trails_artists[i] xs, ys = Matplotlib2DPlotter._trail_extract_xy_impl(i, trail_task) artist.set_data(xs, ys) if trail_task.influence_lim: self._update_lim(xs, ys) def _create_impl(self, task_list): for task in task_list: self._create_impl_callables[task.task_type](task) self._draw() def _update_impl(self, task_list): for task in task_list: self._update_impl_callables[task.task_type](task) self._draw() def _set_aspect_equal_2d(self, zero_centered=True): xlim = self._ax.get_xlim() ylim = self._ax.get_ylim() if not zero_centered: xmean = np.mean(xlim) ymean = np.mean(ylim) else: xmean = 0 ymean = 0 plot_radius = max( [ abs(lim - mean_) for lims, mean_ in ((xlim, xmean), (ylim, ymean)) for lim in lims ] ) self._ax.set_xlim([xmean - plot_radius, xmean + plot_radius]) self._ax.set_ylim([ymean - plot_radius, ymean + plot_radius]) def _draw(self): self._set_lim() self._set_aspect_equal_2d() self._fig.canvas.draw() self._fig.canvas.flush_events() plt.pause(0.00001) class Matplotlib3DPlotter(BasePlotter): _fig: plt.figure # plt figure _ax: p3.Axes3D # plt 3d axis # stores artist objects for each task (task name as the key) _artist_cache: Dict[str, Any] # callables for each task primitives _create_impl_callables: Dict[str, Callable] _update_impl_callables: Dict[str, Callable] def __init__(self, task: "BasePlotterTask") -> None: self._fig = plt.figure() self._ax = p3.Axes3D(self._fig) self._artist_cache = {} self._create_impl_callables = { "Draw3DLines": self._lines_create_impl, "Draw3DDots": self._dots_create_impl, "Draw3DTrail": self._trail_create_impl, } self._update_impl_callables = { "Draw3DLines": self._lines_update_impl, "Draw3DDots": self._dots_update_impl, "Draw3DTrail": self._trail_update_impl, } self._init_lim() super().__init__(task) @property def ax(self): return self._ax @property def fig(self): return self._fig def show(self): plt.show() def _min(self, x, y): if x is None: return y if y is None: return x return min(x, y) def _max(self, x, y): if x is None: return y if y is None: return x return max(x, y) def _init_lim(self): self._curr_x_min = None self._curr_y_min = None self._curr_z_min = None self._curr_x_max = None self._curr_y_max = None self._curr_z_max = None def _update_lim(self, xs, ys, zs): self._curr_x_min = self._min(np.min(xs), self._curr_x_min) self._curr_y_min = self._min(np.min(ys), self._curr_y_min) self._curr_z_min = self._min(np.min(zs), self._curr_z_min) self._curr_x_max = self._max(np.max(xs), self._curr_x_max) self._curr_y_max = self._max(np.max(ys), self._curr_y_max) self._curr_z_max = self._max(np.max(zs), self._curr_z_max) def _set_lim(self): if not ( self._curr_x_min is None or self._curr_x_max is None or self._curr_y_min is None or self._curr_y_max is None or self._curr_z_min is None or self._curr_z_max is None ): self._ax.set_xlim3d(self._curr_x_min, self._curr_x_max) self._ax.set_ylim3d(self._curr_y_min, self._curr_y_max) self._ax.set_zlim3d(self._curr_z_min, self._curr_z_max) self._init_lim() @staticmethod def _lines_extract_xyz_impl(index, lines_task): return lines_task[index, :, 0], lines_task[index, :, 1], lines_task[index, :, 2] @staticmethod def _trail_extract_xyz_impl(index, trail_task): return ( trail_task[index : index + 2, 0], trail_task[index : index + 2, 1], trail_task[index : index + 2, 2], ) def _lines_create_impl(self, lines_task): color = lines_task.color self._artist_cache[lines_task.task_name] = [ self._ax.plot( *Matplotlib3DPlotter._lines_extract_xyz_impl(i, lines_task), color=color, linewidth=lines_task.line_width, alpha=lines_task.alpha )[0] for i in range(len(lines_task)) ] def _lines_update_impl(self, lines_task): lines_artists = self._artist_cache[lines_task.task_name] for i in range(len(lines_task)): artist = lines_artists[i] xs, ys, zs = Matplotlib3DPlotter._lines_extract_xyz_impl(i, lines_task) artist.set_data(xs, ys) artist.set_3d_properties(zs) if lines_task.influence_lim: self._update_lim(xs, ys, zs) def _dots_create_impl(self, dots_task): color = dots_task.color self._artist_cache[dots_task.task_name] = self._ax.plot( dots_task[:, 0], dots_task[:, 1], dots_task[:, 2], c=color, linestyle="", marker=".", markersize=dots_task.marker_size, alpha=dots_task.alpha, )[0] def _dots_update_impl(self, dots_task): dots_artist = self._artist_cache[dots_task.task_name] dots_artist.set_data(dots_task[:, 0], dots_task[:, 1]) dots_artist.set_3d_properties(dots_task[:, 2]) if dots_task.influence_lim: self._update_lim(dots_task[:, 0], dots_task[:, 1], dots_task[:, 2]) def _trail_create_impl(self, trail_task): color = trail_task.color trail_length = len(trail_task) - 1 self._artist_cache[trail_task.task_name] = [ self._ax.plot( *Matplotlib3DPlotter._trail_extract_xyz_impl(i, trail_task), color=trail_task.color, linewidth=trail_task.line_width, alpha=trail_task.alpha * (1.0 - i / (trail_length - 1)) )[0] for i in range(trail_length) ] def _trail_update_impl(self, trail_task): trails_artists = self._artist_cache[trail_task.task_name] for i in range(len(trail_task) - 1): artist = trails_artists[i] xs, ys, zs = Matplotlib3DPlotter._trail_extract_xyz_impl(i, trail_task) artist.set_data(xs, ys) artist.set_3d_properties(zs) if trail_task.influence_lim: self._update_lim(xs, ys, zs) def _create_impl(self, task_list): for task in task_list: self._create_impl_callables[task.task_type](task) self._draw() def _update_impl(self, task_list): for task in task_list: self._update_impl_callables[task.task_type](task) self._draw() def _set_aspect_equal_3d(self): xlim = self._ax.get_xlim3d() ylim = self._ax.get_ylim3d() zlim = self._ax.get_zlim3d() xmean = np.mean(xlim) ymean = np.mean(ylim) zmean = np.mean(zlim) plot_radius = max( [ abs(lim - mean_) for lims, mean_ in ((xlim, xmean), (ylim, ymean), (zlim, zmean)) for lim in lims ] ) self._ax.set_xlim3d([xmean - plot_radius, xmean + plot_radius]) self._ax.set_ylim3d([ymean - plot_radius, ymean + plot_radius]) self._ax.set_zlim3d([zmean - plot_radius, zmean + plot_radius]) def _draw(self): self._set_lim() self._set_aspect_equal_3d() self._fig.canvas.draw() self._fig.canvas.flush_events() plt.pause(0.00001)
14,522
Python
33.171765
89
0.567071
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/skeleton_plotter_tasks.py
# Copyright (c) 2018-2023, 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. """ This is where all skeleton related complex tasks are defined (skeleton state and skeleton motion) """ import numpy as np from .core import BasePlotterTask from .simple_plotter_tasks import Draw3DDots, Draw3DLines, Draw3DTrail class Draw3DSkeletonState(BasePlotterTask): _lines_task: Draw3DLines # sub-task for drawing lines _dots_task: Draw3DDots # sub-task for drawing dots def __init__( self, task_name: str, skeleton_state, joints_color: str = "red", lines_color: str = "blue", alpha=1.0, ) -> None: super().__init__(task_name=task_name, task_type="3DSkeletonState") lines, dots = Draw3DSkeletonState._get_lines_and_dots(skeleton_state) self._lines_task = Draw3DLines( self.get_scoped_name("bodies"), lines, joints_color, alpha=alpha ) self._dots_task = Draw3DDots( self.get_scoped_name("joints"), dots, lines_color, alpha=alpha ) @property def name(self): return "3DSkeleton" def update(self, skeleton_state) -> None: self._update(*Draw3DSkeletonState._get_lines_and_dots(skeleton_state)) @staticmethod def _get_lines_and_dots(skeleton_state): """Get all the lines and dots needed to draw the skeleton state """ assert ( len(skeleton_state.tensor.shape) == 1 ), "the state has to be zero dimensional" dots = skeleton_state.global_translation.numpy() skeleton_tree = skeleton_state.skeleton_tree parent_indices = skeleton_tree.parent_indices.numpy() lines = [] for node_index in range(len(skeleton_tree)): parent_index = parent_indices[node_index] if parent_index != -1: lines.append([dots[node_index], dots[parent_index]]) lines = np.array(lines) return lines, dots def _update(self, lines, dots) -> None: self._lines_task.update(lines) self._dots_task.update(dots) def __iter__(self): yield from self._lines_task yield from self._dots_task class Draw3DSkeletonMotion(BasePlotterTask): def __init__( self, task_name: str, skeleton_motion, frame_index=None, joints_color="red", lines_color="blue", velocity_color="green", angular_velocity_color="purple", trail_color="black", trail_length=10, alpha=1.0, ) -> None: super().__init__(task_name=task_name, task_type="3DSkeletonMotion") self._trail_length = trail_length self._skeleton_motion = skeleton_motion # if frame_index is None: curr_skeleton_motion = self._skeleton_motion.clone() if frame_index is not None: curr_skeleton_motion.tensor = self._skeleton_motion.tensor[frame_index, :] # else: # curr_skeleton_motion = self._skeleton_motion[frame_index, :] self._skeleton_state_task = Draw3DSkeletonState( self.get_scoped_name("skeleton_state"), curr_skeleton_motion, joints_color=joints_color, lines_color=lines_color, alpha=alpha, ) vel_lines, avel_lines = Draw3DSkeletonMotion._get_vel_and_avel( curr_skeleton_motion ) self._com_pos = curr_skeleton_motion.root_translation.numpy()[ np.newaxis, ... ].repeat(trail_length, axis=0) self._vel_task = Draw3DLines( self.get_scoped_name("velocity"), vel_lines, velocity_color, influence_lim=False, alpha=alpha, ) self._avel_task = Draw3DLines( self.get_scoped_name("angular_velocity"), avel_lines, angular_velocity_color, influence_lim=False, alpha=alpha, ) self._com_trail_task = Draw3DTrail( self.get_scoped_name("com_trail"), self._com_pos, trail_color, marker_size=2, influence_lim=True, alpha=alpha, ) @property def name(self): return "3DSkeletonMotion" def update(self, frame_index=None, reset_trail=False, skeleton_motion=None) -> None: if skeleton_motion is not None: self._skeleton_motion = skeleton_motion curr_skeleton_motion = self._skeleton_motion.clone() if frame_index is not None: curr_skeleton_motion.tensor = curr_skeleton_motion.tensor[frame_index, :] if reset_trail: self._com_pos = curr_skeleton_motion.root_translation.numpy()[ np.newaxis, ... ].repeat(self._trail_length, axis=0) else: self._com_pos = np.concatenate( ( curr_skeleton_motion.root_translation.numpy()[np.newaxis, ...], self._com_pos[:-1], ), axis=0, ) self._skeleton_state_task.update(curr_skeleton_motion) self._com_trail_task.update(self._com_pos) self._update(*Draw3DSkeletonMotion._get_vel_and_avel(curr_skeleton_motion)) @staticmethod def _get_vel_and_avel(skeleton_motion): """Get all the velocity and angular velocity lines """ pos = skeleton_motion.global_translation.numpy() vel = skeleton_motion.global_velocity.numpy() avel = skeleton_motion.global_angular_velocity.numpy() vel_lines = np.stack((pos, pos + vel * 0.02), axis=1) avel_lines = np.stack((pos, pos + avel * 0.01), axis=1) return vel_lines, avel_lines def _update(self, vel_lines, avel_lines) -> None: self._vel_task.update(vel_lines) self._avel_task.update(avel_lines) def __iter__(self): yield from self._skeleton_state_task yield from self._vel_task yield from self._avel_task yield from self._com_trail_task class Draw3DSkeletonMotions(BasePlotterTask): def __init__(self, skeleton_motion_tasks) -> None: self._skeleton_motion_tasks = skeleton_motion_tasks @property def name(self): return "3DSkeletonMotions" def update(self, frame_index) -> None: list(map(lambda x: x.update(frame_index), self._skeleton_motion_tasks)) def __iter__(self): yield from self._skeleton_state_tasks
7,974
Python
35.751152
89
0.627163
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/tests/test_plotter.py
# Copyright (c) 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. from typing import cast import matplotlib.pyplot as plt import numpy as np from ..core import BasePlotterTask, BasePlotterTasks from ..plt_plotter import Matplotlib3DPlotter from ..simple_plotter_tasks import Draw3DDots, Draw3DLines task = Draw3DLines(task_name="test", lines=np.array([[[0, 0, 0], [0, 0, 1]], [[0, 1, 1], [0, 1, 0]]]), color="blue") task2 = Draw3DDots(task_name="test2", dots=np.array([[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]]), color="red") task3 = BasePlotterTasks([task, task2]) plotter = Matplotlib3DPlotter(cast(BasePlotterTask, task3)) plt.show()
1,011
Python
41.166665
83
0.738872
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/visualization/tests/__init__.py
# Copyright (c) 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.
423
Python
69.666655
76
0.817967
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/__init__.py
# Copyright (c) 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. from .tensor_utils import * from .rotation3d import * from .backend import Serializable, logger
521
Python
46.454541
76
0.809981
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/rotation3d.py
# Copyright (c) 2018-2023, 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 List, Optional import math import torch @torch.jit.script def quat_mul(a, b): """ quaternion multiplication """ x1, y1, z1, w1 = a[..., 0], a[..., 1], a[..., 2], a[..., 3] x2, y2, z2, w2 = b[..., 0], b[..., 1], b[..., 2], b[..., 3] w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2 x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2 y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2 z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2 return torch.stack([x, y, z, w], dim=-1) @torch.jit.script def quat_pos(x): """ make all the real part of the quaternion positive """ q = x z = (q[..., 3:] < 0).float() q = (1 - 2 * z) * q return q @torch.jit.script def quat_abs(x): """ quaternion norm (unit quaternion represents a 3D rotation, which has norm of 1) """ x = x.norm(p=2, dim=-1) return x @torch.jit.script def quat_unit(x): """ normalized quaternion with norm of 1 """ norm = quat_abs(x).unsqueeze(-1) return x / (norm.clamp(min=1e-9)) @torch.jit.script def quat_conjugate(x): """ quaternion with its imaginary part negated """ return torch.cat([-x[..., :3], x[..., 3:]], dim=-1) @torch.jit.script def quat_real(x): """ real component of the quaternion """ return x[..., 3] @torch.jit.script def quat_imaginary(x): """ imaginary components of the quaternion """ return x[..., :3] @torch.jit.script def quat_norm_check(x): """ verify that a quaternion has norm 1 """ assert bool( (abs(x.norm(p=2, dim=-1) - 1) < 1e-3).all() ), "the quaternion is has non-1 norm: {}".format(abs(x.norm(p=2, dim=-1) - 1)) assert bool((x[..., 3] >= 0).all()), "the quaternion has negative real part" @torch.jit.script def quat_normalize(q): """ Construct 3D rotation from quaternion (the quaternion needs not to be normalized). """ q = quat_unit(quat_pos(q)) # normalized to positive and unit quaternion return q @torch.jit.script def quat_from_xyz(xyz): """ Construct 3D rotation from the imaginary component """ w = (1.0 - xyz.norm()).unsqueeze(-1) assert bool((w >= 0).all()), "xyz has its norm greater than 1" return torch.cat([xyz, w], dim=-1) @torch.jit.script def quat_identity(shape: List[int]): """ Construct 3D identity rotation given shape """ w = torch.ones(shape + [1]) xyz = torch.zeros(shape + [3]) q = torch.cat([xyz, w], dim=-1) return quat_normalize(q) @torch.jit.script def quat_from_angle_axis(angle, axis, degree: bool = False): """ Create a 3D rotation from angle and axis of rotation. The rotation is counter-clockwise along the axis. The rotation can be interpreted as a_R_b where frame "b" is the new frame that gets rotated counter-clockwise along the axis from frame "a" :param angle: angle of rotation :type angle: Tensor :param axis: axis of rotation :type axis: Tensor :param degree: put True here if the angle is given by degree :type degree: bool, optional, default=False """ if degree: angle = angle / 180.0 * math.pi theta = (angle / 2).unsqueeze(-1) axis = axis / (axis.norm(p=2, dim=-1, keepdim=True).clamp(min=1e-9)) xyz = axis * theta.sin() w = theta.cos() return quat_normalize(torch.cat([xyz, w], dim=-1)) @torch.jit.script def quat_from_rotation_matrix(m): """ Construct a 3D rotation from a valid 3x3 rotation matrices. Reference can be found here: http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/teche52.html :param m: 3x3 orthogonal rotation matrices. :type m: Tensor :rtype: Tensor """ m = m.unsqueeze(0) diag0 = m[..., 0, 0] diag1 = m[..., 1, 1] diag2 = m[..., 2, 2] # Math stuff. w = (((diag0 + diag1 + diag2 + 1.0) / 4.0).clamp(0.0, None)) ** 0.5 x = (((diag0 - diag1 - diag2 + 1.0) / 4.0).clamp(0.0, None)) ** 0.5 y = (((-diag0 + diag1 - diag2 + 1.0) / 4.0).clamp(0.0, None)) ** 0.5 z = (((-diag0 - diag1 + diag2 + 1.0) / 4.0).clamp(0.0, None)) ** 0.5 # Only modify quaternions where w > x, y, z. c0 = (w >= x) & (w >= y) & (w >= z) x[c0] *= (m[..., 2, 1][c0] - m[..., 1, 2][c0]).sign() y[c0] *= (m[..., 0, 2][c0] - m[..., 2, 0][c0]).sign() z[c0] *= (m[..., 1, 0][c0] - m[..., 0, 1][c0]).sign() # Only modify quaternions where x > w, y, z c1 = (x >= w) & (x >= y) & (x >= z) w[c1] *= (m[..., 2, 1][c1] - m[..., 1, 2][c1]).sign() y[c1] *= (m[..., 1, 0][c1] + m[..., 0, 1][c1]).sign() z[c1] *= (m[..., 0, 2][c1] + m[..., 2, 0][c1]).sign() # Only modify quaternions where y > w, x, z. c2 = (y >= w) & (y >= x) & (y >= z) w[c2] *= (m[..., 0, 2][c2] - m[..., 2, 0][c2]).sign() x[c2] *= (m[..., 1, 0][c2] + m[..., 0, 1][c2]).sign() z[c2] *= (m[..., 2, 1][c2] + m[..., 1, 2][c2]).sign() # Only modify quaternions where z > w, x, y. c3 = (z >= w) & (z >= x) & (z >= y) w[c3] *= (m[..., 1, 0][c3] - m[..., 0, 1][c3]).sign() x[c3] *= (m[..., 2, 0][c3] + m[..., 0, 2][c3]).sign() y[c3] *= (m[..., 2, 1][c3] + m[..., 1, 2][c3]).sign() return quat_normalize(torch.stack([x, y, z, w], dim=-1)).squeeze(0) @torch.jit.script def quat_mul_norm(x, y): """ Combine two set of 3D rotations together using \**\* operator. The shape needs to be broadcastable """ return quat_normalize(quat_mul(x, y)) @torch.jit.script def quat_rotate(rot, vec): """ Rotate a 3D vector with the 3D rotation """ other_q = torch.cat([vec, torch.zeros_like(vec[..., :1])], dim=-1) return quat_imaginary(quat_mul(quat_mul(rot, other_q), quat_conjugate(rot))) @torch.jit.script def quat_inverse(x): """ The inverse of the rotation """ return quat_conjugate(x) @torch.jit.script def quat_identity_like(x): """ Construct identity 3D rotation with the same shape """ return quat_identity(x.shape[:-1]) @torch.jit.script def quat_angle_axis(x): """ The (angle, axis) representation of the rotation. The axis is normalized to unit length. The angle is guaranteed to be between [0, pi]. """ s = 2 * (x[..., 3] ** 2) - 1 angle = s.clamp(-1, 1).arccos() # just to be safe axis = x[..., :3] axis /= axis.norm(p=2, dim=-1, keepdim=True).clamp(min=1e-9) return angle, axis @torch.jit.script def quat_yaw_rotation(x, z_up: bool = True): """ Yaw rotation (rotation along z-axis) """ q = x if z_up: q = torch.cat([torch.zeros_like(q[..., 0:2]), q[..., 2:3], q[..., 3:]], dim=-1) else: q = torch.cat( [ torch.zeros_like(q[..., 0:1]), q[..., 1:2], torch.zeros_like(q[..., 2:3]), q[..., 3:4], ], dim=-1, ) return quat_normalize(q) @torch.jit.script def transform_from_rotation_translation( r: Optional[torch.Tensor] = None, t: Optional[torch.Tensor] = None ): """ Construct a transform from a quaternion and 3D translation. Only one of them can be None. """ assert r is not None or t is not None, "rotation and translation can't be all None" if r is None: assert t is not None r = quat_identity(list(t.shape)) if t is None: t = torch.zeros(list(r.shape) + [3]) return torch.cat([r, t], dim=-1) @torch.jit.script def transform_identity(shape: List[int]): """ Identity transformation with given shape """ r = quat_identity(shape) t = torch.zeros(shape + [3]) return transform_from_rotation_translation(r, t) @torch.jit.script def transform_rotation(x): """Get rotation from transform""" return x[..., :4] @torch.jit.script def transform_translation(x): """Get translation from transform""" return x[..., 4:] @torch.jit.script def transform_inverse(x): """ Inverse transformation """ inv_so3 = quat_inverse(transform_rotation(x)) return transform_from_rotation_translation( r=inv_so3, t=quat_rotate(inv_so3, -transform_translation(x)) ) @torch.jit.script def transform_identity_like(x): """ identity transformation with the same shape """ return transform_identity(x.shape) @torch.jit.script def transform_mul(x, y): """ Combine two transformation together """ z = transform_from_rotation_translation( r=quat_mul_norm(transform_rotation(x), transform_rotation(y)), t=quat_rotate(transform_rotation(x), transform_translation(y)) + transform_translation(x), ) return z @torch.jit.script def transform_apply(rot, vec): """ Transform a 3D vector """ assert isinstance(vec, torch.Tensor) return quat_rotate(transform_rotation(rot), vec) + transform_translation(rot) @torch.jit.script def rot_matrix_det(x): """ Return the determinant of the 3x3 matrix. The shape of the tensor will be as same as the shape of the matrix """ a, b, c = x[..., 0, 0], x[..., 0, 1], x[..., 0, 2] d, e, f = x[..., 1, 0], x[..., 1, 1], x[..., 1, 2] g, h, i = x[..., 2, 0], x[..., 2, 1], x[..., 2, 2] t1 = a * (e * i - f * h) t2 = b * (d * i - f * g) t3 = c * (d * h - e * g) return t1 - t2 + t3 @torch.jit.script def rot_matrix_integrity_check(x): """ Verify that a rotation matrix has a determinant of one and is orthogonal """ det = rot_matrix_det(x) assert bool((abs(det - 1) < 1e-3).all()), "the matrix has non-one determinant" rtr = x @ x.permute(torch.arange(x.dim() - 2), -1, -2) rtr_gt = rtr.zeros_like() rtr_gt[..., 0, 0] = 1 rtr_gt[..., 1, 1] = 1 rtr_gt[..., 2, 2] = 1 assert bool(((rtr - rtr_gt) < 1e-3).all()), "the matrix is not orthogonal" @torch.jit.script def rot_matrix_from_quaternion(q): """ Construct rotation matrix from quaternion """ # Shortcuts for individual elements (using wikipedia's convention) qi, qj, qk, qr = q[..., 0], q[..., 1], q[..., 2], q[..., 3] # Set individual elements R00 = 1.0 - 2.0 * (qj ** 2 + qk ** 2) R01 = 2 * (qi * qj - qk * qr) R02 = 2 * (qi * qk + qj * qr) R10 = 2 * (qi * qj + qk * qr) R11 = 1.0 - 2.0 * (qi ** 2 + qk ** 2) R12 = 2 * (qj * qk - qi * qr) R20 = 2 * (qi * qk - qj * qr) R21 = 2 * (qj * qk + qi * qr) R22 = 1.0 - 2.0 * (qi ** 2 + qj ** 2) R0 = torch.stack([R00, R01, R02], dim=-1) R1 = torch.stack([R10, R11, R12], dim=-1) R2 = torch.stack([R10, R21, R22], dim=-1) R = torch.stack([R0, R1, R2], dim=-2) return R @torch.jit.script def euclidean_to_rotation_matrix(x): """ Get the rotation matrix on the top-left corner of a Euclidean transformation matrix """ return x[..., :3, :3] @torch.jit.script def euclidean_integrity_check(x): euclidean_to_rotation_matrix(x) # check 3d-rotation matrix assert bool((x[..., 3, :3] == 0).all()), "the last row is illegal" assert bool((x[..., 3, 3] == 1).all()), "the last row is illegal" @torch.jit.script def euclidean_translation(x): """ Get the translation vector located at the last column of the matrix """ return x[..., :3, 3] @torch.jit.script def euclidean_inverse(x): """ Compute the matrix that represents the inverse rotation """ s = x.zeros_like() irot = quat_inverse(quat_from_rotation_matrix(x)) s[..., :3, :3] = irot s[..., :3, 4] = quat_rotate(irot, -euclidean_translation(x)) return s @torch.jit.script def euclidean_to_transform(transformation_matrix): """ Construct a transform from a Euclidean transformation matrix """ return transform_from_rotation_translation( r=quat_from_rotation_matrix( m=euclidean_to_rotation_matrix(transformation_matrix) ), t=euclidean_translation(transformation_matrix), )
13,466
Python
27.471459
96
0.582207
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/tensor_utils.py
# Copyright (c) 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. from collections import OrderedDict from .backend import Serializable import torch class TensorUtils(Serializable): @classmethod def from_dict(cls, dict_repr, *args, **kwargs): """ Read the object from an ordered dictionary :param dict_repr: the ordered dictionary that is used to construct the object :type dict_repr: OrderedDict :param kwargs: the arguments that need to be passed into from_dict() :type kwargs: additional arguments """ return torch.from_numpy(dict_repr["arr"].astype(dict_repr["context"]["dtype"])) def to_dict(self): """ Construct an ordered dictionary from the object :rtype: OrderedDict """ return NotImplemented def tensor_to_dict(x): """ Construct an ordered dictionary from the object :rtype: OrderedDict """ x_np = x.numpy() return { "arr": x_np, "context": { "dtype": x_np.dtype.name } }
1,420
Python
31.295454
87
0.674648
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/backend/abstract.py
# Copyright (c) 2018-2023, 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 ABCMeta, abstractmethod, abstractclassmethod from collections import OrderedDict import json import numpy as np import os TENSOR_CLASS = {} def register(name): global TENSOR_CLASS def core(tensor_cls): TENSOR_CLASS[name] = tensor_cls return tensor_cls return core def _get_cls(name): global TENSOR_CLASS return TENSOR_CLASS[name] class NumpyEncoder(json.JSONEncoder): """ Special json encoder for numpy types """ def default(self, obj): if isinstance( obj, ( np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, ), ): return int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) elif isinstance(obj, (np.ndarray,)): return dict(__ndarray__=obj.tolist(), dtype=str(obj.dtype), shape=obj.shape) return json.JSONEncoder.default(self, obj) def json_numpy_obj_hook(dct): if isinstance(dct, dict) and "__ndarray__" in dct: data = np.asarray(dct["__ndarray__"], dtype=dct["dtype"]) return data.reshape(dct["shape"]) return dct class Serializable: """ Implementation to read/write to file. All class the is inherited from this class needs to implement to_dict() and from_dict() """ @abstractclassmethod def from_dict(cls, dict_repr, *args, **kwargs): """ Read the object from an ordered dictionary :param dict_repr: the ordered dictionary that is used to construct the object :type dict_repr: OrderedDict :param args, kwargs: the arguments that need to be passed into from_dict() :type args, kwargs: additional arguments """ pass @abstractmethod def to_dict(self): """ Construct an ordered dictionary from the object :rtype: OrderedDict """ pass @classmethod def from_file(cls, path, *args, **kwargs): """ Read the object from a file (either .npy or .json) :param path: path of the file :type path: string :param args, kwargs: the arguments that need to be passed into from_dict() :type args, kwargs: additional arguments """ if path.endswith(".json"): with open(path, "r") as f: d = json.load(f, object_hook=json_numpy_obj_hook) elif path.endswith(".npy"): d = np.load(path, allow_pickle=True).item() else: assert False, "failed to load {} from {}".format(cls.__name__, path) assert d["__name__"] == cls.__name__, "the file belongs to {}, not {}".format( d["__name__"], cls.__name__ ) return cls.from_dict(d, *args, **kwargs) def to_file(self, path: str) -> None: """ Write the object to a file (either .npy or .json) :param path: path of the file :type path: string """ if os.path.dirname(path) != "" and not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) d = self.to_dict() d["__name__"] = self.__class__.__name__ if path.endswith(".json"): with open(path, "w") as f: json.dump(d, f, cls=NumpyEncoder, indent=4) elif path.endswith(".npy"): np.save(path, d)
5,159
Python
33.172185
88
0.622795
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/backend/__init__.py
# Copyright (c) 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. from .abstract import Serializable from .logger import logger
488
Python
43.454542
76
0.815574
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/backend/logger.py
# Copyright (c) 2018-2023, 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 logging logger = logging.getLogger("poselib") logger.setLevel(logging.INFO) if not len(logger.handlers): formatter = logging.Formatter( fmt="%(asctime)-15s - %(levelname)s - %(module)s - %(message)s" ) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) logger.info("logger initialized")
1,930
Python
43.906976
80
0.766321
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/tests/test_rotation.py
# Copyright (c) 2018-2023, 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 ..rotation3d import * import numpy as np import torch q = torch.from_numpy(np.array([[0, 1, 2, 3], [-2, 3, -1, 5]], dtype=np.float32)) print("q", q) r = quat_normalize(q) x = torch.from_numpy(np.array([[1, 0, 0], [0, -1, 0]], dtype=np.float32)) print(r) print(quat_rotate(r, x)) angle = torch.from_numpy(np.array(np.random.rand() * 10.0, dtype=np.float32)) axis = torch.from_numpy( np.array([1, np.random.rand() * 10.0, np.random.rand() * 10.0], dtype=np.float32), ) print(repr(angle)) print(repr(axis)) rot = quat_from_angle_axis(angle, axis) x = torch.from_numpy(np.random.rand(5, 6, 3)) y = quat_rotate(quat_inverse(rot), quat_rotate(rot, x)) print(x.numpy()) print(y.numpy()) assert np.allclose(x.numpy(), y.numpy()) m = torch.from_numpy(np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=np.float32)) r = quat_from_rotation_matrix(m) t = torch.from_numpy(np.array([0, 1, 0], dtype=np.float32)) se3 = transform_from_rotation_translation(r=r, t=t) print(se3) print(transform_apply(se3, t)) rot = quat_from_angle_axis( torch.from_numpy(np.array([45, -54], dtype=np.float32)), torch.from_numpy(np.array([[1, 0, 0], [0, 1, 0]], dtype=np.float32)), degree=True, ) trans = torch.from_numpy(np.array([[1, 1, 0], [1, 1, 0]], dtype=np.float32)) transform = transform_from_rotation_translation(r=rot, t=trans) t = transform_mul(transform, transform_inverse(transform)) gt = np.zeros((2, 7)) gt[:, 0] = 1.0 print(t.numpy()) print(gt) # assert np.allclose(t.numpy(), gt) transform2 = torch.from_numpy( np.array( [[1, 0, 0, 1], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=np.float32 ), ) transform2 = euclidean_to_transform(transform2) print(transform2)
3,256
Python
37.317647
86
0.707924
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/core/tests/__init__.py
# Copyright (c) 2018-2023, 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.
1,557
Python
56.703702
80
0.784843
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/skeleton/__init__.py
# Copyright (c) 2018-2023, 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.
1,557
Python
56.703702
80
0.784843
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/skeleton/skeleton3d.py
# Copyright (c) 2018-2023, 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 xml.etree.ElementTree as ET from collections import OrderedDict from typing import List, Optional, Type, Dict import numpy as np import torch from ..core import * from .backend.fbx.fbx_read_wrapper import fbx_to_array import scipy.ndimage.filters as filters class SkeletonTree(Serializable): """ A skeleton tree gives a complete description of a rigid skeleton. It describes a tree structure over a list of nodes with their names indicated by strings. Each edge in the tree has a local translation associated with it which describes the distance between the two nodes that it connects. Basic Usage: >>> t = SkeletonTree.from_mjcf(SkeletonTree.__example_mjcf_path__) >>> t SkeletonTree( node_names=['torso', 'front_left_leg', 'aux_1', 'front_left_foot', 'front_right_leg', 'aux_2', 'front_right_foot', 'left_back_leg', 'aux_3', 'left_back_foot', 'right_back_leg', 'aux_4', 'right_back_foot'], parent_indices=tensor([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11]), local_translation=tensor([[ 0.0000, 0.0000, 0.7500], [ 0.0000, 0.0000, 0.0000], [ 0.2000, 0.2000, 0.0000], [ 0.2000, 0.2000, 0.0000], [ 0.0000, 0.0000, 0.0000], [-0.2000, 0.2000, 0.0000], [-0.2000, 0.2000, 0.0000], [ 0.0000, 0.0000, 0.0000], [-0.2000, -0.2000, 0.0000], [-0.2000, -0.2000, 0.0000], [ 0.0000, 0.0000, 0.0000], [ 0.2000, -0.2000, 0.0000], [ 0.2000, -0.2000, 0.0000]]) ) >>> t.node_names ['torso', 'front_left_leg', 'aux_1', 'front_left_foot', 'front_right_leg', 'aux_2', 'front_right_foot', 'left_back_leg', 'aux_3', 'left_back_foot', 'right_back_leg', 'aux_4', 'right_back_foot'] >>> t.parent_indices tensor([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11]) >>> t.local_translation tensor([[ 0.0000, 0.0000, 0.7500], [ 0.0000, 0.0000, 0.0000], [ 0.2000, 0.2000, 0.0000], [ 0.2000, 0.2000, 0.0000], [ 0.0000, 0.0000, 0.0000], [-0.2000, 0.2000, 0.0000], [-0.2000, 0.2000, 0.0000], [ 0.0000, 0.0000, 0.0000], [-0.2000, -0.2000, 0.0000], [-0.2000, -0.2000, 0.0000], [ 0.0000, 0.0000, 0.0000], [ 0.2000, -0.2000, 0.0000], [ 0.2000, -0.2000, 0.0000]]) >>> t.parent_of('front_left_leg') 'torso' >>> t.index('front_right_foot') 6 >>> t[2] 'aux_1' """ __example_mjcf_path__ = os.path.join( os.path.dirname(os.path.realpath(__file__)), "tests/ant.xml" ) def __init__(self, node_names, parent_indices, local_translation): """ :param node_names: a list of names for each tree node :type node_names: List[str] :param parent_indices: an int32-typed tensor that represents the edge to its parent.\ -1 represents the root node :type parent_indices: Tensor :param local_translation: a 3d vector that gives local translation information :type local_translation: Tensor """ ln, lp, ll = len(node_names), len(parent_indices), len(local_translation) assert len(set((ln, lp, ll))) == 1 self._node_names = node_names self._parent_indices = parent_indices.long() self._local_translation = local_translation self._node_indices = {self.node_names[i]: i for i in range(len(self))} def __len__(self): """ number of nodes in the skeleton tree """ return len(self.node_names) def __iter__(self): """ iterator that iterate through the name of each node """ yield from self.node_names def __getitem__(self, item): """ get the name of the node given the index """ return self.node_names[item] def __repr__(self): return ( "SkeletonTree(\n node_names={},\n parent_indices={}," "\n local_translation={}\n)".format( self._indent(repr(self.node_names)), self._indent(repr(self.parent_indices)), self._indent(repr(self.local_translation)), ) ) def _indent(self, s): return "\n ".join(s.split("\n")) @property def node_names(self): return self._node_names @property def parent_indices(self): return self._parent_indices @property def local_translation(self): return self._local_translation @property def num_joints(self): """ number of nodes in the skeleton tree """ return len(self) @classmethod def from_dict(cls, dict_repr, *args, **kwargs): return cls( list(map(str, dict_repr["node_names"])), TensorUtils.from_dict(dict_repr["parent_indices"], *args, **kwargs), TensorUtils.from_dict(dict_repr["local_translation"], *args, **kwargs), ) def to_dict(self): return OrderedDict( [ ("node_names", self.node_names), ("parent_indices", tensor_to_dict(self.parent_indices)), ("local_translation", tensor_to_dict(self.local_translation)), ] ) @classmethod def from_mjcf(cls, path: str) -> "SkeletonTree": """ Parses a mujoco xml scene description file and returns a Skeleton Tree. We use the model attribute at the root as the name of the tree. :param path: :type path: string :return: The skeleton tree constructed from the mjcf file :rtype: SkeletonTree """ tree = ET.parse(path) xml_doc_root = tree.getroot() xml_world_body = xml_doc_root.find("worldbody") if xml_world_body is None: raise ValueError("MJCF parsed incorrectly please verify it.") # assume this is the root xml_body_root = xml_world_body.find("body") if xml_body_root is None: raise ValueError("MJCF parsed incorrectly please verify it.") node_names = [] parent_indices = [] local_translation = [] # recursively adding all nodes into the skel_tree def _add_xml_node(xml_node, parent_index, node_index): node_name = xml_node.attrib.get("name") # parse the local translation into float list pos = np.fromstring(xml_node.attrib.get("pos"), dtype=float, sep=" ") node_names.append(node_name) parent_indices.append(parent_index) local_translation.append(pos) curr_index = node_index node_index += 1 for next_node in xml_node.findall("body"): node_index = _add_xml_node(next_node, curr_index, node_index) return node_index _add_xml_node(xml_body_root, -1, 0) return cls( node_names, torch.from_numpy(np.array(parent_indices, dtype=np.int32)), torch.from_numpy(np.array(local_translation, dtype=np.float32)), ) def parent_of(self, node_name): """ get the name of the parent of the given node :param node_name: the name of the node :type node_name: string :rtype: string """ return self[int(self.parent_indices[self.index(node_name)].item())] def index(self, node_name): """ get the index of the node :param node_name: the name of the node :type node_name: string :rtype: int """ return self._node_indices[node_name] def drop_nodes_by_names( self, node_names: List[str], pairwise_translation=None ) -> "SkeletonTree": new_length = len(self) - len(node_names) new_node_names = [] new_local_translation = torch.zeros( new_length, 3, dtype=self.local_translation.dtype ) new_parent_indices = torch.zeros(new_length, dtype=self.parent_indices.dtype) parent_indices = self.parent_indices.numpy() new_node_indices: dict = {} new_node_index = 0 for node_index in range(len(self)): if self[node_index] in node_names: continue tb_node_index = parent_indices[node_index] if tb_node_index != -1: local_translation = self.local_translation[node_index, :] while tb_node_index != -1 and self[tb_node_index] in node_names: local_translation += self.local_translation[tb_node_index, :] tb_node_index = parent_indices[tb_node_index] assert tb_node_index != -1, "the root node cannot be dropped" if pairwise_translation is not None: local_translation = pairwise_translation[ tb_node_index, node_index, : ] else: local_translation = self.local_translation[node_index, :] new_node_names.append(self[node_index]) new_local_translation[new_node_index, :] = local_translation if tb_node_index == -1: new_parent_indices[new_node_index] = -1 else: new_parent_indices[new_node_index] = new_node_indices[ self[tb_node_index] ] new_node_indices[self[node_index]] = new_node_index new_node_index += 1 return SkeletonTree(new_node_names, new_parent_indices, new_local_translation) def keep_nodes_by_names( self, node_names: List[str], pairwise_translation=None ) -> "SkeletonTree": nodes_to_drop = list(filter(lambda x: x not in node_names, self)) return self.drop_nodes_by_names(nodes_to_drop, pairwise_translation) class SkeletonState(Serializable): """ A skeleton state contains all the information needed to describe a static state of a skeleton. It requires a skeleton tree, local/global rotation at each joint and the root translation. Example: >>> t = SkeletonTree.from_mjcf(SkeletonTree.__example_mjcf_path__) >>> zero_pose = SkeletonState.zero_pose(t) >>> plot_skeleton_state(zero_pose) # can be imported from `.visualization.common` [plot of the ant at zero pose >>> local_rotation = zero_pose.local_rotation.clone() >>> local_rotation[2] = torch.tensor([0, 0, 1, 0]) >>> new_pose = SkeletonState.from_rotation_and_root_translation( ... skeleton_tree=t, ... r=local_rotation, ... t=zero_pose.root_translation, ... is_local=True ... ) >>> new_pose.local_rotation tensor([[0., 0., 0., 1.], [0., 0., 0., 1.], [0., 1., 0., 0.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.]]) >>> plot_skeleton_state(new_pose) # you should be able to see one of ant's leg is bent [plot of the ant with the new pose >>> new_pose.global_rotation # the local rotation is propagated to the global rotation at joint #3 tensor([[0., 0., 0., 1.], [0., 0., 0., 1.], [0., 1., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.], [0., 0., 0., 1.]]) Global/Local Representation (cont. from the previous example) >>> new_pose.is_local True >>> new_pose.tensor # this will return the local rotation followed by the root translation tensor([0., 0., 0., 1., 0., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0.]) >>> new_pose.tensor.shape # 4 * 13 (joint rotation) + 3 (root translatio torch.Size([55]) >>> new_pose.global_repr().is_local False >>> new_pose.global_repr().tensor # this will return the global rotation followed by the root translation instead tensor([0., 0., 0., 1., 0., 0., 0., 1., 0., 1., 0., 0., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0.]) >>> new_pose.global_repr().tensor.shape # 4 * 13 (joint rotation) + 3 (root translation torch.Size([55]) """ def __init__(self, tensor_backend, skeleton_tree, is_local): self._skeleton_tree = skeleton_tree self._is_local = is_local self.tensor = tensor_backend.clone() def __len__(self): return self.tensor.shape[0] @property def rotation(self): if not hasattr(self, "_rotation"): self._rotation = self.tensor[..., : self.num_joints * 4].reshape( *(self.tensor.shape[:-1] + (self.num_joints, 4)) ) return self._rotation @property def _local_rotation(self): if self._is_local: return self.rotation else: return None @property def _global_rotation(self): if not self._is_local: return self.rotation else: return None @property def is_local(self): """ is the rotation represented in local frame? :rtype: bool """ return self._is_local @property def invariant_property(self): return {"skeleton_tree": self.skeleton_tree, "is_local": self.is_local} @property def num_joints(self): """ number of joints in the skeleton tree :rtype: int """ return self.skeleton_tree.num_joints @property def skeleton_tree(self): """ skeleton tree :rtype: SkeletonTree """ return self._skeleton_tree @property def root_translation(self): """ root translation :rtype: Tensor """ if not hasattr(self, "_root_translation"): self._root_translation = self.tensor[ ..., self.num_joints * 4 : self.num_joints * 4 + 3 ] return self._root_translation @property def global_transformation(self): """ global transformation of each joint (transform from joint frame to global frame) """ if not hasattr(self, "_global_transformation"): local_transformation = self.local_transformation global_transformation = [] parent_indices = self.skeleton_tree.parent_indices.numpy() # global_transformation = local_transformation.identity_like() for node_index in range(len(self.skeleton_tree)): parent_index = parent_indices[node_index] if parent_index == -1: global_transformation.append( local_transformation[..., node_index, :] ) else: global_transformation.append( transform_mul( global_transformation[parent_index], local_transformation[..., node_index, :], ) ) self._global_transformation = torch.stack(global_transformation, axis=-2) return self._global_transformation @property def global_rotation(self): """ global rotation of each joint (rotation matrix to rotate from joint's F.O.R to global F.O.R) """ if self._global_rotation is None: if not hasattr(self, "_comp_global_rotation"): self._comp_global_rotation = transform_rotation( self.global_transformation ) return self._comp_global_rotation else: return self._global_rotation @property def global_translation(self): """ global translation of each joint """ if not hasattr(self, "_global_translation"): self._global_translation = transform_translation(self.global_transformation) return self._global_translation @property def global_translation_xy(self): """ global translation in xy """ trans_xy_data = self.global_translation.zeros_like() trans_xy_data[..., 0:2] = self.global_translation[..., 0:2] return trans_xy_data @property def global_translation_xz(self): """ global translation in xz """ trans_xz_data = self.global_translation.zeros_like() trans_xz_data[..., 0:1] = self.global_translation[..., 0:1] trans_xz_data[..., 2:3] = self.global_translation[..., 2:3] return trans_xz_data @property def local_rotation(self): """ the rotation from child frame to parent frame given in the order of child nodes appeared in `.skeleton_tree.node_names` """ if self._local_rotation is None: if not hasattr(self, "_comp_local_rotation"): local_rotation = quat_identity_like(self.global_rotation) for node_index in range(len(self.skeleton_tree)): parent_index = self.skeleton_tree.parent_indices[node_index] if parent_index == -1: local_rotation[..., node_index, :] = self.global_rotation[ ..., node_index, : ] else: local_rotation[..., node_index, :] = quat_mul_norm( quat_inverse(self.global_rotation[..., parent_index, :]), self.global_rotation[..., node_index, :], ) self._comp_local_rotation = local_rotation return self._comp_local_rotation else: return self._local_rotation @property def local_transformation(self): """ local translation + local rotation. It describes the transformation from child frame to parent frame given in the order of child nodes appeared in `.skeleton_tree.node_names` """ if not hasattr(self, "_local_transformation"): self._local_transformation = transform_from_rotation_translation( r=self.local_rotation, t=self.local_translation ) return self._local_transformation @property def local_translation(self): """ local translation of the skeleton state. It is identical to the local translation in `.skeleton_tree.local_translation` except the root translation. The root translation is identical to `.root_translation` """ if not hasattr(self, "_local_translation"): broadcast_shape = ( tuple(self.tensor.shape[:-1]) + (len(self.skeleton_tree),) + tuple(self.skeleton_tree.local_translation.shape[-1:]) ) local_translation = self.skeleton_tree.local_translation.broadcast_to( *broadcast_shape ).clone() local_translation[..., 0, :] = self.root_translation self._local_translation = local_translation return self._local_translation # Root Properties @property def root_translation_xy(self): """ root translation on xy """ if not hasattr(self, "_root_translation_xy"): self._root_translation_xy = self.global_translation_xy[..., 0, :] return self._root_translation_xy @property def global_root_rotation(self): """ root rotation """ if not hasattr(self, "_global_root_rotation"): self._global_root_rotation = self.global_rotation[..., 0, :] return self._global_root_rotation @property def global_root_yaw_rotation(self): """ root yaw rotation """ if not hasattr(self, "_global_root_yaw_rotation"): self._global_root_yaw_rotation = self.global_root_rotation.yaw_rotation() return self._global_root_yaw_rotation # Properties relative to root @property def local_translation_to_root(self): """ The 3D translation from joint frame to the root frame. """ if not hasattr(self, "_local_translation_to_root"): self._local_translation_to_root = ( self.global_translation - self.root_translation.unsqueeze(-1) ) return self._local_translation_to_root @property def local_rotation_to_root(self): """ The 3D rotation from joint frame to the root frame. It is equivalent to The root_R_world * world_R_node """ return ( quat_inverse(self.global_root_rotation).unsqueeze(-1) * self.global_rotation ) def compute_forward_vector( self, left_shoulder_index, right_shoulder_index, left_hip_index, right_hip_index, gaussian_filter_width=20, ): """ Computes forward vector based on cross product of the up vector with average of the right->left shoulder and hip vectors """ global_positions = self.global_translation # Perpendicular to the forward direction. # Uses the shoulders and hips to find this. side_direction = ( global_positions[:, left_shoulder_index].numpy() - global_positions[:, right_shoulder_index].numpy() + global_positions[:, left_hip_index].numpy() - global_positions[:, right_hip_index].numpy() ) side_direction = ( side_direction / np.sqrt((side_direction ** 2).sum(axis=-1))[..., np.newaxis] ) # Forward direction obtained by crossing with the up direction. forward_direction = np.cross(side_direction, np.array([[0, 1, 0]])) # Smooth the forward direction with a Gaussian. # Axis 0 is the time/frame axis. forward_direction = filters.gaussian_filter1d( forward_direction, gaussian_filter_width, axis=0, mode="nearest" ) forward_direction = ( forward_direction / np.sqrt((forward_direction ** 2).sum(axis=-1))[..., np.newaxis] ) return torch.from_numpy(forward_direction) @staticmethod def _to_state_vector(rot, rt): state_shape = rot.shape[:-2] vr = rot.reshape(*(state_shape + (-1,))) vt = rt.broadcast_to(*state_shape + rt.shape[-1:]).reshape( *(state_shape + (-1,)) ) v = torch.cat([vr, vt], axis=-1) return v @classmethod def from_dict( cls: Type["SkeletonState"], dict_repr: OrderedDict, *args, **kwargs ) -> "SkeletonState": rot = TensorUtils.from_dict(dict_repr["rotation"], *args, **kwargs) rt = TensorUtils.from_dict(dict_repr["root_translation"], *args, **kwargs) return cls( SkeletonState._to_state_vector(rot, rt), SkeletonTree.from_dict(dict_repr["skeleton_tree"], *args, **kwargs), dict_repr["is_local"], ) def to_dict(self) -> OrderedDict: return OrderedDict( [ ("rotation", tensor_to_dict(self.rotation)), ("root_translation", tensor_to_dict(self.root_translation)), ("skeleton_tree", self.skeleton_tree.to_dict()), ("is_local", self.is_local), ] ) @classmethod def from_rotation_and_root_translation(cls, skeleton_tree, r, t, is_local=True): """ Construct a skeleton state from rotation and root translation :param skeleton_tree: the skeleton tree :type skeleton_tree: SkeletonTree :param r: rotation (either global or local) :type r: Tensor :param t: root translation :type t: Tensor :param is_local: to indicate that whether the rotation is local or global :type is_local: bool, optional, default=True """ assert ( r.dim() > 0 ), "the rotation needs to have at least 1 dimension (dim = {})".format(r.dim) return cls( SkeletonState._to_state_vector(r, t), skeleton_tree=skeleton_tree, is_local=is_local, ) @classmethod def zero_pose(cls, skeleton_tree): """ Construct a zero-pose skeleton state from the skeleton tree by assuming that all the local rotation is 0 and root translation is also 0. :param skeleton_tree: the skeleton tree as the rigid body :type skeleton_tree: SkeletonTree """ return cls.from_rotation_and_root_translation( skeleton_tree=skeleton_tree, r=quat_identity([skeleton_tree.num_joints]), t=torch.zeros(3, dtype=skeleton_tree.local_translation.dtype), is_local=True, ) def local_repr(self): """ Convert the skeleton state into local representation. This will only affects the values of .tensor. If the skeleton state already has `is_local=True`. This method will do nothing. :rtype: SkeletonState """ if self.is_local: return self return SkeletonState.from_rotation_and_root_translation( self.skeleton_tree, r=self.local_rotation, t=self.root_translation, is_local=True, ) def global_repr(self): """ Convert the skeleton state into global representation. This will only affects the values of .tensor. If the skeleton state already has `is_local=False`. This method will do nothing. :rtype: SkeletonState """ if not self.is_local: return self return SkeletonState.from_rotation_and_root_translation( self.skeleton_tree, r=self.global_rotation, t=self.root_translation, is_local=False, ) def _get_pairwise_average_translation(self): global_transform_inv = transform_inverse(self.global_transformation) p1 = global_transform_inv.unsqueeze(-2) p2 = self.global_transformation.unsqueeze(-3) pairwise_translation = ( transform_translation(transform_mul(p1, p2)) .reshape(-1, len(self.skeleton_tree), len(self.skeleton_tree), 3) .mean(axis=0) ) return pairwise_translation def _transfer_to(self, new_skeleton_tree: SkeletonTree): old_indices = list(map(self.skeleton_tree.index, new_skeleton_tree)) return SkeletonState.from_rotation_and_root_translation( new_skeleton_tree, r=self.global_rotation[..., old_indices, :], t=self.root_translation, is_local=False, ) def drop_nodes_by_names( self, node_names: List[str], estimate_local_translation_from_states: bool = True ) -> "SkeletonState": """ Drop a list of nodes from the skeleton and re-compute the local rotation to match the original joint position as much as possible. :param node_names: a list node names that specifies the nodes need to be dropped :type node_names: List of strings :param estimate_local_translation_from_states: the boolean indicator that specifies whether\ or not to re-estimate the local translation from the states (avg.) :type estimate_local_translation_from_states: boolean :rtype: SkeletonState """ if estimate_local_translation_from_states: pairwise_translation = self._get_pairwise_average_translation() else: pairwise_translation = None new_skeleton_tree = self.skeleton_tree.drop_nodes_by_names( node_names, pairwise_translation ) return self._transfer_to(new_skeleton_tree) def keep_nodes_by_names( self, node_names: List[str], estimate_local_translation_from_states: bool = True ) -> "SkeletonState": """ Keep a list of nodes and drop all other nodes from the skeleton and re-compute the local rotation to match the original joint position as much as possible. :param node_names: a list node names that specifies the nodes need to be dropped :type node_names: List of strings :param estimate_local_translation_from_states: the boolean indicator that specifies whether\ or not to re-estimate the local translation from the states (avg.) :type estimate_local_translation_from_states: boolean :rtype: SkeletonState """ return self.drop_nodes_by_names( list(filter(lambda x: (x not in node_names), self)), estimate_local_translation_from_states, ) def _remapped_to( self, joint_mapping: Dict[str, str], target_skeleton_tree: SkeletonTree ): joint_mapping_inv = {target: source for source, target in joint_mapping.items()} reduced_target_skeleton_tree = target_skeleton_tree.keep_nodes_by_names( list(joint_mapping_inv) ) n_joints = ( len(joint_mapping), len(self.skeleton_tree), len(reduced_target_skeleton_tree), ) assert ( len(set(n_joints)) == 1 ), "the joint mapping is not consistent with the skeleton trees" source_indices = list( map( lambda x: self.skeleton_tree.index(joint_mapping_inv[x]), reduced_target_skeleton_tree, ) ) target_local_rotation = self.local_rotation[..., source_indices, :] return SkeletonState.from_rotation_and_root_translation( skeleton_tree=reduced_target_skeleton_tree, r=target_local_rotation, t=self.root_translation, is_local=True, ) def retarget_to( self, joint_mapping: Dict[str, str], source_tpose_local_rotation, source_tpose_root_translation: np.ndarray, target_skeleton_tree: SkeletonTree, target_tpose_local_rotation, target_tpose_root_translation: np.ndarray, rotation_to_target_skeleton, scale_to_target_skeleton: float, z_up: bool = True, ) -> "SkeletonState": """ Retarget the skeleton state to a target skeleton tree. This is a naive retarget implementation with rough approximations. The function follows the procedures below. Steps: 1. Drop the joints from the source (self) that do not belong to the joint mapping\ with an implementation that is similar to "keep_nodes_by_names()" - take a\ look at the function doc for more details (same for source_tpose) 2. Rotate the source state and the source tpose by "rotation_to_target_skeleton"\ to align the source with the target orientation 3. Extract the root translation and normalize it to match the scale of the target\ skeleton 4. Extract the global rotation from source state relative to source tpose and\ re-apply the relative rotation to the target tpose to construct the global\ rotation after retargetting 5. Combine the computed global rotation and the root translation from 3 and 4 to\ complete the retargeting. 6. Make feet on the ground (global translation z) :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \ the target skeleton :type joint_mapping: Dict[str, str] :param source_tpose_local_rotation: the local rotation of the source skeleton :type source_tpose_local_rotation: Tensor :param source_tpose_root_translation: the root translation of the source tpose :type source_tpose_root_translation: np.ndarray :param target_skeleton_tree: the target skeleton tree :type target_skeleton_tree: SkeletonTree :param target_tpose_local_rotation: the local rotation of the target skeleton :type target_tpose_local_rotation: Tensor :param target_tpose_root_translation: the root translation of the target tpose :type target_tpose_root_translation: Tensor :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\ skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\ the frame of reference of the target skeleton and s is the frame of reference of the source\ skeleton :type rotation_to_target_skeleton: Tensor :param scale_to_target_skeleton: the factor that needs to be multiplied from source\ skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \ factor needs to be 0.01. :type scale_to_target_skeleton: float :rtype: SkeletonState """ # STEP 0: Preprocess source_tpose = SkeletonState.from_rotation_and_root_translation( skeleton_tree=self.skeleton_tree, r=source_tpose_local_rotation, t=source_tpose_root_translation, is_local=True, ) target_tpose = SkeletonState.from_rotation_and_root_translation( skeleton_tree=target_skeleton_tree, r=target_tpose_local_rotation, t=target_tpose_root_translation, is_local=True, ) # STEP 1: Drop the irrelevant joints pairwise_translation = self._get_pairwise_average_translation() node_names = list(joint_mapping) new_skeleton_tree = self.skeleton_tree.keep_nodes_by_names( node_names, pairwise_translation ) # TODO: combine the following steps before STEP 3 source_tpose = source_tpose._transfer_to(new_skeleton_tree) source_state = self._transfer_to(new_skeleton_tree) source_tpose = source_tpose._remapped_to(joint_mapping, target_skeleton_tree) source_state = source_state._remapped_to(joint_mapping, target_skeleton_tree) # STEP 2: Rotate the source to align with the target new_local_rotation = source_tpose.local_rotation.clone() new_local_rotation[..., 0, :] = quat_mul_norm( rotation_to_target_skeleton, source_tpose.local_rotation[..., 0, :] ) source_tpose = SkeletonState.from_rotation_and_root_translation( skeleton_tree=source_tpose.skeleton_tree, r=new_local_rotation, t=quat_rotate(rotation_to_target_skeleton, source_tpose.root_translation), is_local=True, ) new_local_rotation = source_state.local_rotation.clone() new_local_rotation[..., 0, :] = quat_mul_norm( rotation_to_target_skeleton, source_state.local_rotation[..., 0, :] ) source_state = SkeletonState.from_rotation_and_root_translation( skeleton_tree=source_state.skeleton_tree, r=new_local_rotation, t=quat_rotate(rotation_to_target_skeleton, source_state.root_translation), is_local=True, ) # STEP 3: Normalize to match the target scale root_translation_diff = ( source_state.root_translation - source_tpose.root_translation ) * scale_to_target_skeleton # STEP 4: the global rotation from source state relative to source tpose and # re-apply to the target current_skeleton_tree = source_state.skeleton_tree target_tpose_global_rotation = source_state.global_rotation[0, :].clone() for current_index, name in enumerate(current_skeleton_tree): if name in target_tpose.skeleton_tree: target_tpose_global_rotation[ current_index, : ] = target_tpose.global_rotation[ target_tpose.skeleton_tree.index(name), : ] global_rotation_diff = quat_mul_norm( source_state.global_rotation, quat_inverse(source_tpose.global_rotation) ) new_global_rotation = quat_mul_norm( global_rotation_diff, target_tpose_global_rotation ) # STEP 5: Putting 3 and 4 together current_skeleton_tree = source_state.skeleton_tree shape = source_state.global_rotation.shape[:-1] shape = shape[:-1] + target_tpose.global_rotation.shape[-2:-1] new_global_rotation_output = quat_identity(shape) for current_index, name in enumerate(target_skeleton_tree): while name not in current_skeleton_tree: name = target_skeleton_tree.parent_of(name) parent_index = current_skeleton_tree.index(name) new_global_rotation_output[:, current_index, :] = new_global_rotation[ :, parent_index, : ] source_state = SkeletonState.from_rotation_and_root_translation( skeleton_tree=target_skeleton_tree, r=new_global_rotation_output, t=target_tpose.root_translation + root_translation_diff, is_local=False, ).local_repr() return source_state def retarget_to_by_tpose( self, joint_mapping: Dict[str, str], source_tpose: "SkeletonState", target_tpose: "SkeletonState", rotation_to_target_skeleton, scale_to_target_skeleton: float, ) -> "SkeletonState": """ Retarget the skeleton state to a target skeleton tree. This is a naive retarget implementation with rough approximations. See the method `retarget_to()` for more information :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \ the target skeleton :type joint_mapping: Dict[str, str] :param source_tpose: t-pose of the source skeleton :type source_tpose: SkeletonState :param target_tpose: t-pose of the target skeleton :type target_tpose: SkeletonState :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\ skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\ the frame of reference of the target skeleton and s is the frame of reference of the source\ skeleton :type rotation_to_target_skeleton: Tensor :param scale_to_target_skeleton: the factor that needs to be multiplied from source\ skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \ factor needs to be 0.01. :type scale_to_target_skeleton: float :rtype: SkeletonState """ assert ( len(source_tpose.shape) == 0 and len(target_tpose.shape) == 0 ), "the retargeting script currently doesn't support vectorized operations" return self.retarget_to( joint_mapping, source_tpose.local_rotation, source_tpose.root_translation, target_tpose.skeleton_tree, target_tpose.local_rotation, target_tpose.root_translation, rotation_to_target_skeleton, scale_to_target_skeleton, ) class SkeletonMotion(SkeletonState): def __init__(self, tensor_backend, skeleton_tree, is_local, fps, *args, **kwargs): self._fps = fps super().__init__(tensor_backend, skeleton_tree, is_local, *args, **kwargs) def clone(self): return SkeletonMotion( self.tensor.clone(), self.skeleton_tree, self._is_local, self._fps ) @property def invariant_property(self): return { "skeleton_tree": self.skeleton_tree, "is_local": self.is_local, "fps": self.fps, } @property def global_velocity(self): """ global velocity """ curr_index = self.num_joints * 4 + 3 return self.tensor[..., curr_index : curr_index + self.num_joints * 3].reshape( *(self.tensor.shape[:-1] + (self.num_joints, 3)) ) @property def global_angular_velocity(self): """ global angular velocity """ curr_index = self.num_joints * 7 + 3 return self.tensor[..., curr_index : curr_index + self.num_joints * 3].reshape( *(self.tensor.shape[:-1] + (self.num_joints, 3)) ) @property def fps(self): """ number of frames per second """ return self._fps @property def time_delta(self): """ time between two adjacent frames """ return 1.0 / self.fps @property def global_root_velocity(self): """ global root velocity """ return self.global_velocity[..., 0, :] @property def global_root_angular_velocity(self): """ global root angular velocity """ return self.global_angular_velocity[..., 0, :] @classmethod def from_state_vector_and_velocity( cls, skeleton_tree, state_vector, global_velocity, global_angular_velocity, is_local, fps, ): """ Construct a skeleton motion from a skeleton state vector, global velocity and angular velocity at each joint. :param skeleton_tree: the skeleton tree that the motion is based on :type skeleton_tree: SkeletonTree :param state_vector: the state vector from the skeleton state by `.tensor` :type state_vector: Tensor :param global_velocity: the global velocity at each joint :type global_velocity: Tensor :param global_angular_velocity: the global angular velocity at each joint :type global_angular_velocity: Tensor :param is_local: if the rotation ins the state vector is given in local frame :type is_local: boolean :param fps: number of frames per second :type fps: int :rtype: SkeletonMotion """ state_shape = state_vector.shape[:-1] v = global_velocity.reshape(*(state_shape + (-1,))) av = global_angular_velocity.reshape(*(state_shape + (-1,))) new_state_vector = torch.cat([state_vector, v, av], axis=-1) return cls( new_state_vector, skeleton_tree=skeleton_tree, is_local=is_local, fps=fps, ) @classmethod def from_skeleton_state( cls: Type["SkeletonMotion"], skeleton_state: SkeletonState, fps: int ): """ Construct a skeleton motion from a skeleton state. The velocities are estimated using second order gaussian filter along the last axis. The skeleton state must have at least .dim >= 1 :param skeleton_state: the skeleton state that the motion is based on :type skeleton_state: SkeletonState :param fps: number of frames per second :type fps: int :rtype: SkeletonMotion """ assert ( type(skeleton_state) == SkeletonState ), "expected type of {}, got {}".format(SkeletonState, type(skeleton_state)) global_velocity = SkeletonMotion._compute_velocity( p=skeleton_state.global_translation, time_delta=1 / fps ) global_angular_velocity = SkeletonMotion._compute_angular_velocity( r=skeleton_state.global_rotation, time_delta=1 / fps ) return cls.from_state_vector_and_velocity( skeleton_tree=skeleton_state.skeleton_tree, state_vector=skeleton_state.tensor, global_velocity=global_velocity, global_angular_velocity=global_angular_velocity, is_local=skeleton_state.is_local, fps=fps, ) @staticmethod def _to_state_vector(rot, rt, vel, avel): state_shape = rot.shape[:-2] skeleton_state_v = SkeletonState._to_state_vector(rot, rt) v = vel.reshape(*(state_shape + (-1,))) av = avel.reshape(*(state_shape + (-1,))) skeleton_motion_v = torch.cat([skeleton_state_v, v, av], axis=-1) return skeleton_motion_v @classmethod def from_dict( cls: Type["SkeletonMotion"], dict_repr: OrderedDict, *args, **kwargs ) -> "SkeletonMotion": rot = TensorUtils.from_dict(dict_repr["rotation"], *args, **kwargs) rt = TensorUtils.from_dict(dict_repr["root_translation"], *args, **kwargs) vel = TensorUtils.from_dict(dict_repr["global_velocity"], *args, **kwargs) avel = TensorUtils.from_dict( dict_repr["global_angular_velocity"], *args, **kwargs ) return cls( SkeletonMotion._to_state_vector(rot, rt, vel, avel), skeleton_tree=SkeletonTree.from_dict( dict_repr["skeleton_tree"], *args, **kwargs ), is_local=dict_repr["is_local"], fps=dict_repr["fps"], ) def to_dict(self) -> OrderedDict: return OrderedDict( [ ("rotation", tensor_to_dict(self.rotation)), ("root_translation", tensor_to_dict(self.root_translation)), ("global_velocity", tensor_to_dict(self.global_velocity)), ("global_angular_velocity", tensor_to_dict(self.global_angular_velocity)), ("skeleton_tree", self.skeleton_tree.to_dict()), ("is_local", self.is_local), ("fps", self.fps), ] ) @classmethod def from_fbx( cls: Type["SkeletonMotion"], fbx_file_path, skeleton_tree=None, is_local=True, fps=120, root_joint="", root_trans_index=0, *args, **kwargs, ) -> "SkeletonMotion": """ Construct a skeleton motion from a fbx file (TODO - generalize this). If the skeleton tree is not given, it will use the first frame of the mocap to construct the skeleton tree. :param fbx_file_path: the path of the fbx file :type fbx_file_path: string :param fbx_configs: the configuration in terms of {"tmp_path": ..., "fbx_py27_path": ...} :type fbx_configs: dict :param skeleton_tree: the optional skeleton tree that the rotation will be applied to :type skeleton_tree: SkeletonTree, optional :param is_local: the state vector uses local or global rotation as the representation :type is_local: bool, optional, default=True :param fps: FPS of the FBX animation :type fps: int, optional, default=120 :param root_joint: the name of the root joint for the skeleton :type root_joint: string, optional, default="" or the first node in the FBX scene with animation data :param root_trans_index: index of joint to extract root transform from :type root_trans_index: int, optional, default=0 or the root joint in the parsed skeleton :rtype: SkeletonMotion """ joint_names, joint_parents, transforms, fps = fbx_to_array( fbx_file_path, root_joint, fps ) # swap the last two axis to match the convention local_transform = euclidean_to_transform( transformation_matrix=torch.from_numpy( np.swapaxes(np.array(transforms), -1, -2), ).float() ) local_rotation = transform_rotation(local_transform) root_translation = transform_translation(local_transform)[..., root_trans_index, :] joint_parents = torch.from_numpy(np.array(joint_parents)).int() if skeleton_tree is None: local_translation = transform_translation(local_transform).reshape( -1, len(joint_parents), 3 )[0] skeleton_tree = SkeletonTree(joint_names, joint_parents, local_translation) skeleton_state = SkeletonState.from_rotation_and_root_translation( skeleton_tree, r=local_rotation, t=root_translation, is_local=True ) if not is_local: skeleton_state = skeleton_state.global_repr() return cls.from_skeleton_state( skeleton_state=skeleton_state, fps=fps ) @staticmethod def _compute_velocity(p, time_delta, guassian_filter=True): velocity = torch.from_numpy( filters.gaussian_filter1d( np.gradient(p.numpy(), axis=-3), 2, axis=-3, mode="nearest" ) / time_delta, ) return velocity @staticmethod def _compute_angular_velocity(r, time_delta: float, guassian_filter=True): # assume the second last dimension is the time axis diff_quat_data = quat_identity_like(r) diff_quat_data[..., :-1, :, :] = quat_mul_norm( r[..., 1:, :, :], quat_inverse(r[..., :-1, :, :]) ) diff_angle, diff_axis = quat_angle_axis(diff_quat_data) angular_velocity = diff_axis * diff_angle.unsqueeze(-1) / time_delta angular_velocity = torch.from_numpy( filters.gaussian_filter1d( angular_velocity.numpy(), 2, axis=-3, mode="nearest" ), ) return angular_velocity def crop(self, start: int, end: int, fps: Optional[int] = None): """ Crop the motion along its last axis. This is equivalent to performing a slicing on the object with [..., start: end: skip_every] where skip_every = old_fps / fps. Note that the new fps provided must be a factor of the original fps. :param start: the beginning frame index :type start: int :param end: the ending frame index :type end: int :param fps: number of frames per second in the output (if not given the original fps will be used) :type fps: int, optional :rtype: SkeletonMotion """ if fps is None: new_fps = int(self.fps) old_fps = int(self.fps) else: new_fps = int(fps) old_fps = int(self.fps) assert old_fps % fps == 0, ( "the resampling doesn't support fps with non-integer division " "from the original fps: {} => {}".format(old_fps, fps) ) skip_every = old_fps // new_fps return SkeletonMotion.from_skeleton_state( SkeletonState.from_rotation_and_root_translation( skeleton_tree=self.skeleton_tree, t=self.root_translation[start:end:skip_every], r=self.local_rotation[start:end:skip_every], is_local=True ), fps=self.fps ) def retarget_to( self, joint_mapping: Dict[str, str], source_tpose_local_rotation, source_tpose_root_translation: np.ndarray, target_skeleton_tree: "SkeletonTree", target_tpose_local_rotation, target_tpose_root_translation: np.ndarray, rotation_to_target_skeleton, scale_to_target_skeleton: float, z_up: bool = True, ) -> "SkeletonMotion": """ Same as the one in :class:`SkeletonState`. This method discards all velocity information before retargeting and re-estimate the velocity after the retargeting. The same fps is used in the new retargetted motion. :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \ the target skeleton :type joint_mapping: Dict[str, str] :param source_tpose_local_rotation: the local rotation of the source skeleton :type source_tpose_local_rotation: Tensor :param source_tpose_root_translation: the root translation of the source tpose :type source_tpose_root_translation: np.ndarray :param target_skeleton_tree: the target skeleton tree :type target_skeleton_tree: SkeletonTree :param target_tpose_local_rotation: the local rotation of the target skeleton :type target_tpose_local_rotation: Tensor :param target_tpose_root_translation: the root translation of the target tpose :type target_tpose_root_translation: Tensor :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\ skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\ the frame of reference of the target skeleton and s is the frame of reference of the source\ skeleton :type rotation_to_target_skeleton: Tensor :param scale_to_target_skeleton: the factor that needs to be multiplied from source\ skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \ factor needs to be 0.01. :type scale_to_target_skeleton: float :rtype: SkeletonMotion """ return SkeletonMotion.from_skeleton_state( super().retarget_to( joint_mapping, source_tpose_local_rotation, source_tpose_root_translation, target_skeleton_tree, target_tpose_local_rotation, target_tpose_root_translation, rotation_to_target_skeleton, scale_to_target_skeleton, z_up, ), self.fps, ) def retarget_to_by_tpose( self, joint_mapping: Dict[str, str], source_tpose: "SkeletonState", target_tpose: "SkeletonState", rotation_to_target_skeleton, scale_to_target_skeleton: float, z_up: bool = True, ) -> "SkeletonMotion": """ Same as the one in :class:`SkeletonState`. This method discards all velocity information before retargeting and re-estimate the velocity after the retargeting. The same fps is used in the new retargetted motion. :param joint_mapping: a dictionary of that maps the joint node from the source skeleton to \ the target skeleton :type joint_mapping: Dict[str, str] :param source_tpose: t-pose of the source skeleton :type source_tpose: SkeletonState :param target_tpose: t-pose of the target skeleton :type target_tpose: SkeletonState :param rotation_to_target_skeleton: the rotation that needs to be applied to the source\ skeleton to align with the target skeleton. Essentially the rotation is t_R_s, where t is\ the frame of reference of the target skeleton and s is the frame of reference of the source\ skeleton :type rotation_to_target_skeleton: Tensor :param scale_to_target_skeleton: the factor that needs to be multiplied from source\ skeleton to target skeleton (unit in distance). For example, to go from `cm` to `m`, the \ factor needs to be 0.01. :type scale_to_target_skeleton: float :rtype: SkeletonMotion """ return self.retarget_to( joint_mapping, source_tpose.local_rotation, source_tpose.root_translation, target_tpose.skeleton_tree, target_tpose.local_rotation, target_tpose.root_translation, rotation_to_target_skeleton, scale_to_target_skeleton, z_up, )
57,916
Python
39.78662
217
0.585089
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/skeleton/backend/fbx/fbx_read_wrapper.py
# Copyright (c) 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. """ Script that reads in fbx files from python This requires a configs file, which contains the command necessary to switch conda environments to run the fbx reading script from python """ from ....core import logger import inspect import os import numpy as np from .fbx_backend import parse_fbx def fbx_to_array(fbx_file_path, root_joint, fps): """ Reads an fbx file to an array. :param fbx_file_path: str, file path to fbx :return: tuple with joint_names, parents, transforms, frame time """ # Ensure the file path is valid fbx_file_path = os.path.abspath(fbx_file_path) assert os.path.exists(fbx_file_path) # Parse FBX file joint_names, parents, local_transforms, fbx_fps = parse_fbx(fbx_file_path, root_joint, fps) return joint_names, parents, local_transforms, fbx_fps
1,253
Python
30.349999
95
0.746209
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/skeleton/backend/fbx/__init__.py
# Copyright (c) 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.
423
Python
69.666655
76
0.817967
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/amp/poselib/poselib/skeleton/backend/fbx/fbx_backend.py
# Copyright (c) 2018-2023, 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. """ This script reads an fbx file and returns the joint names, parents, and transforms. NOTE: It requires the Python FBX package to be installed. """ import sys import numpy as np try: import fbx import FbxCommon except ImportError as e: print("Error: FBX library failed to load - importing FBX data will not succeed. Message: {}".format(e)) print("FBX tools must be installed from https://help.autodesk.com/view/FBX/2020/ENU/?guid=FBX_Developer_Help_scripting_with_python_fbx_installing_python_fbx_html") def fbx_to_npy(file_name_in, root_joint_name, fps): """ This function reads in an fbx file, and saves the relevant info to a numpy array Fbx files have a series of animation curves, each of which has animations at different times. This script assumes that for mocap data, there is only one animation curve that contains all the joints. Otherwise it is unclear how to read in the data. If this condition isn't met, then the method throws an error :param file_name_in: str, file path in. Should be .fbx file :return: nothing, it just writes a file. """ # Create the fbx scene object and load the .fbx file fbx_sdk_manager, fbx_scene = FbxCommon.InitializeSdkObjects() FbxCommon.LoadScene(fbx_sdk_manager, fbx_scene, file_name_in) """ To read in the animation, we must find the root node of the skeleton. Unfortunately fbx files can have "scene parents" and other parts of the tree that are not joints As a crude fix, this reader just takes and finds the first thing which has an animation curve attached """ search_root = (root_joint_name is None or root_joint_name == "") # Get the root node of the skeleton, which is the child of the scene's root node possible_root_nodes = [fbx_scene.GetRootNode()] found_root_node = False max_key_count = 0 root_joint = None while len(possible_root_nodes) > 0: joint = possible_root_nodes.pop(0) if not search_root: if joint.GetName() == root_joint_name: root_joint = joint try: curve = _get_animation_curve(joint, fbx_scene) except RuntimeError: curve = None if curve is not None: key_count = curve.KeyGetCount() if key_count > max_key_count: found_root_node = True max_key_count = key_count root_curve = curve if search_root and not root_joint: root_joint = joint for child_index in range(joint.GetChildCount()): possible_root_nodes.append(joint.GetChild(child_index)) if not found_root_node: raise RuntimeError("No root joint found!! Exiting") joint_list, joint_names, parents = _get_skeleton(root_joint) """ Read in the transformation matrices of the animation, taking the scaling into account """ anim_range, frame_count, frame_rate = _get_frame_count(fbx_scene) local_transforms = [] #for frame in range(frame_count): time_sec = anim_range.GetStart().GetSecondDouble() time_range_sec = anim_range.GetStop().GetSecondDouble() - time_sec fbx_fps = frame_count / time_range_sec if fps != 120: fbx_fps = fps print("FPS: ", fbx_fps) while time_sec < anim_range.GetStop().GetSecondDouble(): fbx_time = fbx.FbxTime() fbx_time.SetSecondDouble(time_sec) fbx_time = fbx_time.GetFramedTime() transforms_current_frame = [] # Fbx has a unique time object which you need #fbx_time = root_curve.KeyGetTime(frame) for joint in joint_list: arr = np.array(_recursive_to_list(joint.EvaluateLocalTransform(fbx_time))) scales = np.array(_recursive_to_list(joint.EvaluateLocalScaling(fbx_time))) if not np.allclose(scales[0:3], scales[0]): raise ValueError( "Different X, Y and Z scaling. Unsure how this should be handled. " "To solve this, look at this link and try to upgrade the script " "http://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD" "63C_79C1_4F2D_BB28_AD2BE65A02ED_htm" ) # Adjust the array for scaling arr /= scales[0] arr[3, 3] = 1.0 transforms_current_frame.append(arr) local_transforms.append(transforms_current_frame) time_sec += (1.0/fbx_fps) local_transforms = np.array(local_transforms) print("Frame Count: ", len(local_transforms)) return joint_names, parents, local_transforms, fbx_fps def _get_frame_count(fbx_scene): # Get the animation stacks and layers, in order to pull off animation curves later num_anim_stacks = fbx_scene.GetSrcObjectCount( FbxCommon.FbxCriteria.ObjectType(FbxCommon.FbxAnimStack.ClassId) ) # if num_anim_stacks != 1: # raise RuntimeError( # "More than one animation stack was found. " # "This script must be modified to handle this case. Exiting" # ) if num_anim_stacks > 1: index = 1 else: index = 0 anim_stack = fbx_scene.GetSrcObject( FbxCommon.FbxCriteria.ObjectType(FbxCommon.FbxAnimStack.ClassId), index ) anim_range = anim_stack.GetLocalTimeSpan() duration = anim_range.GetDuration() fps = duration.GetFrameRate(duration.GetGlobalTimeMode()) frame_count = duration.GetFrameCount(True) return anim_range, frame_count, fps def _get_animation_curve(joint, fbx_scene): # Get the animation stacks and layers, in order to pull off animation curves later num_anim_stacks = fbx_scene.GetSrcObjectCount( FbxCommon.FbxCriteria.ObjectType(FbxCommon.FbxAnimStack.ClassId) ) # if num_anim_stacks != 1: # raise RuntimeError( # "More than one animation stack was found. " # "This script must be modified to handle this case. Exiting" # ) if num_anim_stacks > 1: index = 1 else: index = 0 anim_stack = fbx_scene.GetSrcObject( FbxCommon.FbxCriteria.ObjectType(FbxCommon.FbxAnimStack.ClassId), index ) num_anim_layers = anim_stack.GetSrcObjectCount( FbxCommon.FbxCriteria.ObjectType(FbxCommon.FbxAnimLayer.ClassId) ) if num_anim_layers != 1: raise RuntimeError( "More than one animation layer was found. " "This script must be modified to handle this case. Exiting" ) animation_layer = anim_stack.GetSrcObject( FbxCommon.FbxCriteria.ObjectType(FbxCommon.FbxAnimLayer.ClassId), 0 ) def _check_longest_curve(curve, max_curve_key_count): longest_curve = None if curve and curve.KeyGetCount() > max_curve_key_count[0]: max_curve_key_count[0] = curve.KeyGetCount() return True return False max_curve_key_count = [0] longest_curve = None for c in ["X", "Y", "Z"]: curve = joint.LclTranslation.GetCurve( animation_layer, c ) # sample curve for translation if _check_longest_curve(curve, max_curve_key_count): longest_curve = curve curve = joint.LclRotation.GetCurve( animation_layer, "X" ) if _check_longest_curve(curve, max_curve_key_count): longest_curve = curve return longest_curve def _get_skeleton(root_joint): # Do a depth first search of the skeleton to extract all the joints joint_list = [root_joint] joint_names = [root_joint.GetName()] parents = [-1] # -1 means no parent def append_children(joint, pos): """ Depth first search function :param joint: joint item in the fbx :param pos: position of current element (for parenting) :return: Nothing """ for child_index in range(joint.GetChildCount()): child = joint.GetChild(child_index) joint_list.append(child) joint_names.append(child.GetName()) parents.append(pos) append_children(child, len(parents) - 1) append_children(root_joint, 0) return joint_list, joint_names, parents def _recursive_to_list(array): """ Takes some iterable that might contain iterables and converts it to a list of lists [of lists... etc] Mainly used for converting the strange fbx wrappers for c++ arrays into python lists :param array: array to be converted :return: array converted to lists """ try: return float(array) except TypeError: return [_recursive_to_list(a) for a in array] def parse_fbx(file_name_in, root_joint_name, fps): return fbx_to_npy(file_name_in, root_joint_name, fps)
10,372
Python
36.72
167
0.659661
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/industreal/industreal_task_pegs_insert.py
# Copyright (c) 2023, 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. """IndustReal: class for peg insertion task. Inherits IndustReal pegs environment class and Factory abstract task class (not enforced). Trains a peg insertion policy with Simulation-Aware Policy Update (SAPU), SDF-Based Reward, and Sampling-Based Curriculum (SBC). Can be executed with python train.py task=IndustRealTaskPegsInsert. """ import hydra import numpy as np import omegaconf import os import torch import warp as wp from isaacgym import gymapi, gymtorch, torch_utils from isaacgymenvs.tasks.factory.factory_schema_class_task import FactoryABCTask from isaacgymenvs.tasks.factory.factory_schema_config_task import ( FactorySchemaConfigTask, ) import isaacgymenvs.tasks.industreal.industreal_algo_utils as algo_utils from isaacgymenvs.tasks.industreal.industreal_env_pegs import IndustRealEnvPegs from isaacgymenvs.utils import torch_jit_utils class IndustRealTaskPegsInsert(IndustRealEnvPegs, FactoryABCTask): def __init__( self, cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ): """Initialize instance variables. Initialize task superclass.""" self.cfg = cfg self._get_task_yaml_params() super().__init__( cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ) self._acquire_task_tensors() self.parse_controller_spec() # Get Warp mesh objects for SAPU and SDF-based reward wp.init() self.wp_device = wp.get_preferred_device() ( self.wp_plug_meshes, self.wp_plug_meshes_sampled_points, self.wp_socket_meshes, ) = algo_utils.load_asset_meshes_in_warp( plug_files=self.plug_files, socket_files=self.socket_files, num_samples=self.cfg_task.rl.sdf_reward_num_samples, device=self.wp_device, ) if self.viewer != None: self._set_viewer_params() def _get_task_yaml_params(self): """Initialize instance variables from YAML files.""" cs = hydra.core.config_store.ConfigStore.instance() cs.store(name="factory_schema_config_task", node=FactorySchemaConfigTask) self.cfg_task = omegaconf.OmegaConf.create(self.cfg) self.max_episode_length = ( self.cfg_task.rl.max_episode_length ) # required instance var for VecTask ppo_path = os.path.join( "train/IndustRealTaskPegsInsertPPO.yaml" ) # relative to Gym's Hydra search path (cfg dir) self.cfg_ppo = hydra.compose(config_name=ppo_path) self.cfg_ppo = self.cfg_ppo["train"] # strip superfluous nesting def _acquire_task_tensors(self): """Acquire tensors.""" self.identity_quat = ( torch.tensor([0.0, 0.0, 0.0, 1.0], device=self.device) .unsqueeze(0) .repeat(self.num_envs, 1) ) # Compute pose of gripper goal and top of socket in socket frame self.gripper_goal_pos_local = torch.tensor( [ [ 0.0, 0.0, (self.cfg_task.env.socket_base_height + self.plug_grasp_offsets[i]), ] for i in range(self.num_envs) ], device=self.device, ) self.gripper_goal_quat_local = self.identity_quat.clone() self.socket_top_pos_local = torch.tensor( [[0.0, 0.0, self.socket_heights[i]] for i in range(self.num_envs)], device=self.device, ) self.socket_quat_local = self.identity_quat.clone() # Define keypoint tensors self.keypoint_offsets = ( algo_utils.get_keypoint_offsets(self.cfg_task.rl.num_keypoints, self.device) * self.cfg_task.rl.keypoint_scale ) self.keypoints_plug = torch.zeros( (self.num_envs, self.cfg_task.rl.num_keypoints, 3), dtype=torch.float32, device=self.device, ) self.keypoints_socket = torch.zeros_like( self.keypoints_plug, device=self.device ) self.actions = torch.zeros( (self.num_envs, self.cfg_task.env.numActions), device=self.device ) self.curr_max_disp = self.cfg_task.rl.initial_max_disp def _refresh_task_tensors(self): """Refresh tensors.""" # Compute pose of gripper goal and top of socket in global frame self.gripper_goal_quat, self.gripper_goal_pos = torch_jit_utils.tf_combine( self.socket_quat, self.socket_pos, self.gripper_goal_quat_local, self.gripper_goal_pos_local, ) self.socket_top_quat, self.socket_top_pos = torch_jit_utils.tf_combine( self.socket_quat, self.socket_pos, self.socket_quat_local, self.socket_top_pos_local, ) # Add observation noise to socket pos self.noisy_socket_pos = torch.zeros_like( self.socket_pos, dtype=torch.float32, device=self.device ) socket_obs_pos_noise = 2 * ( torch.rand((self.num_envs, 3), dtype=torch.float32, device=self.device) - 0.5 ) socket_obs_pos_noise = socket_obs_pos_noise @ torch.diag( torch.tensor( self.cfg_task.env.socket_pos_obs_noise, dtype=torch.float32, device=self.device, ) ) self.noisy_socket_pos[:, 0] = self.socket_pos[:, 0] + socket_obs_pos_noise[:, 0] self.noisy_socket_pos[:, 1] = self.socket_pos[:, 1] + socket_obs_pos_noise[:, 1] self.noisy_socket_pos[:, 2] = self.socket_pos[:, 2] + socket_obs_pos_noise[:, 2] # Add observation noise to socket rot socket_rot_euler = torch.zeros( (self.num_envs, 3), dtype=torch.float32, device=self.device ) socket_obs_rot_noise = 2 * ( torch.rand((self.num_envs, 3), dtype=torch.float32, device=self.device) - 0.5 ) socket_obs_rot_noise = socket_obs_rot_noise @ torch.diag( torch.tensor( self.cfg_task.env.socket_rot_obs_noise, dtype=torch.float32, device=self.device, ) ) socket_obs_rot_euler = socket_rot_euler + socket_obs_rot_noise self.noisy_socket_quat = torch_utils.quat_from_euler_xyz( socket_obs_rot_euler[:, 0], socket_obs_rot_euler[:, 1], socket_obs_rot_euler[:, 2], ) # Compute observation noise on socket ( self.noisy_gripper_goal_quat, self.noisy_gripper_goal_pos, ) = torch_jit_utils.tf_combine( self.noisy_socket_quat, self.noisy_socket_pos, self.gripper_goal_quat_local, self.gripper_goal_pos_local, ) # Compute pos of keypoints on plug and socket in world frame for idx, keypoint_offset in enumerate(self.keypoint_offsets): self.keypoints_plug[:, idx] = torch_jit_utils.tf_combine( self.plug_quat, self.plug_pos, self.identity_quat, keypoint_offset.repeat(self.num_envs, 1), )[1] self.keypoints_socket[:, idx] = torch_jit_utils.tf_combine( self.socket_quat, self.socket_pos, self.identity_quat, keypoint_offset.repeat(self.num_envs, 1), )[1] def pre_physics_step(self, actions): """Reset environments. Apply actions from policy as position/rotation targets, force/torque targets, and/or PD gains.""" env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1) if len(env_ids) > 0: self.reset_idx(env_ids) self.actions = actions.clone().to( self.device ) # shape = (num_envs, num_actions); values = [-1, 1] self._apply_actions_as_ctrl_targets( actions=self.actions, ctrl_target_gripper_dof_pos=0.0, do_scale=True ) def post_physics_step(self): """Step buffers. Refresh tensors. Compute observations and reward.""" self.progress_buf[:] += 1 self.refresh_base_tensors() self.refresh_env_tensors() self._refresh_task_tensors() self.compute_observations() self.compute_reward() def compute_observations(self): """Compute observations.""" delta_pos = self.gripper_goal_pos - self.fingertip_centered_pos noisy_delta_pos = self.noisy_gripper_goal_pos - self.fingertip_centered_pos # Define observations (for actor) obs_tensors = [ self.arm_dof_pos, # 7 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 1 ], # 4 self.pose_world_to_robot_base( self.noisy_gripper_goal_pos, self.noisy_gripper_goal_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.noisy_gripper_goal_pos, self.noisy_gripper_goal_quat )[ 1 ], # 4 noisy_delta_pos, ] # 3 # Define state (for critic) state_tensors = [ self.arm_dof_pos, # 7 self.arm_dof_vel, # 7 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 1 ], # 4 self.fingertip_centered_linvel, # 3 self.fingertip_centered_angvel, # 3 self.pose_world_to_robot_base( self.gripper_goal_pos, self.gripper_goal_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.gripper_goal_pos, self.gripper_goal_quat )[ 1 ], # 4 delta_pos, # 3 self.pose_world_to_robot_base(self.plug_pos, self.plug_quat)[0], # 3 self.pose_world_to_robot_base(self.plug_pos, self.plug_quat)[1], # 4 noisy_delta_pos - delta_pos, ] # 3 self.obs_buf = torch.cat( obs_tensors, dim=-1 ) # shape = (num_envs, num_observations) self.states_buf = torch.cat(state_tensors, dim=-1) return self.obs_buf def compute_reward(self): """Detect successes and failures. Update reward and reset buffers.""" self._update_rew_buf() self._update_reset_buf() def _update_rew_buf(self): """Compute reward at current timestep.""" self.prev_rew_buf = self.rew_buf.clone() # SDF-Based Reward: Compute reward based on SDF distance sdf_reward = algo_utils.get_sdf_reward( wp_plug_meshes_sampled_points=self.wp_plug_meshes_sampled_points, asset_indices=self.asset_indices, plug_pos=self.plug_pos, plug_quat=self.plug_quat, plug_goal_sdfs=self.plug_goal_sdfs, wp_device=self.wp_device, device=self.device, ) # SDF-Based Reward: Apply reward self.rew_buf[:] = self.cfg_task.rl.sdf_reward_scale * sdf_reward # SDF-Based Reward: Log reward self.extras["sdf_reward"] = torch.mean(self.rew_buf) # SAPU: Compute reward scale based on interpenetration distance low_interpen_envs, high_interpen_envs = [], [] ( low_interpen_envs, high_interpen_envs, sapu_reward_scale, ) = algo_utils.get_sapu_reward_scale( asset_indices=self.asset_indices, plug_pos=self.plug_pos, plug_quat=self.plug_quat, socket_pos=self.socket_pos, socket_quat=self.socket_quat, wp_plug_meshes_sampled_points=self.wp_plug_meshes_sampled_points, wp_socket_meshes=self.wp_socket_meshes, interpen_thresh=self.cfg_task.rl.interpen_thresh, wp_device=self.wp_device, device=self.device, ) # SAPU: For envs with low interpenetration, apply reward scale ("weight" step) self.rew_buf[low_interpen_envs] *= sapu_reward_scale # SAPU: For envs with high interpenetration, do not update reward ("filter" step) if len(high_interpen_envs) > 0: self.rew_buf[high_interpen_envs] = self.prev_rew_buf[high_interpen_envs] # SAPU: Log reward after scaling and adjustment from SAPU self.extras["sapu_adjusted_reward"] = torch.mean(self.rew_buf) is_last_step = self.progress_buf[0] == self.max_episode_length - 1 if is_last_step: # Success bonus: Check which envs have plug engaged (partially inserted) or fully inserted is_plug_engaged_w_socket = algo_utils.check_plug_engaged_w_socket( plug_pos=self.plug_pos, socket_top_pos=self.socket_top_pos, keypoints_plug=self.keypoints_plug, keypoints_socket=self.keypoints_socket, cfg_task=self.cfg_task, progress_buf=self.progress_buf, ) is_plug_inserted_in_socket = algo_utils.check_plug_inserted_in_socket( plug_pos=self.plug_pos, socket_pos=self.socket_pos, keypoints_plug=self.keypoints_plug, keypoints_socket=self.keypoints_socket, cfg_task=self.cfg_task, progress_buf=self.progress_buf, ) # Success bonus: Compute reward scale based on whether plug is engaged with socket, as well as closeness to full insertion engagement_reward_scale = algo_utils.get_engagement_reward_scale( plug_pos=self.plug_pos, socket_pos=self.socket_pos, is_plug_engaged_w_socket=is_plug_engaged_w_socket, success_height_thresh=self.cfg_task.rl.success_height_thresh, device=self.device, ) # Success bonus: Apply reward with reward scale self.rew_buf[:] += ( engagement_reward_scale * self.cfg_task.rl.engagement_bonus ) # Success bonus: Log success rate, ignoring environments with large interpenetration if len(high_interpen_envs) > 0: is_plug_inserted_in_socket_low_interpen = is_plug_inserted_in_socket[ low_interpen_envs ] self.extras["insertion_successes"] = torch.mean( is_plug_inserted_in_socket_low_interpen.float() ) else: self.extras["insertion_successes"] = torch.mean( is_plug_inserted_in_socket.float() ) # SBC: Compute reward scale based on curriculum difficulty sbc_rew_scale = algo_utils.get_curriculum_reward_scale( cfg_task=self.cfg_task, curr_max_disp=self.curr_max_disp ) # SBC: Apply reward scale (shrink negative rewards, grow positive rewards) self.rew_buf[:] = torch.where( self.rew_buf[:] < 0.0, self.rew_buf[:] / sbc_rew_scale, self.rew_buf[:] * sbc_rew_scale, ) # SBC: Log current max downward displacement of plug at beginning of episode self.extras["curr_max_disp"] = self.curr_max_disp # SBC: Update curriculum difficulty based on success rate self.curr_max_disp = algo_utils.get_new_max_disp( curr_success=self.extras["insertion_successes"], cfg_task=self.cfg_task, curr_max_disp=self.curr_max_disp, ) def _update_reset_buf(self): """Assign environments for reset if maximum episode length has been reached.""" self.reset_buf[:] = torch.where( self.progress_buf[:] >= self.cfg_task.rl.max_episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf, ) def reset_idx(self, env_ids): """Reset specified environments.""" self._reset_franka() # Close gripper onto plug self.disable_gravity() # to prevent plug from falling self._reset_object() self._move_gripper_to_grasp_pose( sim_steps=self.cfg_task.env.num_gripper_move_sim_steps ) self.close_gripper(sim_steps=self.cfg_task.env.num_gripper_close_sim_steps) self.enable_gravity() # Get plug SDF in goal pose for SDF-based reward self.plug_goal_sdfs = algo_utils.get_plug_goal_sdfs( wp_plug_meshes=self.wp_plug_meshes, asset_indices=self.asset_indices, socket_pos=self.socket_pos, socket_quat=self.socket_quat, wp_device=self.wp_device, ) self._reset_buffers() def _reset_franka(self): """Reset DOF states, DOF torques, and DOF targets of Franka.""" # Randomize DOF pos self.dof_pos[:] = torch.cat( ( torch.tensor( self.cfg_task.randomize.franka_arm_initial_dof_pos, device=self.device, ), torch.tensor( [self.asset_info_franka_table.franka_gripper_width_max], device=self.device, ), torch.tensor( [self.asset_info_franka_table.franka_gripper_width_max], device=self.device, ), ), dim=-1, ).unsqueeze( 0 ) # shape = (num_envs, num_dofs) # Stabilize Franka self.dof_vel[:, :] = 0.0 # shape = (num_envs, num_dofs) self.dof_torque[:, :] = 0.0 self.ctrl_target_dof_pos = self.dof_pos.clone() self.ctrl_target_fingertip_centered_pos = self.fingertip_centered_pos.clone() self.ctrl_target_fingertip_centered_quat = self.fingertip_centered_quat.clone() # Set DOF state franka_actor_ids_sim = self.franka_actor_ids_sim.clone().to(dtype=torch.int32) self.gym.set_dof_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.dof_state), gymtorch.unwrap_tensor(franka_actor_ids_sim), len(franka_actor_ids_sim), ) # Set DOF torque self.gym.set_dof_actuation_force_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.dof_torque), gymtorch.unwrap_tensor(franka_actor_ids_sim), len(franka_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def _reset_object(self): """Reset root state of plug and socket.""" self._reset_socket() self._reset_plug(before_move_to_grasp=True) def _reset_socket(self): """Reset root state of socket.""" # Randomize socket pos socket_noise_xy = 2 * ( torch.rand((self.num_envs, 2), dtype=torch.float32, device=self.device) - 0.5 ) socket_noise_xy = socket_noise_xy @ torch.diag( torch.tensor( self.cfg_task.randomize.socket_pos_xy_noise, dtype=torch.float32, device=self.device, ) ) socket_noise_z = torch.zeros( (self.num_envs), dtype=torch.float32, device=self.device ) socket_noise_z_mag = ( self.cfg_task.randomize.socket_pos_z_noise_bounds[1] - self.cfg_task.randomize.socket_pos_z_noise_bounds[0] ) socket_noise_z = ( socket_noise_z_mag * torch.rand((self.num_envs), dtype=torch.float32, device=self.device) + self.cfg_task.randomize.socket_pos_z_noise_bounds[0] ) self.socket_pos[:, 0] = ( self.robot_base_pos[:, 0] + self.cfg_task.randomize.socket_pos_xy_initial[0] + socket_noise_xy[:, 0] ) self.socket_pos[:, 1] = ( self.robot_base_pos[:, 1] + self.cfg_task.randomize.socket_pos_xy_initial[1] + socket_noise_xy[:, 1] ) self.socket_pos[:, 2] = self.cfg_base.env.table_height + socket_noise_z # Randomize socket rot socket_rot_noise = 2 * ( torch.rand((self.num_envs, 3), dtype=torch.float32, device=self.device) - 0.5 ) socket_rot_noise = socket_rot_noise @ torch.diag( torch.tensor( self.cfg_task.randomize.socket_rot_noise, dtype=torch.float32, device=self.device, ) ) socket_rot_euler = ( torch.zeros((self.num_envs, 3), dtype=torch.float32, device=self.device) + socket_rot_noise ) socket_rot_quat = torch_utils.quat_from_euler_xyz( socket_rot_euler[:, 0], socket_rot_euler[:, 1], socket_rot_euler[:, 2] ) self.socket_quat[:, :] = socket_rot_quat.clone() # Stabilize socket self.socket_linvel[:, :] = 0.0 self.socket_angvel[:, :] = 0.0 # Set socket root state socket_actor_ids_sim = self.socket_actor_ids_sim.clone().to(dtype=torch.int32) self.gym.set_actor_root_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.root_state), gymtorch.unwrap_tensor(socket_actor_ids_sim), len(socket_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def _reset_plug(self, before_move_to_grasp): """Reset root state of plug.""" if before_move_to_grasp: # Generate randomized downward displacement based on curriculum curr_curriculum_disp_range = ( self.curr_max_disp - self.cfg_task.rl.curriculum_height_bound[0] ) self.curriculum_disp = self.cfg_task.rl.curriculum_height_bound[ 0 ] + curr_curriculum_disp_range * ( torch.rand((self.num_envs,), dtype=torch.float32, device=self.device) ) # Generate plug pos noise self.plug_pos_xy_noise = 2 * ( torch.rand((self.num_envs, 2), dtype=torch.float32, device=self.device) - 0.5 ) self.plug_pos_xy_noise = self.plug_pos_xy_noise @ torch.diag( torch.tensor( self.cfg_task.randomize.plug_pos_xy_noise, dtype=torch.float32, device=self.device, ) ) # Set plug pos to assembled state, but offset plug Z-coordinate by height of socket, # minus curriculum displacement self.plug_pos[:, :] = self.socket_pos.clone() self.plug_pos[:, 2] += self.socket_heights self.plug_pos[:, 2] -= self.curriculum_disp # Apply XY noise to plugs not partially inserted into sockets socket_top_height = self.socket_pos[:, 2] + self.socket_heights plug_partial_insert_idx = np.argwhere( self.plug_pos[:, 2].cpu().numpy() > socket_top_height.cpu().numpy() ).squeeze() self.plug_pos[plug_partial_insert_idx, :2] += self.plug_pos_xy_noise[ plug_partial_insert_idx ] self.plug_quat[:, :] = self.identity_quat.clone() # Stabilize plug self.plug_linvel[:, :] = 0.0 self.plug_angvel[:, :] = 0.0 # Set plug root state plug_actor_ids_sim = self.plug_actor_ids_sim.clone().to(dtype=torch.int32) self.gym.set_actor_root_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.root_state), gymtorch.unwrap_tensor(plug_actor_ids_sim), len(plug_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def _reset_buffers(self): """Reset buffers.""" self.reset_buf[:] = 0 self.progress_buf[:] = 0 def _set_viewer_params(self): """Set viewer parameters.""" cam_pos = gymapi.Vec3(-1.0, -1.0, 2.0) cam_target = gymapi.Vec3(0.0, 0.0, 1.5) self.gym.viewer_camera_look_at(self.viewer, None, cam_pos, cam_target) def _apply_actions_as_ctrl_targets( self, actions, ctrl_target_gripper_dof_pos, do_scale ): """Apply actions from policy as position/rotation targets.""" # Interpret actions as target pos displacements and set pos target pos_actions = actions[:, 0:3] if do_scale: pos_actions = pos_actions @ torch.diag( torch.tensor(self.cfg_task.rl.pos_action_scale, device=self.device) ) self.ctrl_target_fingertip_centered_pos = ( self.fingertip_centered_pos + pos_actions ) # Interpret actions as target rot (axis-angle) displacements rot_actions = actions[:, 3:6] if do_scale: rot_actions = rot_actions @ torch.diag( torch.tensor(self.cfg_task.rl.rot_action_scale, device=self.device) ) # Convert to quat and set rot target angle = torch.norm(rot_actions, p=2, dim=-1) axis = rot_actions / angle.unsqueeze(-1) rot_actions_quat = torch_utils.quat_from_angle_axis(angle, axis) if self.cfg_task.rl.clamp_rot: rot_actions_quat = torch.where( angle.unsqueeze(-1).repeat(1, 4) > self.cfg_task.rl.clamp_rot_thresh, rot_actions_quat, torch.tensor([0.0, 0.0, 0.0, 1.0], device=self.device).repeat( self.num_envs, 1 ), ) self.ctrl_target_fingertip_centered_quat = torch_utils.quat_mul( rot_actions_quat, self.fingertip_centered_quat ) self.ctrl_target_gripper_dof_pos = ctrl_target_gripper_dof_pos self.generate_ctrl_signals() def _move_gripper_to_grasp_pose(self, sim_steps): """Define grasp pose for plug and move gripper to pose.""" # Set target_pos self.ctrl_target_fingertip_midpoint_pos = self.plug_pos.clone() self.ctrl_target_fingertip_midpoint_pos[:, 2] += self.plug_grasp_offsets # Set target rot ctrl_target_fingertip_centered_euler = ( torch.tensor( self.cfg_task.randomize.fingertip_centered_rot_initial, device=self.device, ) .unsqueeze(0) .repeat(self.num_envs, 1) ) self.ctrl_target_fingertip_midpoint_quat = torch_utils.quat_from_euler_xyz( ctrl_target_fingertip_centered_euler[:, 0], ctrl_target_fingertip_centered_euler[:, 1], ctrl_target_fingertip_centered_euler[:, 2], ) self.move_gripper_to_target_pose( gripper_dof_pos=self.asset_info_franka_table.franka_gripper_width_max, sim_steps=sim_steps, ) # Reset plug in case it is knocked away by gripper movement self._reset_plug(before_move_to_grasp=False)
29,491
Python
36.237374
134
0.572514
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/industreal/industreal_task_gears_insert.py
# Copyright (c) 2023, 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. """IndustReal: class for gear insertion task. Inherits IndustReal gears environment class and Factory abstract task class (not enforced). Trains a gear insertion policy with Simulation-Aware Policy Update (SAPU), SDF-Based Reward, and Sampling-Based Curriculum (SBC). Can be executed with python train.py task=IndustRealTaskGearsInsert. """ import hydra import numpy as np import omegaconf import os import torch import warp as wp from isaacgym import gymapi, gymtorch, torch_utils from isaacgymenvs.tasks.factory.factory_schema_class_task import FactoryABCTask from isaacgymenvs.tasks.factory.factory_schema_config_task import ( FactorySchemaConfigTask, ) import isaacgymenvs.tasks.industreal.industreal_algo_utils as algo_utils from isaacgymenvs.tasks.industreal.industreal_env_gears import IndustRealEnvGears from isaacgymenvs.utils import torch_jit_utils class IndustRealTaskGearsInsert(IndustRealEnvGears, FactoryABCTask): def __init__( self, cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ): """Initialize instance variables. Initialize task superclass.""" self.cfg = cfg self._get_task_yaml_params() super().__init__( cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ) self._acquire_task_tensors() self.parse_controller_spec() # Get Warp mesh objects for SAPU and SDF-based reward wp.init() self.wp_device = wp.get_preferred_device() ( self.wp_gear_meshes, self.wp_gear_meshes_sampled_points, self.wp_shaft_meshes, ) = algo_utils.load_asset_meshes_in_warp( plug_files=self.gear_files, socket_files=self.shaft_files, num_samples=self.cfg_task.rl.sdf_reward_num_samples, device=self.wp_device, ) if self.viewer != None: self._set_viewer_params() def _get_task_yaml_params(self): """Initialize instance variables from YAML files.""" cs = hydra.core.config_store.ConfigStore.instance() cs.store(name="factory_schema_config_task", node=FactorySchemaConfigTask) self.cfg_task = omegaconf.OmegaConf.create(self.cfg) self.max_episode_length = ( self.cfg_task.rl.max_episode_length ) # required instance var for VecTask ppo_path = os.path.join( "train/IndustRealTaskGearsInsertPPO.yaml" ) # relative to Gym's Hydra search path (cfg dir) self.cfg_ppo = hydra.compose(config_name=ppo_path) self.cfg_ppo = self.cfg_ppo["train"] # strip superfluous nesting def _acquire_task_tensors(self): """Acquire tensors.""" self.identity_quat = ( torch.tensor([0.0, 0.0, 0.0, 1.0], device=self.device) .unsqueeze(0) .repeat(self.num_envs, 1) ) # Compute pose of gripper goal in gear base frame self.gripper_goal_pos_local = ( torch.tensor( [ 0.0, 0.0, self.asset_info_gears.base.height + self.asset_info_gears.gears.grasp_offset, ] ) .to(self.device) .unsqueeze(0) .repeat(self.num_envs, 1) ) self.gripper_goal_quat_local = self.identity_quat.clone() # Define keypoint tensors self.keypoint_offsets = ( algo_utils.get_keypoint_offsets(self.cfg_task.rl.num_keypoints, self.device) * self.cfg_task.rl.keypoint_scale ) self.keypoints_gear = torch.zeros( (self.num_envs, self.cfg_task.rl.num_keypoints, 3), dtype=torch.float32, device=self.device, ) self.keypoints_shaft = torch.zeros_like(self.keypoints_gear, device=self.device) self.actions = torch.zeros( (self.num_envs, self.cfg_task.env.numActions), device=self.device ) self.curr_max_disp = self.cfg_task.rl.initial_max_disp def _refresh_task_tensors(self): """Refresh tensors.""" # From CAD, gear origin is offset from gear; reverse offset to get pos of gear and base of corresponding shaft self.gear_medium_pos_center = self.gear_medium_pos - torch.tensor( [self.cfg_task.env.gear_medium_pos_offset[1], 0.0, 0.0], device=self.device ) self.shaft_pos = self.base_pos - torch.tensor( [self.cfg_task.env.gear_medium_pos_offset[1], 0.0, 0.0], device=self.device ) # Compute pose of gripper goal in global frame self.gripper_goal_quat, self.gripper_goal_pos = torch_jit_utils.tf_combine( self.base_quat, self.shaft_pos, self.gripper_goal_quat_local, self.gripper_goal_pos_local, ) # Add observation noise to gear base pos self.noisy_base_pos = torch.zeros_like( self.base_pos, dtype=torch.float32, device=self.device ) base_obs_pos_noise = 2 * ( torch.rand((self.num_envs, 3), dtype=torch.float32, device=self.device) - 0.5 ) base_obs_pos_noise = base_obs_pos_noise @ torch.diag( torch.tensor( self.cfg_task.env.base_pos_obs_noise, dtype=torch.float32, device=self.device, ) ) self.noisy_base_pos[:, 0] = self.base_pos[:, 0] + base_obs_pos_noise[:, 0] self.noisy_base_pos[:, 1] = self.base_pos[:, 1] + base_obs_pos_noise[:, 1] self.noisy_base_pos[:, 2] = self.base_pos[:, 2] + base_obs_pos_noise[:, 2] # Add observation noise to gear base rot base_rot_euler = torch.zeros( (self.num_envs, 3), dtype=torch.float32, device=self.device ) base_obs_rot_noise = 2 * ( torch.rand((self.num_envs, 3), dtype=torch.float32, device=self.device) - 0.5 ) base_obs_rot_noise = base_obs_rot_noise @ torch.diag( torch.tensor( self.cfg_task.env.base_rot_obs_noise, dtype=torch.float32, device=self.device, ) ) base_obs_rot_euler = base_rot_euler + base_obs_rot_noise self.noisy_base_quat = torch_utils.quat_from_euler_xyz( base_obs_rot_euler[:, 0], base_obs_rot_euler[:, 1], base_obs_rot_euler[:, 2] ) # Compute observation noise on gear base ( self.noisy_gripper_goal_quat, self.noisy_gripper_goal_pos, ) = torch_jit_utils.tf_combine( self.noisy_base_quat, self.noisy_base_pos, self.gripper_goal_quat_local, self.gripper_goal_pos_local, ) # Compute pos of keypoints on gear and shaft in world frame for idx, keypoint_offset in enumerate(self.keypoint_offsets): self.keypoints_gear[:, idx] = torch_jit_utils.tf_combine( self.gear_medium_quat, self.gear_medium_pos_center, self.identity_quat, keypoint_offset.repeat(self.num_envs, 1), )[1] self.keypoints_shaft[:, idx] = torch_jit_utils.tf_combine( self.base_quat, self.shaft_pos, self.identity_quat, keypoint_offset.repeat(self.num_envs, 1), )[1] def pre_physics_step(self, actions): """Reset environments. Apply actions from policy as position/rotation targets, force/torque targets, and/or PD gains.""" env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1) if len(env_ids) > 0: self.reset_idx(env_ids) self.actions = actions.clone().to( self.device ) # shape = (num_envs, num_actions); values = [-1, 1] self._apply_actions_as_ctrl_targets( actions=self.actions, ctrl_target_gripper_dof_pos=0.0, do_scale=True ) def post_physics_step(self): """Step buffers. Refresh tensors. Compute observations and reward.""" self.progress_buf[:] += 1 self.refresh_base_tensors() self.refresh_env_tensors() self._refresh_task_tensors() self.compute_observations() self.compute_reward() def compute_observations(self): """Compute observations.""" delta_pos = self.gripper_goal_pos - self.fingertip_centered_pos noisy_delta_pos = self.noisy_gripper_goal_pos - self.fingertip_centered_pos # Define observations (for actor) obs_tensors = [ self.arm_dof_pos, # 7 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 1 ], # 4 self.pose_world_to_robot_base( self.noisy_gripper_goal_pos, self.noisy_gripper_goal_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.noisy_gripper_goal_pos, self.noisy_gripper_goal_quat )[ 1 ], # 4 noisy_delta_pos, ] # Define state (for critic) state_tensors = [ self.arm_dof_pos, # 7 self.arm_dof_vel, # 7 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.fingertip_centered_pos, self.fingertip_centered_quat )[ 1 ], # 4 self.fingertip_centered_linvel, # 3 self.fingertip_centered_angvel, # 3 self.pose_world_to_robot_base( self.gripper_goal_pos, self.gripper_goal_quat )[ 0 ], # 3 self.pose_world_to_robot_base( self.gripper_goal_pos, self.gripper_goal_quat )[ 1 ], # 4 delta_pos, # 3 self.pose_world_to_robot_base(self.gear_medium_pos, self.gear_medium_quat)[ 0 ], # 3 self.pose_world_to_robot_base(self.gear_medium_pos, self.gear_medium_quat)[ 1 ], # 4 noisy_delta_pos - delta_pos, ] # 3 self.obs_buf = torch.cat( obs_tensors, dim=-1 ) # shape = (num_envs, num_observations) self.states_buf = torch.cat(state_tensors, dim=-1) return self.obs_buf def compute_reward(self): """Detect successes and failures. Update reward and reset buffers.""" self._update_rew_buf() self._update_reset_buf() def _update_rew_buf(self): """Compute reward at current timestep.""" self.prev_rew_buf = self.rew_buf.clone() # SDF-Based Reward: Compute reward based on SDF distance sdf_reward = algo_utils.get_sdf_reward( wp_plug_meshes_sampled_points=self.wp_gear_meshes_sampled_points, asset_indices=self.asset_indices, plug_pos=self.gear_medium_pos, plug_quat=self.gear_medium_quat, plug_goal_sdfs=self.gear_goal_sdfs, wp_device=self.wp_device, device=self.device, ) # SDF-Based Reward: Apply reward self.rew_buf[:] = self.cfg_task.rl.sdf_reward_scale * sdf_reward self.extras["sdf_reward"] = torch.mean(self.rew_buf) # SAPU: Compute reward scale based on interpenetration distance low_interpen_envs, high_interpen_envs = [], [] ( low_interpen_envs, high_interpen_envs, sapu_reward_scale, ) = algo_utils.get_sapu_reward_scale( asset_indices=self.asset_indices, plug_pos=self.gear_medium_pos, plug_quat=self.gear_medium_quat, socket_pos=self.base_pos, socket_quat=self.base_quat, wp_plug_meshes_sampled_points=self.wp_gear_meshes_sampled_points, wp_socket_meshes=self.wp_shaft_meshes, interpen_thresh=self.cfg_task.rl.interpen_thresh, wp_device=self.wp_device, device=self.device, ) # SAPU: For envs with low interpenetration, apply reward scale ("weight" step) self.rew_buf[low_interpen_envs] *= sapu_reward_scale # SAPU: For envs with high interpenetration, do not update reward ("filter" step) if len(high_interpen_envs) > 0: self.rew_buf[high_interpen_envs] = self.prev_rew_buf[high_interpen_envs] self.extras["sapu_adjusted_reward"] = torch.mean(self.rew_buf) is_last_step = self.progress_buf[0] == self.max_episode_length - 1 if is_last_step: # Check which envs have gear engaged (partially inserted) or fully inserted is_gear_engaged_w_shaft = algo_utils.check_gear_engaged_w_shaft( gear_pos=self.gear_medium_pos, shaft_pos=self.shaft_pos, keypoints_gear=self.keypoints_gear, keypoints_shaft=self.keypoints_shaft, asset_info_gears=self.asset_info_gears, cfg_task=self.cfg_task, progress_buf=self.progress_buf, ) is_gear_inserted_on_shaft = algo_utils.check_gear_inserted_on_shaft( gear_pos=self.gear_medium_pos, shaft_pos=self.shaft_pos, keypoints_gear=self.keypoints_gear, keypoints_shaft=self.keypoints_shaft, cfg_task=self.cfg_task, progress_buf=self.progress_buf, ) # Success bonus: Compute reward scale based on whether gear is engaged with shaft, as well as closeness to full insertion engagement_reward_scale = algo_utils.get_engagement_reward_scale( plug_pos=self.gear_medium_pos, socket_pos=self.base_pos, is_plug_engaged_w_socket=is_gear_engaged_w_shaft, success_height_thresh=self.cfg_task.rl.success_height_thresh, device=self.device, ) # Success bonus: Apply reward with reward scale self.rew_buf[:] += ( engagement_reward_scale * self.cfg_task.rl.engagement_bonus ) # Success bonus: Log success rate, ignoring environments with large interpenetration if len(high_interpen_envs) > 0: is_gear_inserted_on_shaft_low_interpen = is_gear_inserted_on_shaft[ low_interpen_envs ] self.extras["insertion_successes"] = torch.mean( is_gear_inserted_on_shaft_low_interpen.float() ) else: self.extras["insertion_successes"] = torch.mean( is_gear_inserted_on_shaft.float() ) # SBC: Compute reward scale based on curriculum difficulty sbc_rew_scale = algo_utils.get_curriculum_reward_scale( cfg_task=self.cfg_task, curr_max_disp=self.curr_max_disp ) # SBC: Apply reward scale (shrink negative rewards, grow positive rewards) self.rew_buf[:] = torch.where( self.rew_buf[:] < 0.0, self.rew_buf[:] / sbc_rew_scale, self.rew_buf[:] * sbc_rew_scale, ) # SBC: Log current max downward displacement of gear at beginning of episode self.extras["curr_max_disp"] = self.curr_max_disp # SBC: Update curriculum difficulty based on success rate self.curr_max_disp = algo_utils.get_new_max_disp( curr_success=self.extras["insertion_successes"], cfg_task=self.cfg_task, curr_max_disp=self.curr_max_disp, ) def _update_reset_buf(self): """Assign environments for reset if maximum episode length has been reached.""" self.reset_buf[:] = torch.where( self.progress_buf[:] >= self.cfg_task.rl.max_episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf, ) def reset_idx(self, env_ids): """Reset specified environments.""" self._reset_franka() # Close gripper onto gear self.disable_gravity() # to prevent gear from falling self._reset_object() self._move_gripper_to_grasp_pose( sim_steps=self.cfg_task.env.num_gripper_move_sim_steps ) self.close_gripper(sim_steps=self.cfg_task.env.num_gripper_close_sim_steps) self.enable_gravity() # Get gear SDF in goal pose for SDF-based reward self.gear_goal_sdfs = algo_utils.get_plug_goal_sdfs( wp_plug_meshes=self.wp_gear_meshes, asset_indices=self.asset_indices, socket_pos=self.base_pos, socket_quat=self.base_quat, wp_device=self.wp_device, ) self._reset_buffers() def _reset_franka(self): """Reset DOF states, DOF torques, and DOF targets of Franka.""" self.dof_pos[:] = torch.cat( ( torch.tensor( self.cfg_task.randomize.franka_arm_initial_dof_pos, device=self.device, ), torch.tensor( [self.asset_info_franka_table.franka_gripper_width_max], device=self.device, ), torch.tensor( [self.asset_info_franka_table.franka_gripper_width_max], device=self.device, ), ), dim=-1, ).unsqueeze( 0 ) # shape = (num_envs, num_dofs) # Stabilize Franka self.dof_vel[:, :] = 0.0 # shape = (num_envs, num_dofs) self.dof_torque[:, :] = 0.0 self.ctrl_target_dof_pos = self.dof_pos.clone() self.ctrl_target_fingertip_centered_pos = self.fingertip_centered_pos.clone() self.ctrl_target_fingertip_centered_quat = self.fingertip_centered_quat.clone() # Set DOF state franka_actor_ids_sim = self.franka_actor_ids_sim.clone().to(dtype=torch.int32) self.gym.set_dof_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.dof_state), gymtorch.unwrap_tensor(franka_actor_ids_sim), len(franka_actor_ids_sim), ) # Set DOF torque self.gym.set_dof_actuation_force_tensor_indexed( self.sim, gymtorch.unwrap_tensor(torch.zeros_like(self.dof_torque)), gymtorch.unwrap_tensor(franka_actor_ids_sim), len(franka_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def _reset_object(self): """Reset root state of gears and gear base.""" self._reset_base() self._reset_small_large_gears() self._reset_medium_gear(before_move_to_grasp=True) def _reset_base(self): """Reset root state of gear base.""" # Randomize gear base pos base_noise_xy = 2 * ( torch.rand((self.num_envs, 3), dtype=torch.float32, device=self.device) - 0.5 ) base_noise_xy = base_noise_xy @ torch.diag( torch.tensor( self.cfg_task.randomize.base_pos_xy_noise, dtype=torch.float32, device=self.device, ) ) base_noise_z = torch.zeros( (self.num_envs), dtype=torch.float32, device=self.device ) base_noise_z_mag = ( self.cfg_task.randomize.base_pos_z_noise_bounds[1] - self.cfg_task.randomize.base_pos_z_noise_bounds[0] ) base_noise_z = base_noise_z_mag * torch.rand( (self.num_envs), dtype=torch.float32, device=self.device ) self.base_pos[:, 0] = ( self.robot_base_pos[:, 0] + self.cfg_task.randomize.base_pos_xy_initial[0] + base_noise_xy[:, 0] ) self.base_pos[:, 1] = ( self.robot_base_pos[:, 1] + self.cfg_task.randomize.base_pos_xy_initial[1] + base_noise_xy[:, 1] ) self.base_pos[:, 2] = self.cfg_base.env.table_height + base_noise_z # Set gear base rot self.base_quat[:] = self.identity_quat # Stabilize gear base self.base_linvel[:, :] = 0.0 self.base_angvel[:, :] = 0.0 # Set gear base root state base_actor_ids_sim = self.base_actor_ids_sim.clone().to(dtype=torch.int32) self.gym.set_actor_root_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.root_state), gymtorch.unwrap_tensor(base_actor_ids_sim), len(base_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def _reset_small_large_gears(self): """Reset root state of small and large gears.""" # Set small and large gear pos to be pos in assembled state, plus vertical offset to prevent initial collision self.gear_small_pos[:, :] = self.base_pos + torch.tensor( [0.0, 0.0, 0.002], device=self.device ) self.gear_large_pos[:, :] = self.base_pos + torch.tensor( [0.0, 0.0, 0.002], device=self.device ) # Set small and large gear rot self.gear_small_quat[:] = self.identity_quat self.gear_large_quat[:] = self.identity_quat # Stabilize small and large gears self.gear_small_linvel[:, :] = 0.0 self.gear_large_linvel[:, :] = 0.0 self.gear_small_angvel[:, :] = 0.0 self.gear_large_angvel[:, :] = 0.0 # Set small and large gear root state gears_small_large_actor_ids_sim = torch.cat( (self.gear_small_actor_ids_sim, self.gear_large_actor_ids_sim), dim=0 ).to(torch.int32) self.gym.set_actor_root_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.root_state), gymtorch.unwrap_tensor(gears_small_large_actor_ids_sim), len(gears_small_large_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def _reset_medium_gear(self, before_move_to_grasp): """Reset root state of medium gear.""" if before_move_to_grasp: # Generate randomized downward displacement based on curriculum curr_curriculum_disp_range = ( self.curr_max_disp - self.cfg_task.rl.curriculum_height_bound[0] ) self.curriculum_disp = self.cfg_task.rl.curriculum_height_bound[ 0 ] + curr_curriculum_disp_range * ( torch.rand((self.num_envs,), dtype=torch.float32, device=self.device) ) # Generate gear pos noise self.gear_medium_pos_xyz_noise = 2 * ( torch.rand((self.num_envs, 3), dtype=torch.float32, device=self.device) - 0.5 ) self.gear_medium_pos_xyz_noise = ( self.gear_medium_pos_xyz_noise @ torch.diag( torch.tensor( self.cfg_task.randomize.gear_pos_xyz_noise, dtype=torch.float32, device=self.device, ) ) ) # Set medium gear pos to assembled state, but offset gear Z-coordinate by height of gear, # minus curriculum displacement self.gear_medium_pos[:, :] = self.base_pos.clone() self.gear_medium_pos[:, 2] += self.asset_info_gears.shafts.height self.gear_medium_pos[:, 2] -= self.curriculum_disp # Apply XY noise to gears not partially inserted onto gear shafts gear_base_top_height = ( self.base_pos[:, 2] + self.asset_info_gears.base.height + self.asset_info_gears.shafts.height ) gear_partial_insert_idx = np.argwhere( self.gear_medium_pos[:, 2].cpu().numpy() > gear_base_top_height.cpu().numpy() ).squeeze() self.gear_medium_pos[ gear_partial_insert_idx, :2 ] += self.gear_medium_pos_xyz_noise[gear_partial_insert_idx, :2] self.gear_medium_quat[:, :] = self.identity_quat.clone() # Stabilize plug self.gear_medium_linvel[:, :] = 0.0 self.gear_medium_angvel[:, :] = 0.0 # Set medium gear root state gear_medium_actor_ids_sim = self.gear_medium_actor_ids_sim.clone().to( dtype=torch.int32 ) self.gym.set_actor_root_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.root_state), gymtorch.unwrap_tensor(gear_medium_actor_ids_sim), len(gear_medium_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def _reset_buffers(self): """Reset buffers.""" self.reset_buf[:] = 0 self.progress_buf[:] = 0 def _set_viewer_params(self): """Set viewer parameters.""" cam_pos = gymapi.Vec3(-1.0, -1.0, 2.0) cam_target = gymapi.Vec3(0.0, 0.0, 1.5) self.gym.viewer_camera_look_at(self.viewer, None, cam_pos, cam_target) def _apply_actions_as_ctrl_targets( self, actions, ctrl_target_gripper_dof_pos, do_scale ): """Apply actions from policy as position/rotation targets.""" # Interpret actions as target pos displacements and set pos target pos_actions = actions[:, 0:3] if do_scale: pos_actions = pos_actions @ torch.diag( torch.tensor(self.cfg_task.rl.pos_action_scale, device=self.device) ) self.ctrl_target_fingertip_centered_pos = ( self.fingertip_centered_pos + pos_actions ) # Interpret actions as target rot (axis-angle) displacements rot_actions = actions[:, 3:6] if do_scale: rot_actions = rot_actions @ torch.diag( torch.tensor(self.cfg_task.rl.rot_action_scale, device=self.device) ) # Convert to quat and set rot target angle = torch.norm(rot_actions, p=2, dim=-1) axis = rot_actions / angle.unsqueeze(-1) rot_actions_quat = torch_utils.quat_from_angle_axis(angle, axis) if self.cfg_task.rl.clamp_rot: rot_actions_quat = torch.where( angle.unsqueeze(-1).repeat(1, 4) > self.cfg_task.rl.clamp_rot_thresh, rot_actions_quat, torch.tensor([0.0, 0.0, 0.0, 1.0], device=self.device).repeat( self.num_envs, 1 ), ) self.ctrl_target_fingertip_centered_quat = torch_utils.quat_mul( rot_actions_quat, self.fingertip_centered_quat ) self.ctrl_target_gripper_dof_pos = ctrl_target_gripper_dof_pos self.generate_ctrl_signals() def _move_gripper_to_grasp_pose(self, sim_steps): """Define grasp pose for medium gear and move gripper to pose.""" # Set target pos self.ctrl_target_fingertip_midpoint_pos = self.gear_medium_pos_center.clone() self.ctrl_target_fingertip_midpoint_pos[ :, 2 ] += self.asset_info_gears.gears.grasp_offset # Set target rot ctrl_target_fingertip_centered_euler = ( torch.tensor( self.cfg_task.randomize.fingertip_centered_rot_initial, device=self.device, ) .unsqueeze(0) .repeat(self.num_envs, 1) ) self.ctrl_target_fingertip_midpoint_quat = torch_utils.quat_from_euler_xyz( ctrl_target_fingertip_centered_euler[:, 0], ctrl_target_fingertip_centered_euler[:, 1], ctrl_target_fingertip_centered_euler[:, 2], ) self.move_gripper_to_target_pose( gripper_dof_pos=self.asset_info_franka_table.franka_gripper_width_max, sim_steps=sim_steps, ) # Reset medium gear in case it is knocked away by gripper movement self._reset_medium_gear(before_move_to_grasp=False)
30,487
Python
36.408589
133
0.572572
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/industreal/industreal_base.py
# Copyright (c) 2023, 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. """IndustReal: base class. Inherits Factory base class and Factory abstract base class. Inherited by IndustReal environment classes. Not directly executed. Configuration defined in IndustRealBase.yaml. Asset info defined in industreal_asset_info_franka_table.yaml. """ import hydra import math import os import torch from isaacgym import gymapi, gymtorch, torch_utils from isaacgymenvs.tasks.factory.factory_base import FactoryBase import isaacgymenvs.tasks.factory.factory_control as fc from isaacgymenvs.tasks.factory.factory_schema_class_base import FactoryABCBase from isaacgymenvs.tasks.factory.factory_schema_config_base import ( FactorySchemaConfigBase, ) class IndustRealBase(FactoryBase, FactoryABCBase): def __init__( self, cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ): """Initialize instance variables. Initialize VecTask superclass.""" self.cfg = cfg self.cfg["headless"] = headless self._get_base_yaml_params() if self.cfg_base.mode.export_scene: sim_device = "cpu" super().__init__( cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ) # create_sim() is called here def _get_base_yaml_params(self): """Initialize instance variables from YAML files.""" cs = hydra.core.config_store.ConfigStore.instance() cs.store(name="factory_schema_config_base", node=FactorySchemaConfigBase) config_path = ( "task/IndustRealBase.yaml" # relative to Gym's Hydra search path (cfg dir) ) self.cfg_base = hydra.compose(config_name=config_path) self.cfg_base = self.cfg_base["task"] # strip superfluous nesting asset_info_path = "../../assets/industreal/yaml/industreal_asset_info_franka_table.yaml" # relative to Gym's Hydra search path (cfg dir) self.asset_info_franka_table = hydra.compose(config_name=asset_info_path) self.asset_info_franka_table = self.asset_info_franka_table[""][""][""][""][""][ "" ]["assets"]["industreal"][ "yaml" ] # strip superfluous nesting def import_franka_assets(self): """Set Franka and table asset options. Import assets.""" urdf_root = os.path.join( os.path.dirname(__file__), "..", "..", "..", "assets", "industreal", "urdf" ) franka_file = "industreal_franka.urdf" franka_options = gymapi.AssetOptions() franka_options.flip_visual_attachments = True franka_options.fix_base_link = True franka_options.collapse_fixed_joints = False franka_options.thickness = 0.0 # default = 0.02 franka_options.density = 1000.0 # default = 1000.0 franka_options.armature = 0.01 # default = 0.0 franka_options.use_physx_armature = True if self.cfg_base.sim.add_damping: franka_options.linear_damping = ( 1.0 # default = 0.0; increased to improve stability ) franka_options.max_linear_velocity = ( 1.0 # default = 1000.0; reduced to prevent CUDA errors ) franka_options.angular_damping = ( 5.0 # default = 0.5; increased to improve stability ) franka_options.max_angular_velocity = ( 2 * math.pi ) # default = 64.0; reduced to prevent CUDA errors else: franka_options.linear_damping = 0.0 # default = 0.0 franka_options.max_linear_velocity = 1.0 # default = 1000.0 franka_options.angular_damping = 0.5 # default = 0.5 franka_options.max_angular_velocity = 2 * math.pi # default = 64.0 franka_options.disable_gravity = True franka_options.enable_gyroscopic_forces = True franka_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE franka_options.use_mesh_materials = True if self.cfg_base.mode.export_scene: franka_options.mesh_normal_mode = gymapi.COMPUTE_PER_FACE table_options = gymapi.AssetOptions() table_options.flip_visual_attachments = False # default = False table_options.fix_base_link = True table_options.thickness = 0.0 # default = 0.02 table_options.density = 1000.0 # default = 1000.0 table_options.armature = 0.0 # default = 0.0 table_options.use_physx_armature = True table_options.linear_damping = 0.0 # default = 0.0 table_options.max_linear_velocity = 1000.0 # default = 1000.0 table_options.angular_damping = 0.0 # default = 0.5 table_options.max_angular_velocity = 64.0 # default = 64.0 table_options.disable_gravity = False table_options.enable_gyroscopic_forces = True table_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE table_options.use_mesh_materials = False if self.cfg_base.mode.export_scene: table_options.mesh_normal_mode = gymapi.COMPUTE_PER_FACE franka_asset = self.gym.load_asset( self.sim, urdf_root, franka_file, franka_options ) table_asset = self.gym.create_box( self.sim, self.asset_info_franka_table.table_depth, self.asset_info_franka_table.table_width, self.cfg_base.env.table_height, table_options, ) return franka_asset, table_asset def acquire_base_tensors(self): """Acquire and wrap tensors. Create views.""" _root_state = self.gym.acquire_actor_root_state_tensor( self.sim ) # shape = (num_envs * num_actors, 13) _body_state = self.gym.acquire_rigid_body_state_tensor( self.sim ) # shape = (num_envs * num_bodies, 13) _dof_state = self.gym.acquire_dof_state_tensor( self.sim ) # shape = (num_envs * num_dofs, 2) _dof_force = self.gym.acquire_dof_force_tensor( self.sim ) # shape = (num_envs * num_dofs, 1) _contact_force = self.gym.acquire_net_contact_force_tensor( self.sim ) # shape = (num_envs * num_bodies, 3) _jacobian = self.gym.acquire_jacobian_tensor( self.sim, "franka" ) # shape = (num envs, num_bodies, 6, num_dofs) _mass_matrix = self.gym.acquire_mass_matrix_tensor( self.sim, "franka" ) # shape = (num_envs, num_dofs, num_dofs) self.root_state = gymtorch.wrap_tensor(_root_state) self.body_state = gymtorch.wrap_tensor(_body_state) self.dof_state = gymtorch.wrap_tensor(_dof_state) self.dof_force = gymtorch.wrap_tensor(_dof_force) self.contact_force = gymtorch.wrap_tensor(_contact_force) self.jacobian = gymtorch.wrap_tensor(_jacobian) self.mass_matrix = gymtorch.wrap_tensor(_mass_matrix) self.root_pos = self.root_state.view(self.num_envs, self.num_actors, 13)[ ..., 0:3 ] self.root_quat = self.root_state.view(self.num_envs, self.num_actors, 13)[ ..., 3:7 ] self.root_linvel = self.root_state.view(self.num_envs, self.num_actors, 13)[ ..., 7:10 ] self.root_angvel = self.root_state.view(self.num_envs, self.num_actors, 13)[ ..., 10:13 ] self.body_pos = self.body_state.view(self.num_envs, self.num_bodies, 13)[ ..., 0:3 ] self.body_quat = self.body_state.view(self.num_envs, self.num_bodies, 13)[ ..., 3:7 ] self.body_linvel = self.body_state.view(self.num_envs, self.num_bodies, 13)[ ..., 7:10 ] self.body_angvel = self.body_state.view(self.num_envs, self.num_bodies, 13)[ ..., 10:13 ] self.dof_pos = self.dof_state.view(self.num_envs, self.num_dofs, 2)[..., 0] self.dof_vel = self.dof_state.view(self.num_envs, self.num_dofs, 2)[..., 1] self.dof_force_view = self.dof_force.view(self.num_envs, self.num_dofs, 1)[ ..., 0 ] self.contact_force = self.contact_force.view(self.num_envs, self.num_bodies, 3)[ ..., 0:3 ] self.arm_dof_pos = self.dof_pos[:, 0:7] self.arm_dof_vel = self.dof_vel[:, 0:7] self.arm_mass_matrix = self.mass_matrix[ :, 0:7, 0:7 ] # for Franka arm (not gripper) self.robot_base_pos = self.body_pos[:, self.robot_base_body_id_env, 0:3] self.robot_base_quat = self.body_quat[:, self.robot_base_body_id_env, 0:4] self.hand_pos = self.body_pos[:, self.hand_body_id_env, 0:3] self.hand_quat = self.body_quat[:, self.hand_body_id_env, 0:4] self.hand_linvel = self.body_linvel[:, self.hand_body_id_env, 0:3] self.hand_angvel = self.body_angvel[:, self.hand_body_id_env, 0:3] self.hand_jacobian = self.jacobian[ :, self.hand_body_id_env_actor - 1, 0:6, 0:7 ] # minus 1 because base is fixed self.left_finger_pos = self.body_pos[:, self.left_finger_body_id_env, 0:3] self.left_finger_quat = self.body_quat[:, self.left_finger_body_id_env, 0:4] self.left_finger_linvel = self.body_linvel[:, self.left_finger_body_id_env, 0:3] self.left_finger_angvel = self.body_angvel[:, self.left_finger_body_id_env, 0:3] self.left_finger_jacobian = self.jacobian[ :, self.left_finger_body_id_env_actor - 1, 0:6, 0:7 ] # minus 1 because base is fixed self.right_finger_pos = self.body_pos[:, self.right_finger_body_id_env, 0:3] self.right_finger_quat = self.body_quat[:, self.right_finger_body_id_env, 0:4] self.right_finger_linvel = self.body_linvel[ :, self.right_finger_body_id_env, 0:3 ] self.right_finger_angvel = self.body_angvel[ :, self.right_finger_body_id_env, 0:3 ] self.right_finger_jacobian = self.jacobian[ :, self.right_finger_body_id_env_actor - 1, 0:6, 0:7 ] # minus 1 because base is fixed self.left_finger_force = self.contact_force[ :, self.left_finger_body_id_env, 0:3 ] self.right_finger_force = self.contact_force[ :, self.right_finger_body_id_env, 0:3 ] self.gripper_dof_pos = self.dof_pos[:, 7:9] self.fingertip_centered_pos = self.body_pos[ :, self.fingertip_centered_body_id_env, 0:3 ] self.fingertip_centered_quat = self.body_quat[ :, self.fingertip_centered_body_id_env, 0:4 ] self.fingertip_centered_linvel = self.body_linvel[ :, self.fingertip_centered_body_id_env, 0:3 ] self.fingertip_centered_angvel = self.body_angvel[ :, self.fingertip_centered_body_id_env, 0:3 ] self.fingertip_centered_jacobian = self.jacobian[ :, self.fingertip_centered_body_id_env_actor - 1, 0:6, 0:7 ] # minus 1 because base is fixed self.fingertip_midpoint_pos = ( self.fingertip_centered_pos.detach().clone() ) # initial value self.fingertip_midpoint_quat = self.fingertip_centered_quat # always equal self.fingertip_midpoint_linvel = ( self.fingertip_centered_linvel.detach().clone() ) # initial value # From sum of angular velocities (https://physics.stackexchange.com/questions/547698/understanding-addition-of-angular-velocity), # angular velocity of midpoint w.r.t. world is equal to sum of # angular velocity of midpoint w.r.t. hand and angular velocity of hand w.r.t. world. # Midpoint is in sliding contact (i.e., linear relative motion) with hand; angular velocity of midpoint w.r.t. hand is zero. # Thus, angular velocity of midpoint w.r.t. world is equal to angular velocity of hand w.r.t. world. self.fingertip_midpoint_angvel = self.fingertip_centered_angvel # always equal self.fingertip_midpoint_jacobian = ( self.left_finger_jacobian + self.right_finger_jacobian ) * 0.5 # approximation self.dof_torque = torch.zeros( (self.num_envs, self.num_dofs), device=self.device ) self.fingertip_contact_wrench = torch.zeros( (self.num_envs, 6), device=self.device ) self.ctrl_target_fingertip_centered_pos = torch.zeros( (self.num_envs, 3), device=self.device ) self.ctrl_target_fingertip_centered_quat = torch.zeros( (self.num_envs, 4), device=self.device ) self.ctrl_target_fingertip_midpoint_pos = torch.zeros( (self.num_envs, 3), device=self.device ) self.ctrl_target_fingertip_midpoint_quat = torch.zeros( (self.num_envs, 4), device=self.device ) self.ctrl_target_dof_pos = torch.zeros( (self.num_envs, self.num_dofs), device=self.device ) self.ctrl_target_gripper_dof_pos = torch.zeros( (self.num_envs, 2), device=self.device ) self.ctrl_target_fingertip_contact_wrench = torch.zeros( (self.num_envs, 6), device=self.device ) self.prev_actions = torch.zeros( (self.num_envs, self.num_actions), device=self.device ) def generate_ctrl_signals(self): """Get Jacobian. Set Franka DOF position targets or DOF torques.""" # Get desired Jacobian if self.cfg_ctrl['jacobian_type'] == 'geometric': self.fingertip_midpoint_jacobian_tf = self.fingertip_centered_jacobian elif self.cfg_ctrl['jacobian_type'] == 'analytic': self.fingertip_midpoint_jacobian_tf = fc.get_analytic_jacobian( fingertip_quat=self.fingertip_quat, fingertip_jacobian=self.fingertip_centered_jacobian, num_envs=self.num_envs, device=self.device) # Set PD joint pos target or joint torque if self.cfg_ctrl['motor_ctrl_mode'] == 'gym': self._set_dof_pos_target() elif self.cfg_ctrl['motor_ctrl_mode'] == 'manual': self._set_dof_torque() def _set_dof_pos_target(self): """Set Franka DOF position target to move fingertips towards target pose.""" self.ctrl_target_dof_pos = fc.compute_dof_pos_target( cfg_ctrl=self.cfg_ctrl, arm_dof_pos=self.arm_dof_pos, fingertip_midpoint_pos=self.fingertip_centered_pos, fingertip_midpoint_quat=self.fingertip_centered_quat, jacobian=self.fingertip_midpoint_jacobian_tf, ctrl_target_fingertip_midpoint_pos=self.ctrl_target_fingertip_centered_pos, ctrl_target_fingertip_midpoint_quat=self.ctrl_target_fingertip_centered_quat, ctrl_target_gripper_dof_pos=self.ctrl_target_gripper_dof_pos, device=self.device) self.gym.set_dof_position_target_tensor_indexed(self.sim, gymtorch.unwrap_tensor(self.ctrl_target_dof_pos), gymtorch.unwrap_tensor(self.franka_actor_ids_sim), len(self.franka_actor_ids_sim)) def _set_dof_torque(self): """Set Franka DOF torque to move fingertips towards target pose.""" self.dof_torque = fc.compute_dof_torque( cfg_ctrl=self.cfg_ctrl, dof_pos=self.dof_pos, dof_vel=self.dof_vel, fingertip_midpoint_pos=self.fingertip_centered_pos, fingertip_midpoint_quat=self.fingertip_centered_quat, fingertip_midpoint_linvel=self.fingertip_centered_linvel, fingertip_midpoint_angvel=self.fingertip_centered_angvel, left_finger_force=self.left_finger_force, right_finger_force=self.right_finger_force, jacobian=self.fingertip_midpoint_jacobian_tf, arm_mass_matrix=self.arm_mass_matrix, ctrl_target_gripper_dof_pos=self.ctrl_target_gripper_dof_pos, ctrl_target_fingertip_midpoint_pos=self.ctrl_target_fingertip_centered_pos, ctrl_target_fingertip_midpoint_quat=self.ctrl_target_fingertip_centered_quat, ctrl_target_fingertip_contact_wrench=self.ctrl_target_fingertip_contact_wrench, device=self.device) self.gym.set_dof_actuation_force_tensor_indexed(self.sim, gymtorch.unwrap_tensor(self.dof_torque), gymtorch.unwrap_tensor(self.franka_actor_ids_sim), len(self.franka_actor_ids_sim)) def simulate_and_refresh(self): """Simulate one step, refresh tensors, and render results.""" self.gym.simulate(self.sim) self.refresh_base_tensors() self.refresh_env_tensors() self._refresh_task_tensors() self.render() def enable_gravity(self): """Enable gravity.""" sim_params = self.gym.get_sim_params(self.sim) sim_params.gravity = gymapi.Vec3(*self.cfg_base.sim.gravity) self.gym.set_sim_params(self.sim, sim_params) def open_gripper(self, sim_steps): """Open gripper using controller. Called outside RL loop (i.e., after last step of episode).""" self.move_gripper_to_target_pose(gripper_dof_pos=0.1, sim_steps=sim_steps) def close_gripper(self, sim_steps): """Fully close gripper using controller. Called outside RL loop (i.e., after last step of episode).""" self.move_gripper_to_target_pose(gripper_dof_pos=0.0, sim_steps=sim_steps) def move_gripper_to_target_pose(self, gripper_dof_pos, sim_steps): """Move gripper to control target pose.""" for _ in range(sim_steps): # NOTE: midpoint is calculated based on the midpoint between the actual gripper finger pos, # and centered is calculated with the assumption that the gripper fingers are perfectly mirrored. # Here we **intentionally** use *_centered_* pos and quat instead of *_midpoint_*, # since the fingertips are exactly mirrored in the real world. pos_error, axis_angle_error = fc.get_pose_error( fingertip_midpoint_pos=self.fingertip_centered_pos, fingertip_midpoint_quat=self.fingertip_centered_quat, ctrl_target_fingertip_midpoint_pos=self.ctrl_target_fingertip_midpoint_pos, ctrl_target_fingertip_midpoint_quat=self.ctrl_target_fingertip_midpoint_quat, jacobian_type=self.cfg_ctrl["jacobian_type"], rot_error_type="axis_angle", ) delta_hand_pose = torch.cat((pos_error, axis_angle_error), dim=-1) actions = torch.zeros( (self.num_envs, self.cfg_task.env.numActions), device=self.device ) actions[:, :6] = delta_hand_pose self._apply_actions_as_ctrl_targets( actions=actions, ctrl_target_gripper_dof_pos=gripper_dof_pos, do_scale=False, ) # Simulate one step self.simulate_and_refresh() # Stabilize Franka self.dof_vel[:, :] = 0.0 self.dof_torque[:, :] = 0.0 self.ctrl_target_fingertip_centered_pos = self.fingertip_centered_pos.clone() self.ctrl_target_fingertip_centered_quat = self.fingertip_centered_quat.clone() # Set DOF state franka_actor_ids_sim = self.franka_actor_ids_sim.clone().to(dtype=torch.int32) self.gym.set_dof_state_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.dof_state), gymtorch.unwrap_tensor(franka_actor_ids_sim), len(franka_actor_ids_sim), ) # Set DOF torque self.gym.set_dof_actuation_force_tensor_indexed( self.sim, gymtorch.unwrap_tensor(self.dof_torque), gymtorch.unwrap_tensor(franka_actor_ids_sim), len(franka_actor_ids_sim), ) # Simulate one step to apply changes self.simulate_and_refresh() def pose_world_to_robot_base(self, pos, quat): """Convert pose from world frame to robot base frame.""" robot_base_transform_inv = torch_utils.tf_inverse( self.robot_base_quat, self.robot_base_pos ) quat_in_robot_base, pos_in_robot_base = torch_utils.tf_combine( robot_base_transform_inv[0], robot_base_transform_inv[1], quat, pos ) return pos_in_robot_base, quat_in_robot_base
22,518
Python
43.592079
145
0.612266
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/industreal/industreal_env_pegs.py
# Copyright (c) 2023, 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. """IndustReal: class for pegs environment. Inherits IndustReal base class and Factory abstract environment class. Inherited by IndustReal peg insertion task class. Not directly executed. Configuration defined in IndustRealEnvPegs.yaml. Asset info defined in industreal_asset_info_pegs.yaml. """ import hydra import math import numpy as np import os import torch from isaacgym import gymapi from isaacgymenvs.tasks.factory.factory_schema_class_env import FactoryABCEnv from isaacgymenvs.tasks.factory.factory_schema_config_env import FactorySchemaConfigEnv from isaacgymenvs.tasks.industreal.industreal_base import IndustRealBase class IndustRealEnvPegs(IndustRealBase, FactoryABCEnv): def __init__( self, cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ): """Initialize instance variables. Initialize environment superclass. Acquire tensors.""" self._get_env_yaml_params() super().__init__( cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ) self.acquire_base_tensors() # defined in superclass self._acquire_env_tensors() self.refresh_base_tensors() # defined in superclass self.refresh_env_tensors() def _get_env_yaml_params(self): """Initialize instance variables from YAML files.""" cs = hydra.core.config_store.ConfigStore.instance() cs.store(name="factory_schema_config_env", node=FactorySchemaConfigEnv) config_path = "task/IndustRealEnvPegs.yaml" # relative to Gym's Hydra search path (cfg dir) self.cfg_env = hydra.compose(config_name=config_path) self.cfg_env = self.cfg_env["task"] # strip superfluous nesting asset_info_path = "../../assets/industreal/yaml/industreal_asset_info_pegs.yaml" # relative to Gym's Hydra search path (cfg dir) self.asset_info_insertion = hydra.compose(config_name=asset_info_path) self.asset_info_insertion = self.asset_info_insertion[""][""][""][""][""][""][ "assets" ]["industreal"][ "yaml" ] # strip superfluous nesting def create_envs(self): """Set env options. Import assets. Create actors.""" lower = gymapi.Vec3( -self.cfg_base.env.env_spacing, -self.cfg_base.env.env_spacing, 0.0 ) upper = gymapi.Vec3( self.cfg_base.env.env_spacing, self.cfg_base.env.env_spacing, self.cfg_base.env.env_spacing, ) num_per_row = int(np.sqrt(self.num_envs)) self.print_sdf_warning() franka_asset, table_asset = self.import_franka_assets() plug_assets, socket_assets = self._import_env_assets() self._create_actors( lower, upper, num_per_row, franka_asset, plug_assets, socket_assets, table_asset, ) def _import_env_assets(self): """Set plug and socket asset options. Import assets.""" self.plug_files, self.socket_files = [], [] urdf_root = os.path.join( os.path.dirname(__file__), "..", "..", "..", "assets", "industreal", "urdf" ) plug_options = gymapi.AssetOptions() plug_options.flip_visual_attachments = False plug_options.fix_base_link = False plug_options.thickness = 0.0 # default = 0.02 plug_options.armature = 0.0 # default = 0.0 plug_options.use_physx_armature = True plug_options.linear_damping = 0.5 # default = 0.0 plug_options.max_linear_velocity = 1000.0 # default = 1000.0 plug_options.angular_damping = 0.5 # default = 0.5 plug_options.max_angular_velocity = 64.0 # default = 64.0 plug_options.disable_gravity = False plug_options.enable_gyroscopic_forces = True plug_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE plug_options.use_mesh_materials = False if self.cfg_base.mode.export_scene: plug_options.mesh_normal_mode = gymapi.COMPUTE_PER_FACE socket_options = gymapi.AssetOptions() socket_options.flip_visual_attachments = False socket_options.fix_base_link = True socket_options.thickness = 0.0 # default = 0.02 socket_options.armature = 0.0 # default = 0.0 socket_options.use_physx_armature = True socket_options.linear_damping = 0.0 # default = 0.0 socket_options.max_linear_velocity = 1.0 # default = 1000.0 socket_options.angular_damping = 0.0 # default = 0.5 socket_options.max_angular_velocity = 2 * math.pi # default = 64.0 socket_options.disable_gravity = False socket_options.enable_gyroscopic_forces = True socket_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE socket_options.use_mesh_materials = False if self.cfg_base.mode.export_scene: socket_options.mesh_normal_mode = gymapi.COMPUTE_PER_FACE plug_assets = [] socket_assets = [] for subassembly in self.cfg_env.env.desired_subassemblies: components = list(self.asset_info_insertion[subassembly]) plug_file = ( self.asset_info_insertion[subassembly][components[0]]["urdf_path"] + ".urdf" ) socket_file = ( self.asset_info_insertion[subassembly][components[1]]["urdf_path"] + ".urdf" ) plug_options.density = self.asset_info_insertion[subassembly][ components[0] ]["density"] socket_options.density = self.asset_info_insertion[subassembly][ components[1] ]["density"] plug_asset = self.gym.load_asset( self.sim, urdf_root, plug_file, plug_options ) socket_asset = self.gym.load_asset( self.sim, urdf_root, socket_file, socket_options ) plug_assets.append(plug_asset) socket_assets.append(socket_asset) # Save URDF file paths (for loading appropriate meshes during SAPU and SDF-Based Reward calculations) self.plug_files.append(os.path.join(urdf_root, plug_file)) self.socket_files.append(os.path.join(urdf_root, socket_file)) return plug_assets, socket_assets def _create_actors( self, lower, upper, num_per_row, franka_asset, plug_assets, socket_assets, table_asset, ): """Set initial actor poses. Create actors. Set shape and DOF properties.""" # NOTE: Closely adapted from FactoryEnvInsertion; however, plug grasp offsets, plug widths, socket heights, # and asset indices are now stored for possible use during policy learning.""" franka_pose = gymapi.Transform() franka_pose.p.x = -self.cfg_base.env.franka_depth franka_pose.p.y = 0.0 franka_pose.p.z = self.cfg_base.env.table_height franka_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) table_pose = gymapi.Transform() table_pose.p.x = 0.0 table_pose.p.y = 0.0 table_pose.p.z = self.cfg_base.env.table_height * 0.5 table_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) self.env_ptrs = [] self.franka_handles = [] self.plug_handles = [] self.socket_handles = [] self.table_handles = [] self.shape_ids = [] self.franka_actor_ids_sim = [] # within-sim indices self.plug_actor_ids_sim = [] # within-sim indices self.socket_actor_ids_sim = [] # within-sim indices self.table_actor_ids_sim = [] # within-sim indices actor_count = 0 self.plug_grasp_offsets = [] self.plug_widths = [] self.socket_heights = [] self.asset_indices = [] for i in range(self.num_envs): env_ptr = self.gym.create_env(self.sim, lower, upper, num_per_row) franka_handle = self.gym.create_actor( env_ptr, franka_asset, franka_pose, "franka", i, 0, 0 ) self.franka_actor_ids_sim.append(actor_count) actor_count += 1 j = np.random.randint(0, len(self.cfg_env.env.desired_subassemblies)) subassembly = self.cfg_env.env.desired_subassemblies[j] components = list(self.asset_info_insertion[subassembly]) plug_pose = gymapi.Transform() plug_pose.p.x = 0.0 plug_pose.p.y = self.cfg_env.env.plug_lateral_offset plug_pose.p.z = self.cfg_base.env.table_height plug_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) plug_handle = self.gym.create_actor( env_ptr, plug_assets[j], plug_pose, "plug", i, 0, 0 ) self.plug_actor_ids_sim.append(actor_count) actor_count += 1 socket_pose = gymapi.Transform() socket_pose.p.x = 0.0 socket_pose.p.y = 0.0 socket_pose.p.z = self.cfg_base.env.table_height socket_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) socket_handle = self.gym.create_actor( env_ptr, socket_assets[j], socket_pose, "socket", i, 0, 0 ) self.socket_actor_ids_sim.append(actor_count) actor_count += 1 table_handle = self.gym.create_actor( env_ptr, table_asset, table_pose, "table", i, 0, 0 ) self.table_actor_ids_sim.append(actor_count) actor_count += 1 link7_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_link7", gymapi.DOMAIN_ACTOR ) hand_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_hand", gymapi.DOMAIN_ACTOR ) left_finger_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_leftfinger", gymapi.DOMAIN_ACTOR ) right_finger_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_rightfinger", gymapi.DOMAIN_ACTOR ) self.shape_ids = [link7_id, hand_id, left_finger_id, right_finger_id] franka_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, franka_handle ) for shape_id in self.shape_ids: franka_shape_props[ shape_id ].friction = self.cfg_base.env.franka_friction franka_shape_props[shape_id].rolling_friction = 0.0 # default = 0.0 franka_shape_props[shape_id].torsion_friction = 0.0 # default = 0.0 franka_shape_props[shape_id].restitution = 0.0 # default = 0.0 franka_shape_props[shape_id].compliance = 0.0 # default = 0.0 franka_shape_props[shape_id].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, franka_handle, franka_shape_props ) plug_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, plug_handle ) plug_shape_props[0].friction = self.asset_info_insertion[subassembly][ components[0] ]["friction"] plug_shape_props[0].rolling_friction = 0.0 # default = 0.0 plug_shape_props[0].torsion_friction = 0.0 # default = 0.0 plug_shape_props[0].restitution = 0.0 # default = 0.0 plug_shape_props[0].compliance = 0.0 # default = 0.0 plug_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, plug_handle, plug_shape_props ) socket_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, socket_handle ) socket_shape_props[0].friction = self.asset_info_insertion[subassembly][ components[1] ]["friction"] socket_shape_props[0].rolling_friction = 0.0 # default = 0.0 socket_shape_props[0].torsion_friction = 0.0 # default = 0.0 socket_shape_props[0].restitution = 0.0 # default = 0.0 socket_shape_props[0].compliance = 0.0 # default = 0.0 socket_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, socket_handle, socket_shape_props ) table_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, table_handle ) table_shape_props[0].friction = self.cfg_base.env.table_friction table_shape_props[0].rolling_friction = 0.0 # default = 0.0 table_shape_props[0].torsion_friction = 0.0 # default = 0.0 table_shape_props[0].restitution = 0.0 # default = 0.0 table_shape_props[0].compliance = 0.0 # default = 0.0 table_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, table_handle, table_shape_props ) self.franka_num_dofs = self.gym.get_actor_dof_count(env_ptr, franka_handle) self.gym.enable_actor_dof_force_sensors(env_ptr, franka_handle) plug_grasp_offset = self.asset_info_insertion[subassembly][components[0]][ "grasp_offset" ] plug_width = self.asset_info_insertion[subassembly][components[0]][ "plug_width" ] socket_height = self.asset_info_insertion[subassembly][components[1]][ "height" ] self.env_ptrs.append(env_ptr) self.franka_handles.append(franka_handle) self.plug_handles.append(plug_handle) self.socket_handles.append(socket_handle) self.table_handles.append(table_handle) self.plug_grasp_offsets.append(plug_grasp_offset) self.plug_widths.append(plug_width) self.socket_heights.append(socket_height) self.asset_indices.append(j) self.num_actors = int(actor_count / self.num_envs) # per env self.num_bodies = self.gym.get_env_rigid_body_count(env_ptr) # per env self.num_dofs = self.gym.get_env_dof_count(env_ptr) # per env # For setting targets self.franka_actor_ids_sim = torch.tensor( self.franka_actor_ids_sim, dtype=torch.int32, device=self.device ) self.plug_actor_ids_sim = torch.tensor( self.plug_actor_ids_sim, dtype=torch.int32, device=self.device ) self.socket_actor_ids_sim = torch.tensor( self.socket_actor_ids_sim, dtype=torch.int32, device=self.device ) # For extracting root pos/quat self.plug_actor_id_env = self.gym.find_actor_index( env_ptr, "plug", gymapi.DOMAIN_ENV ) self.socket_actor_id_env = self.gym.find_actor_index( env_ptr, "socket", gymapi.DOMAIN_ENV ) # For extracting body pos/quat, force, and Jacobian self.robot_base_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_link0", gymapi.DOMAIN_ENV ) self.plug_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, plug_handle, "plug", gymapi.DOMAIN_ENV ) self.socket_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, socket_handle, "socket", gymapi.DOMAIN_ENV ) self.hand_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_hand", gymapi.DOMAIN_ENV ) self.left_finger_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_leftfinger", gymapi.DOMAIN_ENV ) self.right_finger_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_rightfinger", gymapi.DOMAIN_ENV ) self.fingertip_centered_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_fingertip_centered", gymapi.DOMAIN_ENV ) self.hand_body_id_env_actor = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_hand", gymapi.DOMAIN_ACTOR ) self.left_finger_body_id_env_actor = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_leftfinger", gymapi.DOMAIN_ACTOR ) self.right_finger_body_id_env_actor = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_rightfinger", gymapi.DOMAIN_ACTOR ) self.fingertip_centered_body_id_env_actor = ( self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_fingertip_centered", gymapi.DOMAIN_ACTOR ) ) # For computing body COM pos self.plug_grasp_offsets = torch.tensor( self.plug_grasp_offsets, device=self.device ) self.plug_widths = torch.tensor(self.plug_widths, device=self.device) self.socket_heights = torch.tensor(self.socket_heights, device=self.device) def _acquire_env_tensors(self): """Acquire and wrap tensors. Create views.""" self.plug_pos = self.root_pos[:, self.plug_actor_id_env, 0:3] self.plug_quat = self.root_quat[:, self.plug_actor_id_env, 0:4] self.plug_linvel = self.root_linvel[:, self.plug_actor_id_env, 0:3] self.plug_angvel = self.root_angvel[:, self.plug_actor_id_env, 0:3] self.socket_pos = self.root_pos[:, self.socket_actor_id_env, 0:3] self.socket_quat = self.root_quat[:, self.socket_actor_id_env, 0:4] self.socket_linvel = self.root_linvel[:, self.socket_actor_id_env, 0:3] self.socket_angvel = self.root_angvel[:, self.socket_actor_id_env, 0:3] # TODO: Define socket height and plug height params in asset info YAML. # self.plug_com_pos = self.translate_along_local_z(pos=self.plug_pos, # quat=self.plug_quat, # offset=self.socket_heights + self.plug_heights * 0.5, # device=self.device) self.plug_com_quat = self.plug_quat # always equal # self.plug_com_linvel = self.plug_linvel + torch.cross(self.plug_angvel, # (self.plug_com_pos - self.plug_pos), # dim=1) self.plug_com_angvel = self.plug_angvel # always equal def refresh_env_tensors(self): """Refresh tensors.""" # NOTE: Tensor refresh functions should be called once per step, before setters. pass
20,854
Python
42.538622
143
0.596145
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/industreal/industreal_env_gears.py
# Copyright (c) 2023, 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. """IndustReal: class for gears environment. Inherits IndustReal base class and Factory abstract environment class. Inherited by IndustReal gear insertion task class. Not directly executed. Configuration defined in IndustRealEnvGears.yaml. Asset info defined in industreal_asset_info_gears.yaml. """ import hydra import os import torch import numpy as np from isaacgym import gymapi import isaacgymenvs.tasks.factory.factory_control as fc from isaacgymenvs.tasks.factory.factory_schema_class_env import FactoryABCEnv from isaacgymenvs.tasks.factory.factory_schema_config_env import FactorySchemaConfigEnv from isaacgymenvs.tasks.industreal.industreal_base import IndustRealBase class IndustRealEnvGears(IndustRealBase, FactoryABCEnv): def __init__( self, cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ): """Initialize instance variables. Initialize environment superclass. Acquire tensors.""" self._get_env_yaml_params() super().__init__( cfg, rl_device, sim_device, graphics_device_id, headless, virtual_screen_capture, force_render, ) self.acquire_base_tensors() # defined in superclass self._acquire_env_tensors() self.refresh_base_tensors() # defined in superclass self.refresh_env_tensors() def _get_env_yaml_params(self): """Initialize instance variables from YAML files.""" cs = hydra.core.config_store.ConfigStore.instance() cs.store(name="factory_schema_config_env", node=FactorySchemaConfigEnv) config_path = "task/IndustRealEnvGears.yaml" # relative to Gym's Hydra search path (cfg dir) self.cfg_env = hydra.compose(config_name=config_path) self.cfg_env = self.cfg_env["task"] # strip superfluous nesting asset_info_path = "../../assets/industreal/yaml/industreal_asset_info_gears.yaml" # relative to Hydra search path (cfg dir) self.asset_info_gears = hydra.compose(config_name=asset_info_path) self.asset_info_gears = self.asset_info_gears[""][""][""][""][""][""]["assets"][ "industreal" ][ "yaml" ] # strip superfluous nesting def create_envs(self): """Set env options. Import assets. Create actors.""" lower = gymapi.Vec3( -self.cfg_base.env.env_spacing, -self.cfg_base.env.env_spacing, 0.0 ) upper = gymapi.Vec3( self.cfg_base.env.env_spacing, self.cfg_base.env.env_spacing, self.cfg_base.env.env_spacing, ) num_per_row = int(np.sqrt(self.num_envs)) self.print_sdf_warning() franka_asset, table_asset = self.import_franka_assets() ( gear_small_asset, gear_medium_asset, gear_large_asset, base_asset, ) = self._import_env_assets() self._create_actors( lower, upper, num_per_row, franka_asset, gear_small_asset, gear_medium_asset, gear_large_asset, base_asset, table_asset, ) def _import_env_assets(self): """Set gear and base asset options. Import assets.""" urdf_root = os.path.join( os.path.dirname(__file__), "..", "..", "..", "assets", "industreal", "urdf" ) gear_small_file = "industreal_gear_small.urdf" gear_medium_file = "industreal_gear_medium.urdf" gear_large_file = "industreal_gear_large.urdf" base_file = "industreal_gear_base.urdf" gear_options = gymapi.AssetOptions() gear_options.flip_visual_attachments = False gear_options.fix_base_link = False gear_options.thickness = 0.0 # default = 0.02 gear_options.density = self.asset_info_gears.gears.density # default = 1000.0 gear_options.armature = 0.0 # default = 0.0 gear_options.use_physx_armature = True gear_options.linear_damping = 0.5 # default = 0.0 gear_options.max_linear_velocity = 1000.0 # default = 1000.0 gear_options.angular_damping = 0.5 # default = 0.5 gear_options.max_angular_velocity = 64.0 # default = 64.0 gear_options.disable_gravity = False gear_options.enable_gyroscopic_forces = True gear_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE gear_options.use_mesh_materials = False if self.cfg_base.mode.export_scene: gear_options.mesh_normal_mode = gymapi.COMPUTE_PER_FACE base_options = gymapi.AssetOptions() base_options.flip_visual_attachments = False base_options.fix_base_link = True base_options.thickness = 0.0 # default = 0.02 base_options.density = self.asset_info_gears.base.density # default = 1000.0 base_options.armature = 0.0 # default = 0.0 base_options.use_physx_armature = True base_options.linear_damping = 0.0 # default = 0.0 base_options.max_linear_velocity = 1000.0 # default = 1000.0 base_options.angular_damping = 0.0 # default = 0.5 base_options.max_angular_velocity = 64.0 # default = 64.0 base_options.disable_gravity = False base_options.enable_gyroscopic_forces = True base_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE base_options.use_mesh_materials = False if self.cfg_base.mode.export_scene: base_options.mesh_normal_mode = gymapi.COMPUTE_PER_FACE gear_small_asset = self.gym.load_asset( self.sim, urdf_root, gear_small_file, gear_options ) gear_medium_asset = self.gym.load_asset( self.sim, urdf_root, gear_medium_file, gear_options ) gear_large_asset = self.gym.load_asset( self.sim, urdf_root, gear_large_file, gear_options ) base_asset = self.gym.load_asset(self.sim, urdf_root, base_file, base_options) # Save URDF file paths and asset indices (for loading appropriate meshes during SAPU and SDF-Based Reward calculations) self.gear_files = [os.path.join(urdf_root, gear_medium_file)] self.shaft_files = [os.path.join(urdf_root, base_file)] # NOTE: Saving asset indices is not necessary for IndustRealEnvGears, as each parallel env has same assets; however, asset # indices are saved anyway for parity with IndustRealEnvPegs. self.asset_indices = [0 for _ in range(self.num_envs)] return gear_small_asset, gear_medium_asset, gear_large_asset, base_asset def _create_actors( self, lower, upper, num_per_row, franka_asset, gear_small_asset, gear_medium_asset, gear_large_asset, base_asset, table_asset, ): """Set initial actor poses. Create actors. Set shape and DOF properties.""" franka_pose = gymapi.Transform() franka_pose.p.x = -self.cfg_base.env.franka_depth franka_pose.p.y = 0.0 franka_pose.p.z = self.cfg_base.env.table_height franka_pose.r = gymapi.Quat( 0.0, 0.0, 0.0, 1.0 ) # TODO: Verify pose with Michael table_pose = gymapi.Transform() table_pose.p.x = 0.0 table_pose.p.y = 0.0 table_pose.p.z = self.cfg_base.env.table_height * 0.5 table_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) gear_pose = gymapi.Transform() gear_pose.p.x = 0.0 gear_pose.p.y = self.cfg_env.env.gears_lateral_offset gear_pose.p.z = self.cfg_base.env.table_height gear_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) base_pose = gymapi.Transform() base_pose.p.x = 0.0 base_pose.p.y = 0.0 base_pose.p.z = self.cfg_base.env.table_height base_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) table_pose = gymapi.Transform() table_pose.p.x = 0.0 table_pose.p.y = 0.0 table_pose.p.z = self.cfg_base.env.table_height * 0.5 table_pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) self.env_ptrs = [] self.franka_handles = [] self.gear_small_handles = [] self.gear_medium_handles = [] self.gear_large_handles = [] self.base_handles = [] self.table_handles = [] self.shape_ids = [] self.franka_actor_ids_sim = [] # within-sim indices self.gear_small_actor_ids_sim = [] # within-sim indices self.gear_medium_actor_ids_sim = [] # within-sim indices self.gear_large_actor_ids_sim = [] # within-sim indices self.base_actor_ids_sim = [] # within-sim indices self.table_actor_ids_sim = [] # within-sim indices actor_count = 0 for i in range(self.num_envs): env_ptr = self.gym.create_env(self.sim, lower, upper, num_per_row) if self.cfg_env.sim.disable_franka_collisions: franka_handle = self.gym.create_actor( env_ptr, franka_asset, franka_pose, "franka", i + self.num_envs, 0, 0, ) else: franka_handle = self.gym.create_actor( env_ptr, franka_asset, franka_pose, "franka", i, 0, 0 ) self.franka_actor_ids_sim.append(actor_count) actor_count += 1 gear_small_handle = self.gym.create_actor( env_ptr, gear_small_asset, gear_pose, "gear_small", i, 0, 0 ) self.gear_small_actor_ids_sim.append(actor_count) actor_count += 1 gear_medium_handle = self.gym.create_actor( env_ptr, gear_medium_asset, gear_pose, "gear_medium", i, 0, 0 ) self.gear_medium_actor_ids_sim.append(actor_count) actor_count += 1 gear_large_handle = self.gym.create_actor( env_ptr, gear_large_asset, gear_pose, "gear_large", i, 0, 0 ) self.gear_large_actor_ids_sim.append(actor_count) actor_count += 1 base_handle = self.gym.create_actor( env_ptr, base_asset, base_pose, "base", i, 0, 0 ) self.base_actor_ids_sim.append(actor_count) actor_count += 1 table_handle = self.gym.create_actor( env_ptr, table_asset, table_pose, "table", i, 0, 0 ) self.table_actor_ids_sim.append(actor_count) actor_count += 1 link7_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_link7", gymapi.DOMAIN_ACTOR ) hand_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_hand", gymapi.DOMAIN_ACTOR ) left_finger_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_leftfinger", gymapi.DOMAIN_ACTOR ) right_finger_id = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_rightfinger", gymapi.DOMAIN_ACTOR ) self.shape_ids = [link7_id, hand_id, left_finger_id, right_finger_id] franka_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, franka_handle ) for shape_id in self.shape_ids: franka_shape_props[ shape_id ].friction = self.cfg_base.env.franka_friction franka_shape_props[shape_id].rolling_friction = 0.0 # default = 0.0 franka_shape_props[shape_id].torsion_friction = 0.0 # default = 0.0 franka_shape_props[shape_id].restitution = 0.0 # default = 0.0 franka_shape_props[shape_id].compliance = 0.0 # default = 0.0 franka_shape_props[shape_id].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, franka_handle, franka_shape_props ) gear_small_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, gear_small_handle ) gear_small_shape_props[0].friction = self.cfg_env.env.gears_friction gear_small_shape_props[0].rolling_friction = 0.0 # default = 0.0 gear_small_shape_props[0].torsion_friction = 0.0 # default = 0.0 gear_small_shape_props[0].restitution = 0.0 # default = 0.0 gear_small_shape_props[0].compliance = 0.0 # default = 0.0 gear_small_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, gear_small_handle, gear_small_shape_props ) gear_medium_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, gear_medium_handle ) gear_medium_shape_props[0].friction = self.cfg_env.env.gears_friction gear_medium_shape_props[0].rolling_friction = 0.0 # default = 0.0 gear_medium_shape_props[0].torsion_friction = 0.0 # default = 0.0 gear_medium_shape_props[0].restitution = 0.0 # default = 0.0 gear_medium_shape_props[0].compliance = 0.0 # default = 0.0 gear_medium_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, gear_medium_handle, gear_medium_shape_props ) gear_large_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, gear_large_handle ) gear_large_shape_props[0].friction = self.cfg_env.env.gears_friction gear_large_shape_props[0].rolling_friction = 0.0 # default = 0.0 gear_large_shape_props[0].torsion_friction = 0.0 # default = 0.0 gear_large_shape_props[0].restitution = 0.0 # default = 0.0 gear_large_shape_props[0].compliance = 0.0 # default = 0.0 gear_large_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, gear_large_handle, gear_large_shape_props ) base_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, base_handle ) base_shape_props[0].friction = self.cfg_env.env.base_friction base_shape_props[0].rolling_friction = 0.0 # default = 0.0 base_shape_props[0].torsion_friction = 0.0 # default = 0.0 base_shape_props[0].restitution = 0.0 # default = 0.0 base_shape_props[0].compliance = 0.0 # default = 0.0 base_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, base_handle, base_shape_props ) table_shape_props = self.gym.get_actor_rigid_shape_properties( env_ptr, table_handle ) table_shape_props[0].friction = self.cfg_base.env.table_friction table_shape_props[0].rolling_friction = 0.0 # default = 0.0 table_shape_props[0].torsion_friction = 0.0 # default = 0.0 table_shape_props[0].restitution = 0.0 # default = 0.0 table_shape_props[0].compliance = 0.0 # default = 0.0 table_shape_props[0].thickness = 0.0 # default = 0.0 self.gym.set_actor_rigid_shape_properties( env_ptr, table_handle, table_shape_props ) self.franka_num_dofs = self.gym.get_actor_dof_count(env_ptr, franka_handle) self.gym.enable_actor_dof_force_sensors(env_ptr, franka_handle) self.env_ptrs.append(env_ptr) self.franka_handles.append(franka_handle) self.gear_small_handles.append(gear_small_handle) self.gear_medium_handles.append(gear_medium_handle) self.gear_large_handles.append(gear_large_handle) self.base_handles.append(base_handle) self.table_handles.append(table_handle) self.num_actors = int(actor_count / self.num_envs) # per env self.num_bodies = self.gym.get_env_rigid_body_count(env_ptr) # per env self.num_dofs = self.gym.get_env_dof_count(env_ptr) # per env # For setting targets self.franka_actor_ids_sim = torch.tensor( self.franka_actor_ids_sim, dtype=torch.int32, device=self.device ) self.gear_small_actor_ids_sim = torch.tensor( self.gear_small_actor_ids_sim, dtype=torch.int32, device=self.device ) self.gear_medium_actor_ids_sim = torch.tensor( self.gear_medium_actor_ids_sim, dtype=torch.int32, device=self.device ) self.gear_large_actor_ids_sim = torch.tensor( self.gear_large_actor_ids_sim, dtype=torch.int32, device=self.device ) self.base_actor_ids_sim = torch.tensor( self.base_actor_ids_sim, dtype=torch.int32, device=self.device ) # For extracting root pos/quat self.gear_small_actor_id_env = self.gym.find_actor_index( env_ptr, "gear_small", gymapi.DOMAIN_ENV ) self.gear_medium_actor_id_env = self.gym.find_actor_index( env_ptr, "gear_medium", gymapi.DOMAIN_ENV ) self.gear_large_actor_id_env = self.gym.find_actor_index( env_ptr, "gear_large", gymapi.DOMAIN_ENV ) self.base_actor_id_env = self.gym.find_actor_index( env_ptr, "base", gymapi.DOMAIN_ENV ) # For extracting body pos/quat, force, and Jacobian self.robot_base_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_link0", gymapi.DOMAIN_ENV ) self.gear_small_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, gear_small_handle, "gear_small", gymapi.DOMAIN_ENV ) self.gear_mediums_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, gear_medium_handle, "gear_small", gymapi.DOMAIN_ENV ) self.gear_large_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, gear_large_handle, "gear_small", gymapi.DOMAIN_ENV ) self.base_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, base_handle, "base", gymapi.DOMAIN_ENV ) self.hand_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_hand", gymapi.DOMAIN_ENV ) self.left_finger_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_leftfinger", gymapi.DOMAIN_ENV ) self.right_finger_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_rightfinger", gymapi.DOMAIN_ENV ) self.fingertip_centered_body_id_env = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_fingertip_centered", gymapi.DOMAIN_ENV ) self.hand_body_id_env_actor = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_hand", gymapi.DOMAIN_ACTOR ) self.left_finger_body_id_env_actor = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_leftfinger", gymapi.DOMAIN_ACTOR ) self.right_finger_body_id_env_actor = self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_rightfinger", gymapi.DOMAIN_ACTOR ) self.fingertip_centered_body_id_env_actor = ( self.gym.find_actor_rigid_body_index( env_ptr, franka_handle, "panda_fingertip_centered", gymapi.DOMAIN_ACTOR ) ) def _acquire_env_tensors(self): """Acquire and wrap tensors. Create views.""" self.gear_small_pos = self.root_pos[:, self.gear_small_actor_id_env, 0:3] self.gear_small_quat = self.root_quat[:, self.gear_small_actor_id_env, 0:4] self.gear_small_linvel = self.root_linvel[:, self.gear_small_actor_id_env, 0:3] self.gear_small_angvel = self.root_angvel[:, self.gear_small_actor_id_env, 0:3] self.gear_medium_pos = self.root_pos[:, self.gear_medium_actor_id_env, 0:3] self.gear_medium_quat = self.root_quat[:, self.gear_medium_actor_id_env, 0:4] self.gear_medium_linvel = self.root_linvel[ :, self.gear_medium_actor_id_env, 0:3 ] self.gear_medium_angvel = self.root_angvel[ :, self.gear_medium_actor_id_env, 0:3 ] self.gear_large_pos = self.root_pos[:, self.gear_large_actor_id_env, 0:3] self.gear_large_quat = self.root_quat[:, self.gear_large_actor_id_env, 0:4] self.gear_large_linvel = self.root_linvel[:, self.gear_large_actor_id_env, 0:3] self.gear_large_angvel = self.root_angvel[:, self.gear_large_actor_id_env, 0:3] self.base_pos = self.root_pos[:, self.base_actor_id_env, 0:3] self.base_quat = self.root_quat[:, self.base_actor_id_env, 0:4] self.base_linvel = self.root_linvel[:, self.base_actor_id_env, 0:3] self.base_angvel = self.root_angvel[:, self.base_actor_id_env, 0:3] self.gear_small_com_pos = fc.translate_along_local_z( pos=self.gear_small_pos, quat=self.gear_small_quat, offset=self.asset_info_gears.base.height + self.asset_info_gears.gears.height * 0.5, device=self.device, ) self.gear_small_com_quat = self.gear_small_quat # always equal self.gear_small_com_linvel = self.gear_small_linvel + torch.cross( self.gear_small_angvel, (self.gear_small_com_pos - self.gear_small_pos), dim=1, ) self.gear_small_com_angvel = self.gear_small_angvel # always equal self.gear_medium_com_pos = fc.translate_along_local_z( pos=self.gear_medium_pos, quat=self.gear_medium_quat, offset=self.asset_info_gears.base.height + self.asset_info_gears.gears.height * 0.5, device=self.device, ) self.gear_medium_com_quat = self.gear_medium_quat # always equal self.gear_medium_com_linvel = self.gear_medium_linvel + torch.cross( self.gear_medium_angvel, (self.gear_medium_com_pos - self.gear_medium_pos), dim=1, ) self.gear_medium_com_angvel = self.gear_medium_angvel # always equal self.gear_large_com_pos = fc.translate_along_local_z( pos=self.gear_large_pos, quat=self.gear_large_quat, offset=self.asset_info_gears.base.height + self.asset_info_gears.gears.height * 0.5, device=self.device, ) self.gear_large_com_quat = self.gear_large_quat # always equal self.gear_large_com_linvel = self.gear_large_linvel + torch.cross( self.gear_large_angvel, (self.gear_large_com_pos - self.gear_large_pos), dim=1, ) self.gear_large_com_angvel = self.gear_large_angvel # always equal def refresh_env_tensors(self): """Refresh tensors.""" # NOTE: Tensor refresh functions should be called once per step, before setters. self.gear_small_com_pos = fc.translate_along_local_z( pos=self.gear_small_pos, quat=self.gear_small_quat, offset=self.asset_info_gears.base.height + self.asset_info_gears.gears.height * 0.5, device=self.device, ) self.gear_small_com_linvel = self.gear_small_linvel + torch.cross( self.gear_small_angvel, (self.gear_small_com_pos - self.gear_small_pos), dim=1, ) self.gear_medium_com_pos = fc.translate_along_local_z( pos=self.gear_medium_pos, quat=self.gear_medium_quat, offset=self.asset_info_gears.base.height + self.asset_info_gears.gears.height * 0.5, device=self.device, ) self.gear_medium_com_linvel = self.gear_medium_linvel + torch.cross( self.gear_medium_angvel, (self.gear_medium_com_pos - self.gear_medium_pos), dim=1, ) self.gear_large_com_pos = fc.translate_along_local_z( pos=self.gear_large_pos, quat=self.gear_large_quat, offset=self.asset_info_gears.base.height + self.asset_info_gears.gears.height * 0.5, device=self.device, ) self.gear_large_com_linvel = self.gear_large_linvel + torch.cross( self.gear_large_angvel, (self.gear_large_com_pos - self.gear_large_pos), dim=1, )
26,679
Python
42.666121
144
0.598373
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/tasks/industreal/industreal_algo_utils.py
# Copyright (c) 2023, 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. """IndustReal: algorithms module. Contains functions that implement Simulation-Aware Policy Update (SAPU), SDF-Based Reward, and Sampling-Based Curriculum (SBC). Not intended to be executed as a standalone script. """ import numpy as np from pysdf import SDF import torch import trimesh from urdfpy import URDF import warp as wp """ Simulation-Aware Policy Update (SAPU) """ def load_asset_mesh_in_warp(urdf_path, sample_points, num_samples, device): """Create mesh object in Warp.""" urdf = URDF.load(urdf_path) mesh = urdf.links[0].collision_mesh wp_mesh = wp.Mesh( points=wp.array(mesh.vertices, dtype=wp.vec3, device=device), indices=wp.array(mesh.faces.flatten(), dtype=wp.int32, device=device), ) if sample_points: # Sample points on surface of mesh sampled_points, _ = trimesh.sample.sample_surface_even(mesh, num_samples) wp_mesh_sampled_points = wp.array(sampled_points, dtype=wp.vec3, device=device) return wp_mesh, wp_mesh_sampled_points else: return wp_mesh def load_asset_meshes_in_warp(plug_files, socket_files, num_samples, device): """Create mesh objects in Warp for all environments.""" # Load and store plug meshes and (if desired) sampled points plug_meshes, plug_meshes_sampled_points = [], [] for i in range(len(plug_files)): plug_mesh, sampled_points = load_asset_mesh_in_warp( urdf_path=plug_files[i], sample_points=True, num_samples=num_samples, device=device, ) plug_meshes.append(plug_mesh) plug_meshes_sampled_points.append(sampled_points) # Load and store socket meshes socket_meshes = [ load_asset_mesh_in_warp( urdf_path=socket_files[i], sample_points=False, num_samples=-1, device=device, ) for i in range(len(socket_files)) ] return plug_meshes, plug_meshes_sampled_points, socket_meshes def get_max_interpen_dists( asset_indices, plug_pos, plug_quat, socket_pos, socket_quat, wp_plug_meshes_sampled_points, wp_socket_meshes, wp_device, device, ): """Get maximum interpenetration distances between plugs and sockets.""" num_envs = len(plug_pos) max_interpen_dists = torch.zeros((num_envs,), dtype=torch.float32, device=device) for i in range(num_envs): asset_idx = asset_indices[i] # Compute transform from plug frame to socket frame plug_transform = wp.transform(plug_pos[i], plug_quat[i]) socket_transform = wp.transform(socket_pos[i], socket_quat[i]) socket_inv_transform = wp.transform_inverse(socket_transform) plug_to_socket_transform = wp.transform_multiply( plug_transform, socket_inv_transform ) # Transform plug mesh vertices to socket frame plug_points = wp.clone(wp_plug_meshes_sampled_points[asset_idx]) wp.launch( kernel=transform_points, dim=len(plug_points), inputs=[plug_points, plug_points, plug_to_socket_transform], device=wp_device, ) # Compute max interpenetration distance between plug and socket interpen_dist_plug_socket = wp.zeros( (len(plug_points),), dtype=wp.float32, device=wp_device ) wp.launch( kernel=get_interpen_dist, dim=len(plug_points), inputs=[ plug_points, wp_socket_meshes[asset_idx].id, interpen_dist_plug_socket, ], device=wp_device, ) max_interpen_dist = -torch.min(wp.to_torch(interpen_dist_plug_socket)) # Store interpenetration flag and max interpenetration distance if max_interpen_dist > 0.0: max_interpen_dists[i] = max_interpen_dist return max_interpen_dists def get_sapu_reward_scale( asset_indices, plug_pos, plug_quat, socket_pos, socket_quat, wp_plug_meshes_sampled_points, wp_socket_meshes, interpen_thresh, wp_device, device, ): """Compute reward scale for SAPU.""" # Get max interpenetration distances max_interpen_dists = get_max_interpen_dists( asset_indices=asset_indices, plug_pos=plug_pos, plug_quat=plug_quat, socket_pos=socket_pos, socket_quat=socket_quat, wp_plug_meshes_sampled_points=wp_plug_meshes_sampled_points, wp_socket_meshes=wp_socket_meshes, wp_device=wp_device, device=device, ) # Determine if envs have low interpenetration or high interpenetration low_interpen_envs = torch.nonzero(max_interpen_dists <= interpen_thresh) high_interpen_envs = torch.nonzero(max_interpen_dists > interpen_thresh) # Compute reward scale reward_scale = 1 - torch.tanh( max_interpen_dists[low_interpen_envs] / interpen_thresh ) return low_interpen_envs, high_interpen_envs, reward_scale """ SDF-Based Reward """ def get_plug_goal_sdfs( wp_plug_meshes, asset_indices, socket_pos, socket_quat, wp_device ): """Get SDFs of plug meshes at goal pose.""" num_envs = len(socket_pos) plug_goal_sdfs = [] for i in range(num_envs): # Create copy of plug mesh mesh = wp_plug_meshes[asset_indices[i]] mesh_points = wp.clone(mesh.points) mesh_indices = wp.clone(mesh.indices) mesh_copy = wp.Mesh(points=mesh_points, indices=mesh_indices) # Transform plug mesh from current pose to goal pose # NOTE: In source OBJ files, when plug and socket are assembled, # their poses are identical goal_transform = wp.transform(socket_pos[i], socket_quat[i]) wp.launch( kernel=transform_points, dim=len(mesh_copy.points), inputs=[mesh_copy.points, mesh_copy.points, goal_transform], device=wp_device, ) # Rebuild BVH (see https://nvidia.github.io/warp/_build/html/modules/runtime.html#meshes) mesh_copy.refit() # Create SDF from transformed mesh sdf = SDF(mesh_copy.points.numpy(), mesh_copy.indices.numpy().reshape(-1, 3)) plug_goal_sdfs.append(sdf) return plug_goal_sdfs def get_sdf_reward( wp_plug_meshes_sampled_points, asset_indices, plug_pos, plug_quat, plug_goal_sdfs, wp_device, device, ): """Calculate SDF-based reward.""" num_envs = len(plug_pos) sdf_reward = torch.zeros((num_envs,), dtype=torch.float32, device=device) for i in range(num_envs): # Create copy of sampled points sampled_points = wp.clone(wp_plug_meshes_sampled_points[asset_indices[i]]) # Transform sampled points from original plug pose to current plug pose curr_transform = wp.transform(plug_pos[i], plug_quat[i]) wp.launch( kernel=transform_points, dim=len(sampled_points), inputs=[sampled_points, sampled_points, curr_transform], device=wp_device, ) # Get SDF values at transformed points sdf_dists = torch.from_numpy(plug_goal_sdfs[i](sampled_points.numpy())).double() # Clamp values outside isosurface and take absolute value sdf_dists = torch.abs(torch.where(sdf_dists > 0.0, 0.0, sdf_dists)) sdf_reward[i] = torch.mean(sdf_dists) sdf_reward = -torch.log(sdf_reward) return sdf_reward """ Sampling-Based Curriculum (SBC) """ def get_curriculum_reward_scale(cfg_task, curr_max_disp): """Compute reward scale for SBC.""" # Compute difference between max downward displacement at beginning of training (easiest condition) # and current max downward displacement (based on current curriculum stage) # NOTE: This number increases as curriculum gets harder curr_stage_diff = cfg_task.rl.curriculum_height_bound[1] - curr_max_disp # Compute difference between max downward displacement at beginning of training (easiest condition) # and min downward displacement (hardest condition) final_stage_diff = ( cfg_task.rl.curriculum_height_bound[1] - cfg_task.rl.curriculum_height_bound[0] ) # Compute reward scale reward_scale = curr_stage_diff / final_stage_diff + 1.0 return reward_scale def get_new_max_disp(curr_success, cfg_task, curr_max_disp): """Update max downward displacement of plug at beginning of episode, based on success rate.""" if curr_success > cfg_task.rl.curriculum_success_thresh: # If success rate is above threshold, reduce max downward displacement until min value # NOTE: height_step[0] is negative new_max_disp = max( curr_max_disp + cfg_task.rl.curriculum_height_step[0], cfg_task.rl.curriculum_height_bound[0], ) elif curr_success < cfg_task.rl.curriculum_failure_thresh: # If success rate is below threshold, increase max downward displacement until max value # NOTE: height_step[1] is positive new_max_disp = min( curr_max_disp + cfg_task.rl.curriculum_height_step[1], cfg_task.rl.curriculum_height_bound[1], ) else: # Maintain current max downward displacement new_max_disp = curr_max_disp return new_max_disp """ Bonus and Success Checking """ def get_keypoint_offsets(num_keypoints, device): """Get uniformly-spaced keypoints along a line of unit length, centered at 0.""" keypoint_offsets = torch.zeros((num_keypoints, 3), device=device) keypoint_offsets[:, -1] = ( torch.linspace(0.0, 1.0, num_keypoints, device=device) - 0.5 ) return keypoint_offsets def check_plug_close_to_socket( keypoints_plug, keypoints_socket, dist_threshold, progress_buf ): """Check if plug is close to socket.""" # Compute keypoint distance between plug and socket keypoint_dist = torch.norm(keypoints_socket - keypoints_plug, p=2, dim=-1) # Check if keypoint distance is below threshold is_plug_close_to_socket = torch.where( torch.sum(keypoint_dist, dim=-1) < dist_threshold, torch.ones_like(progress_buf), torch.zeros_like(progress_buf), ) return is_plug_close_to_socket def check_plug_engaged_w_socket( plug_pos, socket_top_pos, keypoints_plug, keypoints_socket, cfg_task, progress_buf ): """Check if plug is engaged with socket.""" # Check if base of plug is below top of socket # NOTE: In assembled state, plug origin is coincident with socket origin; # thus plug pos must be offset to compute actual pos of base of plug is_plug_below_engagement_height = ( plug_pos[:, 2] + cfg_task.env.socket_base_height < socket_top_pos[:, 2] ) # Check if plug is close to socket # NOTE: This check addresses edge case where base of plug is below top of socket, # but plug is outside socket is_plug_close_to_socket = check_plug_close_to_socket( keypoints_plug=keypoints_plug, keypoints_socket=keypoints_socket, dist_threshold=cfg_task.rl.close_error_thresh, progress_buf=progress_buf, ) # Combine both checks is_plug_engaged_w_socket = torch.logical_and( is_plug_below_engagement_height, is_plug_close_to_socket ) return is_plug_engaged_w_socket def check_plug_inserted_in_socket( plug_pos, socket_pos, keypoints_plug, keypoints_socket, cfg_task, progress_buf ): """Check if plug is inserted in socket.""" # Check if plug is within threshold distance of assembled state is_plug_below_insertion_height = ( plug_pos[:, 2] < socket_pos[:, 2] + cfg_task.rl.success_height_thresh ) # Check if plug is close to socket # NOTE: This check addresses edge case where plug is within threshold distance of # assembled state, but plug is outside socket is_plug_close_to_socket = check_plug_close_to_socket( keypoints_plug=keypoints_plug, keypoints_socket=keypoints_socket, dist_threshold=cfg_task.rl.close_error_thresh, progress_buf=progress_buf, ) # Combine both checks is_plug_inserted_in_socket = torch.logical_and( is_plug_below_insertion_height, is_plug_close_to_socket ) return is_plug_inserted_in_socket def check_gear_engaged_w_shaft( keypoints_gear, keypoints_shaft, gear_pos, shaft_pos, asset_info_gears, cfg_task, progress_buf, ): """Check if gear is engaged with shaft.""" # Check if bottom of gear is below top of shaft is_gear_below_engagement_height = ( gear_pos[:, 2] < shaft_pos[:, 2] + asset_info_gears.base.height + asset_info_gears.shafts.height ) # Check if gear is close to shaft # Note: This check addresses edge case where gear is within threshold distance of # assembled state, but gear is outside shaft is_gear_close_to_shaft = check_plug_close_to_socket( keypoints_plug=keypoints_gear, keypoints_socket=keypoints_shaft, dist_threshold=cfg_task.rl.close_error_thresh, progress_buf=progress_buf, ) # Combine both checks is_gear_engaged_w_shaft = torch.logical_and( is_gear_below_engagement_height, is_gear_close_to_shaft ) return is_gear_engaged_w_shaft def check_gear_inserted_on_shaft( gear_pos, shaft_pos, keypoints_gear, keypoints_shaft, cfg_task, progress_buf ): """Check if gear is inserted on shaft.""" # Check if gear is within threshold distance of assembled state is_gear_below_insertion_height = ( gear_pos[:, 2] < shaft_pos[:, 2] + cfg_task.rl.success_height_thresh ) # Check if keypoint distance is below threshold is_gear_close_to_shaft = check_plug_close_to_socket( keypoints_plug=keypoints_gear, keypoints_socket=keypoints_shaft, dist_threshold=cfg_task.rl.close_error_thresh, progress_buf=progress_buf, ) # Combine both checks is_gear_inserted_on_shaft = torch.logical_and( is_gear_below_insertion_height, is_gear_close_to_shaft ) return is_gear_inserted_on_shaft def get_engagement_reward_scale( plug_pos, socket_pos, is_plug_engaged_w_socket, success_height_thresh, device ): """Compute scale on reward. If plug is not engaged with socket, scale is zero. If plug is engaged, scale is proportional to distance between plug and bottom of socket.""" # Set default value of scale to zero num_envs = len(plug_pos) reward_scale = torch.zeros((num_envs,), dtype=torch.float32, device=device) # For envs in which plug and socket are engaged, compute positive scale engaged_idx = np.argwhere(is_plug_engaged_w_socket.cpu().numpy().copy()).squeeze() height_dist = plug_pos[engaged_idx, 2] - socket_pos[engaged_idx, 2] # NOTE: Edge case: if success_height_thresh is greater than 0.1, # denominator could be negative reward_scale[engaged_idx] = 1.0 / ((height_dist - success_height_thresh) + 0.1) return reward_scale """ Warp Kernels """ # Transform points from source coordinate frame to destination coordinate frame @wp.kernel def transform_points( src: wp.array(dtype=wp.vec3), dest: wp.array(dtype=wp.vec3), xform: wp.transform ): tid = wp.tid() p = src[tid] m = wp.transform_point(xform, p) dest[tid] = m # Return interpenetration distances between query points (e.g., plug vertices in current pose) # and mesh surfaces (e.g., of socket mesh in current pose) @wp.kernel def get_interpen_dist( queries: wp.array(dtype=wp.vec3), mesh: wp.uint64, interpen_dists: wp.array(dtype=wp.float32), ): tid = wp.tid() # Declare arguments to wp.mesh_query_point() that will not be modified q = queries[tid] # query point max_dist = 1.5 # max distance on mesh from query point # Declare arguments to wp.mesh_query_point() that will be modified sign = float( 0.0 ) # -1 if query point inside mesh; 0 if on mesh; +1 if outside mesh (NOTE: Mesh must be watertight!) face_idx = int(0) # index of closest face face_u = float(0.0) # barycentric u-coordinate of closest point face_v = float(0.0) # barycentric v-coordinate of closest point # Get closest point on mesh to query point closest_mesh_point_exists = wp.mesh_query_point( mesh, q, max_dist, sign, face_idx, face_u, face_v ) # If point exists within max_dist if closest_mesh_point_exists: # Get 3D position of point on mesh given face index and barycentric coordinates p = wp.mesh_eval_position(mesh, face_idx, face_u, face_v) # Get signed distance between query point and mesh point delta = q - p signed_dist = sign * wp.length(delta) # If signed distance is negative if signed_dist < 0.0: # Store interpenetration distance interpen_dists[tid] = signed_dist
18,554
Python
31.957371
127
0.664924
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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 # 'physx' or 'flex' physics_engine: 'physx' # whether to use cpu or gpu pipeline pipeline: 'gpu' # device for running physics simulation sim_device: 'cuda:0' # device to run RL rl_device: 'cuda:0' graphics_device_id: 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 num_subscenes: 4 # Splits the simulation into N physics scenes and runs each one in a separate thread # RLGames Arguments # test - if set, run policy in inference mode (requires setting checkpoint to load) test: False # used to set checkpoint path checkpoint: '' # set sigma when restoring network sigma: '' # set to True to use multi-gpu training multi_gpu: False wandb_activate: False wandb_group: '' wandb_name: ${train.params.config.name} wandb_entity: '' wandb_project: 'isaacgymenvs' wandb_tags: [] wandb_logcode_dir: '' capture_video: False capture_video_freq: 1464 capture_video_len: 100 force_render: True # disables rendering headless: False # set default task and default training config based on task defaults: - task: Ant - train: ${task}PPO - pbt: no_pbt - override hydra/job_logging: disabled - _self_ # set the directory where the output files get saved hydra: output_subdir: null run: dir: .
1,788
YAML
23.175675
103
0.735459
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryTaskNutBoltScrew.yaml
# See schema in factory_schema_config_task.py for descriptions of common parameters. defaults: - FactoryBase - _self_ # - /factory_schema_config_task name: FactoryTaskNutBoltScrew physics_engine: ${..physics_engine} sim: disable_gravity: False env: numEnvs: ${resolve_default:128,${...num_envs}} numObservations: 32 numActions: 12 randomize: franka_arm_initial_dof_pos: [1.5178e-03, -1.9651e-01, -1.4364e-03, -1.9761e+00, -2.7717e-04, 1.7796e+00, 7.8556e-01] nut_rot_initial: 30.0 # initial rotation of nut from configuration in CAD [deg]; default = 30.0 (gripper aligns with flat surfaces of nut) rl: pos_action_scale: [0.1, 0.1, 0.1] rot_action_scale: [0.1, 0.1, 0.1] force_action_scale: [1.0, 1.0, 1.0] torque_action_scale: [1.0, 1.0, 1.0] unidirectional_rot: True # constrain Franka Z-rot to be unidirectional unidirectional_force: False # constrain Franka Z-force to be unidirectional (useful for debugging) clamp_rot: True clamp_rot_thresh: 1.0e-6 add_obs_finger_force: False # add observations of force on left and right fingers keypoint_reward_scale: 1.0 # scale on keypoint-based reward action_penalty_scale: 0.0 # scale on action penalty max_episode_length: 8192 # terminate episode after this number of timesteps (failure) far_error_thresh: 0.100 # threshold above which nut is considered too far from bolt success_bonus: 0.0 # bonus if nut is close enough to base of bolt shank ctrl: ctrl_type: operational_space_motion # {gym_default, # joint_space_ik, joint_space_id, # task_space_impedance, operational_space_motion, # open_loop_force, closed_loop_force, # hybrid_force_motion} all: jacobian_type: geometric gripper_prop_gains: [100, 100] gripper_deriv_gains: [1, 1] gym_default: ik_method: dls joint_prop_gains: [40, 40, 40, 40, 40, 40, 40] joint_deriv_gains: [8, 8, 8, 8, 8, 8, 8] gripper_prop_gains: [500, 500] gripper_deriv_gains: [20, 20] joint_space_ik: ik_method: dls joint_prop_gains: [1, 1, 1, 1, 1, 1, 1] joint_deriv_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] joint_space_id: ik_method: dls joint_prop_gains: [40, 40, 40, 40, 40, 40, 40] joint_deriv_gains: [8, 8, 8, 8, 8, 8, 8] task_space_impedance: motion_ctrl_axes: [1, 1, 1, 1, 1, 1] task_prop_gains: [40, 40, 40, 40, 40, 40] task_deriv_gains: [8, 8, 8, 8, 8, 8] operational_space_motion: motion_ctrl_axes: [0, 0, 1, 0, 0, 1] task_prop_gains: [1, 1, 1, 1, 1, 200] task_deriv_gains: [1, 1, 1, 1, 1, 1] open_loop_force: force_ctrl_axes: [0, 0, 1, 0, 0, 0] closed_loop_force: force_ctrl_axes: [0, 0, 1, 0, 0, 0] wrench_prop_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1] hybrid_force_motion: motion_ctrl_axes: [1, 1, 0, 1, 1, 1] task_prop_gains: [40, 40, 40, 40, 40, 40] task_deriv_gains: [8, 8, 8, 8, 8, 8] force_ctrl_axes: [0, 0, 1, 0, 0, 0] wrench_prop_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
3,309
YAML
37.045977
143
0.576307
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/AllegroKukaTwoArmsLSTM.yaml
defaults: - AllegroKukaLSTM - _self_ name: AllegroKukaTwoArms env: numArms: 2 envSpacing: 1.75 # two arms essentially need to throw the object to each other # training is much harder with random forces, so we disable it here as we do for the throw task # forceScale: 0.0 armXOfs: 1.1 # distance from the center of the table, distance between arms is 2x this armYOfs: 0.0
395
YAML
20.999999
97
0.718987
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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: 1.5 episodeLength: 500 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 startPositionNoise: 0.0 startRotationNoise: 0.0 numProps: 16 aggregateMode: 3 actionScale: 7.5 dofVelocityScale: 0.1 distRewardScale: 2.0 rotRewardScale: 0.5 aroundHandleRewardScale: 0.25 openRewardScale: 7.5 fingerDistRewardScale: 5.0 actionPenaltyScale: 0.01 asset: assetRoot: "../../assets" assetFileNameFranka: "urdf/franka_description/robots/franka_panda.urdf" assetFileNameCabinet: "urdf/sektion_cabinet_model/urdf/sektion_cabinet_2.urdf" # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.0166 # 1/60 substeps: 1 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 12 num_velocity_iterations: 1 contact_offset: 0.005 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 1000.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 1048576 # 1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False
1,680
YAML
26.112903
171
0.693452
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/IndustRealBase.yaml
# See schema in factory_schema_config_base.py for descriptions of parameters. defaults: - _self_ mode: export_scene: False export_states: False sim: dt: 0.016667 substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_damping: True disable_franka_collisions: False physx: solver_type: ${....solver_type} num_threads: ${....num_threads} num_subscenes: ${....num_subscenes} use_gpu: ${contains:"cuda",${....sim_device}} num_position_iterations: 16 num_velocity_iterations: 0 contact_offset: 0.01 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 5.0 friction_offset_threshold: 0.01 friction_correlation_distance: 0.00625 max_gpu_contact_pairs: 6553600 # 50 * 1024 * 1024 default_buffer_size_multiplier: 8.0 contact_collection: 1 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) env: env_spacing: 0.7 franka_depth: 0.37 # Franka origin 37 cm behind table midpoint table_height: 1.04 franka_friction: 4.0 table_friction: 0.3
1,286
YAML
28.930232
175
0.619751
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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: ${resolve_default:4096,${...num_envs}} envSpacing: 5 episodeLength: 1000 enableDebugVis: False clipActions: 1.0 powerScale: 1.0 controlFrequencyInv: 1 # 60 Hz # reward parameters headingWeight: 0.5 upWeight: 0.1 # cost parameters actionsCost: 0.005 energyCost: 0.05 dofVelocityScale: 0.2 contactForceScale: 0.1 jointsAtLimitCost: 0.1 deathCost: -2.0 terminationHeight: 0.31 plane: staticFriction: 1.0 dynamicFriction: 1.0 restitution: 0.0 asset: assetFileName: "mjcf/nv_ant.xml" # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.0166 # 1/60 s substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 4 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 10.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 8388608 # 8*1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False randomization_params: # specify which attributes to randomize for each actor type and property frequency: 600 # Define how many environment steps between generating new randomizations observations: range: [0, .002] # range for the white noise operation: "additive" distribution: "gaussian" actions: range: [0., .02] operation: "additive" distribution: "gaussian" actor_params: ant: color: True rigid_body_properties: mass: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" setup_only: True # Property will only be randomized once before simulation is started. See Domain Randomization Documentation for more info. dof_properties: damping: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" stiffness: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" lower: range: [0, 0.01] operation: "additive" distribution: "gaussian" upper: range: [0, 0.01] operation: "additive" distribution: "gaussian"
2,841
YAML
26.862745
171
0.62302
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FrankaCubeStack.yaml
# used to create the object name: FrankaCubeStack physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:8192,${...num_envs}} envSpacing: 1.5 episodeLength: 300 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 startPositionNoise: 0.25 startRotationNoise: 0.785 frankaPositionNoise: 0.0 frankaRotationNoise: 0.0 frankaDofNoise: 0.25 aggregateMode: 3 actionScale: 1.0 distRewardScale: 0.1 liftRewardScale: 1.5 alignRewardScale: 2.0 stackRewardScale: 16.0 controlType: osc # options are {joint_tor, osc} asset: assetRoot: "../../assets" assetFileNameFranka: "urdf/franka_description/robots/franka_panda_gripper.urdf" # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.01667 # 1/60 substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 8 num_velocity_iterations: 1 contact_offset: 0.005 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 1000.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 1048576 # 1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False
1,639
YAML
25.451612
171
0.688225
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/HumanoidAMP.yaml
# used to create the object name: HumanoidAMP physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 5 episodeLength: 300 cameraFollow: True # if the camera follows humanoid or not enableDebugVis: False pdControl: True powerScale: 1.0 controlFrequencyInv: 2 # 30 Hz stateInit: "Random" hybridInitProb: 0.5 numAMPObsSteps: 2 localRootObs: False contactBodies: ["right_foot", "left_foot"] terminationHeight: 0.5 enableEarlyTermination: True # animation files to learn from # these motions should use hyperparameters from HumanoidAMPPPO.yaml #motion_file: "amp_humanoid_walk.npy" motion_file: "amp_humanoid_run.npy" #motion_file: "amp_humanoid_dance.npy" # these motions should use hyperparameters from HumanoidAMPPPOLowGP.yaml #motion_file: "amp_humanoid_hop.npy" #motion_file: "amp_humanoid_backflip.npy" asset: assetFileName: "mjcf/amp_humanoid.xml" plane: staticFriction: 1.0 dynamicFriction: 1.0 restitution: 0.0 sim: dt: 0.0166 # 1/60 s substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 4 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 10.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 8388608 # 8*1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 2 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False randomization_params: # specify which attributes to randomize for each actor type and property frequency: 600 # Define how many environment steps between generating new randomizations observations: range: [0, .002] # range for the white noise operation: "additive" distribution: "gaussian" actions: range: [0., .02] operation: "additive" distribution: "gaussian" sim_params: gravity: range: [0, 0.4] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will linearly interpolate between no rand and max rand schedule_steps: 3000 actor_params: humanoid: color: True rigid_body_properties: mass: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" setup_only: True # Property will only be randomized once before simulation is started. See Domain Randomization Documentation for more info. schedule: "linear" # "linear" will linearly interpolate between no rand and max rand schedule_steps: 3000 rigid_shape_properties: friction: num_buckets: 500 range: [0.7, 1.3] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 restitution: range: [0., 0.7] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 dof_properties: damping: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 stiffness: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 lower: range: [0, 0.01] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 upper: range: [0, 0.01] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000
4,881
YAML
34.897059
171
0.629379
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/AnymalTerrain.yaml
# used to create the object name: AnymalTerrain physics_engine: 'physx' env: numEnvs: ${resolve_default:4096,${...num_envs}} numObservations: 188 numActions: 12 envSpacing: 3. # [m] enableDebugVis: False terrain: terrainType: trimesh # none, plane, or trimesh 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: [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: # 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] urdfAsset: file: "urdf/anymal_c/urdf/anymal_minimal.urdf" footName: SHANK # SHANK if collapsing fixed joint, FOOT otherwise kneeName: THIGH collapseFixedJoints: True fixBaseLink: false defaultDofDriveMode: 4 # see GymDofDriveModeFlags (0 is none, 1 is pos tgt, 2 is vel tgt, 4 effort) learn: allowKneeContacts: true # rewards terminalReward: 0.0 linearVelocityXYRewardScale: 1.0 linearVelocityZRewardScale: -4.0 angularVelocityXYRewardScale: -0.05 angularVelocityZRewardScale: 0.5 orientationRewardScale: -0. #-1. torqueRewardScale: -0.00002 # -0.000025 jointAccRewardScale: -0.0005 # -0.0025 baseHeightRewardScale: -0.0 #5 feetAirTimeRewardScale: 1.0 kneeCollisionRewardScale: -0.25 feetStumbleRewardScale: -0. #-2.0 actionRateRewardScale: -0.01 # 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 randomizeFriction: true frictionRange: [0.5, 1.25] pushRobots: true pushInterval_s: 15 # episode length in seconds episodeLength_s: 20 # viewer cam: viewer: refEnv: 0 pos: [0, 0, 10] # [m] lookat: [1., 1, 9] # [m] # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.005 substeps: 1 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 4 num_velocity_iterations: 1 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 100.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 8388608 # 8*1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 1 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False
4,203
YAML
26.657895
171
0.621461
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.01 substeps: 1 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 8 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 1000.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 8388608 # 8*1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False
1,208
YAML
27.785714
171
0.677152
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/IndustRealEnvGears.yaml
# See schema in factory_schema_config_env.py for descriptions of common parameters. defaults: - IndustRealBase - _self_ - /factory_schema_config_env env: env_name: 'IndustRealEnvGears' gears_lateral_offset: 0.1 # Y-axis offset of gears before initial reset to prevent initial interpenetration with base plate gears_friction: 0.5 # coefficient of friction associated with gears base_friction: 0.5 # coefficient of friction associated with base plate
487
YAML
33.85714
128
0.735113
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryBase.yaml
# See schema in factory_schema_config_base.py for descriptions of parameters. defaults: - _self_ #- /factory_schema_config_base mode: export_scene: False export_states: False sim: dt: 0.016667 substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_damping: True physx: solver_type: ${....solver_type} num_threads: ${....num_threads} num_subscenes: ${....num_subscenes} use_gpu: ${contains:"cuda",${....sim_device}} num_position_iterations: 16 num_velocity_iterations: 0 contact_offset: 0.005 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 5.0 friction_offset_threshold: 0.01 friction_correlation_distance: 0.00625 max_gpu_contact_pairs: 1048576 # 1024 * 1024 default_buffer_size_multiplier: 8.0 contact_collection: 1 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) env: env_spacing: 0.5 franka_depth: 0.5 table_height: 0.4 franka_friction: 1.0 table_friction: 0.3
1,229
YAML
26.954545
175
0.613507
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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: ${resolve_default:4096,${...num_envs}} envSpacing: 5 episodeLength: 1000 enableDebugVis: False clipActions: 1.0 powerScale: 1.0 # 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 asset: assetFileName: "mjcf/nv_humanoid.xml" plane: staticFriction: 1.0 dynamicFriction: 1.0 restitution: 0.0 # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.0166 # 1/60 s substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 4 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 10.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 8388608 # 8*1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False randomization_params: # specify which attributes to randomize for each actor type and property frequency: 600 # Define how many environment steps between generating new randomizations observations: range: [0, .002] # range for the white noise operation: "additive" distribution: "gaussian" actions: range: [0., .02] operation: "additive" distribution: "gaussian" sim_params: gravity: range: [0, 0.4] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will linearly interpolate between no rand and max rand schedule_steps: 3000 actor_params: humanoid: color: True rigid_body_properties: mass: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" setup_only: True # Property will only be randomized once before simulation is started. See Domain Randomization Documentation for more info. schedule: "linear" # "linear" will linearly interpolate between no rand and max rand schedule_steps: 3000 rigid_shape_properties: friction: num_buckets: 500 range: [0.7, 1.3] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 restitution: range: [0., 0.7] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 dof_properties: damping: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 stiffness: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 lower: range: [0, 0.01] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 upper: range: [0, 0.01] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000
4,571
YAML
33.37594
171
0.619996
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryEnvGears.yaml
# See schema in factory_schema_config_env.py for descriptions of common parameters. defaults: - FactoryBase - _self_ - /factory_schema_config_env sim: disable_franka_collisions: False env: env_name: 'FactoryEnvGears' tight_or_loose: loose # use assets with loose (maximal clearance) or tight (minimal clearance) shafts gears_lateral_offset: 0.1 # Y-axis offset of gears before initial reset to prevent initial interpenetration with base plate gears_density: 1000.0 # density of gears base_density: 2700.0 # density of base plate gears_friction: 0.3 # coefficient of friction associated with gears base_friction: 0.3 # coefficient of friction associated with base plate
723
YAML
35.199998
128
0.73029
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryTaskNutBoltPick.yaml
# See schema in factory_schema_config_task.py for descriptions of common parameters. defaults: - FactoryBase - _self_ # - /factory_schema_config_task name: FactoryTaskNutBoltPick physics_engine: ${..physics_engine} sim: disable_gravity: False env: numEnvs: ${resolve_default:128,${...num_envs}} numObservations: 20 numActions: 12 close_and_lift: True # close gripper and lift after last step of episode num_gripper_move_sim_steps: 20 # number of timesteps to reserve for moving gripper before first step of episode num_gripper_close_sim_steps: 25 # number of timesteps to reserve for closing gripper after last step of episode num_gripper_lift_sim_steps: 25 # number of timesteps to reserve for lift after last step of episode randomize: franka_arm_initial_dof_pos: [0.3413, -0.8011, -0.0670, -1.8299, 0.0266, 1.0185, 1.0927] fingertip_midpoint_pos_initial: [0.0, -0.2, 0.2] # initial position of hand above table fingertip_midpoint_pos_noise: [0.2, 0.2, 0.1] # noise on hand position fingertip_midpoint_rot_initial: [3.1416, 0, 3.1416] # initial rotation of fingertips (Euler) fingertip_midpoint_rot_noise: [0.3, 0.3, 1] # noise on rotation nut_pos_xy_initial: [0.0, -0.3] # initial XY position of nut on table nut_pos_xy_initial_noise: [0.1, 0.1] # noise on nut position bolt_pos_xy_initial: [0.0, 0.0] # initial position of bolt on table bolt_pos_xy_noise: [0.1, 0.1] # noise on bolt position rl: pos_action_scale: [0.1, 0.1, 0.1] rot_action_scale: [0.1, 0.1, 0.1] force_action_scale: [1.0, 1.0, 1.0] torque_action_scale: [1.0, 1.0, 1.0] clamp_rot: True clamp_rot_thresh: 1.0e-6 num_keypoints: 4 # number of keypoints used in reward keypoint_scale: 0.5 # length of line of keypoints keypoint_reward_scale: 1.0 # scale on keypoint-based reward action_penalty_scale: 0.0 # scale on action penalty max_episode_length: 100 success_bonus: 0.0 # bonus if nut has been lifted ctrl: ctrl_type: joint_space_id # {gym_default, # joint_space_ik, joint_space_id, # task_space_impedance, operational_space_motion, # open_loop_force, closed_loop_force, # hybrid_force_motion} all: jacobian_type: geometric gripper_prop_gains: [50, 50] gripper_deriv_gains: [2, 2] gym_default: ik_method: dls joint_prop_gains: [40, 40, 40, 40, 40, 40, 40] joint_deriv_gains: [8, 8, 8, 8, 8, 8, 8] gripper_prop_gains: [500, 500] gripper_deriv_gains: [20, 20] joint_space_ik: ik_method: dls joint_prop_gains: [1, 1, 1, 1, 1, 1, 1] joint_deriv_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] joint_space_id: ik_method: dls joint_prop_gains: [40, 40, 40, 40, 40, 40, 40] joint_deriv_gains: [8, 8, 8, 8, 8, 8, 8] task_space_impedance: motion_ctrl_axes: [1, 1, 1, 1, 1, 1] task_prop_gains: [40, 40, 40, 40, 40, 40] task_deriv_gains: [8, 8, 8, 8, 8, 8] operational_space_motion: motion_ctrl_axes: [1, 1, 1, 1, 1, 1] task_prop_gains: [1, 1, 1, 1, 1, 1] task_deriv_gains: [1, 1, 1, 1, 1, 1] open_loop_force: force_ctrl_axes: [0, 0, 1, 0, 0, 0] closed_loop_force: force_ctrl_axes: [0, 0, 1, 0, 0, 0] wrench_prop_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1] hybrid_force_motion: motion_ctrl_axes: [1, 1, 0, 1, 1, 1] task_prop_gains: [40, 40, 40, 40, 40, 40] task_deriv_gains: [8, 8, 8, 8, 8, 8] force_ctrl_axes: [0, 0, 1, 0, 0, 0] wrench_prop_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
3,784
YAML
38.427083
116
0.589059
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/HumanoidSAC.yaml
# used to create the object defaults: - Humanoid - _self_ # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:64,${...num_envs}}
168
YAML
20.124997
52
0.678571
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryTaskInsertion.yaml
# See schema in factory_schema_config_task.py for descriptions of common parameters. defaults: - FactoryBase - _self_ # - /factory_schema_config_task name: FactoryTaskInsertion physics_engine: ${..physics_engine} env: numEnvs: ${resolve_default:128,${...num_envs}} numObservations: 32 numActions: 12 randomize: joint_noise: 0.0 # noise on Franka DOF positions [deg] initial_state: random # initialize plugs in random state or goal state {random, goal} plug_bias_y: -0.1 # if random, Y-axis offset of plug during each reset to prevent initial interpenetration with socket plug_bias_z: 0.0 # if random, Z-axis offset of plug during each reset to prevent initial interpenetration with ground plane plug_noise_xy: 0.05 # if random, XY-axis noise on plug position during each reset rl: max_episode_length: 1024
864
YAML
33.599999
128
0.716435
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryEnvInsertion.yaml
# See schema in factory_schema_config_env.py for descriptions of common parameters. defaults: - FactoryBase - _self_ - /factory_schema_config_env sim: disable_franka_collisions: False env: env_name: 'FactoryEnvInsertion' desired_subassemblies: ['round_peg_hole_4mm_loose', 'round_peg_hole_8mm_loose', 'round_peg_hole_12mm_loose', 'round_peg_hole_16mm_loose', 'rectangular_peg_hole_4mm_loose', 'rectangular_peg_hole_8mm_loose', 'rectangular_peg_hole_12mm_loose', 'rectangular_peg_hole_16mm_loose'] plug_lateral_offset: 0.1 # Y-axis offset of plug before initial reset to prevent initial interpenetration with socket # Subassembly options: # {round_peg_hole_4mm_tight, round_peg_hole_4mm_loose, # round_peg_hole_8mm_tight, round_peg_hole_8mm_loose, # round_peg_hole_12mm_tight, round_peg_hole_12mm_loose, # round_peg_hole_16mm_tight, round_peg_hole_16mm_loose, # rectangular_peg_hole_4mm_tight, rectangular_peg_hole_4mm_loose, # rectangular_peg_hole_8mm_tight, rectangular_peg_hole_8mm_loose, # rectangular_peg_hole_12mm_tight, rectangular_peg_hole_12mm_loose, # rectangular_peg_hole_16mm_tight, rectangular_peg_hole_16mm_loose, # bnc, dsub, usb} # # NOTE: BNC, D-sub, and USB are currently unavailable while we await approval from manufacturers.
1,529
YAML
41.499999
122
0.626553
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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 # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.01 substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 6 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 1000.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 1048576 # 1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False
1,184
YAML
26.558139
171
0.673986
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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:8192,${...num_envs}} envSpacing: 1.25 maxEpisodeLength: 500 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.01 substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 4 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 1000.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 1048576 # 1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False
1,189
YAML
27.333333
171
0.671993
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryTaskNutBoltPlace.yaml
# See schema in factory_schema_config_task.py for descriptions of common parameters. defaults: - FactoryBase - _self_ # - /factory_schema_config_task name: FactoryTaskNutBoltPlace physics_engine: ${..physics_engine} sim: disable_gravity: True env: numEnvs: ${resolve_default:128,${...num_envs}} numObservations: 27 numActions: 12 num_gripper_move_sim_steps: 40 # number of timesteps to reserve for moving gripper before first step of episode num_gripper_close_sim_steps: 50 # number of timesteps to reserve for closing gripper onto nut during each reset randomize: franka_arm_initial_dof_pos: [0.00871, -0.10368, -0.00794, -1.49139, -0.00083, 1.38774, 0.7861] fingertip_midpoint_pos_initial: [0.0, 0.0, 0.2] # initial position of midpoint between fingertips above table fingertip_midpoint_pos_noise: [0.2, 0.2, 0.1] # noise on fingertip pos fingertip_midpoint_rot_initial: [3.1416, 0, 3.1416] # initial rotation of fingertips (Euler) fingertip_midpoint_rot_noise: [0.3, 0.3, 1] # noise on rotation nut_noise_pos_in_gripper: [0.0, 0.0, 0.01] # noise on nut position within gripper nut_noise_rot_in_gripper: 0.0 # noise on nut rotation within gripper bolt_pos_xy_initial: [0.0, 0.0] # initial XY position of nut on table bolt_pos_xy_noise: [0.1, 0.1] # noise on nut position rl: pos_action_scale: [0.1, 0.1, 0.1] rot_action_scale: [0.1, 0.1, 0.1] force_action_scale: [1.0, 1.0, 1.0] torque_action_scale: [1.0, 1.0, 1.0] clamp_rot: True clamp_rot_thresh: 1.0e-6 add_obs_bolt_tip_pos: False # add observation of bolt tip position num_keypoints: 4 # number of keypoints used in reward keypoint_scale: 0.5 # length of line of keypoints keypoint_reward_scale: 1.0 # scale on keypoint-based reward action_penalty_scale: 0.0 # scale on action penalty max_episode_length: 200 close_error_thresh: 0.1 # threshold below which nut is considered close enough to bolt success_bonus: 0.0 # bonus if nut is close enough to bolt ctrl: ctrl_type: joint_space_id # {gym_default, # joint_space_ik, joint_space_id, # task_space_impedance, operational_space_motion, # open_loop_force, closed_loop_force, # hybrid_force_motion} all: jacobian_type: geometric gripper_prop_gains: [100, 100] gripper_deriv_gains: [2, 2] gym_default: ik_method: dls joint_prop_gains: [40, 40, 40, 40, 40, 40, 40] joint_deriv_gains: [8, 8, 8, 8, 8, 8, 8] gripper_prop_gains: [500, 500] gripper_deriv_gains: [20, 20] joint_space_ik: ik_method: dls joint_prop_gains: [1, 1, 1, 1, 1, 1, 1] joint_deriv_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] joint_space_id: ik_method: dls joint_prop_gains: [40, 40, 40, 40, 40, 40, 40] joint_deriv_gains: [8, 8, 8, 8, 8, 8, 8] task_space_impedance: motion_ctrl_axes: [1, 1, 1, 1, 1, 1] task_prop_gains: [40, 40, 40, 40, 40, 40] task_deriv_gains: [8, 8, 8, 8, 8, 8] operational_space_motion: motion_ctrl_axes: [1, 1, 1, 1, 1, 1] task_prop_gains: [1, 1, 1, 1, 1, 1] task_deriv_gains: [1, 1, 1, 1, 1, 1] open_loop_force: force_ctrl_axes: [0, 0, 1, 0, 0, 0] closed_loop_force: force_ctrl_axes: [0, 0, 1, 0, 0, 0] wrench_prop_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1] hybrid_force_motion: motion_ctrl_axes: [1, 1, 0, 1, 1, 1] task_prop_gains: [40, 40, 40, 40, 40, 40] task_deriv_gains: [8, 8, 8, 8, 8, 8] force_ctrl_axes: [0, 0, 1, 0, 0, 0] wrench_prop_gains: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
3,827
YAML
37.666666
116
0.593154
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/HumanoidAMPHands.yaml
# used to create the object name: HumanoidAMP physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 5 episodeLength: 300 cameraFollow: True # if the camera follows humanoid or not enableDebugVis: False pdControl: True powerScale: 1.0 controlFrequencyInv: 2 # 30 Hz stateInit: "Random" hybridInitProb: 0.5 numAMPObsSteps: 2 localRootObs: False contactBodies: ["right_foot", "left_foot", "right_hand", "left_hand"] terminationHeight: 0.5 enableEarlyTermination: True # animation files to learn from motion_file: "amp_humanoid_cartwheel.npy" asset: assetFileName: "mjcf/amp_humanoid.xml" plane: staticFriction: 1.0 dynamicFriction: 1.0 restitution: 0.0 sim: dt: 0.0166 # 1/60 s substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 4 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 10.0 default_buffer_size_multiplier: 5.0 max_gpu_contact_pairs: 8388608 # 8*1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 1 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False randomization_params: # specify which attributes to randomize for each actor type and property frequency: 600 # Define how many environment steps between generating new randomizations observations: range: [0, .002] # range for the white noise operation: "additive" distribution: "gaussian" actions: range: [0., .02] operation: "additive" distribution: "gaussian" sim_params: gravity: range: [0, 0.4] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will linearly interpolate between no rand and max rand schedule_steps: 3000 actor_params: humanoid: color: True rigid_body_properties: mass: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" setup_only: True # Property will only be randomized once before simulation is started. See Domain Randomization Documentation for more info. schedule: "linear" # "linear" will linearly interpolate between no rand and max rand schedule_steps: 3000 rigid_shape_properties: friction: num_buckets: 500 range: [0.7, 1.3] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 restitution: range: [0., 0.7] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 dof_properties: damping: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 stiffness: range: [0.5, 1.5] operation: "scaling" distribution: "uniform" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 lower: range: [0, 0.01] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000 upper: range: [0, 0.01] operation: "additive" distribution: "gaussian" schedule: "linear" # "linear" will scale the current random sample by `min(current num steps, schedule_steps) / schedule_steps` schedule_steps: 3000
4,604
YAML
34.697674
171
0.620765
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryTaskGears.yaml
# See schema in factory_schema_config_task.py for descriptions of common parameters. defaults: - FactoryBase - _self_ # - /factory_schema_config_task name: FactoryTaskGears physics_engine: ${..physics_engine} env: numEnvs: ${resolve_default:128,${...num_envs}} numObservations: 32 numActions: 12 randomize: joint_noise: 0.0 # noise on Franka DOF positions [deg] initial_state: random # initialize gears in random state or goal state {random, goal} gears_bias_y: -0.1 # if random, Y-axis offset of gears during each reset to prevent initial interpenetration with base plate gears_bias_z: 0.0 # if random, Z-axis offset of gears during each reset to prevent initial interpenetration with ground plane gears_noise_xy: 0.05 # if random, XY-axis noise on gears during each reset rl: max_episode_length: 1024
861
YAML
33.479999
130
0.715447
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/IndustRealEnvPegs.yaml
# See schema in factory_schema_config_env.py for descriptions of common parameters. defaults: - IndustRealBase - _self_ - /factory_schema_config_env env: env_name: 'IndustRealEnvPegs' desired_subassemblies: ['round_peg_hole_8mm', 'round_peg_hole_12mm', 'round_peg_hole_16mm', 'rectangular_peg_hole_8mm', 'rectangular_peg_hole_12mm', 'rectangular_peg_hole_16mm'] plug_lateral_offset: 0.1 # Y-axis offset of plug before initial reset to prevent initial interpenetration with socket # Density and friction values are specified in industreal_asset_info_pegs.yaml
736
YAML
35.849998
122
0.592391
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/FactoryEnvNutBolt.yaml
# See schema in factory_schema_config_env.py for descriptions of common parameters. defaults: - FactoryBase - _self_ - /factory_schema_config_env sim: disable_franka_collisions: False disable_nut_collisions: False disable_bolt_collisions: False env: env_name: 'FactoryEnvNutBolt' desired_subassemblies: ['nut_bolt_m16_tight', 'nut_bolt_m16_loose'] nut_lateral_offset: 0.1 # Y-axis offset of nut before initial reset to prevent initial interpenetration with bolt nut_bolt_density: 7850.0 nut_bolt_friction: 0.3 # Subassembly options: # {nut_bolt_m4_tight, nut_bolt_m4_loose, # nut_bolt_m8_tight, nut_bolt_m8_loose, # nut_bolt_m12_tight, nut_bolt_m12_loose, # nut_bolt_m16_tight, nut_bolt_m16_loose, # nut_bolt_m20_tight, nut_bolt_m20_loose}
814
YAML
29.185184
118
0.692875
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/AntSAC.yaml
# used to create the object defaults: - Ant - _self_ # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:64,${...num_envs}}
163
YAML
19.499998
52
0.668712
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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 asset: assetRoot: "../../assets" assetFileName: "urdf/cartpole.urdf" # set to True if you use camera sensors in the environment enableCameraSensors: False sim: dt: 0.0166 # 1/60 s substeps: 2 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${contains:"cuda",${....sim_device}} # set to False to run on CPU num_position_iterations: 4 num_velocity_iterations: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 100.0 default_buffer_size_multiplier: 2.0 max_gpu_contact_pairs: 1048576 # 1024*1024 num_subscenes: ${....num_subscenes} contact_collection: 0 # 0: CC_NEVER (don't collect contact info), 1: CC_LAST_SUBSTEP (collect only contacts on last substep), 2: CC_ALL_SUBSTEPS (broken - do not use!) task: randomize: False
1,259
YAML
26.391304
171
0.663225
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/env/regrasping.yaml
subtask: "regrasping" episodeLength: 300 # requires holding a grasp for a whole second, thus trained policies develop a robust grasp successSteps: 30
152
YAML
20.85714
91
0.796053
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/task/env/throw.yaml
subtask: "throw" episodeLength: 300 forceScale: 0.0 # random forces don't allow us to throw precisely so we turn them off # curriculum not needed - if we hit a bin, that's good! successTolerance: 0.075 targetSuccessTolerance: 0.075 # adds a small pause every time we hit a target successSteps: 5 # throwing big objects is hard and they don't fit in the bin, so focus on randomized but smaller objects withSmallCuboids: True withBigCuboids: False withSticks: False
470
YAML
25.166665
104
0.774468
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/FactoryTaskGearsPPO.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, 128, 64] activation: elu d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:FactoryTaskGears,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: True normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 1e-4 lr_schedule: fixed schedule_type: standard kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:8192,${....max_iterations}} save_best_after: 50 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 32 minibatch_size: 512 # batch size = num_envs * horizon_length; minibatch_size = batch_size / num_minibatches mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,624
YAML
21.569444
112
0.600985
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/ShadowHandOpenAI_FFPPO.yaml
# specifies what the default training mode is when # running `ShadowHandOpenAI_FF` (version with DR and asymmetric observations and feedforward network) # (currently defaults to asymmetric training) defaults: - ShadowHandPPOAsymm - _self_
243
YAML
33.857138
101
0.790123
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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} env_name: rlgpu ppo: True multi_gpu: ${....multi_gpu} mixed_precision: 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: 24 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:1500,${....max_iterations}} save_best_after: 100 score_to_win: 20000 save_frequency: 50 print_stats: True
1,854
YAML
21.349397
101
0.59493
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AllegroKukaTwoArmsLSTMPPO.yaml
defaults: - AllegroKukaLSTMPPO - _self_ # TODO: try bigger network for two hands? params: network: mlp: units: [768, 512, 256] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 768 layers: 1 before_mlp: True layer_norm: True config: name: ${resolve_default:AllegroKukaTwoArmsLSTMPPO,${....experiment}} minibatch_size: 32768 mini_epochs: 2
496
YAML
18.115384
72
0.592742
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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 multi_gpu: ${....multi_gpu} 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: 200 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True ppo: 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,589
YAML
21.083333
101
0.600378
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AllegroHandDextremeManualDRPPO.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 inputs: dof_pos_randomized: { } object_pose_cam_randomized: { } goal_pose_randomized: { } goal_relative_rot_cam_randomized: { } last_actions_randomized: { } mlp: units: [256] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 512 layers: 1 before_mlp: True layer_norm: True 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:AllegroHandManualDRAsymmLSTM,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: False num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.998 tau: 0.95 learning_rate: 1e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.016 score_to_win: 100000 max_epochs: ${resolve_default:50000,${....max_iterations}} save_best_after: 200 save_frequency: 500 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: 4 critic_coef: 4 clip_value: True seq_length: 16 bounds_loss_coef: 0.0001 zero_rnn_on_done: False central_value_config: minibatch_size: 16384 mini_epochs: 4 learning_rate: 1e-4 kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True network: name: actor_critic central_value: True inputs: dof_pos: { } dof_vel: { } dof_force: { } object_pose: { } object_pose_cam_randomized: { } object_vels: { } goal_pose: { } goal_relative_rot: {} last_actions: { } ft_force_torques: {} gravity_vec: {} ft_states: {} mlp: units: [512, 256, 128] activation: elu d2rl: False initializer: name: default regularizer: name: None player: deterministic: True use_vecenv: True games_num: 1000000 print_stats: False
2,909
YAML
20.555555
101
0.55758
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/IndustRealTaskPegsInsertPPO.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, 256, 128] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 256 layers: 2 before_mlp: True concat_input: True layer_norm: False load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:IndustRealTaskPegsInsert,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu 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: 1.0 normalize_advantage: True gamma: 0.998 tau: 0.95 learning_rate: 1e-3 lr_schedule: linear schedule_type: standard kl_threshold: 0.016 score_to_win: 200000 max_epochs: ${resolve_default:8192,${....max_iterations}} save_best_after: 10 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 128 minibatch_size: 8192 # batch size = num_envs * horizon_length; minibatch_size = batch_size / num_minibatches mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 8 bounds_loss_coef: 0.0001 central_value_config: minibatch_size: 256 mini_epochs: 4 learning_rate: 1e-3 lr_schedule: linear kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True network: name: actor_critic central_value: True mlp: units: [256, 128, 64] activation: elu d2rl: False initializer: name: default regularizer: name: None # rnn: # name: lstm # units: 256 # layers: 2 # before_mlp: True # concat_input: True # layer_norm: False
2,434
YAML
20.359649
113
0.566557
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/ShadowHandPPOAsymmLSTM.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] activation: relu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 1024 layers: 1 before_mlp: True layer_norm: True 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:ShadowHandAsymmLSTM,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} 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.998 tau: 0.95 learning_rate: 1e-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: 500 save_frequency: 500 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: 4 critic_coef: 4 clip_value: True seq_length: 4 bounds_loss_coef: 0.0001 central_value_config: minibatch_size: 32768 mini_epochs: 4 learning_rate: 1e-4 kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True network: name: actor_critic central_value: True mlp: units: [512] activation: relu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 1024 layers: 1 before_mlp: True layer_norm: True player: #render: True deterministic: True games_num: 1000000 print_stats: False
2,410
YAML
21.119266
101
0.570954
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/FactoryTaskInsertionPPO.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, 128, 64] activation: elu d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:FactoryTaskInsertion,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: True normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 1e-4 lr_schedule: fixed schedule_type: standard kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:8192,${....max_iterations}} save_best_after: 50 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 32 minibatch_size: 512 # batch size = num_envs * horizon_length; minibatch_size = batch_size / num_minibatches mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,628
YAML
21.625
112
0.601966
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AllegroHandDextremeADRPPO.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 inputs: dof_pos_randomized: {} object_pose_cam_randomized: { } goal_pose: { } goal_relative_rot_cam_randomized: { } last_actions: { } mlp: units: [512, 512] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 1024 layers: 1 before_mlp: True layer_norm: True 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:AllegroHandADRAsymmLSTM,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: False num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.998 tau: 0.95 learning_rate: 1e-4 lr_schedule: linear #adaptive schedule_type: standard kl_threshold: 0.01 score_to_win: 1000000 max_epochs: ${resolve_default:1000_000,${....max_iterations}} save_best_after: 10000 save_frequency: 500 print_stats: True grad_norm: 1.0 entropy_coef: 0.002 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 16384 mini_epochs: 4 critic_coef: 4 clip_value: True seq_length: 16 bound_loss_type: regularization bounds_loss_coef: 0.005 zero_rnn_on_done: False # optimize summaries to prevent tf.event files from growing to gigabytes force_interval_writer: True central_value_config: minibatch_size: 16384 mini_epochs: 4 learning_rate: 5e-5 kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True network: name: actor_critic central_value: True inputs: dof_pos: { } dof_vel: { } dof_force: { } object_pose: { } object_pose_cam_randomized: { } object_vels: { } goal_pose: { } goal_relative_rot: {} last_actions: { } stochastic_delay_params: { } affine_params: { } cube_random_params: {} hand_random_params: {} ft_force_torques: {} gravity_vec: {} ft_states: {} rot_dist: {} rb_forces: {} mlp: units: [1024, 512] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 2048 layers: 1 before_mlp: True layer_norm: True player: deterministic: True use_vecenv: True games_num: 1000000 print_stats: False
3,354
YAML
21.366667
101
0.552475
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AllegroKukaPPO.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: [1024, 1024, 512, 512] 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:AllegroKukaPPO,${....experiment}} # full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: True normalize_input: True normalize_value: True normalize_advantage: True reward_shaper: scale_value: 0.01 num_actors: ${....task.env.numEnvs} gamma: 0.99 tau: 0.95 learning_rate: 1e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.016 score_to_win: 1000000 max_epochs: 100000 max_frames: 10_000_000_000 save_best_after: 100 save_frequency: 5000 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.1 minibatch_size: 32768 mini_epochs: 4 critic_coef: 4.0 clip_value: True horizon_length: 16 seq_length: 16 # SampleFactory currently gives better results without bounds loss but I don't think this loss matters too much # bounds_loss_coef: 0.0 bounds_loss_coef: 0.0001 # optimize summaries to prevent tf.event files from growing to gigabytes defer_summaries_sec: ${if:${....pbt},240,5} summaries_interval_sec_min: ${if:${....pbt},60,5} summaries_interval_sec_max: 300 player: #render: True deterministic: False # be careful there's a typo in older versions of rl_games in this parameter name ("determenistic") games_num: 100000 print_stats: False
2,180
YAML
23.784091
126
0.623853
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/ShadowHandPPOAsymm.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} # flag which sets whether to load the checkpoint load_path: ${...checkpoint} # path to the checkpoint to load config: name: ${resolve_default:ShadowHandAsymm,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True reward_shaper: scale_value: 0.01 normalize_advantage: True num_actors: ${....task.env.numEnvs} 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: 500 save_frequency: 200 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 8 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: 16384 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: #render: True deterministic: True games_num: 1000000 print_stats: False
2,243
YAML
21.217822
101
0.586268
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/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} # flag which sets whether to load the checkpoint load_path: ${...checkpoint} # path to the checkpoint to load config: name: ${resolve_default:ShadowHand,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} 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:5000,${....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: 8 minibatch_size: 32768 mini_epochs: 5 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001 player: #render: True deterministic: True games_num: 100000 print_stats: True
1,732
YAML
20.936709
101
0.601039
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AllegroHandLSTM_BigPPO.yaml
params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: complex_net separate: False space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: True inputs: dof_pos_offset_randomized: {} object_pose_delayed_randomized: {} goal_pose: {} goal_relative_rot_delayed_randomized: {} last_actions: {} mlp: units: [512] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 1024 layers: 1 before_mlp: True layer_norm: True 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:AllegroHandAsymmLSTM,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True use_smooth_clamp: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.998 tau: 0.95 learning_rate: 1e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.016 score_to_win: 100000 max_epochs: ${resolve_default:1000000,${....max_iterations}} save_best_after: 200 save_frequency: 500 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: 4 critic_coef: 4 clip_value: True seq_length: 16 bounds_loss_coef: 0.0001 central_value_config: minibatch_size: 16384 #32768 mini_epochs: 4 learning_rate: 1e-4 kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True use_smooth_clamp: True network: name: complex_net central_value: True inputs: dof_pos: {} dof_pos_offset_randomized: {} dof_vel: {} dof_torque: {} object_pose: {} object_vels: {} goal_pose: {} goal_relative_rot: {} object_pose_delayed_randomized: {} goal_relative_rot_delayed_randomized: {} object_obs_delayed_age: {} # ft_states: {} # ft_force_torques: {} last_actions: {} mlp: units: [512, 512, 256, 128] #[256] # activation: elu d2rl: False initializer: name: default regularizer: name: None # rnn: # name: lstm # units: 512 # layers: 1 # before_mlp: True # layer_norm: True player: deterministic: True use_vecenv: True games_num: 1000000 print_stats: False
3,152
YAML
22.183823
101
0.551713
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AllegroHandLSTMPPO.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 inputs: dof_pos_randomized: { } object_pose_cam_randomized: { } goal_pose_randomized: { } goal_relative_rot_cam_randomized: { } last_actions_randomized: { } mlp: units: [256] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 512 layers: 1 before_mlp: True layer_norm: True 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:AllegroHandAsymmLSTM,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: False # TODO: enable bootstrap? num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.998 tau: 0.95 learning_rate: 1e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.016 score_to_win: 100000 max_epochs: ${resolve_default:50000,${....max_iterations}} save_best_after: 200 save_frequency: 500 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: 4 critic_coef: 4 clip_value: True seq_length: 16 bounds_loss_coef: 0.0001 # optimize summaries to prevent tf.event files from growing to gigabytes defer_summaries_sec: ${if:${....pbt},150,5} summaries_interval_sec_min: ${if:${....pbt},20,5} summaries_interval_sec_max: 100 central_value_config: minibatch_size: 16384 #32768 mini_epochs: 4 learning_rate: 1e-4 kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True network: name: actor_critic central_value: True inputs: dof_pos: { } dof_vel: { } dof_force: { } object_pose: { } object_pose_cam_randomized: { } object_vels: { } goal_pose: { } goal_relative_rot: {} last_actions: { } ft_force_torques: {} gravity_vec: {} ft_states: {} mlp: units: [512, 256, 128] #[256] # activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 512 layers: 1 before_mlp: True layer_norm: True player: deterministic: True use_vecenv: True games_num: 1000000 print_stats: False
3,269
YAML
21.39726
101
0.556133
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/HumanoidAMPPPO.yaml
params: seed: ${...seed} algo: name: amp_continuous model: name: continuous_amp network: name: amp separate: True space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: -2.9 fixed_sigma: True learn_sigma: False mlp: units: [1024, 512] activation: relu d2rl: False initializer: name: default regularizer: name: None disc: units: [1024, 512] activation: relu initializer: name: default 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:HumanoidAMP,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu ppo: True multi_gpu: ${....multi_gpu} mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-5 lr_schedule: constant kl_threshold: 0.008 score_to_win: 20000 max_epochs: ${resolve_default:5000,${....max_iterations}} save_best_after: 100 save_frequency: 50 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 16 minibatch_size: 32768 mini_epochs: 6 critic_coef: 5 clip_value: False seq_len: 4 bounds_loss_coef: 10 amp_obs_demo_buffer_size: 200000 amp_replay_buffer_size: 1000000 amp_replay_keep_prob: 0.01 amp_batch_size: 512 amp_minibatch_size: 4096 disc_coef: 5 disc_logit_reg: 0.05 disc_grad_penalty: 5 disc_reward_scale: 2 disc_weight_decay: 0.0001 normalize_amp_input: True task_reward_w: 0.0 disc_reward_w: 1.0
2,055
YAML
20.642105
101
0.60146
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AnymalTerrainPPO_LSTM.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: 256 #128 layers: 1 before_mlp: False #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} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: 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: 24 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:750,${....max_iterations}} save_best_after: 100 score_to_win: 20000 save_frequency: 50 print_stats: True
1,854
YAML
21.349397
101
0.598706
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/FrankaCubeStackPPO.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, 128, 64] 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:FrankaCubeStack,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.008 score_to_win: 10000 max_epochs: ${resolve_default:10000,${....max_iterations}} save_best_after: 200 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 32 minibatch_size: 16384 mini_epochs: 5 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,623
YAML
21.555555
101
0.604436
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/HumanoidSAC.yaml
params: seed: ${...seed} algo: name: sac model: name: soft_actor_critic network: name: soft_actor_critic separate: True space: continuous: mlp: units: [512, 256] activation: relu initializer: name: default log_std_bounds: [-5, 2] load_checkpoint: False load_path: nn/Ant.pth config: name: ${resolve_default:HumanoidSAC,${....experiment}} env_name: rlgpu multi_gpu: ${....multi_gpu} normalize_input: True reward_shaper: scale_value: 1.0 max_epochs: 50000 num_steps_per_episode: 8 save_best_after: 100 save_frequency: 1000 gamma: 0.99 init_alpha: 1.0 alpha_lr: 0.005 actor_lr: 0.0005 critic_lr: 0.0005 critic_tau: 0.005 batch_size: 4096 learnable_temperature: true num_seed_steps: 5 num_warmup_steps: 10 replay_buffer_size: 1000000 num_actors: ${....task.env.numEnvs}
945
YAML
17.92
58
0.594709
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/ShadowHandOpenAI_LSTMPPO.yaml
# specifies what the default training mode is when # running `ShadowHandOpenAI_LSTM` (version with DR and asymmetric observations, and LSTM) defaults: - ShadowHandPPOAsymmLSTM - _self_
189
YAML
30.666662
89
0.777778
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/IngenuityPPO.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: 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:Ingenuity,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} 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-3 lr_schedule: adaptive kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:500,${....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,546
YAML
21.1
101
0.595731
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/QuadcopterPPO.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: 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:Quadcopter,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.1 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 1e-3 lr_schedule: adaptive kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:500,${....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: 8 minibatch_size: 16384 mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,545
YAML
21.085714
101
0.595469
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/FactoryTaskNutBoltScrewPPO.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, 128, 64] activation: elu d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:FactoryTaskNutBoltScrew,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: True normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 1.0e-4 lr_schedule: fixed schedule_type: standard kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:1024,${....max_iterations}} save_best_after: 50 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 128 minibatch_size: 512 # batch size = num_envs * horizon_length; minibatch_size = batch_size / num_minibatches mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,634
YAML
21.708333
112
0.602815
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/ShadowHandPPOLSTM.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] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 256 layers: 1 before_mlp: False concat_input: True layer_norm: True 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:ShadowHandLSTM,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} 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 save_best_after: 500 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 32 minibatch_size: 16384 mini_epochs: ${resolve_default:4,${....max_iterations}} critic_coef: 4 clip_value: False seq_len: 4 bounds_loss_coef: 0.0001 player: #render: True deterministic: True games_num: 100000 print_stats: True
1,818
YAML
20.4
101
0.594609
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/BallBalancePPO.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: [128, 64, 32] activation: elu 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:BallBalance,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.1 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 3e-4 lr_schedule: adaptive kl_threshold: 0.008 score_to_win: 20000 max_epochs: ${resolve_default:250,${....max_iterations}} save_best_after: 50 save_frequency: 100 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 8192 mini_epochs: 8 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,526
YAML
21.455882
101
0.596986
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/FactoryTaskNutBoltPlacePPO.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, 128, 64] activation: elu d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:FactoryTaskNutBoltPlace,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} ppo: True mixed_precision: True normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 1e-4 lr_schedule: fixed schedule_type: standard kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:1024,${....max_iterations}} save_best_after: 50 save_frequency: 100 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 120 minibatch_size: 512 mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,543
YAML
20.444444
70
0.595593
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/IndustRealTaskGearsInsertPPO.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, 256, 128] activation: elu d2rl: False initializer: name: default regularizer: name: None rnn: name: lstm units: 256 layers: 2 before_mlp: True concat_input: True layer_norm: False load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:IndustRealTaskGearsInsert,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu 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: 1.0 normalize_advantage: True gamma: 0.998 tau: 0.95 learning_rate: 1e-4 lr_schedule: linear schedule_type: standard kl_threshold: 0.008 score_to_win: 20000 max_epochs: ${resolve_default:8192,${....max_iterations}} save_best_after: 50 save_frequency: 1000 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 128 minibatch_size: 8 # batch size = num_envs * horizon_length; minibatch_size = batch_size / num_minibatches mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001 central_value_config: minibatch_size: 8 mini_epochs: 4 learning_rate: 1e-3 lr_schedule: linear kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True network: name: actor_critic central_value: True mlp: units: [256, 128, 64] activation: elu d2rl: False initializer: name: default regularizer: name: None
2,254
YAML
20.682692
110
0.579858
NVIDIA-Omniverse/IsaacGymEnvs/isaacgymenvs/cfg/train/AntPPO.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, 128, 64] 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:Ant,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu multi_gpu: ${....multi_gpu} 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: 3e-4 lr_schedule: adaptive schedule_type: legacy kl_threshold: 0.008 score_to_win: 20000 max_epochs: ${resolve_default:500,${....max_iterations}} save_best_after: 200 save_frequency: 50 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: False e_clip: 0.2 horizon_length: 16 minibatch_size: 32768 mini_epochs: 4 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
1,592
YAML
21.125
101
0.597362