file_path
stringlengths
21
224
content
stringlengths
0
80.8M
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/sim2real/ur10.py
# Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import asyncio import math import numpy as np try: import rospy # Ref: https://github.com/ros-controls/ros_controllers/blob/melodic-devel/rqt_joint_trajectory_controller/src/rqt_joint_trajectory_controller/joint_trajectory_controller.py from control_msgs.msg import JointTrajectoryControllerState from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint except ImportError: rospy = None class RealWorldUR10(): # Defined in ur10.usd sim_dof_angle_limits = [ (-360, 360, False), (-360, 360, False), (-360, 360, False), (-360, 360, False), (-360, 360, False), (-360, 360, False), ] # _sim_dof_limits[:,2] == True indicates inversed joint angle compared to real # Ref: https://github.com/ros-industrial/universal_robot/issues/112 pi = math.pi servo_angle_limits = [ (-2*pi, 2*pi), (-2*pi, 2*pi), (-2*pi, 2*pi), (-2*pi, 2*pi), (-2*pi, 2*pi), (-2*pi, 2*pi), ] # ROS-related strings state_topic = '/scaled_pos_joint_traj_controller/state' cmd_topic = '/scaled_pos_joint_traj_controller/command' joint_names = [ 'elbow_joint', 'shoulder_lift_joint', 'shoulder_pan_joint', 'wrist_1_joint', 'wrist_2_joint', 'wrist_3_joint' ] # Joint name mapping to simulation action index joint_name_to_idx = { 'elbow_joint': 2, 'shoulder_lift_joint': 1, 'shoulder_pan_joint': 0, 'wrist_1_joint': 3, 'wrist_2_joint': 4, 'wrist_3_joint': 5 } def __init__(self, fail_quietely=False, verbose=False) -> None: print("Connecting to real-world UR10") self.fail_quietely = fail_quietely self.verbose = verbose self.pub_freq = 10 # Hz # Not really sure if current_pos and target_pos require mutex here. self.current_pos = None self.target_pos = None if rospy is None: if not self.fail_quietely: raise ValueError("ROS is not installed!") print("ROS is not installed!") return try: rospy.init_node("custom_controller", anonymous=True, disable_signals=True, log_level=rospy.ERROR) except rospy.exceptions.ROSException as e: print("Node has already been initialized, do nothing") if self.verbose: print("Receiving real-world UR10 joint angles...") print("If you didn't see any outputs, you may have set up UR5 or ROS incorrectly.") self.sub = rospy.Subscriber( self.state_topic, JointTrajectoryControllerState, self.sub_callback, queue_size=1 ) self.pub = rospy.Publisher( self.cmd_topic, JointTrajectory, queue_size=1 ) # self.min_traj_dur = 5.0 / self.pub_freq # Minimum trajectory duration self.min_traj_dur = 0 # Minimum trajectory duration # For catching exceptions in asyncio def custom_exception_handler(loop, context): print(context) # Ref: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.set_exception_handler asyncio.get_event_loop().set_exception_handler(custom_exception_handler) # Ref: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_ros_custom_message.html asyncio.ensure_future(self.pub_task()) def sub_callback(self, msg): # msg has type: JointTrajectoryControllerState actual_pos = {} for i in range(len(msg.joint_names)): joint_name = msg.joint_names[i] joint_pos = msg.actual.positions[i] actual_pos[joint_name] = joint_pos self.current_pos = actual_pos if self.verbose: print(f'(sub) {actual_pos}') async def pub_task(self): while not rospy.is_shutdown(): await asyncio.sleep(1.0 / self.pub_freq) if self.current_pos is None: # Not ready (recieved UR state) yet continue if self.target_pos is None: # No command yet continue # Construct message dur = [] # move duration of each joints traj = JointTrajectory() traj.joint_names = self.joint_names point = JointTrajectoryPoint() moving_average = 1 for name in traj.joint_names: pos = self.current_pos[name] cmd = pos * (1-moving_average) + self.target_pos[self.joint_name_to_idx[name]] * moving_average max_vel = 3.15 # from ur5.urdf (or ur5.urdf.xacro) duration = abs(cmd - pos) / max_vel # time = distance / velocity dur.append(max(duration, self.min_traj_dur)) point.positions.append(cmd) point.time_from_start = rospy.Duration(max(dur)) traj.points.append(point) self.pub.publish(traj) print(f'(pub) {point.positions}') def send_joint_pos(self, joint_pos): if len(joint_pos) != 6: raise Exception("The length of UR10 joint_pos is {}, but should be 6!".format(len(joint_pos))) # Convert Sim angles to Real angles target_pos = [0] * 6 for i, pos in enumerate(joint_pos): if i == 5: # Ignore the gripper joints for Reacher task continue # Map [L, U] to [A, B] L, U, inversed = self.sim_dof_angle_limits[i] A, B = self.servo_angle_limits[i] angle = np.rad2deg(float(pos)) if not L <= angle <= U: print("The {}-th simulation joint angle ({}) is out of range! Should be in [{}, {}]".format(i, angle, L, U)) angle = np.clip(angle, L, U) target_pos[i] = (angle - L) * ((B-A)/(U-L)) + A # Map [L, U] to [A, B] if inversed: target_pos[i] = (B-A) - (target_pos[i] - A) + A # Map [A, B] to [B, A] if not A <= target_pos[i] <= B: raise Exception("(Should Not Happen) The {}-th real world joint angle ({}) is out of range! hould be in [{}, {}]".format(i, target_pos[i], A, B)) self.target_pos = target_pos if __name__ == "__main__": print("Make sure you are running `roslaunch ur_robot_driver`.") print("If the machine running Isaac is not the ROS master node, " + \ "make sure you have set the environment variables: " + \ "`ROS_MASTER_URI` and `ROS_HOSTNAME`/`ROS_IP` correctly.") ur10 = RealWorldUR10(verbose=True) rospy.spin()
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/config.yaml
# Task name - used to pick the class to load task_name: ${task.name} # experiment name. defaults to name of training config experiment: '' # if set to positive integer, overrides the default number of environments num_envs: '' # seed - set to -1 to choose random seed seed: 42 # set to True for deterministic performance torch_deterministic: False # set the maximum number of learning iterations to train for. overrides default per-environment setting max_iterations: '' ## Device config physics_engine: 'physx' # whether to use cpu or gpu pipeline pipeline: 'gpu' # whether to use cpu or gpu physx sim_device: 'gpu' # used for gpu simulation only - device id for running sim and task if pipeline=gpu device_id: 0 # device to run RL rl_device: 'cuda:0' ## PhysX arguments num_threads: 4 # Number of worker threads per scene used by PhysX - for CPU PhysX only. solver_type: 1 # 0: pgs, 1: tgs # RLGames Arguments # test - if set, run policy in inference mode (requires setting checkpoint to load) test: False # used to set checkpoint path checkpoint: '' # disables rendering headless: False wandb_activate: False wandb_group: '' wandb_name: ${train.params.config.name} wandb_entity: '' wandb_project: 'omniisaacgymenvs' # set default task and default training config based on task defaults: - task: Cartpole - train: ${task}PPO - hydra/job_logging: disabled # set the directory where the output files get saved hydra: output_subdir: null run: dir: .
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/FrankaCabinet.yaml
# used to create the object name: FrankaCabinet physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 3.0 episodeLength: 500 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 controlFrequencyInv: 2 # 60 Hz startPositionNoise: 0.0 startRotationNoise: 0.0 numProps: 4 aggregateMode: 3 actionScale: 7.5 dofVelocityScale: 0.1 distRewardScale: 2.0 rotRewardScale: 0.5 aroundHandleRewardScale: 10.0 openRewardScale: 7.5 fingerDistRewardScale: 100.0 actionPenaltyScale: 0.01 fingerCloseRewardScale: 10.0 sim: dt: 0.0083 # 1/120 s use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 12 solver_velocity_iteration_count: 1 contact_offset: 0.005 rest_offset: 0.0 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 1000.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 33554432 gpu_found_lost_pairs_capacity: 524288 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 1048576 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 33554432 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 franka: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 12 solver_velocity_iteration_count: 1 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0 # per-shape contact_offset: 0.005 rest_offset: 0.0 cabinet: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 12 solver_velocity_iteration_count: 1 sleep_threshold: 0.0 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0 # per-shape contact_offset: 0.005 rest_offset: 0.0 prop: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 12 solver_velocity_iteration_count: 1 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: 100 max_depenetration_velocity: 1000.0 # per-shape contact_offset: 0.005 rest_offset: 0.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Ant.yaml
# used to create the object name: Ant physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: # numEnvs: ${...num_envs} numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 5 episodeLength: 1000 enableDebugVis: False clipActions: 1.0 powerScale: 0.5 controlFrequencyInv: 2 # 60 Hz # reward parameters headingWeight: 0.5 upWeight: 0.1 # cost parameters actionsCost: 0.005 energyCost: 0.05 dofVelocityScale: 0.2 angularVelocityScale: 1.0 contactForceScale: 0.1 jointsAtLimitCost: 0.1 deathCost: -2.0 terminationHeight: 0.31 alive_reward_scale: 0.5 sim: dt: 0.0083 # 1/120 s use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True add_distant_light: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 10.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 8192 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 Ant: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 10.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/AnymalTerrain.yaml
name: AnymalTerrain physics_engine: ${..physics_engine} env: numEnvs: ${resolve_default:2048,${...num_envs}} numObservations: 188 numActions: 12 envSpacing: 3. # [m] terrain: staticFriction: 1.0 # [-] dynamicFriction: 1.0 # [-] restitution: 0. # [-] # rough terrain only: curriculum: true maxInitMapLevel: 0 mapLength: 8. mapWidth: 8. numLevels: 10 numTerrains: 20 # terrain types: [smooth slope, rough slope, stairs up, stairs down, discrete] terrainProportions: [0.1, 0.1, 0.35, 0.25, 0.2] # tri mesh only: slopeTreshold: 0.5 baseInitState: pos: [0.0, 0.0, 0.62] # x,y,z [m] rot: [1.0, 0.0, 0.0, 0.0] # w,x,y,z [quat] vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s] vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s] randomCommandVelocityRanges: # train linear_x: [-1., 1.] # min max [m/s] linear_y: [-1., 1.] # min max [m/s] yaw: [-3.14, 3.14] # min max [rad/s] control: # PD Drive parameters: stiffness: 80.0 # [N*m/rad] damping: 2.0 # [N*m*s/rad] # action scale: target angle = actionScale * action + defaultAngle actionScale: 0.5 # decimation: Number of control action updates @ sim DT per policy DT decimation: 4 defaultJointAngles: # = target angles when action = 0.0 LF_HAA: 0.03 # [rad] LH_HAA: 0.03 # [rad] RF_HAA: -0.03 # [rad] RH_HAA: -0.03 # [rad] LF_HFE: 0.4 # [rad] LH_HFE: -0.4 # [rad] RF_HFE: 0.4 # [rad] RH_HFE: -0.4 # [rad] LF_KFE: -0.8 # [rad] LH_KFE: 0.8 # [rad] RF_KFE: -0.8 # [rad] RH_KFE: 0.8 # [rad] learn: # rewards terminalReward: 0.0 linearVelocityXYRewardScale: 1.0 linearVelocityZRewardScale: -4.0 angularVelocityXYRewardScale: -0.05 angularVelocityZRewardScale: 0.5 orientationRewardScale: -0. torqueRewardScale: -0.00002 jointAccRewardScale: -0.0005 baseHeightRewardScale: -0.0 actionRateRewardScale: -0.01 fallenOverRewardScale: -1.0 # cosmetics hipRewardScale: -0. #25 # normalization linearVelocityScale: 2.0 angularVelocityScale: 0.25 dofPositionScale: 1.0 dofVelocityScale: 0.05 heightMeasurementScale: 5.0 # noise addNoise: true noiseLevel: 1.0 # scales other values dofPositionNoise: 0.01 dofVelocityNoise: 1.5 linearVelocityNoise: 0.1 angularVelocityNoise: 0.2 gravityNoise: 0.05 heightMeasurementNoise: 0.06 #randomization pushInterval_s: 15 # episode length in seconds episodeLength_s: 20 sim: dt: 0.005 up_axis: "z" use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: False use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 100.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 163840 gpu_found_lost_pairs_capacity: 4194304 gpu_found_lost_aggregate_pairs_capacity: 33554432 gpu_total_aggregate_pairs_capacity: 4194304 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 134217728 gpu_temp_buffer_capacity: 33554432 gpu_max_num_partitions: 8 anymal: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: False # also in stage params # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 100.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/BallBalance.yaml
# used to create the object name: BallBalance physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 2.0 maxEpisodeLength: 500 actionSpeedScale: 20 clipObservations: 5.0 clipActions: 1.0 sim: dt: 0.01 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True add_distant_light: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 1000.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 8192 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 table: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0 ball: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: 200 max_depenetration_velocity: 1000.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Humanoid.yaml
# used to create the object name: Humanoid physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: # numEnvs: ${...num_envs} numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 5 episodeLength: 1000 enableDebugVis: False clipActions: 1.0 powerScale: 1.0 controlFrequencyInv: 2 # 60 Hz # reward parameters headingWeight: 0.5 upWeight: 0.1 # cost parameters actionsCost: 0.01 energyCost: 0.05 dofVelocityScale: 0.1 angularVelocityScale: 0.25 contactForceScale: 0.01 jointsAtLimitCost: 0.25 deathCost: -1.0 terminationHeight: 0.8 alive_reward_scale: 2.0 sim: dt: 0.0083 # 1/120 s use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True add_distant_light: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 10.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 8192 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 Humanoid: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 10.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/AllegroHand.yaml
# used to create the object name: AllegroHand physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:8192,${...num_envs}} envSpacing: 0.75 episodeLength: 600 clipObservations: 5.0 clipActions: 1.0 useRelativeControl: False dofSpeedScale: 20.0 actionsMovingAverage: 1.0 controlFrequencyInv: 4 # 30 Hz startPositionNoise: 0.01 startRotationNoise: 0.0 resetPositionNoise: 0.01 resetRotationNoise: 0.0 resetDofPosRandomInterval: 0.2 resetDofVelRandomInterval: 0.0 # reward -> dictionary distRewardScale: -10.0 rotRewardScale: 1.0 rotEps: 0.1 actionPenaltyScale: -0.0002 reachGoalBonus: 250 fallDistance: 0.24 fallPenalty: 0.0 velObsScale: 0.2 objectType: "block" observationType: "full" # can be "full_no_vel", "full" successTolerance: 0.1 printNumSuccesses: False maxConsecutiveSuccesses: 0 sim: dt: 0.0083 # 1/120 s add_ground_plane: True add_distant_light: True use_gpu_pipeline: ${eq:${...pipeline},"gpu"} use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: # per-scene use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU worker_thread_count: ${....num_threads} solver_type: ${....solver_type} # 0: PGS, 1: TGS bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 33554432 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 1048576 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 33554432 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 allegro_hand: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: False # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.0005 # per-body density: -1 max_depenetration_velocity: 1000.0 object: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.0025 # per-body density: 400.0 max_depenetration_velocity: 1000.0 goal_object: # -1 to use default values override_usd_defaults: False fixed_base: True enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.000 stabilization_threshold: 0.0025 # per-body density: -1 max_depenetration_velocity: 1000.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Ingenuity.yaml
# used to create the object name: Ingenuity physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 2.5 maxEpisodeLength: 2000 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 sim: dt: 0.01 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -3.721] add_ground_plane: True add_distant_light: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 6 solver_velocity_iteration_count: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 1000.0 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: False # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 4194304 gpu_found_lost_aggregate_pairs_capacity: 33554432 gpu_total_aggregate_pairs_capacity: 4194304 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 ingenuity: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 6 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0 ball: # -1 to use default values override_usd_defaults: False fixed_base: True enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 6 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Quadcopter.yaml
# used to create the object name: Quadcopter physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 1.25 maxEpisodeLength: 500 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 sim: dt: 0.01 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True add_distant_light: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 1000.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 8192 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 copter: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Crazyflie.yaml
# used to create the object name: Crazyflie physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 2.5 maxEpisodeLength: 700 enableDebugVis: False clipObservations: 5.0 clipActions: 1.0 sim: dt: 0.01 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True add_distant_light: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False physx: num_threads: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 6 solver_velocity_iteration_count: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 max_depenetration_velocity: 1000.0 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: False # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 4194304 gpu_found_lost_aggregate_pairs_capacity: 33554432 gpu_total_aggregate_pairs_capacity: 4194304 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 crazyflie: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 6 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0 ball: # -1 to use default values override_usd_defaults: False fixed_base: True enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 6 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 1000.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/ShadowHand.yaml
# used to create the object name: ShadowHand physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:8192,${...num_envs}} envSpacing: 0.75 episodeLength: 600 clipObservations: 5.0 clipActions: 1.0 useRelativeControl: False dofSpeedScale: 20.0 actionsMovingAverage: 1.0 controlFrequencyInv: 2 # 60 Hz startPositionNoise: 0.01 startRotationNoise: 0.0 resetPositionNoise: 0.01 resetRotationNoise: 0.0 resetDofPosRandomInterval: 0.2 resetDofVelRandomInterval: 0.0 # Random forces applied to the object forceScale: 0.0 forceProbRange: [0.001, 0.1] forceDecay: 0.99 forceDecayInterval: 0.08 # reward -> dictionary distRewardScale: -10.0 rotRewardScale: 1.0 rotEps: 0.1 actionPenaltyScale: -0.0002 reachGoalBonus: 250 fallDistance: 0.24 fallPenalty: 0.0 velObsScale: 0.2 objectType: "block" observationType: "full" # can be "full_no_vel", "full", "openai", "full_state" asymmetric_observations: False successTolerance: 0.1 printNumSuccesses: False maxConsecutiveSuccesses: 0 sim: dt: 0.0083 # 1/120 s add_ground_plane: True add_distant_light: True use_gpu_pipeline: ${eq:${...pipeline},"gpu"} use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: # per-scene use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU worker_thread_count: ${....num_threads} solver_type: ${....solver_type} # 0: PGS, 1: TGS bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 33554432 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 524288 gpu_total_aggregate_pairs_capacity: 1048576 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 33554432 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 shadow_hand: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.0005 # per-body density: -1 max_depenetration_velocity: 1000.0 object: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.0025 # per-body density: 567.0 max_depenetration_velocity: 1000.0 goal_object: # -1 to use default values override_usd_defaults: False fixed_base: True enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.000 stabilization_threshold: 0.0025 # per-body density: -1 max_depenetration_velocity: 1000.0 domain_randomization: randomize: False min_frequency: 720 randomization_params: observations: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, .0001] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0, .002] actions: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, 0.015] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0., 0.05] simulation: gravity: on_interval: frequency_interval: 720 operation: "additive" distribution: "gaussian" distribution_parameters: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.4]] rigid_prim_views: object_view: material_properties: on_reset: num_buckets: 250 operation: "scaling" distribution: "uniform" distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]] scale: on_startup: operation: "scaling" distribution: "uniform" distribution_parameters: [0.95, 1.05] mass: on_startup: operation: "scaling" distribution: "uniform" distribution_parameters: [0.5, 1.5] articulation_views: shadow_hand_view: stiffness: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.75, 1.5] damping: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.3, 3.0] lower_dof_limits: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0.00, 0.01] upper_dof_limits: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0.00, 0.01] tendon_stiffnesses: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.75, 1.5] tendon_dampings: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.3, 3.0] material_properties: on_reset: num_buckets: 250 operation: "scaling" distribution: "uniform" distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]]
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/UR10Reacher.yaml
# used to create the object name: UR10Reacher physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:512,${...num_envs}} envSpacing: 3 episodeLength: 600 clipObservations: 5.0 clipActions: 1.0 useRelativeControl: False dofSpeedScale: 20.0 actionsMovingAverage: 0.1 controlFrequencyInv: 2 # 60 Hz startPositionNoise: 0.01 startRotationNoise: 0.0 resetPositionNoise: 0.01 resetRotationNoise: 0.0 resetDofPosRandomInterval: 0.2 resetDofVelRandomInterval: 0.0 # Random forces applied to the object forceScale: 0.0 forceProbRange: [0.001, 0.1] forceDecay: 0.99 forceDecayInterval: 0.08 # reward -> dictionary distRewardScale: -2.0 rotRewardScale: 1.0 rotEps: 0.1 actionPenaltyScale: -0.0002 reachGoalBonus: 250 velObsScale: 0.2 observationType: "full" # can only be "full" successTolerance: 0.1 printNumSuccesses: False maxConsecutiveSuccesses: 0 sim: dt: 0.0083 # 1/120 s add_ground_plane: True add_distant_light: True use_gpu_pipeline: ${eq:${...pipeline},"gpu"} use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: # per-scene use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU worker_thread_count: ${....num_threads} solver_type: ${....solver_type} # 0: PGS, 1: TGS bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 33554432 gpu_found_lost_pairs_capacity: 19771 gpu_found_lost_aggregate_pairs_capacity: 524288 gpu_total_aggregate_pairs_capacity: 1048576 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 33554432 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 ur10: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False object: # -1 to use default values override_usd_defaults: False fixed_base: True enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.000 stabilization_threshold: 0.0025 # per-body density: -1 max_depenetration_velocity: 1000.0 goal_object: # -1 to use default values override_usd_defaults: False fixed_base: True enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.000 stabilization_threshold: 0.0025 # per-body density: -1 max_depenetration_velocity: 1000.0 sim2real: enabled: False fail_quietely: False verbose: False safety: # Reduce joint limits during both training & testing enabled: False
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Cartpole.yaml
# used to create the object name: Cartpole physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:512,${...num_envs}} envSpacing: 4.0 resetDist: 3.0 maxEffort: 400.0 clipObservations: 5.0 clipActions: 1.0 controlFrequencyInv: 2 # 60 Hz sim: dt: 0.0083 # 1/120 s use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True add_distant_light: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 100.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 1024 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 1024 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 Cartpole: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 100.0 # per-shape contact_offset: 0.02 rest_offset: 0.001
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/ShadowHandOpenAI_FF.yaml
# used to create the object name: ShadowHand physics_engine: ${..physics_engine} # if given, will override the device setting in gym. env: numEnvs: ${resolve_default:8192,${...num_envs}} envSpacing: 0.75 episodeLength: 160 # Not used, but would be 8 sec if resetTime is not set resetTime: 8 # Max time till reset, in seconds, if a goal wasn't achieved. Will overwrite the episodeLength if is > 0. clipObservations: 5.0 clipActions: 1.0 useRelativeControl: False dofSpeedScale: 20.0 actionsMovingAverage: 0.3 controlFrequencyInv: 3 #20 Hz startPositionNoise: 0.01 startRotationNoise: 0.0 resetPositionNoise: 0.01 resetRotationNoise: 0.0 resetDofPosRandomInterval: 0.2 resetDofVelRandomInterval: 0.0 # Random forces applied to the object forceScale: 1.0 forceProbRange: [0.001, 0.1] forceDecay: 0.99 forceDecayInterval: 0.08 # reward -> dictionary distRewardScale: -10.0 rotRewardScale: 1.0 rotEps: 0.1 actionPenaltyScale: -0.0002 reachGoalBonus: 250 fallDistance: 0.24 fallPenalty: -50.0 velObsScale: 0.2 objectType: "block" observationType: "openai" # can be "full_no_vel", "full", "openai", "full_state" asymmetric_observations: True successTolerance: 0.4 printNumSuccesses: False maxConsecutiveSuccesses: 50 averFactor: 0.1 # running mean factor for consecutive successes calculation sim: dt: 0.016667 # 1/60 s add_ground_plane: True add_distant_light: True use_gpu_pipeline: ${eq:${...pipeline},"gpu"} use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: # per-scene use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU worker_thread_count: ${....num_threads} solver_type: ${....solver_type} # 0: PGS, 1: TGS bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 33554432 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 524288 gpu_total_aggregate_pairs_capacity: 1048576 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 33554432 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 shadow_hand: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.0005 # per-body density: -1 max_depenetration_velocity: 1000.0 object: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.0025 # per-body density: 567.0 max_depenetration_velocity: 1000.0 goal_object: # -1 to use default values override_usd_defaults: False fixed_base: True enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 8 solver_velocity_iteration_count: 0 sleep_threshold: 0.000 stabilization_threshold: 0.0025 # per-body density: -1 max_depenetration_velocity: 1000.0 domain_randomization: randomize: True min_frequency: 720 randomization_params: observations: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, .0001] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0, .002] actions: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, 0.015] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0., 0.05] simulation: gravity: on_interval: frequency_interval: 720 operation: "additive" distribution: "gaussian" distribution_parameters: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.4]] rigid_prim_views: object_view: material_properties: on_reset: num_buckets: 250 operation: "scaling" distribution: "uniform" distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]] scale: on_startup: operation: "scaling" distribution: "uniform" distribution_parameters: [0.95, 1.05] mass: on_startup: operation: "scaling" distribution: "uniform" distribution_parameters: [0.5, 1.5] articulation_views: shadow_hand_view: stiffness: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.75, 1.5] damping: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.3, 3.0] lower_dof_limits: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0.00, 0.01] upper_dof_limits: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0.00, 0.01] tendon_stiffnesses: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.75, 1.5] tendon_dampings: on_reset: operation: "scaling" distribution: "loguniform" distribution_parameters: [0.3, 3.0] material_properties: on_reset: num_buckets: 250 operation: "scaling" distribution: "uniform" distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]]
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/Anymal.yaml
# used to create the object name: Anymal physics_engine: ${..physics_engine} env: numEnvs: ${resolve_default:4096,${...num_envs}} envSpacing: 4. # [m] clipObservations: 5.0 clipActions: 1.0 controlFrequencyInv: 2 baseInitState: pos: [0.0, 0.0, 0.62] # x,y,z [m] rot: [0.0, 0.0, 0.0, 1.0] # x,y,z,w [quat] vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s] vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s] randomCommandVelocityRanges: linear_x: [-2., 2.] # min max [m/s] linear_y: [-1., 1.] # min max [m/s] yaw: [-1., 1.] # min max [rad/s] control: # PD Drive parameters: stiffness: 85.0 # [N*m/rad] damping: 2.0 # [N*m*s/rad] actionScale: 13.5 defaultJointAngles: # = target angles when action = 0.0 LF_HAA: 0.03 # [rad] LH_HAA: 0.03 # [rad] RF_HAA: -0.03 # [rad] RH_HAA: -0.03 # [rad] LF_HFE: 0.4 # [rad] LH_HFE: -0.4 # [rad] RF_HFE: 0.4 # [rad] RH_HFE: -0.4 # [rad] LF_KFE: -0.8 # [rad] LH_KFE: 0.8 # [rad] RF_KFE: -0.8 # [rad] RH_KFE: 0.8 # [rad] learn: # rewards linearVelocityXYRewardScale: 1.0 angularVelocityZRewardScale: 0.5 linearVelocityZRewardScale: -0.03 jointAccRewardScale: -0.0003 actionRateRewardScale: -0.006 cosmeticRewardScale: -0.06 # normalization linearVelocityScale: 2.0 angularVelocityScale: 0.25 dofPositionScale: 1.0 dofVelocityScale: 0.05 # episode length in seconds episodeLength_s: 50 sim: dt: 0.01 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: [0.0, 0.0, -9.81] add_ground_plane: True use_flatcache: True enable_scene_query_support: False # set to True if you use camera sensors in the environment enable_cameras: False default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU solver_position_iteration_count: 4 solver_velocity_iteration_count: 1 contact_offset: 0.02 rest_offset: 0.0 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: True enable_stabilization: True max_depenetration_velocity: 100.0 # GPU buffers gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 163840 gpu_found_lost_pairs_capacity: 4194304 gpu_found_lost_aggregate_pairs_capacity: 33554432 gpu_total_aggregate_pairs_capacity: 4194304 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 134217728 gpu_temp_buffer_capacity: 33554432 gpu_max_num_partitions: 8 Anymal: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: False enable_gyroscopic_forces: True # also in stage params # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 1 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 100.0 # per-shape contact_offset: 0.02 rest_offset: 0.0
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/task/ShadowHandOpenAI_LSTM.yaml
# specifies what the config is when running `ShadowHandOpenAI` in LSTM mode defaults: - ShadowHandOpenAI_FF - _self_ env: numEnvs: ${resolve_default:8192,${...num_envs}}
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/ShadowHandOpenAI_FFPPO.yaml
params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: False space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: True mlp: units: [400, 400, 200, 100] activation: elu d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:ShadowHandOpenAI_FF,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu multi_gpu: False ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.016 score_to_win: 100000 max_epochs: ${resolve_default:10000,${....max_iterations}} save_best_after: 100 save_frequency: 200 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 16384 mini_epochs: 8 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001 central_value_config: minibatch_size: 8192 mini_epochs: 8 learning_rate: 5e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.016 clip_value: True normalize_input: True truncate_grads: True network: name: actor_critic central_value: True mlp: units: [512, 512, 256, 128] activation: elu d2rl: False initializer: name: default regularizer: name: None player: deterministic: True games_num: 100000 print_stats: True
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/AnymalTerrainPPO.yaml
params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: True space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0. # std = 1. fixed_sigma: True mlp: units: [512, 256, 128] activation: elu d2rl: False initializer: name: default regularizer: name: None # rnn: # name: lstm # units: 128 # layers: 1 # before_mlp: True # concat_input: True # layer_norm: False load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint load_path: ${...checkpoint} # path to the checkpoint to load config: name: ${resolve_default:AnymalTerrain,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu ppo: True mixed_precision: False # True normalize_input: True normalize_value: True normalize_advantage: True value_bootstrap: True clip_actions: False num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 1.0 gamma: 0.99 tau: 0.95 e_clip: 0.2 entropy_coef: 0.001 learning_rate: 3.e-4 # overwritten by adaptive lr_schedule lr_schedule: adaptive kl_threshold: 0.008 # target kl for adaptive lr truncate_grads: True grad_norm: 1. horizon_length: 48 minibatch_size: 16384 mini_epochs: 5 critic_coef: 2 clip_value: True seq_len: 4 # only for rnn bounds_loss_coef: 0. max_epochs: ${resolve_default:2000,${....max_iterations}} save_best_after: 100 score_to_win: 20000 save_frequency: 50 print_stats: True
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/HumanoidPPO.yaml
params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: False space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: True mlp: units: [400, 200, 100] activation: elu d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint load_path: ${...checkpoint} # path to the checkpoint to load config: name: ${resolve_default:Humanoid,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu device: ${....rl_device} device_name: ${....rl_device} multi_gpu: False ppo: True mixed_precision: True normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-4 lr_schedule: adaptive kl_threshold: 0.008 score_to_win: 20000 max_epochs: ${resolve_default:1000,${....max_iterations}} save_best_after: 100 save_frequency: 100 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 32 minibatch_size: 32768 mini_epochs: 5 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/CrazyfliePPO.yaml
params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: False space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: True mlp: units: [256, 256, 128] activation: tanh d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint load_path: ${...checkpoint} # path to the checkpoint to load config: name: ${resolve_default:Crazyflie,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu device: ${....rl_device} device_name: ${....rl_device} ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 1e-4 lr_schedule: adaptive kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:1000,${....max_iterations}} save_best_after: 50 save_frequency: 50 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 16384 mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/ShadowHandPPO.yaml
params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: False space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: True mlp: units: [512, 512, 256, 128] activation: elu d2rl: False initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:ShadowHand,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu multi_gpu: False ppo: True mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-4 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.016 score_to_win: 100000 max_epochs: ${resolve_default:10000,${....max_iterations}} save_best_after: 100 save_frequency: 200 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 32768 mini_epochs: 5 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001 player: deterministic: True games_num: 100000 print_stats: True
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/UR10ReacherPPO.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:UR10Reacher,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu multi_gpu: False ppo: True mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-3 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.008 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: 64 minibatch_size: 32768 mini_epochs: 5 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001 player: deterministic: True games_num: 100000 print_stats: True
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/ShadowHandOpenAI_LSTMPPO.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} load_path: ${...checkpoint} config: name: ${resolve_default:ShadowHandOpenAI_LSTM,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu multi_gpu: False ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.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: 100 save_frequency: 200 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 16384 mini_epochs: 4 critic_coef: 4 clip_value: True seq_len: 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: deterministic: True games_num: 100000 print_stats: True
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/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 device: ${....rl_device} device_name: ${....rl_device} ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 1e-3 lr_schedule: adaptive kl_threshold: 0.016 score_to_win: 20000 max_epochs: ${resolve_default:400,${....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
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/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 device: ${....rl_device} device_name: ${....rl_device} ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.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:1000,${....max_iterations}} save_best_after: 50 save_frequency: 50 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 16384 mini_epochs: 8 critic_coef: 2 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/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 device: ${....rl_device} device_name: ${....rl_device} ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.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
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/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 device: ${....rl_device} device_name: ${....rl_device} multi_gpu: False ppo: True mixed_precision: True normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 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: 100 save_frequency: 50 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True 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
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/FrankaCabinetPPO.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:FrankaCabinet,${....experiment}} full_experiment_name: ${.name} env_name: rlgpu device: ${....rl_device} device_name: ${....rl_device} ppo: True mixed_precision: False normalize_input: True normalize_value: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-4 lr_schedule: adaptive kl_threshold: 0.008 score_to_win: 100000000 max_epochs: ${resolve_default:1500,${....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: 16 minibatch_size: 8192 mini_epochs: 8 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/AllegroHandPPO.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 load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:AllegroHand,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu multi_gpu: False ppo: True mixed_precision: False normalize_input: True normalize_value: True value_bootstrap: True num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.01 normalize_advantage: True gamma: 0.99 tau: 0.95 learning_rate: 5e-3 lr_schedule: adaptive schedule_type: standard kl_threshold: 0.02 score_to_win: 100000 max_epochs: ${resolve_default:10000,${....max_iterations}} save_best_after: 100 save_frequency: 200 print_stats: True grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: True e_clip: 0.2 horizon_length: 16 minibatch_size: 32768 mini_epochs: 5 critic_coef: 4 clip_value: True seq_len: 4 bounds_loss_coef: 0.0001 player: deterministic: True games_num: 100000 print_stats: True
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/AnymalPPO.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. # std = 1. 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:Anymal,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu 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 e_clip: 0.2 entropy_coef: 0.0 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: 32768 mini_epochs: 5 critic_coef: 2 clip_value: True seq_len: 4 # only for rnn bounds_loss_coef: 0.001 max_epochs: ${resolve_default:1000,${....max_iterations}} save_best_after: 200 score_to_win: 20000 save_frequency: 50 print_stats: True
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/cfg/train/CartpolePPO.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: [32, 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:Cartpole,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu 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:100,${....max_iterations}} save_best_after: 50 save_frequency: 25 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
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/scripts/rlgames_play.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import * from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from omniisaacgymenvs.utils.demo_util import initialize_demo from omniisaacgymenvs.utils.config_utils.path_utils import retrieve_checkpoint_path from omniisaacgymenvs.envs.vec_env_rlgames import VecEnvRLGames from omniisaacgymenvs.scripts.rlgames_train import RLGTrainer import hydra from omegaconf import DictConfig import datetime import os import torch class RLGDemo(RLGTrainer): def __init__(self, cfg, cfg_dict): RLGTrainer.__init__(self, cfg, cfg_dict) self.cfg.test = True @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") headless = cfg.headless env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id) # ensure checkpoints can be specified as relative paths if cfg.checkpoint: cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint) if cfg.checkpoint is None: quit() cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) task = initialize_demo(cfg_dict, env) # sets seed. if seed is -1 will pick a random one from omni.isaac.core.utils.torch.maths import set_seed cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic) if cfg.wandb_activate: # Make sure to install WandB if you actually use this. import wandb run_name = f"{cfg.wandb_name}_{time_str}" wandb.init( project=cfg.wandb_project, group=cfg.wandb_group, entity=cfg.wandb_entity, config=cfg_dict, sync_tensorboard=True, id=run_name, resume="allow", monitor_gym=True, ) rlg_trainer = RLGDemo(cfg, cfg_dict) rlg_trainer.launch_rlg_hydra(env) rlg_trainer.run() env.close() if cfg.wandb_activate: wandb.finish() if __name__ == '__main__': parse_hydra_configs()
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/scripts/rlgames_train.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import * from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from omniisaacgymenvs.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv from omniisaacgymenvs.utils.task_util import initialize_task from omniisaacgymenvs.utils.config_utils.path_utils import retrieve_checkpoint_path from omniisaacgymenvs.envs.vec_env_rlgames import VecEnvRLGames import hydra from omegaconf import DictConfig from rl_games.common import env_configurations, vecenv from rl_games.torch_runner import Runner import datetime import os import torch class RLGTrainer(): def __init__(self, cfg, cfg_dict): self.cfg = cfg self.cfg_dict = cfg_dict def launch_rlg_hydra(self, env): # `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally. # We use the helper function here to specify the environment config. self.cfg_dict["task"]["test"] = self.cfg.test # register the rl-games adapter to use inside the runner vecenv.register('RLGPU', lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs)) env_configurations.register('rlgpu', { 'vecenv_type': 'RLGPU', 'env_creator': lambda **kwargs: env }) self.rlg_config_dict = omegaconf_to_dict(self.cfg.train) def run(self): # create runner and set the settings runner = Runner(RLGPUAlgoObserver()) runner.load(self.rlg_config_dict) runner.reset() # dump config dict experiment_dir = os.path.join('runs', self.cfg.train.params.config.name) os.makedirs(experiment_dir, exist_ok=True) with open(os.path.join(experiment_dir, 'config.yaml'), 'w') as f: f.write(OmegaConf.to_yaml(self.cfg)) runner.run({ 'train': not self.cfg.test, 'play': self.cfg.test, 'checkpoint': self.cfg.checkpoint, 'sigma': None }) @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") headless = cfg.headless env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id) # ensure checkpoints can be specified as relative paths if cfg.checkpoint: cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint) if cfg.checkpoint is None: quit() cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) task = initialize_task(cfg_dict, env) # sets seed. if seed is -1 will pick a random one from omni.isaac.core.utils.torch.maths import set_seed cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic) if cfg.wandb_activate: # Make sure to install WandB if you actually use this. import wandb run_name = f"{cfg.wandb_name}_{time_str}" wandb.init( project=cfg.wandb_project, group=cfg.wandb_group, entity=cfg.wandb_entity, config=cfg_dict, sync_tensorboard=True, id=run_name, resume="allow", monitor_gym=True, ) rlg_trainer = RLGTrainer(cfg, cfg_dict) rlg_trainer.launch_rlg_hydra(env) rlg_trainer.run() env.close() if cfg.wandb_activate: wandb.finish() if __name__ == '__main__': parse_hydra_configs()
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/scripts/dummy_ur10_policy.py
# Copyright (c) 2018-2022, NVIDIA Corporation # Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np import torch import hydra from omegaconf import DictConfig from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import * from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from omniisaacgymenvs.utils.task_util import initialize_task from omniisaacgymenvs.envs.vec_env_rlgames import VecEnvRLGames @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) headless = cfg.headless render = not headless env = VecEnvRLGames(headless=headless) task = initialize_task(cfg_dict, env) while env._simulation_app.is_running(): if env._world.is_playing(): if env._world.current_time_step_index == 0: env._world.reset(soft=True) actions = torch.tensor(np.array([env.action_space.sample() for _ in range(env.num_envs)]), device=task.rl_device) actions[:, 0] = 0.0 actions[:, 1] = 0.0 actions[:, 2] = 0.0 actions[:, 3] = 0.0 actions[:, 4] = 0.0 actions[:, 5] = 0.0 env._task.pre_physics_step(actions) env._world.step(render=render) env.sim_frame_count += 1 env._task.post_physics_step() else: env._world.step(render=render) env._simulation_app.close() if __name__ == '__main__': parse_hydra_configs()
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/scripts/random_policy.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np import torch import hydra from omegaconf import DictConfig from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import * from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from omniisaacgymenvs.utils.task_util import initialize_task from omniisaacgymenvs.envs.vec_env_rlgames import VecEnvRLGames @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) headless = cfg.headless render = not headless env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id) task = initialize_task(cfg_dict, env) while env._simulation_app.is_running(): if env._world.is_playing(): if env._world.current_time_step_index == 0: env._world.reset(soft=True) actions = torch.tensor(np.array([env.action_space.sample() for _ in range(env.num_envs)]), device=task.rl_device) env._task.pre_physics_step(actions) env._world.step(render=render) env.sim_frame_count += 1 env._task.post_physics_step() else: env._world.step(render=render) env._simulation_app.close() if __name__ == '__main__': parse_hydra_configs()
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/scripts/rlgames_train_mt.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from omniisaacgymenvs.utils.hydra_cfg.hydra_utils import * from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from omniisaacgymenvs.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv from omniisaacgymenvs.utils.task_util import initialize_task from omniisaacgymenvs.utils.config_utils.path_utils import retrieve_checkpoint_path from omniisaacgymenvs.envs.vec_env_rlgames_mt import VecEnvRLGamesMT import hydra from omegaconf import DictConfig from rl_games.common import env_configurations, vecenv from rl_games.torch_runner import Runner import copy import datetime import os import threading import queue from omni.isaac.gym.vec_env.vec_env_mt import TrainerMT class RLGTrainer(): def __init__(self, cfg, cfg_dict): self.cfg = cfg self.cfg_dict = cfg_dict def launch_rlg_hydra(self, env): # `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally. # We use the helper function here to specify the environment config. self.cfg_dict["task"]["test"] = self.cfg.test # register the rl-games adapter to use inside the runner vecenv.register('RLGPU', lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs)) env_configurations.register('rlgpu', { 'vecenv_type': 'RLGPU', 'env_creator': lambda **kwargs: env }) self.rlg_config_dict = omegaconf_to_dict(self.cfg.train) def run(self): # create runner and set the settings runner = Runner(RLGPUAlgoObserver()) runner.load(copy.deepcopy(self.rlg_config_dict)) runner.reset() # dump config dict experiment_dir = os.path.join('runs', self.cfg.train.params.config.name) os.makedirs(experiment_dir, exist_ok=True) with open(os.path.join(experiment_dir, 'config.yaml'), 'w') as f: f.write(OmegaConf.to_yaml(self.cfg)) time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if self.cfg.wandb_activate: # Make sure to install WandB if you actually use this. import wandb run_name = f"{self.cfg.wandb_name}_{time_str}" wandb.init( project=self.cfg.wandb_project, group=self.cfg.wandb_group, entity=self.cfg.wandb_entity, config=self.cfg_dict, sync_tensorboard=True, id=run_name, resume="allow", monitor_gym=True, ) runner.run({ 'train': not self.cfg.test, 'play': self.cfg.test, 'checkpoint': self.cfg.checkpoint, 'sigma': None }) if self.cfg.wandb_activate: wandb.finish() class Trainer(TrainerMT): def __init__(self, trainer, env): self.ppo_thread = None self.action_queue = None self.data_queue = None self.trainer = trainer self.is_running = False self.env = env self.create_task() self.run() def create_task(self): self.trainer.launch_rlg_hydra(self.env) task = initialize_task(self.trainer.cfg_dict, self.env, init_sim=False) self.task = task def run(self): self.is_running = True self.action_queue = queue.Queue(1) self.data_queue = queue.Queue(1) self.env.initialize(self.action_queue, self.data_queue) self.ppo_thread = PPOTrainer(self.env, self.task, self.trainer) self.ppo_thread.daemon = True self.ppo_thread.start() def stop(self): self.env.stop = True self.env.clear_queues() if self.action_queue: self.action_queue.join() if self.data_queue: self.data_queue.join() if self.ppo_thread: self.ppo_thread.join() self.action_queue = None self.data_queue = None self.ppo_thread = None self.is_running = False class PPOTrainer(threading.Thread): def __init__(self, env, task, trainer): super().__init__() self.env = env self.task = task self.trainer = trainer def run(self): from omni.isaac.gym.vec_env import TaskStopException print("starting ppo...") try: self.trainer.run() # trainer finished - send stop signal to main thread self.env.send_actions(None) self.env.stop = True except TaskStopException: print("Task Stopped!") @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): headless = cfg.headless env = VecEnvRLGamesMT(headless=headless, sim_device=cfg.device_id) # ensure checkpoints can be specified as relative paths if cfg.checkpoint: cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint) if cfg.checkpoint is None: quit() cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) # sets seed. if seed is -1 will pick a random one from omni.isaac.core.utils.torch.maths import set_seed cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic) rlg_trainer = RLGTrainer(cfg, cfg_dict) trainer = Trainer(rlg_trainer, env) trainer.env.run(trainer) if __name__ == '__main__': parse_hydra_configs()
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/demos/anymal_terrain.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from omniisaacgymenvs.tasks.anymal_terrain import AnymalTerrainTask, wrap_to_pi from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.core.utils.stage import get_current_stage from omni.isaac.core.utils.torch.rotations import * from omni.isaac.core.utils.torch.transformations import tf_combine import numpy as np import torch import math import omni import carb class AnymalTerrainDemo(AnymalTerrainTask): def __init__( self, name, sim_config, env, offset=None ) -> None: max_num_envs = 128 if sim_config.task_config["env"]["numEnvs"] >= max_num_envs: print(f"num_envs reduced to {max_num_envs} for this demo.") sim_config.task_config["env"]["numEnvs"] = max_num_envs sim_config.task_config["env"]["learn"]["episodeLength_s"] = 120 AnymalTerrainTask.__init__(self, name, sim_config, env) self.add_noise = False self.knee_threshold = 0.05 self.create_camera() self._current_command = [0.0, 0.0, 0.0, 0.0] self.set_up_keyboard() self._prim_selection = omni.usd.get_context().get_selection() self._selected_id = None self._previous_selected_id = None return def create_camera(self): stage = omni.usd.get_context().get_stage() self.view_port = omni.kit.viewport_legacy.get_default_viewport_window() # Create camera self.camera_path = "/World/Camera" self.perspective_path = "/OmniverseKit_Persp" camera_prim = stage.DefinePrim(self.camera_path, "Camera") self.view_port.set_active_camera(self.camera_path) camera_prim.GetAttribute("focalLength").Set(8.5) self.view_port.set_active_camera(self.perspective_path) def set_up_keyboard(self): self._input = carb.input.acquire_input_interface() self._keyboard = omni.appwindow.get_default_app_window().get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._on_keyboard_event) T = 1 R = 1 self._key_to_control = { "UP": [T, 0.0, 0.0, 0.0], "DOWN": [-T, 0.0, 0.0, 0.0], "LEFT": [0.0, T, 0.0, 0.0], "RIGHT": [0.0, -T, 0.0, 0.0], "Z": [0.0, 0.0, R, 0.0], "X": [0.0, 0.0, -R, 0.0], } def _on_keyboard_event(self, event, *args, **kwargs): if event.type == carb.input.KeyboardEventType.KEY_PRESS: if event.input.name in self._key_to_control: self._current_command = self._key_to_control[event.input.name] elif event.input.name == "ESCAPE": self._prim_selection.clear_selected_prim_paths() elif event.input.name == "C": if self._selected_id is not None: if self.view_port.get_active_camera() == self.camera_path: self.view_port.set_active_camera(self.perspective_path) else: self.view_port.set_active_camera(self.camera_path) else: self._current_command = [0.0, 0.0, 0.0, 0.0] def update_selected_object(self): self._previous_selected_id = self._selected_id selected_prim_paths = self._prim_selection.get_selected_prim_paths() if len(selected_prim_paths) == 0: self._selected_id = None self.view_port.set_active_camera(self.perspective_path) elif len(selected_prim_paths) > 1: print("Multiple prims are selected. Please only select one!") else: prim_splitted_path = selected_prim_paths[0].split("/") if len(prim_splitted_path) >= 4 and prim_splitted_path[3][0:4] == "env_": self._selected_id = int(prim_splitted_path[3][4:]) if self._previous_selected_id != self._selected_id: self.view_port.set_active_camera(self.camera_path) self._update_camera() else: print("The selected prim was not an Anymal") if self._previous_selected_id is not None and self._previous_selected_id != self._selected_id: self.commands[self._previous_selected_id, 0] = np.random.uniform(self.command_x_range[0], self.command_x_range[1]) self.commands[self._previous_selected_id, 1] = np.random.uniform(self.command_y_range[0], self.command_y_range[1]) self.commands[self._previous_selected_id, 2] = 0.0 def _update_camera(self): base_pos = self.base_pos[self._selected_id, :].clone() base_quat = self.base_quat[self._selected_id, :].clone() camera_local_transform = torch.tensor([-1.8, 0.0, 0.6], device=self.device) camera_pos = quat_apply(base_quat, camera_local_transform) + base_pos self.view_port.set_camera_position(self.camera_path, camera_pos[0], camera_pos[1], camera_pos[2], True) self.view_port.set_camera_target(self.camera_path, base_pos[0], base_pos[1], base_pos[2]+0.6, True) def post_physics_step(self): self.progress_buf[:] += 1 self.refresh_dof_state_tensors() self.refresh_body_state_tensors() self.update_selected_object() self.common_step_counter += 1 if self.common_step_counter % self.push_interval == 0: self.push_robots() # prepare quantities self.base_lin_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 0:3]) self.base_ang_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 3:6]) self.projected_gravity = quat_rotate_inverse(self.base_quat, self.gravity_vec) forward = quat_apply(self.base_quat, self.forward_vec) heading = torch.atan2(forward[:, 1], forward[:, 0]) self.commands[:, 2] = torch.clip(0.5*wrap_to_pi(self.commands[:, 3] - heading), -1., 1.) self.check_termination() if self._selected_id is not None: self.commands[self._selected_id, :] = torch.tensor(self._current_command, device=self.device) self.timeout_buf[self._selected_id] = 0 self.reset_buf[self._selected_id] = 0 self.get_states() env_ids = self.reset_buf.nonzero(as_tuple=False).flatten() if len(env_ids) > 0: self.reset_idx(env_ids) self.get_observations() if self.add_noise: self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec self.last_actions[:] = self.actions[:] self.last_dof_vel[:] = self.dof_vel[:] return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/demos/ur10_reacher.py
# Copyright (c) 2018-2022, NVIDIA Corporation # Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from omniisaacgymenvs.tasks.ur10_reacher import UR10ReacherTask from omni.isaac.core.utils.torch.rotations import * import torch import omni import carb class UR10ReacherDemo(UR10ReacherTask): def __init__( self, name, sim_config, env, offset=None ) -> None: max_num_envs = 128 if sim_config.task_config["env"]["numEnvs"] >= max_num_envs: print(f"num_envs reduced to {max_num_envs} for this demo.") sim_config.task_config["env"]["numEnvs"] = max_num_envs UR10ReacherTask.__init__(self, name, sim_config, env) self.add_noise = False self.create_camera() self._current_command = [0.0] * 6 self.set_up_keyboard() self._prim_selection = omni.usd.get_context().get_selection() self._selected_id = None self._previous_selected_id = None return def create_camera(self): stage = omni.usd.get_context().get_stage() self.view_port = omni.kit.viewport_legacy.get_default_viewport_window() # Create camera self.camera_path = "/World/Camera" self.perspective_path = "/OmniverseKit_Persp" camera_prim = stage.DefinePrim(self.camera_path, "Camera") self.view_port.set_active_camera(self.camera_path) camera_prim.GetAttribute("focalLength").Set(8.5) self.view_port.set_active_camera(self.perspective_path) def set_up_keyboard(self): self._input = carb.input.acquire_input_interface() self._keyboard = omni.appwindow.get_default_app_window().get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._on_keyboard_event) self._key_to_control = { # Joint 0 "Q": [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0], "A": [1.0, 0.0, 0.0, 0.0, 0.0, 0.0], # Joint 1 "W": [0.0, -1.0, 0.0, 0.0, 0.0, 0.0], "S": [0.0, 1.0, 0.0, 0.0, 0.0, 0.0], # Joint 2 "E": [0.0, 0.0, -1.0, 0.0, 0.0, 0.0], "D": [0.0, 0.0, 1.0, 0.0, 0.0, 0.0], # Joint 3 "R": [0.0, 0.0, 0.0, -1.0, 0.0, 0.0], "F": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], # Joint 4 "T": [0.0, 0.0, 0.0, 0.0, -1.0, 0.0], "G": [0.0, 0.0, 0.0, 0.0, 1.0, 0.0], # Joint 5 "Y": [0.0, 0.0, 0.0, 0.0, 0.0, -1.0], "H": [0.0, 0.0, 0.0, 0.0, 0.0, 1.0], } def _on_keyboard_event(self, event, *args, **kwargs): if event.type == carb.input.KeyboardEventType.KEY_PRESS: if event.input.name in self._key_to_control: self._current_command = self._key_to_control[event.input.name] elif event.input.name == "ESCAPE": self._prim_selection.clear_selected_prim_paths() elif event.input.name == "C": if self._selected_id is not None: if self.view_port.get_active_camera() == self.camera_path: self.view_port.set_active_camera(self.perspective_path) else: self.view_port.set_active_camera(self.camera_path) else: self._current_command = [0.0] * 6 def update_selected_object(self): self._previous_selected_id = self._selected_id selected_prim_paths = self._prim_selection.get_selected_prim_paths() if len(selected_prim_paths) == 0: self._selected_id = None self.view_port.set_active_camera(self.perspective_path) elif len(selected_prim_paths) > 1: print("Multiple prims are selected. Please only select one!") else: prim_splitted_path = selected_prim_paths[0].split("/") if len(prim_splitted_path) >= 4 and prim_splitted_path[3][0:4] == "env_": self._selected_id = int(prim_splitted_path[3][4:]) else: print("The selected prim was not a UR10") def _update_camera(self): base_pos = self.base_pos[self._selected_id, :].clone() base_quat = self.base_quat[self._selected_id, :].clone() camera_local_transform = torch.tensor([-1.8, 0.0, 0.6], device=self.device) camera_pos = quat_apply(base_quat, camera_local_transform) + base_pos self.view_port.set_camera_position(self.camera_path, camera_pos[0], camera_pos[1], camera_pos[2], True) self.view_port.set_camera_target(self.camera_path, base_pos[0], base_pos[1], base_pos[2]+0.6, True) def pre_physics_step(self, actions): if self._selected_id is not None: actions[self._selected_id, :] = torch.tensor(self._current_command, device=self.device) result = super().pre_physics_step(actions) if self._selected_id is not None: print('selected ur10 id:', self._selected_id) print('self.rew_buf[idx]:', self.rew_buf[self._selected_id]) print('self.object_pos[idx]:', self.object_pos[self._selected_id]) print('self.goal_pos[idx]:', self.goal_pos[self._selected_id]) return result def post_physics_step(self): self.progress_buf[:] += 1 self.update_selected_object() if self._selected_id is not None: self.reset_buf[self._selected_id] = 0 self.get_states() env_ids = self.reset_buf.nonzero(as_tuple=False).flatten() if len(env_ids) > 0: self.reset_idx(env_ids) self.get_observations() if self.add_noise: self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec # Calculate rewards self.calculate_metrics() return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/demo_util.py
# Copyright (c) 2018-2022, NVIDIA Corporation # Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def initialize_demo(config, env, init_sim=True): from omniisaacgymenvs.demos.anymal_terrain import AnymalTerrainDemo from omniisaacgymenvs.demos.ur10_reacher import UR10ReacherDemo # Mappings from strings to environments task_map = { "AnymalTerrain": AnymalTerrainDemo, "UR10Reacher": UR10ReacherDemo, } from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig sim_config = SimConfig(config) cfg = sim_config.config task = task_map[cfg["task_name"]]( name=cfg["task_name"], sim_config=sim_config, env=env ) env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim) return task
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/task_util.py
# Copyright (c) 2018-2022, NVIDIA Corporation # Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def initialize_task(config, env, init_sim=True): from omniisaacgymenvs.tasks.allegro_hand import AllegroHandTask from omniisaacgymenvs.tasks.ant import AntLocomotionTask from omniisaacgymenvs.tasks.anymal import AnymalTask from omniisaacgymenvs.tasks.anymal_terrain import AnymalTerrainTask from omniisaacgymenvs.tasks.ball_balance import BallBalanceTask from omniisaacgymenvs.tasks.cartpole import CartpoleTask from omniisaacgymenvs.tasks.franka_cabinet import FrankaCabinetTask from omniisaacgymenvs.tasks.humanoid import HumanoidLocomotionTask from omniisaacgymenvs.tasks.ingenuity import IngenuityTask from omniisaacgymenvs.tasks.quadcopter import QuadcopterTask from omniisaacgymenvs.tasks.shadow_hand import ShadowHandTask from omniisaacgymenvs.tasks.crazyflie import CrazyflieTask from omniisaacgymenvs.tasks.ur10_reacher import UR10ReacherTask # Mappings from strings to environments task_map = { "AllegroHand": AllegroHandTask, "Ant": AntLocomotionTask, "Anymal": AnymalTask, "AnymalTerrain": AnymalTerrainTask, "BallBalance": BallBalanceTask, "Cartpole": CartpoleTask, "FrankaCabinet": FrankaCabinetTask, "Humanoid": HumanoidLocomotionTask, "Ingenuity": IngenuityTask, "Quadcopter": QuadcopterTask, "Crazyflie": CrazyflieTask, "ShadowHand": ShadowHandTask, "ShadowHandOpenAI_FF": ShadowHandTask, "ShadowHandOpenAI_LSTM": ShadowHandTask, "UR10Reacher": UR10ReacherTask, } from .config_utils.sim_config import SimConfig sim_config = SimConfig(config) cfg = sim_config.config task = task_map[cfg["task_name"]]( name=cfg["task_name"], sim_config=sim_config, env=env ) env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim) return task
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/domain_randomization/randomize.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import copy import omni import omni.replicator.core as rep import omni.replicator.isaac as dr import numpy as np import torch from omni.isaac.core.prims import RigidPrimView class Randomizer(): def __init__(self, sim_config): self._cfg = sim_config.task_config self._config = sim_config.config self.randomize = False dr_config = self._cfg.get("domain_randomization", None) self.distributions = dict() self.active_domain_randomizations = dict() self._observations_dr_params = None self._actions_dr_params = None if dr_config is not None: randomize = dr_config.get("randomize", False) randomization_params = dr_config.get("randomization_params", None) if randomize and randomization_params is not None: self.randomize = True self.min_frequency = dr_config.get("min_frequency", 1) def apply_on_startup_domain_randomization(self, task): if self.randomize: torch.manual_seed(self._config["seed"]) randomization_params = self._cfg["domain_randomization"]["randomization_params"] for opt in randomization_params.keys(): if opt == "rigid_prim_views": if randomization_params["rigid_prim_views"] is not None: for view_name in randomization_params["rigid_prim_views"].keys(): if randomization_params["rigid_prim_views"][view_name] is not None: for attribute, params in randomization_params["rigid_prim_views"][view_name].items(): params = randomization_params["rigid_prim_views"][view_name][attribute] if attribute in ["scale", "mass", "density"] and params is not None: if "on_startup" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_startup"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} " + \ "on_startup are provided: operation, distribution, distribution_parameters.") view = task._env._world.scene._scene_registry.rigid_prim_views[view_name] if attribute == "scale": self.randomize_scale_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], sync_dim_noise=True, ) elif attribute == "mass": self.randomize_mass_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], ) elif attribute == "density": self.randomize_density_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], ) if opt == "articulation_views": if randomization_params["articulation_views"] is not None: for view_name in randomization_params["articulation_views"].keys(): if randomization_params["articulation_views"][view_name] is not None: for attribute, params in randomization_params["articulation_views"][view_name].items(): params = randomization_params["articulation_views"][view_name][attribute] if attribute in ["scale"] and params is not None: if "on_startup" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_startup"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} " + \ "on_startup are provided: operation, distribution, distribution_parameters.") view = task._env._world.scene._scene_registry.articulated_views[view_name] if attribute == "scale": self.randomize_scale_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], sync_dim_noise=True ) else: dr_config = self._cfg.get("domain_randomization", None) if dr_config is None: raise ValueError("No domain randomization parameters are specified in the task yaml config file") randomize = dr_config.get("randomize", False) randomization_params = dr_config.get("randomization_params", None) if randomize == False or randomization_params is None: print("On Startup Domain randomization will not be applied.") def set_up_domain_randomization(self, task): if self.randomize: randomization_params = self._cfg["domain_randomization"]["randomization_params"] rep.set_global_seed(self._config["seed"]) with dr.trigger.on_rl_frame(num_envs=self._cfg["env"]["numEnvs"]): for opt in randomization_params.keys(): if opt == "observations": self._set_up_observations_randomization(task) elif opt == "actions": self._set_up_actions_randomization(task) elif opt == "simulation": if randomization_params["simulation"] is not None: self.distributions["simulation"] = dict() dr.physics_view.register_simulation_context(task._env._world) for attribute, params in randomization_params["simulation"].items(): self._set_up_simulation_randomization(attribute, params) elif opt == "rigid_prim_views": if randomization_params["rigid_prim_views"] is not None: self.distributions["rigid_prim_views"] = dict() for view_name in randomization_params["rigid_prim_views"].keys(): if randomization_params["rigid_prim_views"][view_name] is not None: self.distributions["rigid_prim_views"][view_name] = dict() dr.physics_view.register_rigid_prim_view( rigid_prim_view=task._env._world.scene._scene_registry.rigid_prim_views[view_name], ) for attribute, params in randomization_params["rigid_prim_views"][view_name].items(): if attribute not in ["scale", "density"]: self._set_up_rigid_prim_view_randomization(view_name, attribute, params) elif opt == "articulation_views": if randomization_params["articulation_views"] is not None: self.distributions["articulation_views"] = dict() for view_name in randomization_params["articulation_views"].keys(): if randomization_params["articulation_views"][view_name] is not None: self.distributions["articulation_views"][view_name] = dict() dr.physics_view.register_articulation_view( articulation_view=task._env._world.scene._scene_registry.articulated_views[view_name], ) for attribute, params in randomization_params["articulation_views"][view_name].items(): if attribute not in ["scale"]: self._set_up_articulation_view_randomization(view_name, attribute, params) rep.orchestrator.run() else: dr_config = self._cfg.get("domain_randomization", None) if dr_config is None: raise ValueError("No domain randomization parameters are specified in the task yaml config file") randomize = dr_config.get("randomize", False) randomization_params = dr_config.get("randomization_params", None) if randomize == False or randomization_params is None: print("Domain randomization will not be applied.") def _set_up_observations_randomization(self, task): task.randomize_observations = True self._observations_dr_params = self._cfg["domain_randomization"]["randomization_params"]["observations"] if self._observations_dr_params is None: raise ValueError(f"Observations randomization parameters are not provided.") if "on_reset" in self._observations_dr_params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(self._observations_dr_params["on_reset"].keys()): raise ValueError(f"Please ensure the following observations on_reset randomization parameters are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("observations", "on_reset")] = np.array(self._observations_dr_params["on_reset"]["distribution_parameters"]) if "on_interval" in self._observations_dr_params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(self._observations_dr_params["on_interval"].keys()): raise ValueError(f"Please ensure the following observations on_interval randomization parameters are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("observations", "on_interval")] = np.array(self._observations_dr_params["on_interval"]["distribution_parameters"]) self._observations_counter_buffer = torch.zeros((self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["sim_device"]) self._observations_correlated_noise = torch.zeros((self._cfg["env"]["numEnvs"], task.num_observations), device=self._config["sim_device"]) def _set_up_actions_randomization(self, task): task.randomize_actions = True self._actions_dr_params = self._cfg["domain_randomization"]["randomization_params"]["actions"] if self._actions_dr_params is None: raise ValueError(f"Actions randomization parameters are not provided.") if "on_reset" in self._actions_dr_params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(self._actions_dr_params["on_reset"].keys()): raise ValueError(f"Please ensure the following actions on_reset randomization parameters are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("actions", "on_reset")] = np.array(self._actions_dr_params["on_reset"]["distribution_parameters"]) if "on_interval" in self._actions_dr_params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(self._actions_dr_params["on_interval"].keys()): raise ValueError(f"Please ensure the following actions on_interval randomization parameters are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("actions", "on_interval")] = np.array(self._actions_dr_params["on_interval"]["distribution_parameters"]) self._actions_counter_buffer = torch.zeros((self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["sim_device"]) self._actions_correlated_noise = torch.zeros((self._cfg["env"]["numEnvs"], task.num_actions), device=self._config["sim_device"]) def apply_observations_randomization(self, observations, reset_buf): env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1) self._observations_counter_buffer[env_ids] = 0 self._observations_counter_buffer += 1 if "on_reset" in self._observations_dr_params.keys(): observations[:] = self._apply_correlated_noise( buffer_type="observations", buffer=observations, reset_ids=env_ids, operation=self._observations_dr_params["on_reset"]["operation"], distribution=self._observations_dr_params["on_reset"]["distribution"], distribution_parameters=self._observations_dr_params["on_reset"]["distribution_parameters"], ) if "on_interval" in self._observations_dr_params.keys(): randomize_ids = (self._observations_counter_buffer >= self._observations_dr_params["on_interval"]["frequency_interval"]).nonzero(as_tuple=False).squeeze(-1) self._observations_counter_buffer[randomize_ids] = 0 observations[:] = self._apply_uncorrelated_noise( buffer=observations, randomize_ids=randomize_ids, operation=self._observations_dr_params["on_interval"]["operation"], distribution=self._observations_dr_params["on_interval"]["distribution"], distribution_parameters=self._observations_dr_params["on_interval"]["distribution_parameters"], ) return observations def apply_actions_randomization(self, actions, reset_buf): env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1) self._actions_counter_buffer[env_ids] = 0 self._actions_counter_buffer += 1 if "on_reset" in self._actions_dr_params.keys(): actions[:] = self._apply_correlated_noise( buffer_type="actions", buffer=actions, reset_ids=env_ids, operation=self._actions_dr_params["on_reset"]["operation"], distribution=self._actions_dr_params["on_reset"]["distribution"], distribution_parameters=self._actions_dr_params["on_reset"]["distribution_parameters"], ) if "on_interval" in self._actions_dr_params.keys(): randomize_ids = (self._actions_counter_buffer >= self._actions_dr_params["on_interval"]["frequency_interval"]).nonzero(as_tuple=False).squeeze(-1) self._actions_counter_buffer[randomize_ids] = 0 actions[:] = self._apply_uncorrelated_noise( buffer=actions, randomize_ids=randomize_ids, operation=self._actions_dr_params["on_interval"]["operation"], distribution=self._actions_dr_params["on_interval"]["distribution"], distribution_parameters=self._actions_dr_params["on_interval"]["distribution_parameters"], ) return actions def _apply_uncorrelated_noise(self, buffer, randomize_ids, operation, distribution, distribution_parameters): if distribution == "gaussian" or distribution == "normal": noise = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=(len(randomize_ids), buffer.shape[1]), device=self._config["sim_device"]) elif distribution == "uniform": noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["sim_device"]) + distribution_parameters[0] elif distribution == "loguniform" or distribution == "log_uniform": noise = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["sim_device"]) + np.log(distribution_parameters[0])) else: print(f"The specified {distribution} distribution is not supported.") if operation == "additive": buffer[randomize_ids] += noise elif operation == "scaling": buffer[randomize_ids] *= noise else: print(f"The specified {operation} operation type is not supported.") return buffer def _apply_correlated_noise(self, buffer_type, buffer, reset_ids, operation, distribution, distribution_parameters): if buffer_type == "observations": correlated_noise_buffer = self._observations_correlated_noise elif buffer_type == "actions": correlated_noise_buffer = self._actions_correlated_noise if len(reset_ids) > 0: if distribution == "gaussian" or distribution == "normal": correlated_noise_buffer[reset_ids] = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=(len(reset_ids), buffer.shape[1]), device=self._config["sim_device"]) elif distribution == "uniform": correlated_noise_buffer[reset_ids] = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["sim_device"]) + distribution_parameters[0] elif distribution == "loguniform" or distribution == "log_uniform": correlated_noise_buffer[reset_ids] = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["sim_device"]) + np.log(distribution_parameters[0])) else: print(f"The specified {distribution} distribution is not supported.") if operation == "additive": buffer += correlated_noise_buffer elif operation == "scaling": buffer *= correlated_noise_buffer else: print(f"The specified {operation} operation type is not supported.") return buffer def _set_up_simulation_randomization(self, attribute, params): if params is None: raise ValueError(f"Randomization parameters for simulation {attribute} is not provided.") if attribute in dr.SIMULATION_CONTEXT_ATTRIBUTES: self.distributions["simulation"][attribute] = dict() if "on_reset" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]): raise ValueError(f"Please ensure the following randomization parameters for simulation {attribute} on_reset are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("simulation", attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"]) kwargs = {"operation": params["on_reset"]["operation"]} self.distributions["simulation"][attribute]["on_reset"] = self._generate_distribution( dimension=dr.physics_view._simulation_context_initial_values[attribute].shape[0], view_name="simulation", attribute=attribute, params=params["on_reset"], ) kwargs[attribute] = self.distributions["simulation"][attribute]["on_reset"] with dr.gate.on_env_reset(): dr.physics_view.randomize_simulation_context(**kwargs) if "on_interval" in params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]): raise ValueError(f"Please ensure the following randomization parameters for simulation {attribute} on_interval are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("simulation", attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"]) kwargs = {"operation": params["on_interval"]["operation"]} self.distributions["simulation"][attribute]["on_interval"] = self._generate_distribution( dimension=dr.physics_view._simulation_context_initial_values[attribute].shape[0], view_name="simulation", attribute=attribute, params=params["on_interval"], ) kwargs[attribute] = self.distributions["simulation"][attribute]["on_interval"] with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]): dr.physics_view.randomize_simulation_context(**kwargs) def _set_up_rigid_prim_view_randomization(self, view_name, attribute, params): if params is None: raise ValueError(f"Randomization parameters for rigid prim view {view_name} {attribute} is not provided.") if attribute in dr.RIGID_PRIM_ATTRIBUTES: self.distributions["rigid_prim_views"][view_name][attribute] = dict() if "on_reset" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys(): kwargs["num_buckets"] = params["on_reset"]["num_buckets"] self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"] = self._generate_distribution( dimension=dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_reset"], ) kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"] with dr.gate.on_env_reset(): dr.physics_view.randomize_rigid_prim_view(**kwargs) if "on_interval" in params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys(): kwargs["num_buckets"] = params["on_interval"]["num_buckets"] self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"] = self._generate_distribution( dimension=dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_interval"], ) kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"] with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]): dr.physics_view.randomize_rigid_prim_view(**kwargs) else: raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.") def _set_up_articulation_view_randomization(self, view_name, attribute, params): if params is None: raise ValueError(f"Randomization parameters for articulation view {view_name} {attribute} is not provided.") if attribute in dr.ARTICULATION_ATTRIBUTES: self.distributions["articulation_views"][view_name][attribute] = dict() if "on_reset" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys(): kwargs["num_buckets"] = params["on_reset"]["num_buckets"] self.distributions["articulation_views"][view_name][attribute]["on_reset"] = self._generate_distribution( dimension=dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_reset"], ) kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_reset"] with dr.gate.on_env_reset(): dr.physics_view.randomize_articulation_view(**kwargs) if "on_interval" in params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys(): kwargs["num_buckets"] = params["on_interval"]["num_buckets"] self.distributions["articulation_views"][view_name][attribute]["on_interval"] = self._generate_distribution( dimension=dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_interval"], ) kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_interval"] with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]): dr.physics_view.randomize_articulation_view(**kwargs) else: raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.") def _generate_distribution(self, view_name, attribute, dimension, params): dist_params = self._sanitize_distribution_parameters(attribute, dimension, params["distribution_parameters"]) if params["distribution"] == "uniform": return rep.distribution.uniform(tuple(dist_params[0]), tuple(dist_params[1])) elif params["distribution"] == "gaussian" or params["distribution"] == "normal": return rep.distribution.normal(tuple(dist_params[0]), tuple(dist_params[1])) elif params["distribution"] == "loguniform" or params["distribution"] == "log_uniform": return rep.distribution.log_uniform(tuple(dist_params[0]), tuple(dist_params[1])) else: raise ValueError(f"The provided distribution for {view_name} {attribute} is not supported. " + "Options: uniform, gaussian/normal, loguniform/log_uniform" ) def _sanitize_distribution_parameters(self, attribute, dimension, params): distribution_parameters = np.array(params) if distribution_parameters.shape == (2,): # if the user does not provide a set of parameters for each dimension dist_params = [[distribution_parameters[0]]*dimension, [distribution_parameters[1]]*dimension] elif distribution_parameters.shape == (2, dimension): # if the user provides a set of parameters for each dimension in the format [[...], [...]] dist_params = distribution_parameters.tolist() elif attribute in ["material_properties", "body_inertias"] and distribution_parameters.shape == (2, 3): # if the user only provides the parameters for one body in the articulation, assume the same parameters for all other links dist_params = [[distribution_parameters[0]] * (dimension // 3), [distribution_parameters[1]] * (dimension // 3)] else: raise ValueError(f"The provided distribution_parameters for {view_name} {attribute} is invalid due to incorrect dimensions.") return dist_params def set_dr_distribution_parameters(self, distribution_parameters, *distribution_path): if distribution_path not in self.active_domain_randomizations.keys(): raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.") if distribution_path[0] == "observations": if len(distribution_parameters) == 2: self._observations_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters else: raise ValueError(f"Please provide distribution_parameters for observations {distribution_path[1]} " + "in the form of [dist_param_1, dist_param_2]") elif distribution_path[0] == "actions": if len(distribution_parameters) == 2: self._actions_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters else: raise ValueError(f"Please provide distribution_parameters for actions {distribution_path[1]} " + "in the form of [dist_param_1, dist_param_2]") else: replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][distribution_path[2]] if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views": replicator_distribution = replicator_distribution[distribution_path[3]] if replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform" \ or replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleLogUniform": dimension = len(dr.utils.get_distribution_params(replicator_distribution, ["lower"])[0]) dist_params = self._sanitize_distribution_parameters(distribution_path[-2], dimension, distribution_parameters) dr.utils.set_distribution_params(replicator_distribution, {"lower": dist_params[0], "upper": dist_params[1]}) elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal": dimension = len(dr.utils.get_distribution_params(replicator_distribution, ["mean"])[0]) dist_params = self._sanitize_distribution_parameters(distribution_path[-2], dimension, distribution_parameters) dr.utils.set_distribution_params(replicator_distribution, {"mean": dist_params[0], "std": dist_params[1]}) def get_dr_distribution_parameters(self, *distribution_path): if distribution_path not in self.active_domain_randomizations.keys(): raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.") if distribution_path[0] == "observations": return self._observations_dr_params[distribution_path[1]]["distribution_parameters"] elif distribution_path[0] == "actions": return self._actions_dr_params[distribution_path[1]]["distribution_parameters"] else: replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][distribution_path[2]] if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views": replicator_distribution = replicator_distribution[distribution_path[3]] if replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform" \ or replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleLogUniform": return dr.utils.get_distribution_params(replicator_distribution, ["lower", "upper"]) elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal": return dr.utils.get_distribution_params(replicator_distribution, ["mean", "std"]) def get_initial_dr_distribution_parameters(self, *distribution_path): if distribution_path not in self.active_domain_randomizations.keys(): raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.") return self.active_domain_randomizations[distribution_path].copy() def _generate_noise(self, distribution, distribution_parameters, size, device): if distribution == "gaussian" or distribution == "normal": noise = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=size, device=device) elif distribution == "uniform": noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand(size, device=device) + distribution_parameters[0] elif distribution == "loguniform" or distribution == "log_uniform": noise = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand(size, device=device) + np.log(distribution_parameters[0])) else: print(f"The specified {distribution} distribution is not supported.") return noise def randomize_scale_on_startup(self, view, distribution, distribution_parameters, operation, sync_dim_noise=True): scales = view.get_local_scales() if sync_dim_noise: dist_params = np.asarray(self._sanitize_distribution_parameters(attribute="scale", dimension=1, params=distribution_parameters)) noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device).repeat(3,1).T else: dist_params = np.asarray(self._sanitize_distribution_parameters(attribute="scale", dimension=3, params=distribution_parameters)) noise = torch.zeros((view.count, 3), device=view._device) for i in range(3): noise[:, i] = self._generate_noise(distribution, dist_params[:, i], (view.count,), view._device) if operation == "additive": scales += noise elif operation == "scaling": scales *= noise elif operation == "direct": scales = noise else: print(f"The specified {operation} operation type is not supported.") view.set_local_scales(scales=scales) def randomize_mass_on_startup(self, view, distribution, distribution_parameters, operation): if isinstance(view, omni.isaac.core.prims.RigidPrimView): masses = view.get_masses() dist_params = np.asarray(self._sanitize_distribution_parameters(attribute=f"{view.name} mass", dimension=1, params=distribution_parameters)) noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device) set_masses = view.set_masses if operation == "additive": masses += noise elif operation == "scaling": masses *= noise elif operation == "direct": masses = noise else: print(f"The specified {operation} operation type is not supported.") set_masses(masses) def randomize_density_on_startup(self, view, distribution, distribution_parameters, operation): if isinstance(view, omni.isaac.core.prims.RigidPrimView): densities = view.get_densities() dist_params = np.asarray(self._sanitize_distribution_parameters(attribute=f"{view.name} density", dimension=1, params=distribution_parameters)) noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device) set_densities = view.set_densities if operation == "additive": densities += noise elif operation == "scaling": densities *= noise elif operation == "direct": densities = noise else: print(f"The specified {operation} operation type is not supported.") set_densities(densities)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/rlgames/rlgames_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from rl_games.common import env_configurations, vecenv from rl_games.common.algo_observer import AlgoObserver from rl_games.algos_torch import torch_ext import torch import numpy as np from typing import Callable class RLGPUAlgoObserver(AlgoObserver): """Allows us to log stats from the env along with the algorithm running stats. """ def __init__(self): pass def after_init(self, algo): self.algo = algo self.mean_scores = torch_ext.AverageMeter(1, self.algo.games_to_track).to(self.algo.ppo_device) self.ep_infos = [] self.direct_info = {} self.writer = self.algo.writer def process_infos(self, infos, done_indices): assert isinstance(infos, dict), "RLGPUAlgoObserver expects dict info" if isinstance(infos, dict): if 'episode' in infos: self.ep_infos.append(infos['episode']) if len(infos) > 0 and isinstance(infos, dict): # allow direct logging from env self.direct_info = {} for k, v in infos.items(): # only log scalars if isinstance(v, float) or isinstance(v, int) or (isinstance(v, torch.Tensor) and len(v.shape) == 0): self.direct_info[k] = v def after_clear_stats(self): self.mean_scores.clear() def after_print_stats(self, frame, epoch_num, total_time): if self.ep_infos: for key in self.ep_infos[0]: infotensor = torch.tensor([], device=self.algo.device) for ep_info in self.ep_infos: # handle scalar and zero dimensional tensor infos if not isinstance(ep_info[key], torch.Tensor): ep_info[key] = torch.Tensor([ep_info[key]]) if len(ep_info[key].shape) == 0: ep_info[key] = ep_info[key].unsqueeze(0) infotensor = torch.cat((infotensor, ep_info[key].to(self.algo.device))) value = torch.mean(infotensor) self.writer.add_scalar('Episode/' + key, value, epoch_num) self.ep_infos.clear() for k, v in self.direct_info.items(): self.writer.add_scalar(f'{k}/frame', v, frame) self.writer.add_scalar(f'{k}/iter', v, epoch_num) self.writer.add_scalar(f'{k}/time', v, total_time) if self.mean_scores.current_size > 0: mean_scores = self.mean_scores.get_mean() self.writer.add_scalar('scores/mean', mean_scores, frame) self.writer.add_scalar('scores/iter', mean_scores, epoch_num) self.writer.add_scalar('scores/time', mean_scores, total_time) class RLGPUEnv(vecenv.IVecEnv): def __init__(self, config_name, num_actors, **kwargs): self.env = env_configurations.configurations[config_name]['env_creator'](**kwargs) def step(self, action): return self.env.step(action) def reset(self): return self.env.reset() def get_number_of_agents(self): return self.env.get_number_of_agents() def get_env_info(self): info = {} info['action_space'] = self.env.action_space info['observation_space'] = self.env.observation_space if self.env.num_states > 0: info['state_space'] = self.env.state_space print(info['action_space'], info['observation_space'], info['state_space']) else: print(info['action_space'], info['observation_space']) return info
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/config_utils/sim_config.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from omniisaacgymenvs.utils.config_utils.default_scene_params import * import copy import omni.usd import numpy as np import torch class SimConfig(): def __init__(self, config: dict = None): if config is None: config = dict() self._config = config self._cfg = config.get("task", dict()) self._parse_config() if self._config["test"] == True: self._sim_params["enable_scene_query_support"] = True if self._config["headless"] == True and not self._sim_params["enable_cameras"]: self._sim_params["use_flatcache"] = False self._sim_params["enable_viewport"] = False def _parse_config(self): # general sim parameter self._sim_params = copy.deepcopy(default_sim_params) self._default_physics_material = copy.deepcopy(default_physics_material) sim_cfg = self._cfg.get("sim", None) if sim_cfg is not None: for opt in sim_cfg.keys(): if opt in self._sim_params: if opt == "default_physics_material": for material_opt in sim_cfg[opt]: self._default_physics_material[material_opt] = sim_cfg[opt][material_opt] else: self._sim_params[opt] = sim_cfg[opt] else: print("Sim params does not have attribute: ", opt) self._sim_params["default_physics_material"] = self._default_physics_material # physx parameters self._physx_params = copy.deepcopy(default_physx_params) if sim_cfg is not None and "physx" in sim_cfg: for opt in sim_cfg["physx"].keys(): if opt in self._physx_params: self._physx_params[opt] = sim_cfg["physx"][opt] else: print("Physx sim params does not have attribute: ", opt) self._sanitize_device() def _sanitize_device(self): if self._sim_params["use_gpu_pipeline"]: self._physx_params["use_gpu"] = True # device should be in sync with pipeline if self._sim_params["use_gpu_pipeline"]: self._config["sim_device"] = f"cuda:{self._config['device_id']}" else: self._config["sim_device"] = "cpu" # also write to physics params for setting sim device self._physx_params["sim_device"] = self._config["sim_device"] print("Pipeline: ", "GPU" if self._sim_params["use_gpu_pipeline"] else "CPU") print("Pipeline Device: ", self._config["sim_device"]) print("Sim Device: ", "GPU" if self._physx_params["use_gpu"] else "CPU") def parse_actor_config(self, actor_name): actor_params = copy.deepcopy(default_actor_options) if "sim" in self._cfg and actor_name in self._cfg["sim"]: actor_cfg = self._cfg["sim"][actor_name] for opt in actor_cfg.keys(): if actor_cfg[opt] != -1 and opt in actor_params: actor_params[opt] = actor_cfg[opt] elif opt not in actor_params: print("Actor params does not have attribute: ", opt) return actor_params def _get_actor_config_value(self, actor_name, attribute_name, attribute=None): actor_params = self.parse_actor_config(actor_name) if attribute is not None: if attribute_name not in actor_params: return attribute.Get() if actor_params[attribute_name] != -1: return actor_params[attribute_name] elif actor_params["override_usd_defaults"] and not attribute.IsAuthored(): return self._physx_params[attribute_name] else: if actor_params[attribute_name] != -1: return actor_params[attribute_name] @property def sim_params(self): return self._sim_params @property def config(self): return self._config @property def task_config(self): return self._cfg @property def physx_params(self): return self._physx_params def get_physics_params(self): return {**self.sim_params, **self.physx_params} def _get_physx_collision_api(self, prim): from pxr import UsdPhysics, PhysxSchema physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim) if not physx_collision_api: physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim) return physx_collision_api def _get_physx_rigid_body_api(self, prim): from pxr import UsdPhysics, PhysxSchema physx_rb_api = PhysxSchema.PhysxRigidBodyAPI(prim) if not physx_rb_api: physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim) return physx_rb_api def _get_physx_articulation_api(self, prim): from pxr import UsdPhysics, PhysxSchema arti_api = PhysxSchema.PhysxArticulationAPI(prim) if not arti_api: arti_api = PhysxSchema.PhysxArticulationAPI.Apply(prim) return arti_api def set_contact_offset(self, name, prim, value=None): physx_collision_api = self._get_physx_collision_api(prim) contact_offset = physx_collision_api.GetContactOffsetAttr() # if not contact_offset: # contact_offset = physx_collision_api.CreateContactOffsetAttr() if value is None: value = self._get_actor_config_value(name, "contact_offset", contact_offset) if value != -1: contact_offset.Set(value) def set_rest_offset(self, name, prim, value=None): physx_collision_api = self._get_physx_collision_api(prim) rest_offset = physx_collision_api.GetRestOffsetAttr() # if not rest_offset: # rest_offset = physx_collision_api.CreateRestOffsetAttr() if value is None: value = self._get_actor_config_value(name, "rest_offset", rest_offset) if value != -1: rest_offset.Set(value) def set_position_iteration(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) solver_position_iteration_count = physx_rb_api.GetSolverPositionIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_position_iteration_count", solver_position_iteration_count) if value != -1: solver_position_iteration_count.Set(value) def set_velocity_iteration(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) solver_velocity_iteration_count = physx_rb_api.GetSolverVelocityIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_velocity_iteration_count", solver_position_iteration_count) if value != -1: solver_velocity_iteration_count.Set(value) def set_max_depenetration_velocity(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) max_depenetration_velocity = physx_rb_api.GetMaxDepenetrationVelocityAttr() if value is None: value = self._get_actor_config_value(name, "max_depenetration_velocity", max_depenetration_velocity) if value != -1: max_depenetration_velocity.Set(value) def set_sleep_threshold(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) sleep_threshold = physx_rb_api.GetSleepThresholdAttr() if value is None: value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold) if value != -1: sleep_threshold.Set(value) def set_stabilization_threshold(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) stabilization_threshold = physx_rb_api.GetStabilizationThresholdAttr() if value is None: value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold) if value != -1: stabilization_threshold.Set(value) def set_gyroscopic_forces(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) enable_gyroscopic_forces = physx_rb_api.GetEnableGyroscopicForcesAttr() if value is None: value = self._get_actor_config_value(name, "enable_gyroscopic_forces", enable_gyroscopic_forces) if value != -1: enable_gyroscopic_forces.Set(value) def set_density(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) density = physx_rb_api.GetDensityAttr() if value is None: value = self._get_actor_config_value(name, "density", density) if value != -1: density.Set(value) # auto-compute mass self.set_mass(prim, 0.0) def set_mass(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) mass = physx_rb_api.GetMassAttr() if value is None: value = self._get_actor_config_value(name, "mass", mass) if value != -1: mass.Set(value) def retain_acceleration(self, prim): # retain accelerations if running with more than one substep physx_rb_api = self._get_physx_rigid_body_api(prim) if self._sim_params["substeps"] > 1: physx_rb_api.GetRetainAccelerationsAttr().Set(True) def add_fixed_base(self, name, prim, cfg, value=None): from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() if value is None: value = self._get_actor_config_value(name, "fixed_base") if value: root_joint_path = f"{prim.GetPath()}_fixedBaseRootJoint" joint = UsdPhysics.Joint.Define(stage, root_joint_path) joint.CreateBody1Rel().SetTargets([prim.GetPath()]) self.apply_articulation_settings(name, joint.GetPrim(), cfg, force_articulation=True) def set_articulation_position_iteration(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) solver_position_iteration_count = arti_api.GetSolverPositionIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_position_iteration_count", solver_position_iteration_count) if value != -1: solver_position_iteration_count.Set(value) def set_articulation_velocity_iteration(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) solver_velocity_iteration_count = arti_api.GetSolverVelocityIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_velocity_iteration_count", solver_position_iteration_count) if value != -1: solver_velocity_iteration_count.Set(value) def set_articulation_sleep_threshold(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) sleep_threshold = arti_api.GetSleepThresholdAttr() if value is None: value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold) if value != -1: sleep_threshold.Set(value) def set_articulation_stabilization_threshold(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) stabilization_threshold = arti_api.GetStabilizationThresholdAttr() if value is None: value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold) if value != -1: stabilization_threshold.Set(value) def apply_rigid_body_settings(self, name, prim, cfg, is_articulation): from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() rb_api = UsdPhysics.RigidBodyAPI.Get(stage, prim.GetPath()) physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Get(stage, prim.GetPath()) if not physx_rb_api: physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim) # if it's a body in an articulation, it's handled at articulation root if not is_articulation: self.add_fixed_base(name, prim, cfg, cfg["fixed_base"]) self.set_position_iteration(name, prim, cfg["solver_position_iteration_count"]) self.set_velocity_iteration(name, prim, cfg["solver_velocity_iteration_count"]) self.set_max_depenetration_velocity(name, prim, cfg["max_depenetration_velocity"]) self.set_sleep_threshold(name, prim, cfg["sleep_threshold"]) self.set_stabilization_threshold(name, prim, cfg["stabilization_threshold"]) self.set_gyroscopic_forces(name, prim, cfg["enable_gyroscopic_forces"]) # density and mass mass_api = UsdPhysics.MassAPI.Get(stage, prim.GetPath()) if mass_api is None: mass_api = UsdPhysics.MassAPI.Apply(prim) mass_attr = mass_api.GetMassAttr() density_attr = mass_api.GetDensityAttr() if not mass_attr: mass_attr = mass_api.CreateMassAttr() if not density_attr: density_attr = mass_api.CreateDensityAttr() if cfg["density"] != -1: density_attr.Set(cfg["density"]) mass_attr.Set(0.0) # mass is to be computed elif cfg["override_usd_defaults"] and not density_attr.IsAuthored() and not mass_attr.IsAuthored(): density_attr.Set(self._physx_params["density"]) self.retain_acceleration(prim) def apply_rigid_shape_settings(self, name, prim, cfg): from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() # collision APIs collision_api = UsdPhysics.CollisionAPI(prim) if not collision_api: collision_api = UsdPhysics.CollisionAPI.Apply(prim) physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim) if not physx_collision_api: physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim) self.set_contact_offset(name, prim, cfg["contact_offset"]) self.set_rest_offset(name, prim, cfg["rest_offset"]) def apply_articulation_settings(self, name, prim, cfg, force_articulation=False): from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() is_articulation = False # check if is articulation prims = [prim] while len(prims) > 0: prim = prims.pop(0) articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, prim.GetPath()) physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, prim.GetPath()) if articulation_api or physx_articulation_api: is_articulation = True if not is_articulation and force_articulation: articulation_api = UsdPhysics.ArticulationRootAPI.Apply(prim) physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Apply(prim) # parse through all children prims prims = [prim] while len(prims) > 0: prim = prims.pop(0) rb = UsdPhysics.RigidBodyAPI(prim) collision_body = UsdPhysics.CollisionAPI(prim) articulation = UsdPhysics.ArticulationRootAPI(prim) if rb: self.apply_rigid_body_settings(name, prim, cfg, is_articulation) if collision_body: self.apply_rigid_shape_settings(name, prim, cfg) if articulation: articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, prim.GetPath()) physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, prim.GetPath()) # enable self collisions enable_self_collisions = physx_articulation_api.GetEnabledSelfCollisionsAttr() if cfg["enable_self_collisions"] != -1: enable_self_collisions.Set(cfg["enable_self_collisions"]) if not force_articulation: self.add_fixed_base(name, prim, cfg, cfg["fixed_base"]) self.set_articulation_position_iteration(name, prim, cfg["solver_position_iteration_count"]) self.set_articulation_velocity_iteration(name, prim, cfg["solver_velocity_iteration_count"]) self.set_articulation_sleep_threshold(name, prim, cfg["sleep_threshold"]) self.set_articulation_stabilization_threshold(name, prim, cfg["stabilization_threshold"]) children_prims = prim.GetPrim().GetChildren() prims = prims + children_prims
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/config_utils/default_scene_params.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. default_physx_params = { ### Per-scene settings "use_gpu": False, "worker_thread_count": 4, "solver_type": 1, # 0: PGS, 1:TGS "bounce_threshold_velocity": 0.2, "friction_offset_threshold": 0.04, # A threshold of contact separation distance used to decide if a contact # point will experience friction forces. "friction_correlation_distance": 0.025, # Contact points can be merged into a single friction anchor if the # distance between the contacts is smaller than correlation distance. # disabling these can be useful for debugging "enable_sleeping": True, "enable_stabilization": True, # GPU buffers "gpu_max_rigid_contact_count": 512 * 1024, "gpu_max_rigid_patch_count": 80 * 1024, "gpu_found_lost_pairs_capacity": 1024, "gpu_found_lost_aggregate_pairs_capacity": 1024, "gpu_total_aggregate_pairs_capacity": 1024, "gpu_max_soft_body_contacts": 1024 * 1024, "gpu_max_particle_contacts": 1024 * 1024, "gpu_heap_capacity": 64 * 1024 * 1024, "gpu_temp_buffer_capacity": 16 * 1024 * 1024, "gpu_max_num_partitions": 8, ### Per-actor settings ( can override in actor_options ) "solver_position_iteration_count": 4, "solver_velocity_iteration_count": 1, "sleep_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may go to sleep. # Allowed range [0, max_float). "stabilization_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may # participate in stabilization. Allowed range [0, max_float). ### Per-body settings ( can override in actor_options ) "enable_gyroscopic_forces": False, "density": 1000.0, # density to be used for bodies that do not specify mass or density "max_depenetration_velocity": 100.0, ### Per-shape settings ( can override in actor_options ) "contact_offset": 0.02, "rest_offset": 0.001 } default_physics_material = { "static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0 } default_sim_params = { "gravity": [0.0, 0.0, -9.81], "dt": 1.0 / 60.0, "substeps": 1, "use_gpu_pipeline": True, "add_ground_plane": True, "add_distant_light": True, "use_flatcache": True, "enable_scene_query_support": False, "enable_cameras": False, "default_physics_material": default_physics_material } default_actor_options = { # -1 means use authored value from USD or default values from default_sim_params if not explicitly authored in USD. # If an attribute value is not explicitly authored in USD, add one with the value given here, # which overrides the USD default. "override_usd_defaults": False, "fixed_base": -1, "enable_self_collisions": -1, "enable_gyroscopic_forces": -1, "solver_position_iteration_count": -1, "solver_velocity_iteration_count": -1, "sleep_threshold": -1, "stabilization_threshold": -1, "max_depenetration_velocity": -1, "density": -1, "mass": -1, "contact_offset": -1, "rest_offset": -1 }
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/config_utils/path_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import carb from hydra.utils import to_absolute_path import os def is_valid_local_file(path): return os.path.isfile(path) def is_valid_ov_file(path): import omni.client result, entry = omni.client.stat(path) return result == omni.client.Result.OK def download_ov_file(source_path, target_path): import omni.client result = omni.client.copy(source_path, target_path) if result == omni.client.Result.OK: return True return False def break_ov_path(path): import omni.client return omni.client.break_url(path) def retrieve_checkpoint_path(path): # check if it's a local path if is_valid_local_file(path): return to_absolute_path(path) # check if it's an OV path elif is_valid_ov_file(path): ov_path = break_ov_path(path) file_name = os.path.basename(ov_path.path) target_path = f"checkpoints/{file_name}" copy_to_local = download_ov_file(path, target_path) return to_absolute_path(target_path) else: carb.log_error(f"Invalid checkpoint path: {path}") return None
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/hydra_cfg/hydra_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import hydra from omegaconf import DictConfig, OmegaConf ## OmegaConf & Hydra Config # Resolvers used in hydra configs (see https://omegaconf.readthedocs.io/en/2.1_branch/usage.html#resolvers) OmegaConf.register_new_resolver('eq', lambda x, y: x.lower()==y.lower()) OmegaConf.register_new_resolver('contains', lambda x, y: x.lower() in y.lower()) OmegaConf.register_new_resolver('if', lambda pred, a, b: a if pred else b) # allows us to resolve default arguments which are copied in multiple places in the config. used primarily for # num_ensv OmegaConf.register_new_resolver('resolve_default', lambda default, arg: default if arg=='' else arg)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/hydra_cfg/reformat.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from omegaconf import DictConfig, OmegaConf from typing import Dict def omegaconf_to_dict(d: DictConfig)->Dict: """Converts an omegaconf DictConfig to a python Dict, respecting variable interpolation.""" ret = {} for k, v in d.items(): if isinstance(v, DictConfig): ret[k] = omegaconf_to_dict(v) else: ret[k] = v return ret def print_dict(val, nesting: int = -4, start: bool = True): """Outputs a nested dictionory.""" if type(val) == dict: if not start: print('') nesting += 4 for k in val: print(nesting * ' ', end='') print(k, end=': ') print_dict(val[k], nesting, start=False) else: print(val)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/terrain_utils/terrain_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np from numpy.random import choice from scipy import interpolate from math import sqrt from omni.isaac.core.prims import XFormPrim from pxr import UsdPhysics, Sdf, Gf, PhysxSchema def random_uniform_terrain(terrain, min_height, max_height, step=1, downsampled_scale=None,): """ Generate a uniform noise terrain Parameters terrain (SubTerrain): the terrain min_height (float): the minimum height of the terrain [meters] max_height (float): the maximum height of the terrain [meters] step (float): minimum height change between two points [meters] downsampled_scale (float): distance between two randomly sampled points ( musty be larger or equal to terrain.horizontal_scale) """ if downsampled_scale is None: downsampled_scale = terrain.horizontal_scale # switch parameters to discrete units min_height = int(min_height / terrain.vertical_scale) max_height = int(max_height / terrain.vertical_scale) step = int(step / terrain.vertical_scale) heights_range = np.arange(min_height, max_height + step, step) height_field_downsampled = np.random.choice(heights_range, (int(terrain.width * terrain.horizontal_scale / downsampled_scale), int( terrain.length * terrain.horizontal_scale / downsampled_scale))) x = np.linspace(0, terrain.width * terrain.horizontal_scale, height_field_downsampled.shape[0]) y = np.linspace(0, terrain.length * terrain.horizontal_scale, height_field_downsampled.shape[1]) f = interpolate.interp2d(y, x, height_field_downsampled, kind='linear') x_upsampled = np.linspace(0, terrain.width * terrain.horizontal_scale, terrain.width) y_upsampled = np.linspace(0, terrain.length * terrain.horizontal_scale, terrain.length) z_upsampled = np.rint(f(y_upsampled, x_upsampled)) terrain.height_field_raw += z_upsampled.astype(np.int16) return terrain def sloped_terrain(terrain, slope=1): """ Generate a sloped terrain Parameters: terrain (SubTerrain): the terrain slope (int): positive or negative slope Returns: terrain (SubTerrain): update terrain """ x = np.arange(0, terrain.width) y = np.arange(0, terrain.length) xx, yy = np.meshgrid(x, y, sparse=True) xx = xx.reshape(terrain.width, 1) max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * terrain.width) terrain.height_field_raw[:, np.arange(terrain.length)] += (max_height * xx / terrain.width).astype(terrain.height_field_raw.dtype) return terrain def pyramid_sloped_terrain(terrain, slope=1, platform_size=1.): """ Generate a sloped terrain Parameters: terrain (terrain): the terrain slope (int): positive or negative slope platform_size (float): size of the flat platform at the center of the terrain [meters] Returns: terrain (SubTerrain): update terrain """ x = np.arange(0, terrain.width) y = np.arange(0, terrain.length) center_x = int(terrain.width / 2) center_y = int(terrain.length / 2) xx, yy = np.meshgrid(x, y, sparse=True) xx = (center_x - np.abs(center_x-xx)) / center_x yy = (center_y - np.abs(center_y-yy)) / center_y xx = xx.reshape(terrain.width, 1) yy = yy.reshape(1, terrain.length) max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * (terrain.width / 2)) terrain.height_field_raw += (max_height * xx * yy).astype(terrain.height_field_raw.dtype) platform_size = int(platform_size / terrain.horizontal_scale / 2) x1 = terrain.width // 2 - platform_size x2 = terrain.width // 2 + platform_size y1 = terrain.length // 2 - platform_size y2 = terrain.length // 2 + platform_size min_h = min(terrain.height_field_raw[x1, y1], 0) max_h = max(terrain.height_field_raw[x1, y1], 0) terrain.height_field_raw = np.clip(terrain.height_field_raw, min_h, max_h) return terrain def discrete_obstacles_terrain(terrain, max_height, min_size, max_size, num_rects, platform_size=1.): """ Generate a terrain with gaps Parameters: terrain (terrain): the terrain max_height (float): maximum height of the obstacles (range=[-max, -max/2, max/2, max]) [meters] min_size (float): minimum size of a rectangle obstacle [meters] max_size (float): maximum size of a rectangle obstacle [meters] num_rects (int): number of randomly generated obstacles platform_size (float): size of the flat platform at the center of the terrain [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units max_height = int(max_height / terrain.vertical_scale) min_size = int(min_size / terrain.horizontal_scale) max_size = int(max_size / terrain.horizontal_scale) platform_size = int(platform_size / terrain.horizontal_scale) (i, j) = terrain.height_field_raw.shape height_range = [-max_height, -max_height // 2, max_height // 2, max_height] width_range = range(min_size, max_size, 4) length_range = range(min_size, max_size, 4) for _ in range(num_rects): width = np.random.choice(width_range) length = np.random.choice(length_range) start_i = np.random.choice(range(0, i-width, 4)) start_j = np.random.choice(range(0, j-length, 4)) terrain.height_field_raw[start_i:start_i+width, start_j:start_j+length] = np.random.choice(height_range) x1 = (terrain.width - platform_size) // 2 x2 = (terrain.width + platform_size) // 2 y1 = (terrain.length - platform_size) // 2 y2 = (terrain.length + platform_size) // 2 terrain.height_field_raw[x1:x2, y1:y2] = 0 return terrain def wave_terrain(terrain, num_waves=1, amplitude=1.): """ Generate a wavy terrain Parameters: terrain (terrain): the terrain num_waves (int): number of sine waves across the terrain length Returns: terrain (SubTerrain): update terrain """ amplitude = int(0.5*amplitude / terrain.vertical_scale) if num_waves > 0: div = terrain.length / (num_waves * np.pi * 2) x = np.arange(0, terrain.width) y = np.arange(0, terrain.length) xx, yy = np.meshgrid(x, y, sparse=True) xx = xx.reshape(terrain.width, 1) yy = yy.reshape(1, terrain.length) terrain.height_field_raw += (amplitude*np.cos(yy / div) + amplitude*np.sin(xx / div)).astype( terrain.height_field_raw.dtype) return terrain def stairs_terrain(terrain, step_width, step_height): """ Generate a stairs Parameters: terrain (terrain): the terrain step_width (float): the width of the step [meters] step_height (float): the height of the step [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units step_width = int(step_width / terrain.horizontal_scale) step_height = int(step_height / terrain.vertical_scale) num_steps = terrain.width // step_width height = step_height for i in range(num_steps): terrain.height_field_raw[i * step_width: (i + 1) * step_width, :] += height height += step_height return terrain def pyramid_stairs_terrain(terrain, step_width, step_height, platform_size=1.): """ Generate stairs Parameters: terrain (terrain): the terrain step_width (float): the width of the step [meters] step_height (float): the step_height [meters] platform_size (float): size of the flat platform at the center of the terrain [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units step_width = int(step_width / terrain.horizontal_scale) step_height = int(step_height / terrain.vertical_scale) platform_size = int(platform_size / terrain.horizontal_scale) height = 0 start_x = 0 stop_x = terrain.width start_y = 0 stop_y = terrain.length while (stop_x - start_x) > platform_size and (stop_y - start_y) > platform_size: start_x += step_width stop_x -= step_width start_y += step_width stop_y -= step_width height += step_height terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = height return terrain def stepping_stones_terrain(terrain, stone_size, stone_distance, max_height, platform_size=1., depth=-10): """ Generate a stepping stones terrain Parameters: terrain (terrain): the terrain stone_size (float): horizontal size of the stepping stones [meters] stone_distance (float): distance between stones (i.e size of the holes) [meters] max_height (float): maximum height of the stones (positive and negative) [meters] platform_size (float): size of the flat platform at the center of the terrain [meters] depth (float): depth of the holes (default=-10.) [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units stone_size = int(stone_size / terrain.horizontal_scale) stone_distance = int(stone_distance / terrain.horizontal_scale) max_height = int(max_height / terrain.vertical_scale) platform_size = int(platform_size / terrain.horizontal_scale) height_range = np.arange(-max_height-1, max_height, step=1) start_x = 0 start_y = 0 terrain.height_field_raw[:, :] = int(depth / terrain.vertical_scale) if terrain.length >= terrain.width: while start_y < terrain.length: stop_y = min(terrain.length, start_y + stone_size) start_x = np.random.randint(0, stone_size) # fill first hole stop_x = max(0, start_x - stone_distance) terrain.height_field_raw[0: stop_x, start_y: stop_y] = np.random.choice(height_range) # fill row while start_x < terrain.width: stop_x = min(terrain.width, start_x + stone_size) terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = np.random.choice(height_range) start_x += stone_size + stone_distance start_y += stone_size + stone_distance elif terrain.width > terrain.length: while start_x < terrain.width: stop_x = min(terrain.width, start_x + stone_size) start_y = np.random.randint(0, stone_size) # fill first hole stop_y = max(0, start_y - stone_distance) terrain.height_field_raw[start_x: stop_x, 0: stop_y] = np.random.choice(height_range) # fill column while start_y < terrain.length: stop_y = min(terrain.length, start_y + stone_size) terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = np.random.choice(height_range) start_y += stone_size + stone_distance start_x += stone_size + stone_distance x1 = (terrain.width - platform_size) // 2 x2 = (terrain.width + platform_size) // 2 y1 = (terrain.length - platform_size) // 2 y2 = (terrain.length + platform_size) // 2 terrain.height_field_raw[x1:x2, y1:y2] = 0 return terrain def convert_heightfield_to_trimesh(height_field_raw, horizontal_scale, vertical_scale, slope_threshold=None): """ Convert a heightfield array to a triangle mesh represented by vertices and triangles. Optionally, corrects vertical surfaces above the provide slope threshold: If (y2-y1)/(x2-x1) > slope_threshold -> Move A to A' (set x1 = x2). Do this for all directions. B(x2,y2) /| / | / | (x1,y1)A---A'(x2',y1) Parameters: height_field_raw (np.array): input heightfield horizontal_scale (float): horizontal scale of the heightfield [meters] vertical_scale (float): vertical scale of the heightfield [meters] slope_threshold (float): the slope threshold above which surfaces are made vertical. If None no correction is applied (default: None) Returns: vertices (np.array(float)): array of shape (num_vertices, 3). Each row represents the location of each vertex [meters] triangles (np.array(int)): array of shape (num_triangles, 3). Each row represents the indices of the 3 vertices connected by this triangle. """ hf = height_field_raw num_rows = hf.shape[0] num_cols = hf.shape[1] y = np.linspace(0, (num_cols-1)*horizontal_scale, num_cols) x = np.linspace(0, (num_rows-1)*horizontal_scale, num_rows) yy, xx = np.meshgrid(y, x) if slope_threshold is not None: slope_threshold *= horizontal_scale / vertical_scale move_x = np.zeros((num_rows, num_cols)) move_y = np.zeros((num_rows, num_cols)) move_corners = np.zeros((num_rows, num_cols)) move_x[:num_rows-1, :] += (hf[1:num_rows, :] - hf[:num_rows-1, :] > slope_threshold) move_x[1:num_rows, :] -= (hf[:num_rows-1, :] - hf[1:num_rows, :] > slope_threshold) move_y[:, :num_cols-1] += (hf[:, 1:num_cols] - hf[:, :num_cols-1] > slope_threshold) move_y[:, 1:num_cols] -= (hf[:, :num_cols-1] - hf[:, 1:num_cols] > slope_threshold) move_corners[:num_rows-1, :num_cols-1] += (hf[1:num_rows, 1:num_cols] - hf[:num_rows-1, :num_cols-1] > slope_threshold) move_corners[1:num_rows, 1:num_cols] -= (hf[:num_rows-1, :num_cols-1] - hf[1:num_rows, 1:num_cols] > slope_threshold) xx += (move_x + move_corners*(move_x == 0)) * horizontal_scale yy += (move_y + move_corners*(move_y == 0)) * horizontal_scale # create triangle mesh vertices and triangles from the heightfield grid vertices = np.zeros((num_rows*num_cols, 3), dtype=np.float32) vertices[:, 0] = xx.flatten() vertices[:, 1] = yy.flatten() vertices[:, 2] = hf.flatten() * vertical_scale triangles = -np.ones((2*(num_rows-1)*(num_cols-1), 3), dtype=np.uint32) for i in range(num_rows - 1): ind0 = np.arange(0, num_cols-1) + i*num_cols ind1 = ind0 + 1 ind2 = ind0 + num_cols ind3 = ind2 + 1 start = 2*i*(num_cols-1) stop = start + 2*(num_cols-1) triangles[start:stop:2, 0] = ind0 triangles[start:stop:2, 1] = ind3 triangles[start:stop:2, 2] = ind1 triangles[start+1:stop:2, 0] = ind0 triangles[start+1:stop:2, 1] = ind2 triangles[start+1:stop:2, 2] = ind3 return vertices, triangles def add_terrain_to_stage(stage, vertices, triangles, position=None, orientation=None): num_faces = triangles.shape[0] terrain_mesh = stage.DefinePrim("/World/terrain", "Mesh") terrain_mesh.GetAttribute("points").Set(vertices) terrain_mesh.GetAttribute("faceVertexIndices").Set(triangles.flatten()) terrain_mesh.GetAttribute("faceVertexCounts").Set(np.asarray([3]*num_faces)) terrain = XFormPrim(prim_path="/World/terrain", name="terrain", position=position, orientation=orientation) UsdPhysics.CollisionAPI.Apply(terrain.prim) # collision_api = UsdPhysics.MeshCollisionAPI.Apply(terrain.prim) # collision_api.CreateApproximationAttr().Set("meshSimplification") physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(terrain.prim) physx_collision_api.GetContactOffsetAttr().Set(0.02) physx_collision_api.GetRestOffsetAttr().Set(0.00) class SubTerrain: def __init__(self, terrain_name="terrain", width=256, length=256, vertical_scale=1.0, horizontal_scale=1.0): self.terrain_name = terrain_name self.vertical_scale = vertical_scale self.horizontal_scale = horizontal_scale self.width = width self.length = length self.height_field_raw = np.zeros((self.width, self.length), dtype=np.int16)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/terrain_utils/create_terrain_demo.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os, sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(SCRIPT_DIR) import omni from omni.isaac.kit import SimulationApp import numpy as np import torch simulation_app = SimulationApp({"headless": False}) from abc import abstractmethod from omni.isaac.core.tasks import BaseTask from omni.isaac.core.prims import RigidPrimView, RigidPrim, XFormPrim from omni.isaac.core import World from omni.isaac.core.objects import DynamicSphere from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.core.utils.nucleus import find_nucleus_server from omni.isaac.core.utils.stage import add_reference_to_stage, get_current_stage from omni.isaac.core.materials import PreviewSurface from omni.isaac.cloner import GridCloner from pxr import UsdPhysics, UsdLux, UsdShade, Sdf, Gf, UsdGeom, PhysxSchema from terrain_utils import * class TerrainCreation(BaseTask): def __init__(self, name, num_envs, num_per_row, env_spacing, config=None, offset=None,) -> None: BaseTask.__init__(self, name=name, offset=offset) self._num_envs = num_envs self._num_per_row = num_per_row self._env_spacing = env_spacing self._device = "cpu" self._cloner = GridCloner(self._env_spacing, self._num_per_row) self._cloner.define_base_env(self.default_base_env_path) define_prim(self.default_zero_env_path) @property def default_base_env_path(self): return "/World/envs" @property def default_zero_env_path(self): return f"{self.default_base_env_path}/env_0" def set_up_scene(self, scene) -> None: self._stage = get_current_stage() distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight")) distantLight.CreateIntensityAttr(2000) self.get_terrain() self.get_ball() super().set_up_scene(scene) prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs) print(f"cloning {self._num_envs} environments...") self._env_pos = self._cloner.clone( source_prim_path="/World/envs/env_0", prim_paths=prim_paths ) return def get_terrain(self): # create all available terrain types num_terains = 8 terrain_width = 12. terrain_length = 12. horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terains*num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = random_uniform_terrain(new_sub_terrain(), min_height=-0.2, max_height=0.2, step=0.2, downsampled_scale=0.5).height_field_raw heightfield[num_rows:2*num_rows, :] = sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw heightfield[2*num_rows:3*num_rows, :] = pyramid_sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw heightfield[3*num_rows:4*num_rows, :] = discrete_obstacles_terrain(new_sub_terrain(), max_height=0.5, min_size=1., max_size=5., num_rects=20).height_field_raw heightfield[4*num_rows:5*num_rows, :] = wave_terrain(new_sub_terrain(), num_waves=2., amplitude=1.).height_field_raw heightfield[5*num_rows:6*num_rows, :] = stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw heightfield[6*num_rows:7*num_rows, :] = pyramid_stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw heightfield[7*num_rows:8*num_rows, :] = stepping_stones_terrain(new_sub_terrain(), stone_size=1., stone_distance=1., max_height=0.5, platform_size=0.).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-6.0, 48.0, 0]) orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_ball(self): ball = DynamicSphere(prim_path=self.default_zero_env_path + "/ball", name="ball", translation=np.array([0.0, 0.0, 1.0]), mass=0.5, radius=0.2,) def post_reset(self): for i in range(self._num_envs): ball_prim = self._stage.GetPrimAtPath(f"{self.default_base_env_path}/env_{i}/ball") color = 0.5 + 0.5 * np.random.random(3) visual_material = PreviewSurface(prim_path=f"{self.default_base_env_path}/env_{i}/ball/Looks/visual_material", color=color) binding_api = UsdShade.MaterialBindingAPI(ball_prim) binding_api.Bind(visual_material.material, bindingStrength=UsdShade.Tokens.strongerThanDescendants) def get_observations(self): pass def calculate_metrics(self) -> None: pass def is_done(self) -> None: pass if __name__ == "__main__": world = World( stage_units_in_meters=1.0, rendering_dt=1.0/60.0, backend="torch", device="cpu", ) num_envs = 800 num_per_row = 80 env_spacing = 0.56*2 terrain_creation_task = TerrainCreation(name="TerrainCreation", num_envs=num_envs, num_per_row=num_per_row, env_spacing=env_spacing, ) world.add_task(terrain_creation_task) world.reset() while simulation_app.is_running(): if world.is_playing(): if world.current_time_step_index == 0: world.reset(soft=True) world.step(render=True) else: world.step(render=True) simulation_app.close()
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import omni.usd import omni.client from pxr import UsdGeom, Sdf def update_reference(source_prim_path, source_reference_path, target_reference_path): stage = omni.usd.get_context().get_stage() prims = [stage.GetPrimAtPath(source_prim_path)] while len(prims) > 0: prim = prims.pop(0) prim_spec = stage.GetRootLayer().GetPrimAtPath(prim.GetPath()) reference_list = prim_spec.referenceList refs = reference_list.GetAddedOrExplicitItems() if len(refs) > 0: for ref in refs: if ref.assetPath == source_reference_path: prim.GetReferences().RemoveReference(ref) prim.GetReferences().AddReference(assetPath=target_reference_path, primPath=prim.GetPath()) prims = prims + prim.GetChildren() def create_parent_xforms(asset_usd_path, source_prim_path, save_as_path=None): """ Adds a new UsdGeom.Xform prim for each Mesh/Geometry prim under source_prim_path. Moves material assignment to new parent prim if any exists on the Mesh/Geometry prim. Args: asset_usd_path (str): USD file path for asset source_prim_path (str): USD path of root prim save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file. """ omni.usd.get_context().open_stage(asset_usd_path) stage = omni.usd.get_context().get_stage() prims = [stage.GetPrimAtPath(source_prim_path)] edits = Sdf.BatchNamespaceEdit() while len(prims) > 0: prim = prims.pop(0) print(prim) if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]: new_xform = UsdGeom.Xform.Define(stage, str(prim.GetPath()) + "_xform") print(prim, new_xform) edits.Add(Sdf.NamespaceEdit.Reparent(prim.GetPath(), new_xform.GetPath(), 0)) continue children_prims = prim.GetChildren() prims = prims + children_prims stage.GetRootLayer().Apply(edits) if save_as_path is None: omni.usd.get_context().save_stage() else: omni.usd.get_context().save_as_stage(save_as_path) def convert_asset_instanceable(asset_usd_path, source_prim_path, save_as_path=None, create_xforms=True): """ Makes all mesh/geometry prims instanceable. Can optionally add UsdGeom.Xform prim as parent for all mesh/geometry prims. Makes a copy of the asset USD file, which will be used for referencing. Updates asset file to convert all parent prims of mesh/geometry prims to reference cloned USD file. Args: asset_usd_path (str): USD file path for asset source_prim_path (str): USD path of root prim save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file. create_xforms (bool): Whether to add new UsdGeom.Xform prims to mesh/geometry prims. """ if create_xforms: create_parent_xforms(asset_usd_path, source_prim_path, save_as_path) asset_usd_path = save_as_path instance_usd_path = ".".join(asset_usd_path.split(".")[:-1]) + "_meshes.usd" omni.client.copy(asset_usd_path, instance_usd_path) omni.usd.get_context().open_stage(asset_usd_path) stage = omni.usd.get_context().get_stage() prims = [stage.GetPrimAtPath(source_prim_path)] while len(prims) > 0: prim = prims.pop(0) if prim: if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]: parent_prim = prim.GetParent() if parent_prim and not parent_prim.IsInstance(): parent_prim.GetReferences().AddReference(assetPath=instance_usd_path, primPath=str(parent_prim.GetPath())) parent_prim.SetInstanceable(True) continue children_prims = prim.GetChildren() prims = prims + children_prims if save_as_path is None: omni.usd.get_context().save_stage() else: omni.usd.get_context().save_as_stage(save_as_path)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/utils/usd_utils/create_instanceable_ur10.py
# Copyright (c) 2018-2022, NVIDIA Corporation # Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import omni.usd import omni.client from pxr import UsdGeom, Sdf, UsdPhysics, UsdShade # Note: this script should be executed in Isaac Sim `Script Editor` window def create_ur10(asset_dir_usd_path, ur10_dir_usd_path): # Duplicate UR10 folder omni.client.copy(asset_dir_usd_path, ur10_dir_usd_path) def create_ur10_mesh(asset_usd_path, ur10_mesh_usd_path): # Create ur10_mesh.usd file omni.client.copy(asset_usd_path, ur10_mesh_usd_path) omni.usd.get_context().open_stage(ur10_mesh_usd_path) stage = omni.usd.get_context().get_stage() edits = Sdf.BatchNamespaceEdit() # Create parent Xforms reparent_tasks = [ # base_link ['/ur10/base_link/cylinder', 'geoms_xform'], ['/ur10/base_link/ur10_base', 'geoms_xform'], # shoulder_link ['/ur10/shoulder_link/cylinder', 'geoms_xform'], ['/ur10/shoulder_link/cylinder_0', 'geoms_xform'], ['/ur10/shoulder_link/ur10_shoulder', 'geoms_xform'], # upper_arm_link ['/ur10/upper_arm_link/cylinder', 'geoms_xform'], ['/ur10/upper_arm_link/cylinder_0', 'geoms_xform'], ['/ur10/upper_arm_link/cylinder_1', 'geoms_xform'], ['/ur10/upper_arm_link/ur10_upper_arm', 'geoms_xform'], # forearm_link ['/ur10/forearm_link/cylinder', 'geoms_xform'], ['/ur10/forearm_link/cylinder_0', 'geoms_xform'], ['/ur10/forearm_link/cylinder_1', 'geoms_xform'], ['/ur10/forearm_link/ur10_forearm', 'geoms_xform'], # wrist_1_link ['/ur10/wrist_1_link/cylinder', 'geoms_xform'], ['/ur10/wrist_1_link/cylinder_0', 'geoms_xform'], ['/ur10/wrist_1_link/ur10_wrist_1', 'geoms_xform'], # wrist_2_link ['/ur10/wrist_2_link/cylinder', 'geoms_xform'], ['/ur10/wrist_2_link/cylinder_0', 'geoms_xform'], ['/ur10/wrist_2_link/ur10_wrist_2', 'geoms_xform'], # wrist_3_link ['/ur10/wrist_3_link/cylinder', 'geoms_xform'], ['/ur10/wrist_3_link/ur10_wrist_3', 'geoms_xform'], ] # [prim_path, parent_xform_name] for task in reparent_tasks: prim_path, parent_xform_name = task old_parent_path = '/'.join(prim_path.split('/')[:-1]) new_parent_path = f'{old_parent_path}/{parent_xform_name}' UsdGeom.Xform.Define(stage, new_parent_path) edits.Add(Sdf.NamespaceEdit.Reparent(prim_path, new_parent_path, -1)) stage.GetRootLayer().Apply(edits) # Save to file omni.usd.get_context().save_stage() def create_ur10_instanceable(ur10_mesh_usd_path, ur10_instanceable_usd_path): omni.client.copy(ur10_mesh_usd_path, ur10_instanceable_usd_path) omni.usd.get_context().open_stage(ur10_instanceable_usd_path) stage = omni.usd.get_context().get_stage() # Set up references and instanceables for prim in stage.Traverse(): if prim.GetTypeName() != 'Xform': continue # Add reference to visuals_xform, collisions_xform, geoms_xform, and make them instanceable path = str(prim.GetPath()) if path.endswith('visuals_xform') or path.endswith('collisions_xform') or path.endswith('geoms_xform'): ref = prim.GetReferences() ref.ClearReferences() ref.AddReference('./ur10_mesh.usd', path) prim.SetInstanceable(True) # Save to file omni.usd.get_context().save_stage() def create_block_indicator(): asset_usd_path = 'omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Props/Blocks/block.usd' block_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2022.1/Isaac/Props/Blocks/block.usd' omni.client.copy(asset_usd_path, block_usd_path) omni.usd.get_context().open_stage(block_usd_path) stage = omni.usd.get_context().get_stage() edits = Sdf.BatchNamespaceEdit() edits.Add(Sdf.NamespaceEdit.Remove('/object/object/collisions')) stage.GetRootLayer().Apply(edits) omni.usd.get_context().save_stage() asset_usd_path = 'omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Props/Blocks/block_instanceable.usd' block_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2022.1/Isaac/Props/Blocks/block_instanceable.usd' omni.client.copy(asset_usd_path, block_usd_path) omni.usd.get_context().open_stage(block_usd_path) stage = omni.usd.get_context().get_stage() edits = Sdf.BatchNamespaceEdit() edits.Add(Sdf.NamespaceEdit.Remove('/object/object/collisions')) stage.GetRootLayer().Apply(edits) omni.usd.get_context().save_stage() if __name__ == '__main__': asset_dir_usd_path = 'omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Robots/UR10' ur10_dir_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2022.1/Isaac/Robots/UR10' ur10_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2022.1/Isaac/Robots/UR10/ur10.usd' ur10_mesh_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2022.1/Isaac/Robots/UR10/ur10_mesh.usd' ur10_instanceable_usd_path = 'omniverse://localhost/Projects/J3soon/Isaac/2022.1/Isaac/Robots/UR10/ur10_instanceable.usd' create_ur10(asset_dir_usd_path, ur10_dir_usd_path) create_ur10_mesh(ur10_usd_path, ur10_mesh_usd_path) create_ur10_instanceable(ur10_mesh_usd_path, ur10_instanceable_usd_path) create_block_indicator() print("Done!")
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/balance_bot.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omniisaacgymenvs.tasks.utils.usd_utils import set_drive import numpy as np import torch class BalanceBot(Robot): def __init__( self, prim_path: str, name: Optional[str] = "BalanceBot", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: """[summary] """ self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/BalanceBot/balance_bot.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, ) for j in range(3): # set leg joint properties joint_path = f"joints/lower_leg{j}" set_drive(f"{self.prim_path}/{joint_path}", "angular", "position", 0, 400, 40, 1000)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/allegro_hand.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import carb from pxr import Usd, UsdGeom, Sdf, Gf, PhysxSchema, UsdPhysics class AllegroHand(Robot): def __init__( self, prim_path: str, name: Optional[str] = "allegro_hand", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/AllegroHand/allegro_hand_instanceable.usd" self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation self._orientation = torch.tensor([0.257551, 0.283045, 0.683330, -0.621782]) if orientation is None else orientation add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, ) def set_allegro_hand_properties(self, stage, allegro_hand_prim): for link_prim in allegro_hand_prim.GetChildren(): if not(link_prim == stage.GetPrimAtPath("/allegro/Looks") or link_prim == stage.GetPrimAtPath("/allegro/root_joint")): rb = PhysxSchema.PhysxRigidBodyAPI.Apply(link_prim) rb.GetDisableGravityAttr().Set(True) rb.GetRetainAccelerationsAttr().Set(False) rb.GetEnableGyroscopicForcesAttr().Set(False) rb.GetAngularDampingAttr().Set(0.01) rb.GetMaxLinearVelocityAttr().Set(1000) rb.GetMaxAngularVelocityAttr().Set(64/np.pi*180) rb.GetMaxDepenetrationVelocityAttr().Set(1000) rb.GetMaxContactImpulseAttr().Set(1e32) def set_motor_control_mode(self, stage, allegro_hand_path): prim = stage.GetPrimAtPath(allegro_hand_path) self._set_joint_properties(stage, prim) def _set_joint_properties(self, stage, prim): if prim.HasAPI(UsdPhysics.DriveAPI): drive = UsdPhysics.DriveAPI.Apply(prim, "angular") drive.GetStiffnessAttr().Set(3*np.pi/180) drive.GetDampingAttr().Set(0.1*np.pi/180) drive.GetMaxForceAttr().Set(0.5) revolute_joint = PhysxSchema.PhysxJointAPI.Get(stage, prim.GetPath()) revolute_joint.GetJointFrictionAttr().Set(0.01) for child_prim in prim.GetChildren(): self._set_joint_properties(stage, child_prim)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/shadow_hand.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omniisaacgymenvs.tasks.utils.usd_utils import set_drive import carb from pxr import Usd, UsdGeom, Sdf, Gf, PhysxSchema, UsdPhysics class ShadowHand(Robot): def __init__( self, prim_path: str, name: Optional[str] = "shadow_hand", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/ShadowHand/shadow_hand_instanceable.usd" self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation self._orientation = torch.tensor([1.0, 0.0, 0.0, 0.0]) if orientation is None else orientation add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, ) def set_shadow_hand_properties(self, stage, shadow_hand_prim): for link_prim in shadow_hand_prim.GetChildren(): if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI): rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath()) rb.GetDisableGravityAttr().Set(True) rb.GetRetainAccelerationsAttr().Set(True) def set_motor_control_mode(self, stage, shadow_hand_path): joints_config = { "robot0_WRJ1": {"stiffness": 5, "damping": 0.5, "max_force": 4.785}, "robot0_WRJ0": {"stiffness": 5, "damping": 0.5, "max_force": 2.175}, "robot0_FFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_FFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_FFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_MFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_MFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_MFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_RFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_RFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_RFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_LFJ4": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_LFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_LFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_LFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_THJ4": {"stiffness": 1, "damping": 0.1, "max_force": 2.3722}, "robot0_THJ3": {"stiffness": 1, "damping": 0.1, "max_force": 1.45}, "robot0_THJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.99}, "robot0_THJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.99}, "robot0_THJ0": {"stiffness": 1, "damping": 0.1, "max_force": 0.81}, } for joint_name, config in joints_config.items(): set_drive( f"{self.prim_path}/joints/{joint_name}", "angular", "position", 0.0, config["stiffness"]*np.pi/180, config["damping"]*np.pi/180, config["max_force"] )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/ur10.py
# Copyright (c) 2018-2022, NVIDIA Corporation # Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import carb class UR10(Robot): def __init__( self, prim_path: str, name: Optional[str] = "UR10", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = "omniverse://localhost/Projects/J3soon/Isaac/2022.1/Isaac/Robots/UR10/ur10_instanceable.usd" # Depends on your real robot setup self._position = torch.tensor([0.0, 0.0, 0.0]) if translation is None else translation self._orientation = torch.tensor([1.0, 0.0, 0.0, 0.0]) if orientation is None else orientation add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/__init__.py
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/crazyflie.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import numpy as np import torch import carb class Crazyflie(Robot): def __init__( self, prim_path: str, name: Optional[str] = "crazyflie", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, scale: Optional[np.array] = None ) -> None: """[summary] """ self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Crazyflie/cf2x.usd" add_reference_to_stage(self._usd_path, prim_path) scale = torch.tensor([5, 5, 5]) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/cabinet.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Optional from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import numpy as np import torch class Cabinet(Robot): def __init__( self, prim_path: str, name: Optional[str] = "cabinet", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: """[summary] """ self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Props/Sektion_Cabinet/sektion_cabinet_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) self._position = torch.tensor([0.0, 0.0, 0.4]) if translation is None else translation self._orientation = torch.tensor([0.1, 0.0, 0.0, 0.0]) if orientation is None else orientation super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/humanoid.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import carb class Humanoid(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Humanoid", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Humanoid/humanoid_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/franka.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Optional import math import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omniisaacgymenvs.tasks.utils.usd_utils import set_drive from omni.isaac.core.utils.prims import get_prim_at_path from pxr import PhysxSchema class Franka(Robot): def __init__( self, prim_path: str, name: Optional[str] = "franka", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: """[summary] """ self._usd_path = usd_path self._name = name self._position = torch.tensor([1.0, 0.0, 0.0]) if translation is None else translation self._orientation = torch.tensor([0.0, 0.0, 0.0, 1.0]) if orientation is None else orientation if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Franka/franka_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, ) dof_paths = [ "panda_link0/panda_joint1", "panda_link1/panda_joint2", "panda_link2/panda_joint3", "panda_link3/panda_joint4", "panda_link4/panda_joint5", "panda_link5/panda_joint6", "panda_link6/panda_joint7", "panda_hand/panda_finger_joint1", "panda_hand/panda_finger_joint2" ] drive_type = ["angular"] * 7 + ["linear"] * 2 default_dof_pos = [math.degrees(x) for x in [0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8]] + [0.02, 0.02] stiffness = [400*np.pi/180] * 7 + [10000] * 2 damping = [80*np.pi/180] * 7 + [100] * 2 max_force = [87, 87, 87, 87, 12, 12, 12, 200, 200] max_velocity = [math.degrees(x) for x in [2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]] + [0.2, 0.2] for i, dof in enumerate(dof_paths): set_drive( prim_path=f"{self.prim_path}/{dof}", drive_type=drive_type[i], target_type="position", target_value=default_dof_pos[i], stiffness=stiffness[i], damping=damping[i], max_force=max_force[i] ) PhysxSchema.PhysxJointAPI(get_prim_at_path(f"{self.prim_path}/{dof}")).CreateMaxJointVelocityAttr().Set(max_velocity[i])
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/ant.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import carb class Ant(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Ant", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Ant/ant_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/cartpole.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import carb class Cartpole(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Cartpole", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Cartpole/cartpole.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/quadcopter.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import numpy as np import torch class Quadcopter(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Quadcopter", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: """[summary] """ self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Quadcopter/quadcopter.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, position=translation, orientation=orientation, articulation_controller=None, )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/ingenuity.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.prims import RigidPrimView from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import numpy as np import torch class Ingenuity(Robot): def __init__( self, prim_path: str, name: Optional[str] = "ingenuity", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, scale: Optional[np.array] = None ) -> None: """[summary] """ self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Ingenuity/ingenuity.usd" add_reference_to_stage(self._usd_path, prim_path) scale = torch.tensor([0.01, 0.01, 0.01]) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale )
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/anymal.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.prims import RigidPrimView from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage import numpy as np import torch from pxr import PhysxSchema class Anymal(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Anymal", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: """[summary] """ self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find nucleus server with /Isaac folder") self._usd_path = assets_root_path + "/Isaac/Robots/ANYbotics/anymal_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, ) self._dof_names = ["LF_HAA", "LH_HAA", "RF_HAA", "RH_HAA", "LF_HFE", "LH_HFE", "RF_HFE", "RH_HFE", "LF_KFE", "LH_KFE", "RF_KFE", "RH_KFE"] @property def dof_names(self): return self._dof_names def set_anymal_properties(self, stage, prim): for link_prim in prim.GetChildren(): if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI): rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath()) rb.GetDisableGravityAttr().Set(False) rb.GetRetainAccelerationsAttr().Set(False) rb.GetLinearDampingAttr().Set(0.0) rb.GetMaxLinearVelocityAttr().Set(1000.0) rb.GetAngularDampingAttr().Set(0.0) rb.GetMaxAngularVelocityAttr().Set(64/np.pi*180)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/cabinet_view.py
from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class CabinetView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "CabinetView", ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self._drawers = RigidPrimView(prim_paths_expr="/World/envs/.*/cabinet/drawer_top", name="drawers_view", reset_xform_properties=False)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/shadow_hand_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView import torch class ShadowHandView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "ShadowHandView", ) -> None: super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self._fingers = RigidPrimView(prim_paths_expr="/World/envs/.*/shadow_hand/robot0.*distal", name="finger_view", reset_xform_properties=False) @property def actuated_dof_indices(self): return self._actuated_dof_indices def initialize(self, physics_sim_view): super().initialize(physics_sim_view) self.actuated_joint_names = ['robot0_WRJ1', 'robot0_WRJ0', 'robot0_FFJ3', 'robot0_FFJ2', 'robot0_FFJ1', 'robot0_MFJ3', 'robot0_MFJ2', 'robot0_MFJ1', 'robot0_RFJ3', 'robot0_RFJ2', 'robot0_RFJ1', 'robot0_LFJ4', 'robot0_LFJ3', 'robot0_LFJ2', 'robot0_LFJ1', 'robot0_THJ4', 'robot0_THJ3', 'robot0_THJ2', 'robot0_THJ1', 'robot0_THJ0', ] self._actuated_dof_indices = list() for joint_name in self.actuated_joint_names: self._actuated_dof_indices.append(self.get_dof_index(joint_name)) self._actuated_dof_indices.sort() limit_stiffness = torch.tensor([30.0] * self.num_fixed_tendons, device=self._device) damping = torch.tensor([0.1] * self.num_fixed_tendons, device=self._device) self.set_fixed_tendon_properties(dampings=damping, limit_stiffnesses=limit_stiffness)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/franka_view.py
from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class FrankaView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "FrankaView", ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self._hands = RigidPrimView(prim_paths_expr="/World/envs/.*/franka/panda_link7", name="hands_view", reset_xform_properties=False) self._lfingers = RigidPrimView(prim_paths_expr="/World/envs/.*/franka/panda_leftfinger", name="lfingers_view", reset_xform_properties=False) self._rfingers = RigidPrimView(prim_paths_expr="/World/envs/.*/franka/panda_rightfinger", name="rfingers_view", reset_xform_properties=False) def initialize(self, physics_sim_view): super().initialize(physics_sim_view) self._gripper_indices = [self.get_dof_index("panda_finger_joint1"), self.get_dof_index("panda_finger_joint2")] @property def gripper_indices(self): return self._gripper_indices
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/__init__.py
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/anymal_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class AnymalView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "AnymalView", ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self._knees = RigidPrimView(prim_paths_expr="/World/envs/.*/anymal/.*_SHANK", name="knees_view", reset_xform_properties=False) self._base = RigidPrimView(prim_paths_expr="/World/envs/.*/anymal/base", name="base_view", reset_xform_properties=False) def get_knee_transforms(self): return self._knees.get_world_poses() def is_knee_below_threshold(self, threshold, ground_heights=None): knee_pos, _ = self._knees.get_world_poses() knee_heights = knee_pos.view((-1, 4, 3))[:, :, 2] if ground_heights is not None: knee_heights -= ground_heights return (knee_heights[:, 0] < threshold) | (knee_heights[:, 1] < threshold) | (knee_heights[:, 2] < threshold) | (knee_heights[:, 3] < threshold) def is_base_below_threshold(self, threshold, ground_heights): base_pos, _ = self.get_world_poses() base_heights = base_pos[:, 2] base_heights -= ground_heights return (base_heights[:] < threshold)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/ur10_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # Copyright (c) 2022-2023, Johnson Sun # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView import torch class UR10View(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "UR10View", ) -> None: super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) # Use RigidPrimView instead of XFormPrimView, since the XForm is not updated when running self._end_effectors = RigidPrimView(prim_paths_expr="/World/envs/.*/ur10/ee_link", name="end_effector_view", reset_xform_properties=False) def initialize(self, physics_sim_view): super().initialize(physics_sim_view)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/quadcopter_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class QuadcopterView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "QuadcopterView" ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self.rotors = RigidPrimView(prim_paths_expr=f"/World/envs/.*/Quadcopter/rotor[0-3]", reset_xform_properties=False)
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/allegro_hand_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView import torch class AllegroHandView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "AllegroHandView", ) -> None: super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self._actuated_dof_indices = list() @property def actuated_dof_indices(self): return self._actuated_dof_indices def initialize(self, physics_sim_view): super().initialize(physics_sim_view) self._actuated_dof_indices = [i for i in range(self.num_dof)]
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/crazyflie_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class CrazyflieView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "CrazyflieView" ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, ) self.physics_rotors = [RigidPrimView(prim_paths_expr=f"/World/envs/.*/Crazyflie/m{i}_prop", name=f"m{i}_prop_view") for i in range(1, 5)]
j3soon/OmniIsaacGymEnvs-UR10Reacher/omniisaacgymenvs/robots/articulations/views/ingenuity_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class IngenuityView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "IngenuityView" ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self.physics_rotors = [RigidPrimView(prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_physics_{i}", name=f"physics_rotor_{i}_view", reset_xform_properties=False) for i in range(2)] self.visual_rotors = [RigidPrimView(prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_visual_{i}", name=f"visual_rotor_{i}_view", reset_xform_properties=False) for i in range(2)]
j3soon/OmniIsaacGymEnvs-UR10Reacher/docs/domain_randomization.md
Domain Randomization ==================== Overview -------- We sometimes need our reinforcement learning agents to be robust to different physics than they are trained with, such as when attempting a sim2real policy transfer. Using domain randomization (DR), we repeatedly randomize the simulation dynamics during training in order to learn a good policy under a wide range of physical parameters. OmniverseIsaacGymEnvs supports "on the fly" domain randomization, allowing dynamics to be changed without requiring reloading of assets. This allows us to efficiently apply domain randomizations without common overheads like re-parsing asset files. The OmniverseIsaacGymEnvs DR framework utilizes the `omni.replicator.isaac` extension in its backend to perform "on the fly" randomization. Users can add domain randomization by either directly using methods provided in `omni.replicator.isaac` in python, or specifying DR settings in the task configuration `yaml` file. The following sections will focus on setting up DR using the `yaml` file interface. For more detailed documentations regarding methods provided in the `omni.replicator.isaac` extension, please visit [here](https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.replicator.isaac/docs/index.html). Domain Randomization Options ------------------------------- We will first explain what can be randomized in the scene and the sampling distributions. There are five main parameter groups that support randomization. They are: - `observations`: Add noise directly to the agent observations - `actions`: Add noise directly to the agent actions - `simulation`: Add noise to physical parameters defined for the entire scene, such as `gravity` - `rigid_prim_views`: Add noise to properties belonging to rigid prims, such as `material_properties`. - `articulation_views`: Add noise to properties belonging to articulations, such as `stiffness` of joints. For each parameter you wish to randomize, you can specify two ways that determine when the randomization is applied: - `on_reset`: Adds correlated noise to a parameter of an environment when that environment gets reset. This correlated noise will remain with an environment until that environemnt gets reset again, which will then set a new correlated noise. To trigger `on_reset`, the indices for the environemnts that need to be reset must be passed in to `omni.replicator.isaac.physics_view.step_randomization(reset_inds)`. - `on_interval`: Adds uncorrelated noise to a parameter at a frequency specified by `frequency_interval`. If a parameter also has `on_reset` randomization, the `on_interval` noise is combined with the noise applied at `on_reset`. - `on_startup`: Applies randomization once prior to the start of the simulation. Only available to rigid prim scale, mass, density and articulation scale parameters. For `on_reset`, `on_interval`, and `on_startup`, you can specify the following settings: - `distribution`: The distribution to generate a sample `x` from. The available distributions are listed below. Note that parameters `a` and `b` are defined by the `distribution_parameters` setting. - `uniform`: `x ~ unif(a, b)` - `loguniform`: `x ~ exp(unif(log(a), log(b)))` - `gaussian`: `x ~ normal(a, b)` - `distribution_parameters`: The parameters to the distribution. - For observations and actions, this setting is specified as a tuple `[a, b]` of real values. - For simulation and view parameters, this setting is specified as a nested tuple in the form of `[[a_1, a_2, ..., a_n], [[b_1, b_2, ..., b_n]]`, where the `n` is the dimension of the parameter (*i.e.* `n` is 3 for position). It can also be specified as a tuple in the form of `[a, b]`, which will be broadcasted to the correct dimensions. - For `uniform` and `loguniform` distributions, `a` and `b` are the lower and upper bounds. - For `gaussian`, `a` is the distribution mean and `b` is the variance. - `operation`: Defines how the generated sample `x` will be applied to the original simulation parameter. The options are `additive`, `scaling`, `direct`. - `additive`:, add the sample to the original value. - `scaling`: multiply the original value by the sample. - `direct`: directly sets the sample as the parameter value. - `frequency_interval`: Specifies the number of steps to apply randomization. - Only used with `on_interval`. - Steps of each environemnt are incremented with each `omni.replicator.isaac.physics_view.step_randomization(reset_inds)` call and reset if the environment index is in `reset_inds`. - `num_buckets`: Only used for `material_properties` randomization - Physx only allows 64000 unique physics materials in the scene at once. If more than 64000 materials are needed, increase `num_buckets` to allow materials to be shared between prims. YAML Interface -------------- Now that we know what options are available for domain randomization, let's put it all together in the YAML config. In your `omniverseisaacgymenvs/cfg/task` yaml file, you can specify your domain randomization parameters under the `domain_randomization` key. First, we turn on domain randomization by setting `randomize` to `True`: ```yaml domain_randomization: randomize: True randomization_params: ... ``` This can also be set as a command line argument at launch time with `task.domain_randomization.randomize=True`. Next, we will define our parameters under the `randomization_params` keys. Here you can see how we used the previous settings to define some randomization parameters for a ShadowHand cube manipulation task: ```yaml randomization_params: randomization_params: observations: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, .0001] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0, .002] actions: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, 0.015] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0., 0.05] simulation: gravity: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.4]] rigid_prim_views: object_view: material_properties: on_reset: num_buckets: 250 operation: "scaling" distribution: "uniform" distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]] articulation_views: shadow_hand_view: stiffness: on_reset: operation: "scaling" distribution: "uniform" distribution_parameters: [0.75, 1.5] ``` Note how we structured `rigid_prim_views` and `articulation_views`. When creating a `RigidPrimView` or `ArticulationView` in the task python file, you have the option to pass in `name` as an argument. **To use domain randomization, the name of the `RigidPrimView` or `ArticulationView` must match the name provided in the randomization `yaml` file.** In the example above, `object_view` is the name of a `RigidPrimView` and `shadow_hand_view` is the name of the `ArticulationView`. The exact parameters that can be randomized are listed below: **simulation**: - gravity (dim=3): The gravity vector of the entire scene. **rigid\_prim\_views**: - position (dim=3): The position of the rigid prim. In meters. - orientation (dim=3): The orientation of the rigid prim, specified with euler angles. In radians. - linear_velocity (dim=3): The linear velocity of the rigid prim. In m/s. **CPU pipeline only** - angular_velocity (dim=3): The angular velocity of the rigid prim. In rad/s. **CPU pipeline only** - velocity (dim=6): The linear + angular velocity of the rigid prim. - force (dim=3): Apply a force to the rigid prim. In N. - mass (dim=1): Mass of the rigid prim. In kg. **CPU pipeline only during runtime**. - inertia (dim=3): The diagonal values of the inertia matrix. **CPU pipeline only** - material_properties (dim=3): Static friction, Dynamic friction, and Restitution. - contact_offset (dim=1): A small distance from the surface of the collision geometry at which contacts start being generated. - rest_offset (dim=1): A small distance from the surface of the collision geometry at which the effective contact with the shape takes place. - scale (dim=1): The scale of the rigid prim. `on_startup` only. - density (dim=1): Density of the rigid prim. `on_startup` only. **articulation\_views**: - position (dim=3): The position of the articulation root. In meters. - orientation (dim=3): The orientation of the articulation root, specified with euler angles. In radians. - linear_velocity (dim=3): The linear velocity of the articulation root. In m/s. **CPU pipeline only** - angular_velocity (dim=3): The angular velocity of the articulation root. In rad/s. **CPU pipeline only** - velocity (dim=6): The linear + angular velocity of the articulation root. - stiffness (dim=num_dof): The stiffness of the joints. - damping (dim=num_dof): The damping of the joints - joint_friction (dim=num_dof): The friction coefficient of the joints. - joint_positions (dim=num_dof): The joint positions. In radians or meters. - joint_velocities (dim=num_dof): The joint velocities. In rad/s or m/s. - lower_dof_limits (dim=num_dof): The lower limit of the joints. In radians or meters. - upper_dof_limits (dim=num_dof): The upper limit of the joints. In radians or meters. - max_efforts (dim=num_dof): The maximum force or torque that the joints can exert. In N or Nm. - joint_armatures (dim=num_dof): A value added to the diagonal of the joint-space inertia matrix. Physically, it corresponds to the rotating part of a motor - joint_max_velocities (dim=num_dof): The maximum velocity allowed on the joints. In rad/s or m/s. - joint_efforts (dim=num_dof): Applies a force or a torque on the joints. In N or Nm. - body_masses (dim=num_bodies): The mass of each body in the articulation. In kg. **CPU pipeline only** - body_inertias (dim=num_bodies×3): The diagonal values of the inertia matrix of each body. **CPU pipeline only** - material_properties (dim=num_bodies×3): The static friction, dynamic friction, and restitution of each body in the articulation, specified in the following order: [body_1_static_friciton, body_1_dynamic_friciton, body_1_restitution, body_1_static_friciton, body_2_dynamic_friciton, body_2_restitution, ... ] - tendon_stiffnesses (dim=num_tendons): The stiffness of the fixed tendons in the articulation. - tendon_dampings (dim=num_tendons): The damping of the fixed tendons in the articulation. - tendon_limit_stiffnesses (dim=num_tendons): The limit stiffness of the fixed tendons in the articulation. - tendon_lower_limits (dim=num_tendons): The lower limits of the fixed tendons in the articulation. - tendon_upper_limits (dim=num_tendons): The upper limits of the fixed tendons in the articulation. - tendon_rest_lengths (dim=num_tendons): The rest lengths of the fixed tendons in the articulation. - tendon_offsets (dim=num_tendons): The offsets of the fixed tendons in the articulation. - scale (dim=1): The scale of the articulation. `on_startup` only. Applying Domain Randomization ------------------------------ To parse the domain randomization configurations in the task `yaml` file and set up the DR pipeline, it is necessary to call `self._randomizer.set_up_domain_randomization(self)`, where `self._randomizer` is the `Randomizer` object created in RLTask's `__init__`. It is worth noting that the names of the views provided under `rigid_prim_views` or `articulation_views` in the task `yaml` file must match the names passed into `RigidPrimView` or `ArticulationView` objects in the python task file. In addition, all `RigidPrimView` and `ArticulationView` that would have domain randomizaiton applied must be added to the scene in the task's `set_up_scene()` via `scene.add()`. To trigger `on_startup` randomizations, call `self._randomizer.apply_on_startup_domain_randomization(self)` in `set_up_scene()` after all views are added to the scene. Note that `on_startup` randomizations are only availble to rigid prim scale, mass, density and articulation scale parameters since these parameters cannot be randomized after the simulation begins on GPU pipeline. Therefore, randomizations must be applied to these parameters in `set_up_scene()` prior to the start of the simulation. To trigger `on_reset` and `on_interval` randomizations, it is required to step the interal counter of the DR pipeline in `pre_physics_step()`: ```python if self._randomizer.randomize: omni.replicator.isaac.physics_view.step_randomization(reset_inds) ``` `reset_inds` is a list of indices of the environments that need to be reset. For those environments, it will trigger the randomizations defined with `on_reset`. All other environments will follow randomizations defined with `on_interval`. Randomization Scheduling ---------------------------- We provide methods to modify distribution parameters defined in the `yaml` file during training, which allows custom DR scheduling. There are three methods from the `Randomizer` class that are relevant to DR scheduling: - `get_initial_dr_distribution_parameters`: returns a numpy array of the initial parameters (as defined in the `yaml` file) of a specified distribution - `get_dr_distribution_parameters`: returns a numpy array of the current parameters of a specified distribution - `set_dr_distribution_parameters`: sets new parameters to a specified distribution Using the DR configuration example defined above, we can get the current parameters and set new parameters to gravity randomization and shadow hand joint stiffness randomization as follows: ```python current_gravity_dr_params = self._randomizer.get_dr_distribution_parameters( "simulation", "gravity", "on_reset", ) self._randomizer.set_dr_distribution_parameters( [[0.0, 0.0, 0.0], [0.0, 0.0, 0.5]], "simulation", "gravity", "on_reset", ) current_joint_stiffness_dr_params = self._randomizer.get_dr_distribution_parameters( "articulation_views", "shadow_hand_view", "stiffness", "on_reset", ) self._randomizer.set_dr_distribution_parameters( [0.7, 1.55], "articulation_views", "shadow_hand_view", "stiffness", "on_reset", ) ``` The following is an example of using these methods to perform linear scheduling of gaussian noise that is added to observations and actions in the above shadow hand example. The following method linearly adds more noise to observations and actions every epoch up until the `schedule_epoch`. This method can be added to the Task python class and be called in `pre_physics_step()`. ```python def apply_observations_actions_noise_linear_scheduling(self, schedule_epoch=100): current_epoch = self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"] // self._cfg["train"]["params"]["config"]["horizon_length"] if current_epoch <= schedule_epoch: if (self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"]) % self._cfg["train"]["params"]["config"]["horizon_length"] == 0: for distribution_path in [("observations", "on_reset"), ("observations", "on_interval"), ("actions", "on_reset"), ("actions", "on_interval")]: scheduled_params = self._randomizer.get_initial_dr_distribution_parameters(*distribution_path) scheduled_params[1] = (1/schedule_epoch) * current_epoch * scheduled_params[1] self._randomizer.set_dr_distribution_parameters(scheduled_params, *distribution_path) ```
j3soon/OmniIsaacGymEnvs-UR10Reacher/docs/instanceable_assets.md
## A Note on Instanceable USD Assets The following section presents a method that modifies existing USD assets which allows Isaac Sim to load significantly more environments. This is currently an experimental method and has thus not been completely integrated into the framework. As a result, this section is reserved for power users who wish to maxmimize the performance of the Isaac Sim RL framework. ### Motivation One common issue in Isaac Sim that occurs when we try to increase the number of environments `numEnvs` is running out of RAM. This occurs because the Isaac Sim RL framework uses `omni.isaac.cloner` to duplicate environments. As a result, there are `numEnvs` number of identical copies of the visual and collision meshes in the scene, which consumes lots of memory. However, only one copy of the meshes are needed on stage since prims in all other environments could merely reference that one copy, thus reducing the amount of memory used for loading environments. To enable this functionality, USD assets need to be modified to be `instanceable`. ### Creating Instanceable Assets Assets can now be directly imported as Instanceable assets through the URDF and MJCF importers provided in Isaac Sim. By selecting this option, imported assets will be split into two separate USD files that follow the above hierarchy definition. Any mesh data will be written to an USD stage to be referenced by the main USD stage, which contains the main robot definition. To use the Instanceable option in the importers, first check the `Create Instanceable Asset` option. Then, specify a file path to indicate the location for saving the mesh data in the `Instanceable USD Path` textbox. This will default to `./instanceable_meshes.usd`, which will generate a file `instanceable_meshes.usd` that is saved to the current directory. Once the asset is imported with these options enabled, you will see the robot definition in the stage - we will refer to this stage as the master stage. If we expand the robot hierarchy in the Stage, we will notice that the parent prims that have mesh decendants have been marked as Instanceable and they reference a prim in our `Instanceable USD Path` USD file. We are also no longer able to modify attributes of descendant meshes. To add the instanced asset into a new stage, we will simply need to add the master USD file. ### Converting Existing Assets We provide the utility function `convert_asset_instanceable`, which creates an instanceable version of a given USD asset in `/omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py`. To run this function, launch Isaac Sim and open the script editor via `Window -> Script Editor`. Enter the following script and press `Run (Ctrl + Enter)`: ```bash from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import convert_asset_instanceable convert_asset_instanceable( asset_usd_path=ASSET_USD_PATH, source_prim_path=SOURCE_PRIM_PATH, save_as_path=SAVE_AS_PATH ) ``` Note that `ASSET_USD_PATH` is the file path to the USD asset (*e.g.* robot_asset.usd). `SOURCE_PRIM_PATH` is the USD path of the root prim of the asset on stage. `SAVE_AS_PATH` is the file path of the generated instanceable version of the asset (*e.g.* robot_asset_instanceable.usd). Assuming that `SAVE_AS_PATH` is `OUTPUT_NAME.usd`, the above script will generate two files: `OUTPUT_NAME.usd` and `OUTPUT_NAME_meshes.usd`. `OUTPUT_NAME.usd` is the instanceable version of the asset that can be imported to stage and used by `omni.isaac.cloner` to create numerous duplicates without consuming much memory. `OUTPUT_NAME_meshes.usd` contains all the visual and collision meshes that `OUTPUT_NAME.usd` references. It is worth noting that any [USD Relationships](https://graphics.pixar.com/usd/dev/api/class_usd_relationship.html) on the referenced meshes are removed in `OUTPUT_NAME.usd`. This is because those USD Relationships originally have targets set to prims in `OUTPUT_NAME_meshes.usd` and hence cannot be accessed from `OUTPUT_NAME.usd`. Common examples of USD Relationships that could exist on the meshes are visual materials, physics materials, and filtered collision pairs. Therefore, it is recommanded to set these USD Relationships on the meshes' parent Xforms instead of the meshes themselves. In a case where we would like to update the main USD file where the instanceable USD file is being referenced from, we also provide a utility method to update all references in the stage that matches a source reference path to a new USD file path. ```bash from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import update_reference update_reference( source_prim_path=SOURCE_PRIM_PATH, source_reference_path=SOURCE_REFERENCE_PATH, target_reference_path=TARGET_REFERENCE_PATH ) ``` ### Limitations USD requires a specific structure in the asset tree definition in order for the instanceable flag to take action. To mark any mesh or primitive geometry prim in the asset as instanceable, the mesh prim requires a parent Xform prim to be present, which will be used to add a reference to a master USD file containing definition of the mesh prim. For example, the following definition: ``` World |_ Robot |_ Collisions |_ Sphere |_ Box ``` would have to be modified to: ``` World |_ Robot |_ Collisions |_ Sphere_Xform | |_ Sphere |_ Box_Xform |_ Box ``` Any references that exist on the original `Sphere` and `Box` prims would have to be moved to `Sphere_Xform` and `Box_Xform` prims. To help with the process of creating new parent prims, we provide a utility method `create_parent_xforms()` in `omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py` to automatically insert a new Xform prim as a parent of every mesh prim in the stage. This method can be run on an existing non-instanced USD file for an asset from the script editor: ```bash from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import create_parent_xforms create_parent_xforms( asset_usd_path=ASSET_USD_PATH, source_prim_path=SOURCE_PRIM_PATH, save_as_path=SAVE_AS_PATH ) ``` This method can also be run as part of `convert_asset_instanceable()` method, by passing in the argument `create_xforms=True`. It is also worth noting that once an instanced asset is added to the stage, we can no longer modify USD attributes on the instanceable prims. For example, to modify attributes of collision meshes that are set as instanceable, we have to first modify the attributes on the corresponding prims in the master prim which our instanced asset references from. Then, we can allow the instanced asset to pick up the updated values from the master prim.
j3soon/OmniIsaacGymEnvs-UR10Reacher/docs/troubleshoot.md
## Troubleshooting ### Common Issues #### Simulation * When running simulation on GPU, be mindful of the dimensions of GPU buffers defined for physics. We have exposed GPU buffer size settings in the task confg files, which should be modified accordingly based on the number of actors and environments in the scene. If you see an error such as the following, try increasing the size of the corresponding buffer in the config `yaml` file. ```bash PhysX error: the application need to increase the PxgDynamicsMemoryConfig::foundLostPairsCapacity parameter to 3072, otherwise the simulation will miss interactions ``` * When running with the GPU pipeline, updates to states in the scene will not sync to USD. Therefore, values in the UI may appear wrong when simulation is running. Although objects may be updating in the Viewport, attribute values in the UI will not update along with them. Similarly, during simulation, any updates made through the USD APIs will not be synced with physics. * To enable USD sync, please use the CPU pipeline with `pipeline=cpu` and disable flatcache by setting `use_flatcache: False` in the task config. #### Load Time * At initial load up of Isaac Sim, the process may appear to be frozen at an `app ready` message. This is normal and may take a few minutes for everything to load on the first run of Isaac Sim. Subsequent runs should be faster to start up, but may still take some time. * Please note that once the Isaac Sim app loads, the environment creation time may scale linearly with the number of environments. Please expect a longer load time if running with thousands of environments or if each environment contains a larger number of assets. We are continually working on improving the time needed for this. * When an instance of Isaac Sim is already running, launching another Isaac Sim instance in a different process may appear to hang at startup for the first time. Please be patient and give it some time as the second process will take longer to start up due to shader compilation. #### Memory Consumption * Memory consumption will increase with the number of environments and number of objects in the simulation scene. Below is a rough estimate of the amount of memory required for CPU and GPU for some of our example tasks and how they vary with the number of environments under the current settings defined in the task config files. If your machine is running out of memory, or if you are hitting Segmentation Faults, please try reducing the number of environments and the GPU buffer sizes in the task config file. | Task | # of Envs | CPU Mem | GPU Mem | |:-----------:|:---------:|:-------:|:-------:| | Humanoid | 1024 | 4.85 GB | 3.55 GB | | Humanoid | 2048 | 5.39 GB | 3.88 GB | | Humanoid | 4096 | 6.55 GB | 4.46 GB | | Shadow Hand | 1024 | 9.43 GB | 5.97 GB | | Shadow Hand | 2048 | 10.5 GB | 6.74 GB | | Shadow Hand | 4096 | 12.4 GB | 7.83 GB | | Shadow Hand | 8192 | 16.3 GB | 9.90 GB | | Shadow Hand | 16384 | 18.5 GB | 14.0 GB | #### Interaction with the Environment * During training mode, we have set `enable_scene_query_support=False` in our task config files by default. This will prevent certain interactions with the environments in the UI. If you wish to allow interaction during training, set `enable_scene_query_support=True`. This variable will always be set to `True` in inference/test mode. * Please note that the single-threaded training script `rlgames_train.py` provides limited interaction with the UI during training. The main loop is controlled by the RL library and therefore, we have to terminate the process once the RL loop terminates. In both training and infrencing modes, once simulation is terminated from the UI, all views defined and used by the task will become invalid. Therefore, if we try to restart simulation from the UI, an error will occur. * The multi-threaded training script `rlgames_train_mt.py` will allow for better control in stopping and restarting simulation during training and inferencing. #### RL Training * rl-games requires `minibatch_size` defined in the training config to be a factor of `horizon_length * num_envs`. If this is not the case, you may see an assertion error `assert(self.batch_size % self.minibatch_size == 0)`. Please adjust the parameters in the training config `yaml` file accordingly. * In the train configuration `yaml` file (*e.g.* [HumanoidPPO.yaml](../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml)), setting the parameter `mixed_precision` to `True` should only be used with gpu pipeline. It is recommended to set `mixed_precision` to `False` when using cpu pipeline to prevent crashes. * If running with the multi-threaded environment wrapper class `VecEnvMT`, you may see a timeout error that looks something like `Getting states: timeout occurred.`. If you hit this error with your environment, try increasing the timeout variable in `VecEnvMT`, which can be passed as a parameter on the `initialize()` call. It may also be easier to debug an environment using the single-threaded class first to iron out any bugs.
j3soon/OmniIsaacGymEnvs-UR10Reacher/docs/rl_examples.md
## Reinforcement Learning Examples We introduce the following reinforcement learning examples that are implemented using Isaac Sim's RL framework. Pre-trained checkpoints can be found on the Nucleus server. To set up localhost, please refer to the [Isaac Sim installation guide](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_basic.html). *Note: All commands should be executed from `omniisaacgymenvs/omniisaacgymenvs`.* - [Reinforcement Learning Examples](#reinforcement-learning-examples) - [Cartpole cartpole.py](#cartpole-cartpolepy) - [Ant ant.py](#ant-antpy) - [Humanoid humanoid.py](#humanoid-humanoidpy) - [Shadow Hand Object Manipulation shadow_hand.py](#shadow-hand-object-manipulation-shadow_handpy) - [OpenAI Variant](#openai-variant) - [LSTM Training Variant](#lstm-training-variant) - [Allegro Hand Object Manipulation allegro_hand.py](#allegro-hand-object-manipulation-allegro_handpy) - [ANYmal anymal.py](#anymal-anymalpy) - [Anymal Rough Terrain anymal_terrain.py](#anymal-rough-terrain-anymal_terrainpy) - [NASA Ingenuity Helicopter ingenuity.py](#nasa-ingenuity-helicopter-ingenuitypy) - [Quadcopter quadcopter.py](#quadcopter-quadcopterpy) - [Crazyflie crazyflie.py](#crazyflie-crazyfliepy) - [Ball Balance ball_balance.py](#ball-balance-ball_balancepy) - [Franka Cabinet franka_cabinet.py](#franka-cabinet-franka_cabinetpy) ### Cartpole [cartpole.py](../omniisaacgymenvs/tasks/cartpole.py) Cartpole is a simple example that demonstrates getting and setting usage of DOF states using `ArticulationView` from `omni.isaac.core`. The goal of this task is to move a cart horizontally such that the pole, which is connected to the cart via a revolute joint, stays upright. Joint positions and joint velocities are retrieved using `get_joint_positions` and `get_joint_velocities` respectively, which are required in computing observations. Actions are applied onto the cartpoles via `set_joint_efforts`. Cartpoles are reset by using `set_joint_positions` and `set_joint_velocities`. Training can be launched with command line argument `task=Cartpole`. Running inference with pre-trained model can be launched with command line argument `task=Cartpole test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/cartpole.pth` Config files used for this task are: - **Task config**: [Cartpole.yaml](../omniisaacgymenvs/cfg/task/Cartpole.yaml) - **rl_games training config**: [CartpolePPO.yaml](../omniisaacgymenvs/cfg/train/CartpolePPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/171454189-6afafbff-bb61-4aac-b518-24646007cb9f.gif" width="300" height="150"/> ### Ant [ant.py](../omniisaacgymenvs/tasks/ant.py) Ant is an example of a simple locomotion task. The goal of this task is to train quadruped robots (ants) to run forward as fast as possible. This example inherets from [LocomotionTask](../omniisaacgymenvs/tasks/shared/locomotion.py), which is a shared class between this example and the humanoid example; this simplifies implementations for both environemnts since they compute rewards, observations, and resets in a similar manner. This framework allows us to easily switch between robots used in the task. The Ant task includes more examples of utilizing `ArticulationView` from `omni.isaac.core`, which provides various functions to get and set both DOF states and articulation root states in a tensorized fashion across all of the actors in the environment. `get_world_poses`, `get_linear_velocities`, and `get_angular_velocities`, can be used to determine whether the ants have been moving towards the desired direction and whether they have fallen or flipped over. Actions are applied onto the ants via `set_joint_efforts`, which moves the ants by setting torques to the DOFs. Force sensors are also placed on each of the legs to observe contacts with the ground plane; the sensor values can be retrieved using `get_force_sensor_forces`. Training can be launched with command line argument `task=Ant`. Running inference with pre-trained model can be launched with command line argument `task=Ant test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth` Config files used for this task are: - **Task config**: [Ant.yaml](../omniisaacgymenvs/cfg/task/Ant.yaml) - **rl_games training config**: [AntPPO.yaml](../omniisaacgymenvs/cfg/train/AntPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/171454182-0be1b830-bceb-4cfd-93fb-e1eb8871ec68.gif" width="300" height="150"/> ### Humanoid [humanoid.py](../omniisaacgymenvs/tasks/humanoid.py) Humanoid is another environment that uses [LocomotionTask](../omniisaacgymenvs/tasks/shared/locomotion.py). It is conceptually very similar to the Ant example, where the goal for the humanoid is to run forward as fast as possible. Training can be launched with command line argument `task=Humanoid`. Running inference with pre-trained model can be launched with command line argument `task=Humanoid test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/humanoid.pth` Config files used for this task are: - **Task config**: [Humanoid.yaml](../omniisaacgymenvs/cfg/task/Humanoid.yaml) - **rl_games training config**: [HumanoidPPO.yaml](../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/171454193-e027885d-1510-4ef4-b838-06b37f70c1c7.gif" width="300" height="150"/> ### Shadow Hand Object Manipulation [shadow_hand.py](../omniisaacgymenvs/tasks/shadow_hand.py) The Shadow Hand task is an example of a challenging dexterity manipulation task with complex contact dynamics. It resembles OpenAI's [Learning Dexterity](https://openai.com/blog/learning-dexterity/) project and [Robotics Shadow Hand](https://github.com/openai/gym/tree/master/gym/envs/robotics) training environments. The goal of this task is to orient the object in the robot hand to match a random target orientation, which is visually displayed by a goal object in the scene. This example inherets from [InHandManipulationTask](../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py), which is a shared class between this example and the Allegro Hand example. The idea of this shared [InHandManipulationTask](../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py) class is similar to that of the [LocomotionTask](../omniisaacgymenvs/tasks/shared/locomotion.py); since the Shadow Hand example and the Allegro Hand example only differ by the robot hand used in the task, using this shared class simplifies implementation across the two. In this example, motion of the hand is controlled using position targets with `set_joint_position_targets`. The object and the goal object are reset using `set_world_poses`; their states are retrieved via `get_world_poses` for computing observations. It is worth noting that the Shadow Hand model in this example also demonstrates the use of tendons, which are imported using the `omni.isaac.mjcf` extension. Training can be launched with command line argument `task=ShadowHand`. Training with Domain Randomization can be launched with command line argument `task.domain_randomization.randomize=True`. For best training results with DR, use `num_envs=16384`. Running inference with pre-trained model can be launched with command line argument `task=ShadowHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand.pth` Config files used for this task are: - **Task config**: [ShadowHand.yaml](../omniisaacgymenvs/cfg/task/ShadowHand.yaml) - **rl_games training config**: [ShadowHandPPO.yaml](../omniisaacgymenvs/cfg/train/ShadowHandPPO.yaml) #### OpenAI Variant In addition to the basic version of this task, there is an additional variant matching OpenAI's [Learning Dexterity](https://openai.com/blog/learning-dexterity/) project. This variant uses the **openai** observations in the policy network, but asymmetric observations of the **full_state** in the value network. This can be launched with command line argument `task=ShadowHandOpenAI_FF`. Config files used for this are: - **Task config**: [ShadowHandOpenAI_FF.yaml](../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_FF.yaml) - **rl_games training config**: [ShadowHandOpenAI_FFPPO.yaml](../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_FFPPO.yaml). #### LSTM Training Variant This variant uses LSTM policy and value networks instead of feed forward networks, and also asymmetric LSTM critic designed for the OpenAI variant of the task. This can be launched with command line argument `task=ShadowHandOpenAI_LSTM`. Config files used for this are: - **Task config**: [ShadowHandOpenAI_LSTM.yaml](../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_LSTM.yaml) - **rl_games training config**: [ShadowHandOpenAI_LSTMPPO.yaml](../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_LSTMPPO.yaml). <img src="https://user-images.githubusercontent.com/34286328/171454160-8cb6739d-162a-4c84-922d-cda04382633f.gif" width="300" height="150"/> ### Allegro Hand Object Manipulation [allegro_hand.py](../omniisaacgymenvs/tasks/allegro_hand.py) This example performs the same object orientation task as the Shadow Hand example, but using the Allegro hand instead of the Shadow hand. Training can be launched with command line argument `task=AllegroHand`. Running inference with pre-trained model can be launched with command line argument `task=AllegroHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/allegro_hand.pth` Config files used for this task are: - **Task config**: [AllegroHand.yaml](../omniisaacgymenvs/cfg/task/Allegro.yaml) - **rl_games training config**: [AllegroHandPPO.yaml](../omniisaacgymenvs/cfg/train/AllegroHandPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/171454176-ce08f6d0-3087-4ecc-9273-7d30d8f73f6d.gif" width="300" height="150"/> ### ANYmal [anymal.py](../omniisaacgymenvs/tasks/anymal.py) This example trains a model of the ANYmal quadruped robot from ANYbotics to follow randomly chosen x, y, and yaw target velocities. Training can be launched with command line argument `task=Anymal`. Running inference with pre-trained model can be launched with command line argument `task=Anymal test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal.pth` Config files used for this task are: - **Task config**: [Anymal.yaml](../omniisaacgymenvs/cfg/task/Anymal.yaml) - **rl_games training config**: [AnymalPPO.yaml](../omniisaacgymenvs/cfg/train/AnymalPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184168200-152567a8-3354-4947-9ae0-9443a56fee4c.gif" width="300" height="150"/> ### Anymal Rough Terrain [anymal_terrain.py](../omniisaacgymenvs/tasks/anymal_terrain.py) A more complex version of the above Anymal environment that supports traversing various forms of rough terrain. Training can be launched with command line argument `task=AnymalTerrain`. Running inference with pre-trained model can be launched with command line argument `task=AnymalTerrain test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal_terrain.pth` - **Task config**: [AnymalTerrain.yaml](../omniisaacgymenvs/cfg/task/AnymalTerrain.yaml) - **rl_games training config**: [AnymalTerrainPPO.yaml](../omniisaacgymenvs/cfg/train/AnymalTerrainPPO.yaml) **Note** during test time use the last weights generated, rather than the usual best weights. Due to curriculum training, the reward goes down as the task gets more challenging, so the best weights do not typically correspond to the best outcome. **Note** if you use the ANYmal rough terrain environment in your work, please ensure you cite the following work: ``` @misc{rudin2021learning, title={Learning to Walk in Minutes Using Massively Parallel Deep Reinforcement Learning}, author={Nikita Rudin and David Hoeller and Philipp Reist and Marco Hutter}, year={2021}, journal = {arXiv preprint arXiv:2109.11978} ``` **Note** The OmniIsaacGymEnvs implementation slightly differs from the implementation used in the paper above, which also uses a different RL library and PPO implementation. The original implementation is made available [here](https://github.com/leggedrobotics/legged_gym). Results reported in the Isaac Gym technical paper are based on that repository, not this one. <img src="https://user-images.githubusercontent.com/34286328/184170040-3f76f761-e748-452e-b8c8-3cc1c7c8cb98.gif" width="300" height="150"/> ### NASA Ingenuity Helicopter [ingenuity.py](../omniisaacgymenvs/tasks/ingenuity.py) This example trains a simplified model of NASA's Ingenuity helicopter to navigate to a moving target. It showcases the use of velocity tensors and applying force vectors to rigid bodies. Note that we are applying force directly to the chassis, rather than simulating aerodynamics. This example also demonstrates using different values for gravitational forces. Ingenuity Helicopter visual 3D Model courtesy of NASA: https://mars.nasa.gov/resources/25043/mars-ingenuity-helicopter-3d-model/. Training can be launched with command line argument `task=Ingenuity`. Running inference with pre-trained model can be launched with command line argument `task=Ingenuity test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ingenuity.pth` Config files used for this task are: - **Task config**: [Ingenuity.yaml](../omniisaacgymenvs/cfg/task/Ingenuity.yaml) - **rl_games training config**: [IngenuityPPO.yaml](../omniisaacgymenvs/cfg/train/IngenuityPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184176312-df7d2727-f043-46e3-b537-48a583d321b9.gif" width="300" height="150"/> ### Quadcopter [quadcopter.py](../omniisaacgymenvs/tasks/quadcopter.py) This example trains a very simple quadcopter model to reach and hover near a fixed position. Lift is achieved by applying thrust forces to the "rotor" bodies, which are modeled as flat cylinders. In addition to thrust, the pitch and roll of each rotor is controlled using DOF position targets. Training can be launched with command line argument `task=Quadcopter`. Running inference with pre-trained model can be launched with command line argument `task=Quadcopter test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/quadcopter.pth` Config files used for this task are: - **Task config**: [Quadcopter.yaml](../omniisaacgymenvs/cfg/task/Quadcopter.yaml) - **rl_games training config**: [QuadcopterPPO.yaml](../omniisaacgymenvs/cfg/train/QuadcopterPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184178817-9c4b6b3c-c8a2-41fb-94be-cfc8ece51d5d.gif" width="300" height="150"/> ### Crazyflie [crazyflie.py](../omniisaacgymenvs/tasks/crazyflie.py) This example trains the Crazyflie drone model to hover near a fixed position. It is achieved by applying thrust forces to the four rotors. Training can be launched with command line argument `task=Crazyflie`. Running inference with pre-trained model can be launched with command line argument `task=Crazyflie test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/crazyflie.pth` Config files used for this task are: - **Task config**: [Crazyflie.yaml](../omniisaacgymenvs/cfg/task/Crazyflie.yaml) - **rl_games training config**: [CrazyfliePPO.yaml](../omniisaacgymenvs/cfg/train/CrazyfliePPO.yaml) <img src="https://user-images.githubusercontent.com/6352136/185715165-b430a0c7-948b-4dce-b3bb-7832be714c37.gif" width="300" height="150"/> ### Ball Balance [ball_balance.py](../omniisaacgymenvs/tasks/ball_balance.py) This example trains balancing tables to balance a ball on the table top. This is a great example to showcase the use of force and torque sensors, as well as DOF states for the table and root states for the ball. In this example, the three-legged table has a force sensor attached to each leg. We use the force sensor APIs to collect force and torque data on the legs, which guide position target outputs produced by the policy. Training can be launched with command line argument `task=BallBalance`. Running inference with pre-trained model can be launched with command line argument `task=BallBalance test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ball_balance.pth` Config files used for this task are: - **Task config**: [BallBalance.yaml](../omniisaacgymenvs/cfg/task/BallBalance.yaml) - **rl_games training config**: [BallBalancePPO.yaml](../omniisaacgymenvs/cfg/train/BallBalancePPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184172037-cdad9ee8-f705-466f-bbde-3caa6c7dea37.gif" width="300" height="150"/> ### Franka Cabinet [franka_cabinet.py](../omniisaacgymenvs/tasks/franka_cabinet.py) This Franka example demonstrates interaction between Franka arm and cabinet, as well as setting states of objects inside the drawer. It also showcases control of the Franka arm using position targets. In this example, we use DOF state tensors to retrieve the state of the Franka arm, as well as the state of the drawer on the cabinet. Actions are applied as position targets to the Franka arm DOFs. Training can be launched with command line argument `task=FrankaCabinet`. Running inference with pre-trained model can be launched with command line argument `task=FrankaCabinet test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/franka_cabinet.pth` Config files used for this task are: - **Task config**: [FrankaCabinet.yaml](../omniisaacgymenvs/cfg/task/FrankaCabinet.yaml) - **rl_games training config**: [FrankaCabinetPPO.yaml](../omniisaacgymenvs/cfg/train/FrankaCabinetPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184174894-03767aa0-936c-4bfe-bbe9-a6865f539bb4.gif" width="300" height="150"/>
j3soon/OmniIsaacGymEnvs-UR10Reacher/docs/release_notes.md
Release Notes ============= 1.1.0 - August 22, 2022 ----------------------- Additions --------- - Additional examples: Anymal, AnymalTerrain, BallBalance, Crazyflie, FrankaCabinet, Ingenuity, Quadcopter - Add OpenAI variantions for Feed-Forward and LSTM networks for ShadowHand - Add domain randomization framework `using omni.replicator.isaac` - Add AnymalTerrain interactable demo - Automatically disable `omni.kit.window.viewport` and `omni.physx.flatcache` extensions in headless mode to improve start-up load time - Introduce `reset_xform_properties` flag for initializing Views of cloned environments to reduce load time - Add WandB support - Update RL-Games version to 1.5.2 Fixes ----- - Correctly sets simulation device for GPU simulation - Fix omni.client import order - Fix episode length reset condition for ShadowHand and AllegroHand 1.0.0 - June 03, 2022 ---------------------- - Initial release for RL examples with Isaac Sim - Examples provided: AllegroHand, Ant, Cartpole, Humanoid, ShadowHand
j3soon/OmniIsaacGymEnvs-UR10Reacher/docs/transfering_policies_from_isaac_gym.md
## Transfering Policies from Isaac Gym Preview Releases This section delineates some of the differences between the standalone [Isaac Gym Preview Releases](https://developer.nvidia.com/isaac-gym) and Isaac Sim reinforcement learning extensions, in hopes of facilitating the process of transferring policies trained in the standalone preview releases to Isaac Sim. ### Isaac Sim RL Extensions Unlike the monolithic standalone Isaac Gym Preview Releases, Omniverse is a highly modular system, with functionality split between various [Extensions](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions.html). The APIs used by typical robotics RL systems are split between a handful of extensions in Isaac Sim. These include `omni.isaac.core`, which provides tensorized access to physics simulation state as well as a task management framework, the `omni.isaac.cloner` extension for creating many copies of your environments, and the `omni.isaac.gym` extension for interfacing with external RL training libraries. For naming clarity, we'll refer collectively to the extensions used for RL within Isaac Sim as the **Isaac Sim RL extensions**, in contrast with the older **Isaac Gym Preview Releases**. ### Quaternion Convention The Isaac Sim RL extensions use various classes and methods in `omni.isaac.core`, which adopts `wxyz` as the quaternion convention. However, the quaternion convention used in Isaac Gym Preview Releases is `xyzw`. Therefore, if a policy trained in one of the Isaac Gym Preview Releases takes in quaternions as part of its observations, remember to switch all quaternions to use the `xyzw` convention in the observation buffer `self.obs_buf`. Similarly, please ensure all quaternions are in `wxyz` before passing them in any of the utility functions in `omni.isaac.core`. ### Joint Order Isaac Sim's `ArticulationView` in `omni.isaac.core` assumes a breadth-first ordering for the joints in a given kinematic tree. Specifically, for the following kinematic tree, the method `ArticulationView.get_joint_positions` returns a tensor of shape `(number of articulations in the view, number of joints in the articulation)`. Along the second dimension of this tensor, the values represent the articulation's joint positions in the following order: `[Joint 1, Joint 2, Joint 4, Joint 3, Joint 5]`. On the other hand, the Isaac Gym Preview Releases assume a depth-first ordering for the joints in the kinematic tree; In the example below, the joint orders would be the following: `[Joint 1, Joint 2, Joint 3, Joint 4, Joint 5]`. <img src="./media/KinematicTree.png" height="300"/> With this in mind, it is important to change the joint order to depth-first in the observation buffer before feeding it into an existing policy trained in one of the Isaac Gym Preview Releases. Similarly, you would also need to change the joint order in the output (the action buffer) of the Isaac Gym Preview Release trained policy to breadth-first before applying joint actions to articulations via methods in `ArticulationView`. ### Physics Parameters One factor that could dictate the success of policy transfer from Isaac Gym Preview Releases to Isaac Sim is to ensure the physics parameters used in both simulations are identical or very similar. In general, the `sim` parameters specified in the task configuration `yaml` file overwrite the corresponding parameters in the USD asset. However, there are additional parameters in the USD asset that are not included in the task configuration `yaml` file. These additional parameters may sometimes impact the performance of Isaac Gym Preview Release trained policies and hence need modifications in the USD asset itself to match the values set in Isaac Gym Preview Releases. For instance, the following parameters in the `RigidBodyAPI` could be modified in the USD asset to yield better policy transfer performance: | RigidBodyAPI Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases | |:----------------------:|:--------------------------:|:--------------------------:| | Linear Damping | 0.00 | 0.00 | | Angular Damping | 0.05 | 0.00 | | Max Linear Velocity | inf | 1000 | | Max Angular Velocity | 5729.58008 (deg/s) | 64 (rad/s) | | Max Contact Impulse | inf | 1e32 | <img src="./media/RigidBodyAPI.png" width="500"/> Parameters in the `JointAPI` as well as the `DriveAPI` could be altered as well. Note that the Isaac Sim UI assumes the unit of angle to be degrees. It is particularly worth noting that the `Damping` and `Stiffness` paramters in the `DriveAPI` have the unit of `1/deg` in the Isaac Sim UI but `1/rad` in Isaac Gym Preview Releases. | Joint Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases | |:----------------------:|:--------------------------:|:--------------------------:| | Maximum Joint Velocity | 1000000.0 (deg) | 100.0 (rad) | <img src="./media/JointAPI.png" width="500"/> ### Differences in APIs APIs for accessing physics states in Isaac Sim require the creation of an ArticulationView or RigidPrimView object. Multiple view objects can be initialized for different articulations or bodies in the scene by defining a regex expression that matches the paths of the desired objects. This approach eliminates the need of retrieving body handles to slice states for specific bodies in the scene. We have also removed `acquire` and `refresh` APIs in Isaac Sim. Physics states can be directly applied or retrieved by using `set`/`get` APIs defined for the views. New APIs provided in Isaac Sim no longer require explicit wrapping and un-wrapping of underlying buffers. APIs can now work with tensors directly for reading and writing data. Most APIs in Isaac Sim also provide the option to specify an `indices` parameter, which can be used when reading or writing data for a subset of environments. Note that when setting states with the `indices` parameter, the shape of the states buffer should match with the dimension of the `indices` list. Note some naming differences between APIs in Isaac Gym Preview Release and Isaac Sim. Most `dof` related APIs have been named to `joint` in Isaac Sim. `root_states` is now separated into different APIs for `world_poses` and `velocities`. Similary, `dof_states` are retrieved individually in Isaac Sim as `joint_positions` and `joint_velocities`. APIs in Isaac Sim also no longer follow the explicit `_tensors` or `_tensor_indexed` suffixes in naming. Indexed versions of APIs now happen implicitly through the optional `indices` parameter. As part of our API improvements, we are defining a new set of contact APIs that aim to provide more useful details on contacts and collisions. This will be a replacement of `net_contact_force` in the Isaac Gym Preview Release and will be available in the next release of Isaac Sim. For now, Isaac Sim does not provide a tensorized API for collecting contacts. ### Task Configuration Files There are a few modifications that need to be made to an existing Isaac Gym Preview Release task `yaml` file in order for it to be compatible with the Isaac Sim RL extensions. #### Frequencies of Physics Simulation and RL Policy The way in which physics simulation frequency and RL policy frequency are specified is different between Isaac Gym Preview Releases and Isaac Sim, dictated by the following three parameters: `dt`, `substeps`, and `controlFrequencyInv`. - `dt`: The simulation time difference between each simulation step. - `substeps`: The number of physics steps within one simulation step. *i.e.* if `dt: 1/60` and `substeps: 4`, physics is simulated at 240 hz. - `controlFrequencyInv`: The control decimation of the RL policy, which is the number of simulation steps between RL actions. *i.e.* if `dt: 1/60` and `controlFrequencyInv: 2`, RL policy is running at 30 hz. In Isaac Gym Preview Releases, all three of the above parameters are used to specify the frequencies of physics simulation and RL policy. However, Isaac Sim only uses `controlFrequencyInv` and `dt` as `substeps` is always fixed at `1`. Note that despite only using two parameters, Isaac Sim can still achieve the same substeps definition as Isaac Gym. For example, if in an Isaac Gym Preview Release policy, we set `substeps: 2`, `dt: 1/60` and `controlFrequencyInv: 1`, we can achieve the equivalent in Isaac Sim by setting `controlFrequencyInv: 2` and `dt: 1/120`. In the Isaac Sim RL extensions, `dt` is specified in the task configuration `yaml` file under `sim`, whereas `controlFrequencyInv` is a parameter under `env`. #### Physx Parameters Parameters under `physx` in the task configuration `yaml` file remain mostly unchanged. In Isaac Gym Preview Releases, `use_gpu` is frequently set to `${contains:"cuda",${....sim_device}}`. For Isaac Sim, please ensure this is changed to `${eq:${....sim_device},"gpu"}`. In Isaac Gym Preview Releases, GPU buffer sizes are specified using the following two parameters: `default_buffer_size_multiplier` and `max_gpu_contact_pairs`. With the Isaac Sim RL extensions, these two parameters are no longer used; instead, the various GPU buffer sizes can be set explicitly. For instance, in the [Humanoid task configuration file](../omniisaacgymenvs/cfg/task/Humanoid.yaml), GPU buffer sizes are specified as follows: ```yaml gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 8192 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 ``` Please refer to the [Troubleshooting](./troubleshoot.md#simulation) documentation should you encounter errors related to GPU buffer sizes. #### Articulation Parameters The articulation parameters of each actor can now be individually specified tn the Isaac Sim task configuration `yaml` file. The following is an example template for setting these parameters: ```yaml ARTICULATION_NAME: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 10.0 ``` These articulation parameters can be parsed using the `parse_actor_config` method in the [SimConfig](../omniisaacgymenvs/utils/config_utils/sim_config.py) class, which can then be applied to a prim in simulation via the `apply_articulation_settings` method. A concrete example of this is the following code snippet from the [HumanoidTask](../omniisaacgymenvs/tasks/humanoid.py#L75): ```python self._sim_config.apply_articulation_settings("Humanoid", get_prim_at_path(humanoid.prim_path), self._sim_config.parse_actor_config("Humanoid")) ``` #### Additional Simulation Parameters - `use_flatcache`: Setting this paramter to `True` enables [PhysX Flatcache](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html#flatcache), which offers a significant increase in simulation speed. However, this parameter must be set to `False` if soft-body simulation is required because `PhysX Flatcache` curently only supports rigid-body simulation. - `enable_scene_query_support`: Setting this paramter to `True` allows the user to interact with prims in the scene. Keeping this setting to `False` during training improves simulation speed. Note that this parameter is always set to `True` if in test/inference mode to enable user interaction with trained models. ### Training Configuration Files The Omniverse Isaac Gym RL Environments are trained using a third-party highly-optimized RL library, [rl_games](https://github.com/Denys88/rl_games), which is also used to train the Isaac Gym Preview Release examples in [IsaacGymEnvs](https://github.com/NVIDIA-Omniverse/IsaacGymEnvs). Therefore, the rl_games training configuration `yaml` files in Isaac Sim are compatible with those from IsaacGymEnvs. However, please add the following lines under `config` in the training configuration `yaml` files (*i.e.* line 41-42 in [HumanoidPPO.yaml](../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml#L41)) to ensure RL training runs on the intended device. ```yaml device: ${....rl_device} device_name: ${....rl_device} ```
j3soon/OmniIsaacGymEnvs-UR10Reacher/docs/framework.md
## RL Framework ### Overview Our RL examples are built on top of Isaac Sim's RL framework provided in `omni.isaac.gym`. Tasks are implemented following `omni.isaac.core`'s Task structure. PPO training is performed using the [rl_games](https://github.com/Denys88/rl_games) library, but we provide the flexibility to use other RL libraries for training. For a list of examples provided, refer to the [RL List of Examples](rl.md) ### Class Definition We can view the RL ecosystem as three main pieces: the Task, the RL policy, and the Environment wrapper that provides an interface for communication between the task and the RL policy. #### Task The Task class is where main task logic is implemented, such as computing observations and rewards. This is where we can collect states of actors in the scene and apply controls or actions to our actors. For convenience, we provide a base Task class, `RLTask`, which inherits from the `BaseTask` class in `omni.isaac.core`. This class is responsible for dealing with common configuration parsing, buffer initialization, and environment creation. Note that some config parameters and buffers in this class are specific to the rl_games library, and it is not necessary to inherit new tasks from `RLTask`. A few key methods in `RLTask` include: * `__init__(self, name: str, env: VecEnvBase, offset: np.ndarray = None)` - Parses config values common to all tasks and initializes action/observation spaces if not defined in the child class. Defines a GridCloner by default and creates a base USD scope for holding all environment prims. Can be called from child class. * `set_up_scene(self, scene: Scene)` - Adds ground plane and creates clones of environment 0 based on values specifid in config. Can be called from child class `set_up_scene()`. * `pre_physics_step(self, actions: torch.Tensor)` - Takes in actions buffer from RL policy. Can be overriden by child class to process actions. * `post_physics_step(self)` - Controls flow of RL data processing by triggering APIs to compute observations, retrieve states, compute rewards, resets, and extras. Will return observation, reward, reset, and extras buffers. #### Environment Wrappers As part of the RL framework in Isaac Sim, we have introduced environment wrapper classes in `omni.isaac.gym` for RL policies to communicate with simulation in Isaac Sim. This class provides a vectorized interface for common RL APIs used by `gym.Env` and can be easily extended towards RL libraries that require additional APIs. We show an example of this extension process in this repository, where we extend `VecEnvBase` as provided in `omni.isaac.gym` to include additional APIs required by the rl_games library. Commonly used APIs provided by the base wrapper class `VecEnvBase` include: * `render(self, mode: str = "human")` - renders the current frame * `close(self)` - closes the simulator * `seed(self, seed: int = -1)` - sets a seed. Use `-1` for a random seed. * `step(self, actions: Union[np.ndarray, torch.Tensor])` - triggers task `pre_physics_step` with actions, steps simulation and renderer, computes observations, rewards, dones, and returns state buffers * `reset(self)` - triggers task `reset()`, steps simulation, and re-computes observations ##### Multi-Threaded Environment Wrapper `VecEnvBase` is a simple interface that’s designed to provide commonly used `gym.Env` APIs required by RL libraries. Users can create an instance of this class, attach your task to the interface, and provide your wrapper instance to the RL policy. Since the RL algorithm maintains the main loop of execution, interaction with the UI and environments in the scene can be limited and may interfere with the training loop. We also provide another environment wrapper class called `VecEnvMT`, which is designed to isolate the RL policy in a new thread, separate from the main simulation and rendering thread. This class provides the same set of interface as `VecEnvBase`, but also provides threaded queues for sending and receiving actions and states between the RL policy and the task. In order to use this wrapper interface, users have to implement a `TrainerMT` class, which should implement a `run()` method that initiates the RL loop on a new thread. We show an example of this in OmniIsaacGymEnvs under `omniisaacgymenvs/scripts/rlgames_train_mt.py`. The setup for using `VecEnvMT` is more involved compared to the single-threaded `VecEnvBase` interface, but will allow users to have more control over starting and stopping the training loop through interaction with the UI. Note that `VecEnvMT` has a timeout variable, which defaults to 30 seconds. If either the RL thread waiting for physics state exceeds the timeout amount or the simulation thread waiting for RL actions exceeds the timeout amount, the threaded queues will throw an exception and terminate training. For larger scenes that require longer simulation or training time, try increasing the timeout variable in `VecEnvMT` to prevent unnecessary timeouts. This can be done by passing in a `timeout` argument when calling `VecEnvMT.initialize()`. ### Creating New Examples For simplicity, we will focus on using the single-threaded `VecEnvBase` interface in this tutorial. To run any example, first make sure an instance of `VecEnvBase` or descendant of `VecEnvBase` is initialized. This will be required as an argumet to our new Task. For example: ``` python env = VecEnvBase(headless=False) ``` The headless parameter indicates whether a viewer should be created for visualizing results. Then, create our task class, extending it from `RLTask`: ```python class MyNewTask(RLTask): def __init__( self, name: str, # name of the Task sim_config: SimConfig, # SimConfig instance for parsing cfg env: VecEnvBase, # env instance of VecEnvBase or inherited class offset=None # transform offset in World ) -> None: # parse configurations, set task-specific members ... self._num_observations = 4 self._num_actions = 1 # call parent class’s __init__ RLTask.__init__(self, name, env) ``` The `__init__` method should take 4 arguments: * `name`: a string for the name of the task (required by BaseTask) * `sim_config`: an instance of `SimConfig` used for config parsing, can be `None`. This object is created in `omniisaacgymenvs/utils/task_utils.py`. * `env`: an instance of `VecEnvBase` or an inherited class of `VecEnvBase` * `offset`: any offset required to place the `Task` in `World` (required by `BaseTask`) In the `__init__` method of `MyNewTask`, we can populate any task-specific parameters, such as dimension of observations and actions, and retrieve data from config dictionaries. Make sure to make a call to `RLTask`’s `__init__` at the end of the method to perform additional data initialization. Next, we can implement the methods required by the RL framework. These methods follow APIs defined in `omni.isaac.core` `BaseTask` class. Below is an example of a simple implementation for each method. ```python def set_up_scene(self, scene: Scene) -> None: # implement environment setup here add_prim_to_stage(my_robot) # add a robot actor to the stage super().set_up_scene(scene) # pass scene to parent class - this method in RLTask also uses GridCloner to clone the robot and adds a ground plane if desired self._my_robots = ArticulationView(...) # create a view of robots scene.add(self._my_robots) # add view to scene for initialization def post_reset(self): # implement any logic required for simulation on-start here pass def pre_physics_step(self, actions: torch.Tensor) -> None: # implement logic to be performed before physics steps self.perform_reset() self.apply_action(actions) def get_observations(self) -> dict: # implement logic to retrieve observation states self.obs_buf = self.compute_observations() def calculate_metrics(self) -> None: # implement logic to compute rewards self.rew_buf = self.compute_rewards() def is_done(self) -> None: # implement logic to update dones/reset buffer self.reset_buf = self.compute_resets() ``` To launch the new example from one of our training scripts, add `MyNewTask` to `omniisaacgymenvs/utils/task_util.py`. In `initialize_task()`, add an import to the `MyNewTask` class and add an instance to the `task_map` dictionary to register it into the command line parsing. To use the Hydra config parsing system, also add a task and train config files into `omniisaacgymenvs/cfg`. The config files should be named `cfg/task/MyNewTask.yaml` and `cfg/train/MyNewTaskPPO.yaml`. Finally, we can launch `MyNewTask` with: ```bash PYTHON_PATH random_policy.py task=MyNewTask ``` ### Using a New RL Library In this repository, we provide an example of extending Isaac Sim's environment wrapper classes to work with the rl_games library, which can be found at `omniisaacgymenvs/envs/vec_env_rlgames.py` and `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`. The first script, `omniisaacgymenvs/envs/vec_env_rlgames.py`, extends from `VecEnvBase`. ```python from omni.isaac.gym.vec_env import VecEnvBase class VecEnvRLGames(VecEnvBase): ``` One of the features in rl_games is the support for asymmetrical actor-critic policies, which requires a `states` buffer in addition to the `observations` buffer. Thus, we have overriden a few of the class in `VecEnvBase` to incorporate this requirement. ```python def set_task( self, task, backend="numpy", sim_params=None, init_sim=True ) -> None: super().set_task(task, backend, sim_params, init_sim) # class VecEnvBase's set_task to register task to the environment instance # special variables required by rl_games self.num_states = self._task.num_states self.state_space = self._task.state_space def step(self, actions): # we clamp the actions so that values are within a defined range actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone() # pass actions buffer to task for processing self._task.pre_physics_step(actions) # allow users to specify the control frequency through config for _ in range(self._task.control_frequency_inv): self._world.step(render=self._render) self.sim_frame_count += 1 # compute new buffers self._obs, self._rew, self._resets, self._extras = self._task.post_physics_step() self._states = self._task.get_states() # special buffer required by rl_games # return buffers in format required by rl_games obs_dict = {"obs": self._obs, "states": self._states} return obs_dict, self._rew, self._resets, self._extras ``` Similarly, we also have a multi-threaded version of the rl_games environment wrapper implementation, `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`. This class extends from `VecEnvMT` and `VecEnvRLGames`: ```python from omni.isaac.gym.vec_env import VecEnvMT from .vec_env_rlgames import VecEnvRLGames class VecEnvRLGamesMT(VecEnvRLGames, VecEnvMT): ``` In this class, we also have a special method `_parse_data(self, data)`, which is required to be implemented to parse dictionary values passed through queues. Since multiple buffers of data are required by the RL policy, we concatenate all of the buffers in a single dictionary, and send that to the queue to be received by the RL thread. ```python def _parse_data(self, data): self._obs = torch.clamp(data["obs"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone() self._rew = data["rew"].to(self._task.rl_device).clone() self._states = torch.clamp(data["states"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone() self._resets = data["reset"].to(self._task.rl_device).clone() self._extras = data["extras"].copy() ```
j3soon/OmniIsaacGymEnvs-UR10Reacher/isaac_sim-2022.1.1-patch/windows/setup_conda_env.bat
@echo off set CARB_APP_PATH=%~dp0kit set ISAAC_PATH=%~dp0 set EXP_PATH=%~dp0apps call .\setup_python_env.bat
j3soon/OmniIsaacGymEnvs-UR10Reacher/isaac_sim-2022.1.1-patch/linux/setup_python_env.sh
#!/bin/bash # SCRIPT_DIR="$(dirname "${BASH_SOURCE}")" SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$SCRIPT_DIR/../../../$LD_LIBRARY_PATH:$SCRIPT_DIR/.:$SCRIPT_DIR/exts/omni.usd.schema.isaac/bin:$SCRIPT_DIR/exts/omni.isaac.motion_planning/bin:$SCRIPT_DIR/kit:$SCRIPT_DIR/kit/exts/omni.kit.filebrowser_column.tags/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.file/bin:$SCRIPT_DIR/kit/exts/omni.kit.procedural.mesh/bin:$SCRIPT_DIR/kit/exts/omni.kit.primitive.mesh/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.audio/bin:$SCRIPT_DIR/kit/exts/omni.kit.thumbnails.usd/bin:$SCRIPT_DIR/kit/exts/omni.kit.gfn/bin:$SCRIPT_DIR/kit/exts/omni.kit.filebrowser_column.acl/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.console/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.inspector/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.versioning/bin:$SCRIPT_DIR/kit/exts/omni.kit.tool.collect/bin:$SCRIPT_DIR/kit/exts/omni.flowusd/bin:$SCRIPT_DIR/kit/exts/omni.ansel/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.geometry/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.audio.oscilloscope/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.render/bin:$SCRIPT_DIR/kit/exts/omni.mdl.usd_converter/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.material_swap/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.usd_paths/bin:$SCRIPT_DIR/kit/exts/omni.graph/bin:$SCRIPT_DIR/kit/exts/omni.kit.quicklayout/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.usd/bin:$SCRIPT_DIR/kit/exts/omni.rtx.window.settings/bin:$SCRIPT_DIR/kit/exts/omni.kit.menu.edit/bin:$SCRIPT_DIR/kit/exts/omni.graph.tools/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.images/bin:$SCRIPT_DIR/kit/exts/omni.graph.bundle.action/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.transform/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.provide_feedback/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.title/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.popup_dialog/bin:$SCRIPT_DIR/kit/exts/omni.iray.settings.core/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.layer/bin:$SCRIPT_DIR/kit/exts/omni.graph.instancing/bin:$SCRIPT_DIR/kit/exts/omni.kit.viewport_widgets_manager/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.imageview/bin:$SCRIPT_DIR/kit/exts/omni.kit.livestream.native/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.audioplayer/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.filebrowser/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.tests/bin:$SCRIPT_DIR/kit/exts/omni.graph.core/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.preferences/bin:$SCRIPT_DIR/kit/exts/omni.kit.numpy.common/bin:$SCRIPT_DIR/kit/exts/omni.kit.audio.test.usd/bin:$SCRIPT_DIR/kit/exts/omni.graph.test/bin:$SCRIPT_DIR/kit/exts/omni.kit.menu.aov/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.file_importer/bin:$SCRIPT_DIR/kit/exts/omni.rtx.multinode.dev/bin:$SCRIPT_DIR/kit/exts/omni.kit.menu.common/bin:$SCRIPT_DIR/kit/exts/omni.resourcemonitor/bin:$SCRIPT_DIR/kit/exts/omni.graph.ui/bin:$SCRIPT_DIR/kit/exts/omni.kit.compatibility_checker/bin:$SCRIPT_DIR/kit/exts/omni.kit.selection/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.property/bin:$SCRIPT_DIR/kit/exts/omni.kit.viewport.utility/bin:$SCRIPT_DIR/kit/exts/omni.hydra.pxr.settings/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.filepicker/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.browser_bar/bin:$SCRIPT_DIR/kit/exts/omni.kit.telemetry/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.stage/bin:$SCRIPT_DIR/kit/exts/omni.kit.debug.python/bin:$SCRIPT_DIR/kit/exts/omni.graph.action/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.inspector/bin:$SCRIPT_DIR/kit/exts/omni.graph.examples.cpp/bin:$SCRIPT_DIR/kit/exts/omni.example.ui/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.drop_support/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.light/bin:$SCRIPT_DIR/kit/exts/omni.kit.documentation.builder/bin:$SCRIPT_DIR/kit/exts/omni.kit.stage.mdl_converter/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.live/bin:$SCRIPT_DIR/kit/exts/omni.kit.collaboration.channel_manager/bin:$SCRIPT_DIR/kit/exts/omni.graph.tutorials/bin:$SCRIPT_DIR/kit/exts/omni.graph.io/bin:$SCRIPT_DIR/kit/exts/omni.kit.audiodeviceenum/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.stage/bin:$SCRIPT_DIR/kit/exts/omni.kit.viewport.legacy_gizmos/bin:$SCRIPT_DIR/kit/exts/omni.kit.collaboration.viewport.camera/bin:$SCRIPT_DIR/kit/exts/omni.rtx.settings.core/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.settings/bin:$SCRIPT_DIR/kit/exts/omni.kit.livestream.webrtc/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.fast_search/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.stage_icons/bin:$SCRIPT_DIR/kit/exts/omni.kit.search_core/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.imageviewer/bin:$SCRIPT_DIR/kit/exts/omni.kit.stage_templates/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.toolbar/bin:$SCRIPT_DIR/kit/exts/omni.volume/bin:$SCRIPT_DIR/kit/exts/omni.graph.scriptnode/bin:$SCRIPT_DIR/kit/exts/omni.kit.search_example/bin:$SCRIPT_DIR/kit/exts/omni.uiaudio/bin:$SCRIPT_DIR/kit/exts/omni.command.usd/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.stageviewer/bin:$SCRIPT_DIR/kit/exts/omni.rtx.tests/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.graph/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.commands/bin:$SCRIPT_DIR/kit/exts/omni.kit.viewport.ready/bin:$SCRIPT_DIR/kit/exts/omni.kit.hydra_texture/bin:$SCRIPT_DIR/kit/exts/omni.kit.usda_edit/bin:$SCRIPT_DIR/kit/exts/omni.kit.stage.copypaste/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.skel/bin:$SCRIPT_DIR/kit/exts/omni.graph.expression/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.content_browser/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.script_editor/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.splash_close_example/bin:$SCRIPT_DIR/kit/exts/omni.videoencoding/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.extensions/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.tagging/bin:$SCRIPT_DIR/kit/exts/omni.kit.debug.vscode/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.layers/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.path_field/bin:$SCRIPT_DIR/kit/exts/omni.audiorecorder/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.file_exporter/bin:$SCRIPT_DIR/kit/exts/omni.threadtime-tracker.dev/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.status_bar/bin:$SCRIPT_DIR/kit/exts/omni.kit.search.service/bin:$SCRIPT_DIR/kit/exts/omni.audioplayer/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.stream_viewport/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.about/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.bundle/bin:$SCRIPT_DIR/kit/exts/omni.kit.tagging/bin:$SCRIPT_DIR/kit/exts/omni.kit.menu.file/bin:$SCRIPT_DIR/kit/exts/omni.graph.examples.python/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.camera/bin:$SCRIPT_DIR/kit/exts/omni.inspect/bin:$SCRIPT_DIR/kit/exts/omni.kit.example.toolbar_button/bin:$SCRIPT_DIR/kit/exts/omni.kit.widget.prompt/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.cursor/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.stats/bin:$SCRIPT_DIR/kit/exts/omni.graph.nodes/bin:$SCRIPT_DIR/kit/exts/omni.debugdraw/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.material/bin:$SCRIPT_DIR/kit/exts/omni.kit.notification_manager/bin:$SCRIPT_DIR/kit/exts/omni.kit.window.audiorecorder/bin:$SCRIPT_DIR/kit/exts/omni.kit.agent.watcher/bin:$SCRIPT_DIR/kit/exts/omni.kit.property.file/bin:$SCRIPT_DIR/kit/exts/omni.kit.multinode/bin:$SCRIPT_DIR/kit/exts/omni.kit.embedded_script/bin:$SCRIPT_DIR/kit/exts/omni.kit.capture/bin:$SCRIPT_DIR/kit/extscore/omni.stats/bin:$SCRIPT_DIR/kit/extscore/omni.kit.pipapi/bin:$SCRIPT_DIR/kit/extscore/omni.timeline/bin:$SCRIPT_DIR/kit/extscore/omni.kit.agent/bin:$SCRIPT_DIR/kit/extscore/omni.hydra.ui/bin:$SCRIPT_DIR/kit/extscore/omni.appwindow/bin:$SCRIPT_DIR/kit/extscore/omni.usd.schema.physics/bin:$SCRIPT_DIR/kit/extscore/omni.usd.libs/bin:$SCRIPT_DIR/kit/extscore/omni.kit.test_app_compat/bin:$SCRIPT_DIR/kit/extscore/omni.kit.registry.nucleus/bin:$SCRIPT_DIR/kit/extscore/omni.ui_query/bin:$SCRIPT_DIR/kit/extscore/omni.hydra.rtx/bin:$SCRIPT_DIR/kit/extscore/omni.usd.schema.omnigraph/bin:$SCRIPT_DIR/kit/extscore/omni.kit.loop-default/bin:$SCRIPT_DIR/kit/extscore/omni.kit.uiapp/bin:$SCRIPT_DIR/kit/extscore/omni.kit.autocapture/bin:$SCRIPT_DIR/kit/extscore/omni.assets.plugins/bin:$SCRIPT_DIR/kit/extscore/omni.kit.test/bin:$SCRIPT_DIR/kit/extscore/omni.hydra.iray/bin:$SCRIPT_DIR/kit/extscore/omni.usd/bin:$SCRIPT_DIR/kit/extscore/omni.kit.core.tests/bin:$SCRIPT_DIR/kit/extscore/omni.usd.schema.semantics/bin:$SCRIPT_DIR/kit/extscore/omni.kit.profile_python/bin:$SCRIPT_DIR/kit/extscore/omni.kit.ui_test/bin:$SCRIPT_DIR/kit/extscore/omni.kit.menu.utils/bin:$SCRIPT_DIR/kit/extscore/omni.client/bin:$SCRIPT_DIR/kit/extscore/omni.mdl.neuraylib/bin:$SCRIPT_DIR/kit/extscore/omni.kit.test_async_rendering/bin:$SCRIPT_DIR/kit/extscore/omni.gpu_foundation/bin:$SCRIPT_DIR/kit/extscore/omni.kit.extpath.git/bin:$SCRIPT_DIR/kit/extscore/omni.hydra.engine.stats/bin:$SCRIPT_DIR/kit/extscore/omni.kit.renderer.init/bin:$SCRIPT_DIR/kit/extscore/omni.kit.test_helpers_gfx/bin:$SCRIPT_DIR/kit/extscore/omni.ui/bin:$SCRIPT_DIR/kit/extscore/omni.kit.livestream.core/bin:$SCRIPT_DIR/kit/extscore/omni.kit.renderer.core/bin:$SCRIPT_DIR/kit/extscore/omni.syntheticdata/bin:$SCRIPT_DIR/kit/extscore/omni.usd.schema.audio/bin:$SCRIPT_DIR/kit/extscore/omni.kit.app_snippets/bin:$SCRIPT_DIR/kit/extscore/omni.hydra.pxr/bin:$SCRIPT_DIR/kit/extscore/omni.hydra.scene_delegate/bin:$SCRIPT_DIR/kit/extscore/omni.kit.splash/bin:$SCRIPT_DIR/kit/extscore/omni.hydra.scene_api/bin:$SCRIPT_DIR/kit/extscore/carb.windowing.plugins/bin:$SCRIPT_DIR/kit/extscore/omni.kit.window.splash/bin:$SCRIPT_DIR/kit/extscore/omni.kit.commands/bin:$SCRIPT_DIR/kit/extscore/omni.kit.material.library/bin:$SCRIPT_DIR/kit/extscore/omni.kit.streamsdk.plugins/bin:$SCRIPT_DIR/kit/extscore/omni.kit.usd_undo/bin:$SCRIPT_DIR/kit/extscore/omni.kit.window.privacy/bin:$SCRIPT_DIR/kit/extscore/omni.kit.pip_archive/bin:$SCRIPT_DIR/kit/extscore/omni.kit.menu.create/bin:$SCRIPT_DIR/kit/extscore/omni.assets/bin:$SCRIPT_DIR/kit/extscore/omni.kit.mainwindow/bin:$SCRIPT_DIR/kit/extscore/omni.kit.console/bin:$SCRIPT_DIR/kit/extscore/omni.usd.config/bin:$SCRIPT_DIR/kit/extscore/omni.usd.schema.anim/bin:$SCRIPT_DIR/kit/extscore/omni.kit.context_menu/bin:$SCRIPT_DIR/kit/extscore/carb.audio/bin:$SCRIPT_DIR/kit/extscore/omni.renderer-rtx/bin:$SCRIPT_DIR/kit/extscore/omni.kit.window.viewport/bin:$SCRIPT_DIR/kit/extscore/omni.kit.async_engine/bin:$SCRIPT_DIR/kit/extscore/omni.kit.renderer.capture/bin:$SCRIPT_DIR/kit/extscore/omni.ui.scene/bin:$SCRIPT_DIR/kit/extscore/omni.mdl/bin:$SCRIPT_DIR/kit/extscore/omni.kit.test_suite.helpers/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.cct-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.usd.schema.physx/bin:$SCRIPT_DIR/kit/extsPhysics/omni.localcache/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.camera.tests-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.usd.schema.physics/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.preview-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.blockworld-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.kvdb/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.ui-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.bundle-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.tests.visual-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.kit.property.physx/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.vehicle-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.zerogravity.tests-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.forcefields-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.camera-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.tests-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.usd.schema.forcefield/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.tensors-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.usdphysics.tests-1.4.15/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.demos-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.vehicle.tests-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.pvd-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.flatcache-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.zerogravity-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.convexdecomposition-1.4.15/bin:$SCRIPT_DIR/kit/extsPhysics/omni.usdphysics-1.4.15/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physx.commands-1.4.15-5.1/bin:$SCRIPT_DIR/kit/extsPhysics/omni.physics.tensors-1.4.15-5.1/bin:$SCRIPT_DIR/kit/libs/iray:$SCRIPT_DIR/kit/plugins:$SCRIPT_DIR/kit/plugins/bindings-python:$SCRIPT_DIR/kit/plugins/carb_gfx:$SCRIPT_DIR/kit/plugins/rtx:$SCRIPT_DIR/kit/extensions/extensions-bundled/bin export PYTHONPATH=$PYTHONPATH:$SCRIPT_DIR/../../../$PYTHONPATH:$SCRIPT_DIR/exts/omni.isaac.motion_generation:$SCRIPT_DIR/exts/omni.isaac.motion_planning:$SCRIPT_DIR/exts/omni.isaac.core_archive:$SCRIPT_DIR/exts/omni.isaac.dynamic_control:$SCRIPT_DIR/exts/omni.isaac.core:$SCRIPT_DIR/exts/omni.isaac.statistics_logging:$SCRIPT_DIR/exts/omni.isaac.assets_check:$SCRIPT_DIR/exts/omni.isaac.ros2_bridge:$SCRIPT_DIR/exts/omni.isaac.universal_robots:$SCRIPT_DIR/exts/omni.isaac.internal_tools:$SCRIPT_DIR/exts/omni.isaac.cortex:$SCRIPT_DIR/exts/omni.usd.schema.isaac:$SCRIPT_DIR/exts/omni.isaac.dofbot:$SCRIPT_DIR/exts/omni.replicator.isaac:$SCRIPT_DIR/exts/omni.isaac.ros_bridge:$SCRIPT_DIR/exts/omni.isaac.articulation_inspector:$SCRIPT_DIR/exts/omni.isaac.asset_browser:$SCRIPT_DIR/exts/omni.isaac.manipulators:$SCRIPT_DIR/exts/omni.isaac.mjcf:$SCRIPT_DIR/exts/omni.isaac.benchmark_environments:$SCRIPT_DIR/exts/omni.isaac.isaac_sensor:$SCRIPT_DIR/exts/omni.isaac.gain_tuner:$SCRIPT_DIR/exts/omni.isaac.physics_utilities:$SCRIPT_DIR/exts/omni.isaac.repl:$SCRIPT_DIR/exts/omni.isaac.franka:$SCRIPT_DIR/exts/omni.isaac.lula:$SCRIPT_DIR/exts/omni.isaac.synthetic_utils:$SCRIPT_DIR/exts/omni.isaac.ml_archive:$SCRIPT_DIR/exts/omni.isaac.cloner:$SCRIPT_DIR/exts/omni.isaac.unit_converter:$SCRIPT_DIR/exts/omni.isaac.demos:$SCRIPT_DIR/exts/omni.isaac.window.about:$SCRIPT_DIR/exts/omni.isaac.range_sensor:$SCRIPT_DIR/exts/omni.isaac.shapenet:$SCRIPT_DIR/exts/omni.kit.property.isaac:$SCRIPT_DIR/exts/omni.isaac.app.setup:$SCRIPT_DIR/exts/omni.isaac.wheeled_robots:$SCRIPT_DIR/exts/omni.isaac.examples:$SCRIPT_DIR/exts/omni.isaac.proximity_sensor:$SCRIPT_DIR/exts/omni.isaac.splash:$SCRIPT_DIR/exts/omni.isaac.urdf:$SCRIPT_DIR/exts/omni.isaac.occupancy_map:$SCRIPT_DIR/exts/omni.isaac.synthetic_recorder:$SCRIPT_DIR/exts/omni.isaac.ui_template:$SCRIPT_DIR/exts/omni.isaac.app.selector:$SCRIPT_DIR/exts/omni.isaac.core_nodes:$SCRIPT_DIR/exts/omni.isaac.onshape:$SCRIPT_DIR/exts/omni.isaac.tests:$SCRIPT_DIR/exts/omni.isaac.quadruped:$SCRIPT_DIR/exts/omni.kit.loop-isaac:$SCRIPT_DIR/exts/omni.drivesim.sensors.nv.lidar:$SCRIPT_DIR/exts/omni.isaac.version:$SCRIPT_DIR/exts/omni.isaac.surface_gripper:$SCRIPT_DIR/exts/omni.isaac.diff_usd:$SCRIPT_DIR/exts/omni.isaac.ui:$SCRIPT_DIR/exts/omni.isaac.kit:$SCRIPT_DIR/exts/omni.isaac.gym:$SCRIPT_DIR/exts/omni.isaac.partition:$SCRIPT_DIR/exts/omni.isaac.robot_benchmark:$SCRIPT_DIR/exts/omni.isaac.physics_inspector:$SCRIPT_DIR/exts/omni.isaac.conveyor:$SCRIPT_DIR/exts/omni.isaac.merge_mesh:$SCRIPT_DIR/exts/omni.isaac.utils:$SCRIPT_DIR/exts/omni.isaac.debug_draw:$SCRIPT_DIR/kit/exts/omni.kit.filebrowser_column.tags:$SCRIPT_DIR/kit/exts/omni.kit.window.file:$SCRIPT_DIR/kit/exts/omni.kit.procedural.mesh:$SCRIPT_DIR/kit/exts/omni.kit.primitive.mesh:$SCRIPT_DIR/kit/exts/omni.kit.property.audio:$SCRIPT_DIR/kit/exts/omni.kit.thumbnails.usd:$SCRIPT_DIR/kit/exts/omni.kit.gfn:$SCRIPT_DIR/kit/exts/omni.kit.filebrowser_column.acl:$SCRIPT_DIR/kit/exts/omni.kit.window.console:$SCRIPT_DIR/kit/exts/omni.kit.widget.inspector:$SCRIPT_DIR/kit/exts/omni.kit.widget.versioning:$SCRIPT_DIR/kit/exts/omni.kit.tool.collect:$SCRIPT_DIR/kit/exts/omni.flowusd:$SCRIPT_DIR/kit/exts/omni.ansel:$SCRIPT_DIR/kit/exts/omni.kit.property.geometry:$SCRIPT_DIR/kit/exts/omni.kit.window.audio.oscilloscope:$SCRIPT_DIR/kit/exts/omni.kit.property.render:$SCRIPT_DIR/kit/exts/omni.mdl.usd_converter:$SCRIPT_DIR/kit/exts/omni.kit.window.material_swap:$SCRIPT_DIR/kit/exts/omni.kit.window.usd_paths:$SCRIPT_DIR/kit/exts/omni.graph:$SCRIPT_DIR/kit/exts/omni.kit.quicklayout:$SCRIPT_DIR/kit/exts/omni.kit.property.usd:$SCRIPT_DIR/kit/exts/omni.rtx.window.settings:$SCRIPT_DIR/kit/exts/omni.kit.menu.edit:$SCRIPT_DIR/kit/exts/omni.graph.tools:$SCRIPT_DIR/kit/exts/omni.kit.window.images:$SCRIPT_DIR/kit/exts/omni.graph.bundle.action:$SCRIPT_DIR/kit/exts/omni.kit.property.transform:$SCRIPT_DIR/kit/exts/omni.kit.window.provide_feedback:$SCRIPT_DIR/kit/exts/omni.kit.window.title:$SCRIPT_DIR/kit/exts/omni.kit.window.popup_dialog:$SCRIPT_DIR/kit/exts/omni.iray.settings.core:$SCRIPT_DIR/kit/exts/omni.kit.property.layer:$SCRIPT_DIR/kit/exts/omni.graph.instancing:$SCRIPT_DIR/kit/exts/omni.kit.viewport_widgets_manager:$SCRIPT_DIR/kit/exts/omni.kit.widget.imageview:$SCRIPT_DIR/kit/exts/omni.kit.livestream.native:$SCRIPT_DIR/kit/exts/omni.kit.window.audioplayer:$SCRIPT_DIR/kit/exts/omni.kit.widget.filebrowser:$SCRIPT_DIR/kit/exts/omni.kit.window.tests:$SCRIPT_DIR/kit/exts/omni.graph.core:$SCRIPT_DIR/kit/exts/omni.kit.window.preferences:$SCRIPT_DIR/kit/exts/omni.kit.numpy.common:$SCRIPT_DIR/kit/exts/omni.kit.audio.test.usd:$SCRIPT_DIR/kit/exts/omni.graph.test:$SCRIPT_DIR/kit/exts/omni.kit.menu.aov:$SCRIPT_DIR/kit/exts/omni.kit.window.file_importer:$SCRIPT_DIR/kit/exts/omni.rtx.multinode.dev:$SCRIPT_DIR/kit/exts/omni.kit.menu.common:$SCRIPT_DIR/kit/exts/omni.resourcemonitor:$SCRIPT_DIR/kit/exts/omni.graph.ui:$SCRIPT_DIR/kit/exts/omni.kit.compatibility_checker:$SCRIPT_DIR/kit/exts/omni.kit.selection:$SCRIPT_DIR/kit/exts/omni.kit.window.property:$SCRIPT_DIR/kit/exts/omni.kit.viewport.utility:$SCRIPT_DIR/kit/exts/omni.hydra.pxr.settings:$SCRIPT_DIR/kit/exts/omni.kit.window.filepicker:$SCRIPT_DIR/kit/exts/omni.kit.widget.browser_bar:$SCRIPT_DIR/kit/exts/omni.kit.telemetry:$SCRIPT_DIR/kit/exts/omni.kit.widget.stage:$SCRIPT_DIR/kit/exts/omni.kit.debug.python:$SCRIPT_DIR/kit/exts/omni.graph.action:$SCRIPT_DIR/kit/exts/omni.kit.window.inspector:$SCRIPT_DIR/kit/exts/omni.graph.examples.cpp:$SCRIPT_DIR/kit/exts/omni.example.ui:$SCRIPT_DIR/kit/exts/omni.kit.window.drop_support:$SCRIPT_DIR/kit/exts/omni.kit.property.light:$SCRIPT_DIR/kit/exts/omni.kit.documentation.builder:$SCRIPT_DIR/kit/exts/omni.kit.stage.mdl_converter:$SCRIPT_DIR/kit/exts/omni.kit.widget.live:$SCRIPT_DIR/kit/exts/omni.kit.collaboration.channel_manager:$SCRIPT_DIR/kit/exts/omni.graph.tutorials:$SCRIPT_DIR/kit/exts/omni.graph.io:$SCRIPT_DIR/kit/exts/omni.kit.audiodeviceenum:$SCRIPT_DIR/kit/exts/omni.kit.window.stage:$SCRIPT_DIR/kit/exts/omni.kit.viewport.legacy_gizmos:$SCRIPT_DIR/kit/exts/omni.kit.collaboration.viewport.camera:$SCRIPT_DIR/kit/exts/omni.rtx.settings.core:$SCRIPT_DIR/kit/exts/omni.kit.widget.settings:$SCRIPT_DIR/kit/exts/omni.kit.livestream.webrtc:$SCRIPT_DIR/kit/exts/omni.kit.widget.fast_search:$SCRIPT_DIR/kit/exts/omni.kit.widget.stage_icons:$SCRIPT_DIR/kit/exts/omni.kit.search_core:$SCRIPT_DIR/kit/exts/omni.kit.window.imageviewer:$SCRIPT_DIR/kit/exts/omni.kit.stage_templates:$SCRIPT_DIR/kit/exts/omni.kit.window.toolbar:$SCRIPT_DIR/kit/exts/omni.volume:$SCRIPT_DIR/kit/exts/omni.graph.scriptnode:$SCRIPT_DIR/kit/exts/omni.kit.search_example:$SCRIPT_DIR/kit/exts/omni.uiaudio:$SCRIPT_DIR/kit/exts/omni.command.usd:$SCRIPT_DIR/kit/exts/omni.kit.window.stageviewer:$SCRIPT_DIR/kit/exts/omni.rtx.tests:$SCRIPT_DIR/kit/exts/omni.kit.widget.graph:$SCRIPT_DIR/kit/exts/omni.kit.window.commands:$SCRIPT_DIR/kit/exts/omni.kit.viewport.ready:$SCRIPT_DIR/kit/exts/omni.kit.hydra_texture:$SCRIPT_DIR/kit/exts/omni.kit.usda_edit:$SCRIPT_DIR/kit/exts/omni.kit.stage.copypaste:$SCRIPT_DIR/kit/exts/omni.kit.property.skel:$SCRIPT_DIR/kit/exts/omni.graph.expression:$SCRIPT_DIR/kit/exts/omni.kit.window.content_browser:$SCRIPT_DIR/kit/exts/omni.kit.window.script_editor:$SCRIPT_DIR/kit/exts/omni.kit.window.splash_close_example:$SCRIPT_DIR/kit/exts/omni.videoencoding:$SCRIPT_DIR/kit/exts/omni.kit.window.extensions:$SCRIPT_DIR/kit/exts/omni.kit.property.tagging:$SCRIPT_DIR/kit/exts/omni.kit.debug.vscode:$SCRIPT_DIR/kit/exts/omni.kit.widget.layers:$SCRIPT_DIR/kit/exts/omni.kit.widget.path_field:$SCRIPT_DIR/kit/exts/omni.audiorecorder:$SCRIPT_DIR/kit/exts/omni.kit.window.file_exporter:$SCRIPT_DIR/kit/exts/omni.threadtime-tracker.dev:$SCRIPT_DIR/kit/exts/omni.kit.window.status_bar:$SCRIPT_DIR/kit/exts/omni.kit.search.service:$SCRIPT_DIR/kit/exts/omni.audioplayer:$SCRIPT_DIR/kit/exts/omni.kit.window.stream_viewport:$SCRIPT_DIR/kit/exts/omni.kit.window.about:$SCRIPT_DIR/kit/exts/omni.kit.property.bundle:$SCRIPT_DIR/kit/exts/omni.kit.tagging:$SCRIPT_DIR/kit/exts/omni.kit.menu.file:$SCRIPT_DIR/kit/exts/omni.graph.examples.python:$SCRIPT_DIR/kit/exts/omni.kit.property.camera:$SCRIPT_DIR/kit/exts/omni.inspect:$SCRIPT_DIR/kit/exts/omni.kit.example.toolbar_button:$SCRIPT_DIR/kit/exts/omni.kit.widget.prompt:$SCRIPT_DIR/kit/exts/omni.kit.window.cursor:$SCRIPT_DIR/kit/exts/omni.kit.window.stats:$SCRIPT_DIR/kit/exts/omni.graph.nodes:$SCRIPT_DIR/kit/exts/omni.debugdraw:$SCRIPT_DIR/kit/exts/omni.kit.property.material:$SCRIPT_DIR/kit/exts/omni.kit.notification_manager:$SCRIPT_DIR/kit/exts/omni.kit.window.audiorecorder:$SCRIPT_DIR/kit/exts/omni.kit.agent.watcher:$SCRIPT_DIR/kit/exts/omni.kit.property.file:$SCRIPT_DIR/kit/exts/omni.kit.multinode:$SCRIPT_DIR/kit/exts/omni.kit.embedded_script:$SCRIPT_DIR/kit/exts/omni.kit.capture:$SCRIPT_DIR/kit/extscore/omni.stats:$SCRIPT_DIR/kit/extscore/omni.kit.pipapi:$SCRIPT_DIR/kit/extscore/omni.timeline:$SCRIPT_DIR/kit/extscore/omni.kit.agent:$SCRIPT_DIR/kit/extscore/omni.hydra.ui:$SCRIPT_DIR/kit/extscore/omni.appwindow:$SCRIPT_DIR/kit/extscore/omni.usd.schema.physics:$SCRIPT_DIR/kit/extscore/omni.usd.libs:$SCRIPT_DIR/kit/extscore/omni.kit.test_app_compat:$SCRIPT_DIR/kit/extscore/omni.kit.registry.nucleus:$SCRIPT_DIR/kit/extscore/omni.ui_query:$SCRIPT_DIR/kit/extscore/omni.hydra.rtx:$SCRIPT_DIR/kit/extscore/omni.usd.schema.omnigraph:$SCRIPT_DIR/kit/extscore/omni.kit.loop-default:$SCRIPT_DIR/kit/extscore/omni.kit.uiapp:$SCRIPT_DIR/kit/extscore/omni.kit.autocapture:$SCRIPT_DIR/kit/extscore/omni.assets.plugins:$SCRIPT_DIR/kit/extscore/omni.kit.test:$SCRIPT_DIR/kit/extscore/omni.hydra.iray:$SCRIPT_DIR/kit/extscore/omni.usd:$SCRIPT_DIR/kit/extscore/omni.kit.core.tests:$SCRIPT_DIR/kit/extscore/omni.usd.schema.semantics:$SCRIPT_DIR/kit/extscore/omni.kit.profile_python:$SCRIPT_DIR/kit/extscore/omni.kit.ui_test:$SCRIPT_DIR/kit/extscore/omni.kit.menu.utils:$SCRIPT_DIR/kit/extscore/omni.client:$SCRIPT_DIR/kit/extscore/omni.mdl.neuraylib:$SCRIPT_DIR/kit/extscore/omni.kit.test_async_rendering:$SCRIPT_DIR/kit/extscore/omni.gpu_foundation:$SCRIPT_DIR/kit/extscore/omni.kit.extpath.git:$SCRIPT_DIR/kit/extscore/omni.hydra.engine.stats:$SCRIPT_DIR/kit/extscore/omni.kit.renderer.init:$SCRIPT_DIR/kit/extscore/omni.kit.test_helpers_gfx:$SCRIPT_DIR/kit/extscore/omni.ui:$SCRIPT_DIR/kit/extscore/omni.kit.livestream.core:$SCRIPT_DIR/kit/extscore/omni.kit.renderer.core:$SCRIPT_DIR/kit/extscore/omni.syntheticdata:$SCRIPT_DIR/kit/extscore/omni.usd.schema.audio:$SCRIPT_DIR/kit/extscore/omni.kit.app_snippets:$SCRIPT_DIR/kit/extscore/omni.hydra.pxr:$SCRIPT_DIR/kit/extscore/omni.hydra.scene_delegate:$SCRIPT_DIR/kit/extscore/omni.kit.splash:$SCRIPT_DIR/kit/extscore/omni.hydra.scene_api:$SCRIPT_DIR/kit/extscore/carb.windowing.plugins:$SCRIPT_DIR/kit/extscore/omni.kit.window.splash:$SCRIPT_DIR/kit/extscore/omni.kit.commands:$SCRIPT_DIR/kit/extscore/omni.kit.material.library:$SCRIPT_DIR/kit/extscore/omni.kit.streamsdk.plugins:$SCRIPT_DIR/kit/extscore/omni.kit.usd_undo:$SCRIPT_DIR/kit/extscore/omni.kit.window.privacy:$SCRIPT_DIR/kit/extscore/omni.kit.pip_archive:$SCRIPT_DIR/kit/extscore/omni.kit.menu.create:$SCRIPT_DIR/kit/extscore/omni.assets:$SCRIPT_DIR/kit/extscore/omni.kit.mainwindow:$SCRIPT_DIR/kit/extscore/omni.kit.console:$SCRIPT_DIR/kit/extscore/omni.usd.config:$SCRIPT_DIR/kit/extscore/omni.usd.schema.anim:$SCRIPT_DIR/kit/extscore/omni.kit.context_menu:$SCRIPT_DIR/kit/extscore/carb.audio:$SCRIPT_DIR/kit/extscore/omni.renderer-rtx:$SCRIPT_DIR/kit/extscore/omni.kit.window.viewport:$SCRIPT_DIR/kit/extscore/omni.kit.async_engine:$SCRIPT_DIR/kit/extscore/omni.kit.renderer.capture:$SCRIPT_DIR/kit/extscore/omni.ui.scene:$SCRIPT_DIR/kit/extscore/omni.mdl:$SCRIPT_DIR/kit/extscore/omni.kit.test_suite.helpers:$SCRIPT_DIR/kit/extensions/extensions-bundled:$SCRIPT_DIR/kit/plugins/bindings-python:$SCRIPT_DIR/kit/extscore/omni.kit.pip_archive/pip_prebundle:$SCRIPT_DIR/exts/omni.isaac.core_archive/pip_prebundle:$SCRIPT_DIR/exts/omni.isaac.ml_archive/pip_prebundle:$SCRIPT_DIR/exts/omni.kit.pip_torch-1_11_0-0.1.3+103.1.wx64.cp37/torch-1-11-0:$SCRIPT_DIR/exts/omni.kit.pip_torch-1_11_0-0.1.3+103.1.lx64.cp37/torch-1-11-0
timedomain-tech/Timedomain-Ai-Singer-Extension/link_app.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) cd "$SCRIPT_DIR" exec "tools/packman/python.sh" tools/scripts/link_app.py $@
timedomain-tech/Timedomain-Ai-Singer-Extension/link_app.bat
@echo off call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %* if %errorlevel% neq 0 ( goto Error ) :Success exit /b 0 :Error exit /b %errorlevel%
timedomain-tech/Timedomain-Ai-Singer-Extension/README.md
# Abstract Timedomain AI Singer Omniverse Extension is a convenient tool for singing synthesis on the Omniverse platform. FEATURES: - Create lifelike human singing voices with one click - Choose from a rich variety of voice library - Mix up to 10 singer voices to create your own singing - Support utafomatix file which can be converted from almost all kinds of singing score format <img src="./image/demo.gif"> # About TimedomAIn is a technology company that focuses on AI. We aim to make AI meet the emotional needs of human beings and endow AI with the ability to express emotion through “Rich-Emotion” human voice synthesis technology. # Get started ## Add extension to Omniverse 1. **[Open extension manager]** After opening Omniverse Code, go to `Menu` -> `Window` -> `Extension` 2. **[Add this extension to Omniverse]** Click the <img src="https://github.githubassets.com/images/icons/emoji/unicode/2699.png?v8" width="18"> button and add absolute extension path to `Extension Search Paths`. Finally, you can search `timedomain.ai.singer` and enable this extension. > **Note**: > the extension path to add is: `<your-path-to-timedomain-ai-singer>/exts` ![add_extension](./image/picture_6.png) 3. **[We also need to add some dependencies]** Click the <img src="https://github.githubassets.com/images/icons/emoji/unicode/2699.png?v8" width="18"> button and add absolute extension path to `Extension Registries`. > **Note**: > the extension registries to add is: `omniverse://kit-extensions.ov.nvidia.com/exts/kit/default` ![add_registries](./image/picture_7.png) ## Usage Click the file button on the right to open the directory selection window, select the directory and the path will be displayed in the box. You can also paste the directory path directly to the display box. <img src="./image/picture_1.png"> Currently, only utafomatix files are available, and more file formats will be supported in the future. <img src="./image/picture_2.png"> > **Note**: > the duration of the score must within 10 minutes > **Note**: > only the first track of the score will be synthesised Once you have your score chosen, you can select a singer voice or mix singer voices: > **Note**: > up to 10 singer voices can be used for mixing <img src="./image/picture_5.png"> Click "add" button to add a singer voice, move the slider (from 0 to 1) to adjust the similarity between the synthesis result and the chosen singer voice Finally, click "synthesis" button to send the request, the button will change to loading state when the request is being processed. <img src="./image/picture_3.png"> <img src="./image/picture_4.png"> > **Note**: > the frequency of the synthesis request is limited to 4 per minute > **Note**: > The synthesis time will increase according to the score duration
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" export PYTHONNOUSERSITE=1 # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" -u "$@"
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/python.bat
:: Copyright 2019-2020 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. @echo off setlocal call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" set PYTHONNOUSERSITE=1 "%PM_PYTHON%" -u %*
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/packman.cmd
:: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx] @call :ECHO_AND_RESET_ERROR :: You can remove the call below if you do your own manual configuration of the dev machines call "%~dp0\bootstrap\configure.bat" if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR :: Generate temporary path for variable file for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^ -File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a if %1.==. ( set PM_VAR_PATH_ARG= ) else ( set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" ) "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/bootstrap/generate_temp_file_name.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf # 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0 # IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg # U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow # gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT # YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL # DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI # hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP # YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH # jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa # HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj # 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU # z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w # ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF # BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v # ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j # b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk # MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB # BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw # AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB # AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr # K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk # fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3 # SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz # D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla # ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo # MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp # Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV # BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl # IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj # YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow # gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf # MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50 # ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG # SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp # NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t # HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p # XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP # fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg # mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4 # MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk # LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH # FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB # BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg # J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE # DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY # BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh # uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG # 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x # +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt # nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN # xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0 # vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0 # 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw # CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV # BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs # YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK # 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN # AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw # LwYJKoZIhvcNAQkEMSIEIPW+EpFrZSdzrjFFo0UT+PzFeYn/GcWNyWFaU/JMrMfR # MA0GCSqGSIb3DQEBAQUABIIBAA8fmU/RJcF9t60DZZAjf8FB3EZddOaHgI9z40nV # CnfTGi0OEYU48Pe9jkQQV2fABpACfW74xmNv3QNgP2qP++mkpKBVv28EIAuINsFt # YAITEljLN/VOVul8lvjxar5GSFFgpE5F6j4xcvI69LuCWbN8cteTVsBGg+eGmjfx # QZxP252z3FqPN+mihtFegF2wx6Mg6/8jZjkO0xjBOwSdpTL4uyQfHvaPBKXuWxRx # ioXw4ezGAwkuBoxWK8UG7Qu+7CSfQ3wMOjvyH2+qn30lWEsvRMdbGAp7kvfr3EGZ # a3WN7zXZ+6KyZeLeEH7yCDzukAjptaY/+iLVjJsuzC6tCSqhgg1EMIINQAYKKwYB # BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl # AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg # hkgBZQMEAgEFAAQg14BnPazQkW9whhZu1d0bC3lqqScvxb3SSb1QT8e3Xg0CEFhw # aMBZ2hExXhr79A9+bXEYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC # AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT # MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j # b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp # bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG # EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0 # IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA # wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/ # m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e # dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ # Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ # Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l # chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG # A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2 # BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j # b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW # BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v # Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0 # cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG # AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t # ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl # cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA # A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ # B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B # Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y # 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk # JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2 # YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa # NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln # aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE # aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw # MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j # MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT # SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF # AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N # aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj # RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo # CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe # /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG # 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD # VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC # MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG # MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw # AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v # Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0 # MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln # aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp # Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw # OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy # dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH # VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu # mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy # x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS # Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/IwP42+1ASa2bKXuh1Eh # 5Fhgm7oMLSttosR+u8QlK0cCCHxJrhO24XxCQijGGFbPQTS2Zl22dHv1VjMiLyI2 # skuiSpXY9aaOUjGCAk0wggJJAgEBMIGGMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV # BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C # SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G # CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCCHEAmNNj2zWjWYRfEi4FgzZvrI16kv/U2b9b3oHw6UVDANBgkqhkiG # 9w0BAQEFAASCAQCdefEKh6Qmwx7xGCkrYi/A+/Cla6LdnYJp38eMs3fqTTvjhyDw # HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/bootstrap/configure.bat
:: Copyright 2019 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. set PM_PACKMAN_VERSION=6.33.2 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating directory %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.7.9-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic rename rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul :: Failure during move, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error renaming python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\packman.py if exist "%PM_MODULE%" goto ENSURE_7ZA set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" :ENSURE_7ZA set PM_7Za_VERSION=16.02.4 set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml" if %errorlevel% neq 0 ( echo !!! Error fetching packman dependencies !!! goto ERROR ) goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: Copyright 2019 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists and is larger than 0 bytes: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @if %~z2==0 goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/bootstrap/download_file_from_url.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 3 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) $triesLeft = 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force } } while ($triesLeft -gt 0)
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/bootstrap/generate_temp_folder.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$parentPath=$null ) [string] $name = [System.Guid]::NewGuid() $out = Join-Path $parentPath $name New-Item -ItemType Directory -Path ($out) | Out-Null Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCB29nsqMEu+VmSF # 7ckeVTPrEZ6hsXjOgPFlJm9ilgHUB6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0 # IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg # U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow # gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT # YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL # DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI # hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP # YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH # jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa # HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj # 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU # z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w # ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF # BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v # ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j # b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk # MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB # BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw # AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB # AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr # K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk # fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3 # SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz # D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla # ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo # MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp # Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV # BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl # IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj # YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow # gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf # MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50 # ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG # SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp # NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t # HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p # XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP # fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg # mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4 # MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk # LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH # FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB # BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg # J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE # DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY # BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh # uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG # 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x # +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt # nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN # xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0 # vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0 # 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw # CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV # BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs # YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK # 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN # AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw # LwYJKoZIhvcNAQkEMSIEIG5YDmcpqLxn4SB0H6OnuVkZRPh6OJ77eGW/6Su/uuJg # MA0GCSqGSIb3DQEBAQUABIIBAA3N2vqfA6WDgqz/7EoAKVIE5Hn7xpYDGhPvFAMV # BslVpeqE3apTcYFCEcwLtzIEc/zmpULxsX8B0SUT2VXbJN3zzQ80b+gbgpq62Zk+ # dQLOtLSiPhGW7MXLahgES6Oc2dUFaQ+wDfcelkrQaOVZkM4wwAzSapxuf/13oSIk # ZX2ewQEwTZrVYXELO02KQIKUR30s/oslGVg77ALnfK9qSS96Iwjd4MyT7PzCkHUi # ilwyGJi5a4ofiULiPSwUQNynSBqxa+JQALkHP682b5xhjoDfyG8laR234FTPtYgs # P/FaeviwENU5Pl+812NbbtRD+gKlWBZz+7FKykOT/CG8sZahgg1EMIINQAYKKwYB # BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl # AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg # hkgBZQMEAgEFAAQgJhABfkDIPbI+nWYnA30FLTyaPK+W3QieT21B/vK+CMICEDF0 # worcGsdd7OxpXLP60xgYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC # AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT # MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j # b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp # bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG # EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0 # IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA # wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/ # m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e # dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ # Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ # Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l # chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG # A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2 # BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j # b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW # BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v # Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0 # cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG # AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t # ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl # cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA # A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ # B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B # Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y # 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk # JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2 # YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa # NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln # aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE # aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw # MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j # MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT # SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF # AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N # aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj # RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo # CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe # /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG # 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD # VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC # MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG # MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw # AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v # Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0 # MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln # aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp # Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw # OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy # dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH # VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu # mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy # x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS # Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/IwP42+1ASa2bKXuh1Eh # 5Fhgm7oMLSttosR+u8QlK0cCCHxJrhO24XxCQijGGFbPQTS2Zl22dHv1VjMiLyI2 # skuiSpXY9aaOUjGCAk0wggJJAgEBMIGGMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV # BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C # SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G # CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG # 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy # LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ # 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P # O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq # 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6 # VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM # SIG # End signature block
timedomain-tech/Timedomain-Ai-Singer-Extension/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/instance.py
from .settings import BoolSetting, CategoricalSetting, SettingItem class InstanceManagerBase: def __init__(self): self._settings = SettingItem("ace") self._setting = CategoricalSetting("ace") self.boolSetting = BoolSetting("ace") def shutdown(self): self._settings = None self._setting = None self.boolSetting = None