file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
AndreiVoica/P10-MAP/src/kr3_config_dispenser/config/stomp_planning.yaml | stomp/arm:
group_name: arm
optimization:
num_timesteps: 60
num_iterations: 40
num_iterations_after_valid: 0
num_rollouts: 30
max_rollouts: 30
initialization_method: 1 # [1 : LINEAR_INTERPOLATION, 2 : CUBIC_POLYNOMIAL, 3 : MININUM_CONTROL_COST]
control_cost_weight: 0.0
task:
noise_generator:
- class: stomp_moveit/NormalDistributionSampling
stddev: [0.05, 0.05, 0.05, 0.05, 0.05, 0.05]
cost_functions:
- class: stomp_moveit/CollisionCheck
collision_penalty: 1.0
cost_weight: 1.0
kernel_window_percentage: 0.2
longest_valid_joint_move: 0.05
noisy_filters:
- class: stomp_moveit/JointLimits
lock_start: True
lock_goal: True
- class: stomp_moveit/MultiTrajectoryVisualization
line_width: 0.02
rgb: [255, 255, 0]
marker_array_topic: stomp_trajectories
marker_namespace: noisy
update_filters:
- class: stomp_moveit/PolynomialSmoother
poly_order: 6
- class: stomp_moveit/TrajectoryVisualization
line_width: 0.05
rgb: [0, 191, 255]
error_rgb: [255, 0, 0]
publish_intermediate: True
marker_topic: stomp_trajectory
marker_namespace: optimized
stomp/hand:
group_name: hand
optimization:
num_timesteps: 60
num_iterations: 40
num_iterations_after_valid: 0
num_rollouts: 30
max_rollouts: 30
initialization_method: 1 # [1 : LINEAR_INTERPOLATION, 2 : CUBIC_POLYNOMIAL, 3 : MININUM_CONTROL_COST]
control_cost_weight: 0.0
task:
noise_generator:
- class: stomp_moveit/NormalDistributionSampling
stddev: []
cost_functions:
- class: stomp_moveit/CollisionCheck
collision_penalty: 1.0
cost_weight: 1.0
kernel_window_percentage: 0.2
longest_valid_joint_move: 0.05
noisy_filters:
- class: stomp_moveit/JointLimits
lock_start: True
lock_goal: True
- class: stomp_moveit/MultiTrajectoryVisualization
line_width: 0.02
rgb: [255, 255, 0]
marker_array_topic: stomp_trajectories
marker_namespace: noisy
update_filters:
- class: stomp_moveit/PolynomialSmoother
poly_order: 6
- class: stomp_moveit/TrajectoryVisualization
line_width: 0.05
rgb: [0, 191, 255]
error_rgb: [255, 0, 0]
publish_intermediate: True
marker_topic: stomp_trajectory
marker_namespace: optimized | 2,497 | YAML | 31.025641 | 106 | 0.632759 |
AndreiVoica/P10-MAP/src/kr3_config_dispenser/config/kinematics.yaml | arm:
kinematics_solver: kdl_kinematics_plugin/KDLKinematicsPlugin
kinematics_solver_search_resolution: 0.005
kinematics_solver_timeout: 0.005 | 147 | YAML | 35.999991 | 62 | 0.816327 |
AndreiVoica/P10-MAP/src/kr3_config_dispenser/config/gazebo_controllers.yaml | # Publish joint_states
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 50
| 118 | YAML | 22.799995 | 51 | 0.805085 |
AndreiVoica/P10-MAP/src/kr3_config_dispenser/config/joint_limits.yaml | # joint_limits.yaml allows the dynamics properties specified in the URDF to be overwritten or augmented as needed
# For beginners, we downscale velocity and acceleration limits.
# You can always specify higher scaling factors (<= 1.0) in your motion requests. # Increase the values below to 1.0 to always move at maximum speed.
default_velocity_scaling_factor: 0.1
default_acceleration_scaling_factor: 0.1
# Specific joint properties can be changed with the keys [max_position, min_position, max_velocity, max_acceleration]
# Joint limits can be turned off with [has_velocity_limits, has_acceleration_limits]
joint_limits:
joint_a1:
has_velocity_limits: true
max_velocity: 9.250245035569947
has_acceleration_limits: false
max_acceleration: 0
joint_a2:
has_velocity_limits: true
max_velocity: 9.232791743050003
has_acceleration_limits: false
max_acceleration: 0
joint_a3:
has_velocity_limits: true
max_velocity: 9.389871375729493
has_acceleration_limits: false
max_acceleration: 0
joint_a4:
has_velocity_limits: true
max_velocity: 10.47197551196598
has_acceleration_limits: false
max_acceleration: 0
joint_a5:
has_velocity_limits: true
max_velocity: 10.47197551196598
has_acceleration_limits: false
max_acceleration: 0
joint_a6:
has_velocity_limits: true
max_velocity: 13.96263401595464
has_acceleration_limits: false
max_acceleration: 0 | 1,447 | YAML | 35.199999 | 150 | 0.744299 |
AndreiVoica/P10-MAP/src/kr3_config_dispenser/config/fake_controllers.yaml | controller_list:
- name: fake_arm_controller
type: $(arg fake_execution_type)
joints:
- joint_a1
- joint_a2
- joint_a3
- joint_a4
- joint_a5
- joint_a6
- name: fake_hand_controller
type: $(arg fake_execution_type)
joints:
[]
initial: # Define initial robot poses per group
- group: arm
pose: down | 365 | YAML | 20.529411 | 48 | 0.583562 |
AndreiVoica/P10-MAP/src/kr3_config_dispenser/config/ros_controllers.yaml | arm_controller:
type: effort_controllers/JointTrajectoryController
joints:
- joint_a1
- joint_a2
- joint_a3
- joint_a4
- joint_a5
- joint_a6
gains:
joint_a1:
p: 100
d: 1
i: 1
i_clamp: 1
joint_a2:
p: 100
d: 1
i: 1
i_clamp: 1
joint_a3:
p: 100
d: 1
i: 1
i_clamp: 1
joint_a4:
p: 100
d: 1
i: 1
i_clamp: 1
joint_a5:
p: 100
d: 1
i: 1
i_clamp: 1
joint_a6:
p: 100
d: 1
i: 1
i_clamp: 1 | 573 | YAML | 13.35 | 52 | 0.425829 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/package.xml | <package>
<name>kr3_config_gripper</name>
<version>0.3.0</version>
<description>
An automatically generated package with all the configuration and launch files for using the kuka_kr3r540 with the MoveIt Motion Planning Framework
</description>
<author email="[email protected]">Andrei Voica</author>
<maintainer email="[email protected]">Andrei Voica</maintainer>
<license>BSD</license>
<url type="website">http://moveit.ros.org/</url>
<url type="bugtracker">https://github.com/ros-planning/moveit/issues</url>
<url type="repository">https://github.com/ros-planning/moveit</url>
<buildtool_depend>catkin</buildtool_depend>
<run_depend>moveit_ros_move_group</run_depend>
<run_depend>moveit_fake_controller_manager</run_depend>
<run_depend>moveit_kinematics</run_depend>
<run_depend>moveit_planners</run_depend>
<run_depend>moveit_ros_visualization</run_depend>
<run_depend>moveit_setup_assistant</run_depend>
<run_depend>moveit_simple_controller_manager</run_depend>
<run_depend>joint_state_publisher</run_depend>
<run_depend>joint_state_publisher_gui</run_depend>
<run_depend>robot_state_publisher</run_depend>
<run_depend>rviz</run_depend>
<run_depend>tf2_ros</run_depend>
<run_depend>xacro</run_depend>
<!-- The next 2 packages are required for the gazebo simulation.
We don't include them by default to prevent installing gazebo and all its dependencies. -->
<!-- <run_depend>joint_trajectory_controller</run_depend> -->
<!-- <run_depend>gazebo_ros_control</run_depend> -->
<!-- This package is referenced in the warehouse launch files, but does not build out of the box at the moment. Commented the dependency until this works. -->
<!-- <run_depend>warehouse_ros_mongo</run_depend> -->
<run_depend>kuka_kr3_support</run_depend>
</package>
| 1,834 | XML | 42.690475 | 160 | 0.731734 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/sensor_manager.launch.xml | <launch>
<!-- This file makes it easy to include the settings for sensor managers -->
<!-- Params for 3D sensors config -->
<rosparam command="load" file="$(find kr3_config_gripper)/config/sensors_3d.yaml" />
<!-- Params for the octomap monitor -->
<!-- <param name="octomap_frame" type="string" value="some frame in which the robot moves" /> -->
<param name="octomap_resolution" type="double" value="0.025" />
<param name="max_range" type="double" value="5.0" />
<!-- Load the robot specific sensor manager; this sets the moveit_sensor_manager ROS parameter -->
<arg name="moveit_sensor_manager" default="kuka_kr3r540" />
<include file="$(dirname)/$(arg moveit_sensor_manager)_moveit_sensor_manager.launch.xml" />
</launch>
| 751 | XML | 40.777776 | 100 | 0.680426 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/kuka_kr3r540_moveit_sensor_manager.launch.xml | <launch>
</launch>
| 20 | XML | 4.249999 | 9 | 0.6 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/fake_moveit_controller_manager.launch.xml | <launch>
<!-- execute the trajectory in 'interpolate' mode or jump to goal position in 'last point' mode -->
<arg name="fake_execution_type" default="interpolate" />
<!-- Set the param that trajectory_execution_manager needs to find the controller plugin -->
<param name="moveit_controller_manager" value="moveit_fake_controller_manager/MoveItFakeControllerManager"/>
<!-- The rest of the params are specific to this plugin -->
<rosparam subst_value="true" file="$(find kr3_config_gripper)/config/fake_controllers.yaml"/>
</launch>
| 548 | XML | 41.230766 | 110 | 0.729927 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/stomp_planning_pipeline.launch.xml | <launch>
<!-- Stomp Plugin for MoveIt -->
<arg name="planning_plugin" value="stomp_moveit/StompPlannerManager" />
<arg name="start_state_max_bounds_error" value="0.1" />
<arg name="jiggle_fraction" value="0.05" />
<!-- The request adapters (plugins) used when planning. ORDER MATTERS! -->
<arg name="planning_adapters"
default="default_planner_request_adapters/LimitMaxCartesianLinkSpeed
default_planner_request_adapters/AddTimeParameterization
default_planner_request_adapters/FixWorkspaceBounds
default_planner_request_adapters/FixStartStateBounds
default_planner_request_adapters/FixStartStateCollision
default_planner_request_adapters/FixStartStatePathConstraints" />
<param name="planning_plugin" value="$(arg planning_plugin)" />
<param name="request_adapters" value="$(arg planning_adapters)" />
<param name="start_state_max_bounds_error" value="$(arg start_state_max_bounds_error)" />
<param name="jiggle_fraction" value="$(arg jiggle_fraction)" />
<rosparam command="load" file="$(find kr3_config_gripper)/config/stomp_planning.yaml"/>
</launch>
| 1,168 | XML | 47.708331 | 91 | 0.699486 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/pilz_industrial_motion_planner_planning_pipeline.launch.xml | <launch>
<!-- The request adapters (plugins) used when planning. ORDER MATTERS! -->
<arg name="planning_adapters" default="" />
<param name="planning_plugin" value="pilz_industrial_motion_planner::CommandPlanner" />
<param name="request_adapters" value="$(arg planning_adapters)" />
<!-- Define default planner (for all groups) -->
<param name="default_planner_config" value="PTP" />
<!-- MoveGroup capabilities to load for this pipeline, append sequence capability -->
<param name="capabilities" value="pilz_industrial_motion_planner/MoveGroupSequenceAction
pilz_industrial_motion_planner/MoveGroupSequenceService" />
</launch>
| 685 | XML | 41.874997 | 95 | 0.691971 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/simple_moveit_controller_manager.launch.xml | <launch>
<!-- Define the MoveIt controller manager plugin to use for trajectory execution -->
<param name="moveit_controller_manager" value="moveit_simple_controller_manager/MoveItSimpleControllerManager" />
<!-- Load controller list to the parameter server -->
<rosparam file="$(find kr3_config_gripper)/config/simple_moveit_controllers.yaml" />
<rosparam file="$(find kr3_config_gripper)/config/ros_controllers.yaml" />
</launch>
| 443 | XML | 48.333328 | 115 | 0.747178 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/chomp_planning_pipeline.launch.xml | <launch>
<arg name="start_state_max_bounds_error" default="0.1" />
<arg name="jiggle_fraction" default="0.05" />
<!-- The request adapters (plugins) used when planning. ORDER MATTERS! -->
<arg name="planning_adapters"
default="default_planner_request_adapters/LimitMaxCartesianLinkSpeed
default_planner_request_adapters/AddTimeParameterization
default_planner_request_adapters/ResolveConstraintFrames
default_planner_request_adapters/FixWorkspaceBounds
default_planner_request_adapters/FixStartStateBounds
default_planner_request_adapters/FixStartStateCollision
default_planner_request_adapters/FixStartStatePathConstraints"
/>
<param name="planning_plugin" value="chomp_interface/CHOMPPlanner" />
<param name="request_adapters" value="$(arg planning_adapters)" />
<param name="start_state_max_bounds_error" value="$(arg start_state_max_bounds_error)" />
<param name="jiggle_fraction" value="$(arg jiggle_fraction)" />
<rosparam command="load" file="$(find kr3_config_gripper)/config/chomp_planning.yaml" />
</launch>
| 1,157 | XML | 51.636361 | 91 | 0.696629 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/ros_control_moveit_controller_manager.launch.xml | <launch>
<!-- Define MoveIt controller manager plugin -->
<param name="moveit_controller_manager" value="moveit_ros_control_interface::MoveItControllerManager" />
</launch>
| 175 | XML | 34.199993 | 105 | 0.754286 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/ompl-chomp_planning_pipeline.launch.xml | <launch>
<!-- load OMPL planning pipeline, but add the CHOMP planning adapter. -->
<include file="$(find kr3_config_gripper)/launch/ompl_planning_pipeline.launch.xml">
<arg name="planning_adapters"
default="default_planner_request_adapters/LimitMaxCartesianLinkSpeed
default_planner_request_adapters/AddTimeParameterization
default_planner_request_adapters/FixWorkspaceBounds
default_planner_request_adapters/FixStartStateBounds
default_planner_request_adapters/FixStartStateCollision
default_planner_request_adapters/FixStartStatePathConstraints
chomp/OptimizerAdapter"
/>
</include>
<!-- load chomp config -->
<rosparam command="load" file="$(find kr3_config_gripper)/config/chomp_planning.yaml" />
<!-- override trajectory_initialization_method: Use OMPL-generated trajectory -->
<param name="trajectory_initialization_method" value="fillTrajectory"/>
</launch>
| 1,020 | XML | 47.619045 | 90 | 0.688235 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/planning_pipeline.launch.xml | <launch>
<!-- This file makes it easy to include different planning pipelines;
It is assumed that all planning pipelines are named XXX_planning_pipeline.launch -->
<arg name="pipeline" default="ompl" />
<include ns="$(arg pipeline)" file="$(dirname)/$(arg pipeline)_planning_pipeline.launch.xml" />
</launch>
| 327 | XML | 28.818179 | 97 | 0.69419 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/warehouse_settings.launch.xml | <launch>
<!-- Set the parameters for the warehouse and run the mongodb server. -->
<!-- The default DB port for moveit (not default MongoDB port to avoid potential conflicts) -->
<arg name="moveit_warehouse_port" default="33829" />
<!-- The default DB host for moveit -->
<arg name="moveit_warehouse_host" default="localhost" />
<!-- Set parameters for the warehouse -->
<param name="warehouse_port" value="$(arg moveit_warehouse_port)"/>
<param name="warehouse_host" value="$(arg moveit_warehouse_host)"/>
<param name="warehouse_exec" value="mongod" />
<param name="warehouse_plugin" value="warehouse_ros_mongo::MongoDatabaseConnection" />
</launch>
| 675 | XML | 38.764704 | 97 | 0.694815 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/trajectory_execution.launch.xml | <launch>
<!-- This file summarizes all settings required for trajectory execution -->
<!-- Define moveit controller manager plugin: fake, simple, or ros_control -->
<arg name="moveit_controller_manager" />
<arg name="fake_execution_type" default="interpolate" />
<!-- Flag indicating whether MoveIt is allowed to load/unload or switch controllers -->
<arg name="moveit_manage_controllers" default="true"/>
<param name="moveit_manage_controllers" value="$(arg moveit_manage_controllers)"/>
<!-- When determining the expected duration of a trajectory, this multiplicative factor is applied to get the allowed duration of execution -->
<param name="trajectory_execution/allowed_execution_duration_scaling" value="1.2"/> <!-- default 1.2 -->
<!-- Allow more than the expected execution time before triggering a trajectory cancel (applied after scaling) -->
<param name="trajectory_execution/allowed_goal_duration_margin" value="0.5"/> <!-- default 0.5 -->
<!-- Allowed joint-value tolerance for validation that trajectory's first point matches current robot state -->
<param name="trajectory_execution/allowed_start_tolerance" value="0.01"/> <!-- default 0.01 -->
<!-- We use pass_all_args=true here to pass fake_execution_type, which is required by fake controllers, but not by real-robot controllers.
As real-robot controller_manager.launch files shouldn't be required to define this argument, we use the trick of passing all args. -->
<include file="$(dirname)/$(arg moveit_controller_manager)_moveit_controller_manager.launch.xml" pass_all_args="true" />
</launch>
| 1,609 | XML | 66.083331 | 145 | 0.73151 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/launch/ompl_planning_pipeline.launch.xml | <launch>
<!-- The request adapters (plugins) used when planning with OMPL. ORDER MATTERS! -->
<arg name="planning_adapters"
default="default_planner_request_adapters/LimitMaxCartesianLinkSpeed
default_planner_request_adapters/AddTimeParameterization
default_planner_request_adapters/ResolveConstraintFrames
default_planner_request_adapters/FixWorkspaceBounds
default_planner_request_adapters/FixStartStateBounds
default_planner_request_adapters/FixStartStateCollision
default_planner_request_adapters/FixStartStatePathConstraints"
/>
<arg name="start_state_max_bounds_error" default="0.1" />
<arg name="jiggle_fraction" default="0.05" />
<param name="planning_plugin" value="ompl_interface/OMPLPlanner" />
<param name="request_adapters" value="$(arg planning_adapters)" />
<param name="start_state_max_bounds_error" value="$(arg start_state_max_bounds_error)" />
<param name="jiggle_fraction" value="$(arg jiggle_fraction)" />
<rosparam command="load" file="$(find kr3_config_gripper)/config/ompl_planning.yaml"/>
</launch>
| 1,166 | XML | 45.679998 | 91 | 0.69554 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/simple_moveit_controllers.yaml | controller_list:
- name: hand_controller
action_ns: follow_joint_trajectory
type: FollowJointTrajectory
default: True
joints:
- joint_left
- joint_right
- name: arm_controller
action_ns: follow_joint_trajectory
type: FollowJointTrajectory
default: True
joints:
- joint_a1
- joint_a2
- joint_a3
- joint_a4
- joint_a5
- joint_a6 | 410 | YAML | 20.631578 | 38 | 0.614634 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/chomp_planning.yaml | planning_time_limit: 10.0
max_iterations: 200
max_iterations_after_collision_free: 5
smoothness_cost_weight: 0.1
obstacle_cost_weight: 1.0
learning_rate: 0.01
smoothness_cost_velocity: 0.0
smoothness_cost_acceleration: 1.0
smoothness_cost_jerk: 0.0
ridge_factor: 0.0
use_pseudo_inverse: false
pseudo_inverse_ridge_factor: 1e-4
joint_update_limit: 0.1
collision_clearance: 0.2
collision_threshold: 0.07
use_stochastic_descent: true
enable_failure_recovery: false
max_recovery_attempts: 5
| 487 | YAML | 24.684209 | 38 | 0.794661 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/stomp_planning.yaml | stomp/hand:
group_name: hand
optimization:
num_timesteps: 60
num_iterations: 40
num_iterations_after_valid: 0
num_rollouts: 30
max_rollouts: 30
initialization_method: 1 # [1 : LINEAR_INTERPOLATION, 2 : CUBIC_POLYNOMIAL, 3 : MININUM_CONTROL_COST]
control_cost_weight: 0.0
task:
noise_generator:
- class: stomp_moveit/NormalDistributionSampling
stddev: [0.05, 0.05]
cost_functions:
- class: stomp_moveit/CollisionCheck
collision_penalty: 1.0
cost_weight: 1.0
kernel_window_percentage: 0.2
longest_valid_joint_move: 0.05
noisy_filters:
- class: stomp_moveit/JointLimits
lock_start: True
lock_goal: True
- class: stomp_moveit/MultiTrajectoryVisualization
line_width: 0.02
rgb: [255, 255, 0]
marker_array_topic: stomp_trajectories
marker_namespace: noisy
update_filters:
- class: stomp_moveit/PolynomialSmoother
poly_order: 6
- class: stomp_moveit/TrajectoryVisualization
line_width: 0.05
rgb: [0, 191, 255]
error_rgb: [255, 0, 0]
publish_intermediate: True
marker_topic: stomp_trajectory
marker_namespace: optimized
stomp/arm:
group_name: arm
optimization:
num_timesteps: 60
num_iterations: 40
num_iterations_after_valid: 0
num_rollouts: 30
max_rollouts: 30
initialization_method: 1 # [1 : LINEAR_INTERPOLATION, 2 : CUBIC_POLYNOMIAL, 3 : MININUM_CONTROL_COST]
control_cost_weight: 0.0
task:
noise_generator:
- class: stomp_moveit/NormalDistributionSampling
stddev: [0.05, 0.05, 0.05, 0.05, 0.05, 0.05]
cost_functions:
- class: stomp_moveit/CollisionCheck
collision_penalty: 1.0
cost_weight: 1.0
kernel_window_percentage: 0.2
longest_valid_joint_move: 0.05
noisy_filters:
- class: stomp_moveit/JointLimits
lock_start: True
lock_goal: True
- class: stomp_moveit/MultiTrajectoryVisualization
line_width: 0.02
rgb: [255, 255, 0]
marker_array_topic: stomp_trajectories
marker_namespace: noisy
update_filters:
- class: stomp_moveit/PolynomialSmoother
poly_order: 6
- class: stomp_moveit/TrajectoryVisualization
line_width: 0.05
rgb: [0, 191, 255]
error_rgb: [255, 0, 0]
publish_intermediate: True
marker_topic: stomp_trajectory
marker_namespace: optimized | 2,507 | YAML | 31.153846 | 106 | 0.632629 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/kinematics.yaml | arm:
kinematics_solver: kdl_kinematics_plugin/KDLKinematicsPlugin
kinematics_solver_search_resolution: 0.005
kinematics_solver_timeout: 0.005 | 147 | YAML | 35.999991 | 62 | 0.816327 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/gazebo_controllers.yaml | # Publish joint_states
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 50
| 118 | YAML | 22.799995 | 51 | 0.805085 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/joint_limits.yaml | # joint_limits.yaml allows the dynamics properties specified in the URDF to be overwritten or augmented as needed
# For beginners, we downscale velocity and acceleration limits.
# You can always specify higher scaling factors (<= 1.0) in your motion requests. # Increase the values below to 1.0 to always move at maximum speed.
default_velocity_scaling_factor: 0.1
default_acceleration_scaling_factor: 0.1
# Specific joint properties can be changed with the keys [max_position, min_position, max_velocity, max_acceleration]
# Joint limits can be turned off with [has_velocity_limits, has_acceleration_limits]
joint_limits:
joint_a1:
has_velocity_limits: true
max_velocity: 9.250245035569947
has_acceleration_limits: false
max_acceleration: 0
joint_a2:
has_velocity_limits: true
max_velocity: 9.232791743050003
has_acceleration_limits: false
max_acceleration: 0
joint_a3:
has_velocity_limits: true
max_velocity: 9.389871375729493
has_acceleration_limits: false
max_acceleration: 0
joint_a4:
has_velocity_limits: true
max_velocity: 10.47197551196598
has_acceleration_limits: false
max_acceleration: 0
joint_a5:
has_velocity_limits: true
max_velocity: 10.47197551196598
has_acceleration_limits: false
max_acceleration: 0
joint_a6:
has_velocity_limits: true
max_velocity: 13.96263401595464
has_acceleration_limits: false
max_acceleration: 0
joint_left:
has_velocity_limits: true
max_velocity: 2.00001
has_acceleration_limits: false
max_acceleration: 0
joint_right:
has_velocity_limits: true
max_velocity: 2.00001
has_acceleration_limits: false
max_acceleration: 0 | 1,706 | YAML | 33.139999 | 150 | 0.736225 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/fake_controllers.yaml | controller_list:
- name: fake_hand_controller
type: $(arg fake_execution_type)
joints:
- joint_left
- joint_right
- name: fake_arm_controller
type: $(arg fake_execution_type)
joints:
- joint_a1
- joint_a2
- joint_a3
- joint_a4
- joint_a5
- joint_a6
initial: # Define initial robot poses per group
- group: hand
pose: open
- group: arm
pose: down | 426 | YAML | 20.349999 | 48 | 0.584507 |
AndreiVoica/P10-MAP/src/kr3_config_gripper/config/ros_controllers.yaml | hand_controller:
type: velocity_controllers/JointTrajectoryController
joints:
- joint_left
- joint_right
gains:
joint_left:
p: 100
d: 1
i: 1
i_clamp: 1
joint_right:
p: 100
d: 1
i: 1
i_clamp: 1
arm_controller:
type: velocity_controllers/JointTrajectoryController
joints:
- joint_a1
- joint_a2
- joint_a3
- joint_a4
- joint_a5
- joint_a6
gains:
joint_a1:
p: 20000
d: 1
i: 1
i_clamp: 1
joint_a2:
p: 20000
d: 1
i: 1
i_clamp: 1
joint_a3:
p: 20000
d: 1
i: 1
i_clamp: 1
joint_a4:
p: 20000
d: 1
i: 1
i_clamp: 1
joint_a5:
p: 20000
d: 1
i: 1
i_clamp: 1
joint_a6:
p: 20000
d: 1
i: 1
i_clamp: 1 | 850 | YAML | 14.196428 | 54 | 0.469412 |
AndreiVoica/P10-MAP/src/schunk_25nnb/package.xml | <package format="2">
<name>schunk_25nnb</name>
<version>1.0.0</version>
<description>
<p>URDF Description package for schunk_25nnb</p>
<p>This package contains configuration data, 3D models and launch files
for schunk_25nnb robot</p>
</description>
<author>TODO</author>
<maintainer email="[email protected]" />
<license>BSD</license>
<buildtool_depend>catkin</buildtool_depend>
<depend>roslaunch</depend>
<depend>robot_state_publisher</depend>
<depend>rviz</depend>
<depend>joint_state_publisher_gui</depend>
<depend>gazebo</depend>
<export>
<architecture_independent />
</export>
</package> | 631 | XML | 29.095237 | 75 | 0.708399 |
AndreiVoica/P10-MAP/maps/maps_extension.py | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.maps import MAPs
import asyncio
import omni.ui as ui
from omni.isaac.ui.ui_utils import btn_builder
class MAPsExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="",
submenu_name="",
name="MAPs",
title="Material Acceleration Platform AAU",
doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
sample=MAPs(),
file_path=os.path.abspath(__file__),
number_of_extra_frames=3,
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_simulation_controls_ui(frame)
frame = self.get_frame(index=1)
self.build_real_controls_ui(frame)
frame = self.get_frame(index=2)
self.build_experiment_controls_ui(frame)
return
def _on_sim_control_button_event(self):
asyncio.ensure_future(self.sample._on_sim_control_event_async())
self.task_ui_elements["Simulation Control"].enabled = False
self.task_ui_elements["Real Setup Control"].enabled = True
self.task_ui_elements["Connect PMC"].enabled = True
self.task_ui_elements["Start Experiment"].enabled = True
return
def _on_real_control_button_event(self):
asyncio.ensure_future(self.sample._on_real_control_event_async())
self.task_ui_elements["Real Setup Control"].enabled = False
self.task_ui_elements["Simulation Control"].enabled = True
self.task_ui_elements["Connect PMC"].enabled = False
self.task_ui_elements["Start Experiment"].enabled = True
return
def _on_connect_pmc_button_event(self):
self.sample._connect_pmc()
self.task_ui_elements["Real Setup Control"].enabled = True
self.task_ui_elements["Simulation Control"].enabled = True
self.task_ui_elements["Connect PMC"].enabled = False
self.task_ui_elements["Start Experiment"].enabled = True
return
def _on_start_experiment_button_event(self):
asyncio.ensure_future(self.sample._on_start_experiment_event_async())
self.task_ui_elements["Real Setup Control"].enabled = False
self.task_ui_elements["Simulation Control"].enabled = False
self.task_ui_elements["Connect PMC"].enabled = False
self.task_ui_elements["Start Experiment"].enabled = True
return
def post_reset_button_event(self):
self.task_ui_elements["Simulation Control"].enabled = True
self.task_ui_elements["Real Setup Control"].enabled = True
self.task_ui_elements["Connect PMC"].enabled = True
self.task_ui_elements["Start Experiment"].enabled = True
return
def post_load_button_event(self):
self.task_ui_elements["Simulation Control"].enabled = True
self.task_ui_elements["Real Setup Control"].enabled = False
self.task_ui_elements["Connect PMC"].enabled = True
self.task_ui_elements["Start Experiment"].enabled = True
return
def post_clear_button_event(self):
self.task_ui_elements["Simulation Control"].enabled = False
self.task_ui_elements["Real Setup Control"].enabled = False
self.task_ui_elements["Connect PMC"].enabled = False
self.task_ui_elements["Start Experiment"].enabled = False
return
def build_simulation_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Simulation"
frame.visible = True
dict = {
"label": "Simulation Control",
"type": "button",
"text": "Start Simulation",
"tooltip": "Simulation Control",
"on_clicked_fn": self._on_sim_control_button_event,
}
self.task_ui_elements["Simulation Control"] = btn_builder(**dict)
self.task_ui_elements["Simulation Control"].enabled = False
def build_real_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Real Setup"
frame.visible = True
dict = {
"label": "Connect PMC",
"type": "button",
"text": "Connect",
"tooltip": "Connect PMC",
"on_clicked_fn": self._on_connect_pmc_button_event,
}
self.task_ui_elements["Connect PMC"] = btn_builder(**dict)
self.task_ui_elements["Connect PMC"].enabled = False
dict = {
"label": "Real Setup Control",
"type": "button",
"text": "Start Real Setup",
"tooltip": "Real Setup Control",
"on_clicked_fn": self._on_real_control_button_event,
}
self.task_ui_elements["Real Setup Control"] = btn_builder(**dict)
self.task_ui_elements["Real Setup Control"].enabled = False
def build_experiment_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Experiment Control"
frame.visible = True
dict = {
"label": "Start Experiment",
"type": "button",
"text": "Start",
"tooltip": "Start Experiment",
"on_clicked_fn": self._on_start_experiment_button_event,
}
self.task_ui_elements["Start Experiment"] = btn_builder(**dict)
self.task_ui_elements["Start Experiment"].enabled = False
# dict = {
# "label": "Real Setup Control",
# "type": "button",
# "text": "Start Real Setup",
# "tooltip": "Real Setup Control",
# "on_clicked_fn": self._on_real_control_button_event,
# }
# self.task_ui_elements["Real Setup Control"] = btn_builder(**dict)
# self.task_ui_elements["Real Setup Control"].enabled = False
| 7,136 | Python | 40.982353 | 135 | 0.579036 |
AndreiVoica/P10-MAP/maps/__init__.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 omni.isaac.examples.maps.maps import MAPs
from omni.isaac.examples.maps.maps_extension import MAPsExtension
from omni.isaac.examples.maps.maps_reader import ControllerJointsLoader
| 615 | Python | 42.999997 | 76 | 0.821138 |
AndreiVoica/P10-MAP/maps/maps_reader.py | import yaml
class ControllerJointsLoader:
"""
This class loads the controller joints data from the simple_moveit_controllers.yaml file
"""
def __init__(self, filename):
self.filename = filename
self.controller_data = {}
self.load_controller_data()
def load_controller_data(self):
with open(self.filename, 'r') as file:
data = yaml.safe_load(file)
arm_count = 1
hand_count = 1
for controller in data['controller_list']:
# Remove "_controller" from the name
name = controller['name'].replace('_controller', '')
# Extract the base name for eef_link
eef_name = name.split('_')[0] + '_' + name.split('_')[1]
# Create robot_arm or robot_hand key
if 'arm' in name:
planning_group = 'robot_arm_' + str(arm_count)
arm_count += 1
elif 'hand' in name:
robot_number = name.split('_')[1]
planning_group = 'robot_hand_' + robot_number
hand_count += 1
else:
continue
# Store the planning_group, its corresponding joints, controller name and eef_link in the dictionary
self.controller_data[planning_group] = {
'planning_group': name,
'joints': controller['joints'],
'eef_link': eef_name + '_link_6'
}
def get_controller_data(self):
return self.controller_data
class RecipeLoader:
def __init__(self, actions_file):
self.actions_file = actions_file
def read_instructions_from_yaml(self):
with open(self.actions_file, 'r') as file:
instructions_list = yaml.safe_load(file)
# for instruction in instructions_list:
# instruction_name = instruction['name']
# parameters = instruction['parameters']
return instructions_list
# Using the class
# filename = '/home/robotlab/Documents/Github/P10-MAP/src/kuka_config_multiple/config/simple_moveit_controllers.yaml' # Path to the yaml file
# controller_data = loader.get_controller_data()
# print(controller_data) | 2,216 | Python | 35.344262 | 141 | 0.575361 |
AndreiVoica/P10-MAP/maps/maps.py | # Copyright (c) 2020-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.
# Author: Daniel Moreno París ([email protected]) & Andrei Voica ([email protected])
from omni.isaac.examples.maps.maps_reader import ControllerJointsLoader
from omni.isaac.examples.maps.maps_reader import RecipeLoader
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core import World
from omni.isaac.core.prims import GeometryPrim, XFormPrim, RigidPrim
import omni.kit.commands
from pxr import Sdf, Gf, UsdPhysics
from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles, euler_to_rot_matrix
import numpy as np
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.articulations import Articulation, ArticulationSubset
from omni.isaac.core.physics_context import PhysicsContext
import carb
# PMC Library Imports
from pmclib import system_commands as sys # PMC System related commands
from pmclib import xbot_commands as bot # PMC Mover related commands
from pmclib import pmc_types # PMC API Types
import time
import random
import functools
from omni.isaac.core.utils import viewports, extensions
from omni.isaac.core.utils.prims import set_targets
import asyncio
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import String, Header
from geometry_msgs.msg import Pose, PoseStamped, PoseArray, Point, Quaternion
import math
# import sys
# Action graph imports
import omni.graph.core as og
import rosgraph
#########################################################################################################
class MAPs(BaseSample):
def __init__(self) -> None:
super().__init__()
# # Positions are relative to parents, so set them with reversed values
# SCENE GEOMETRY
# env (group) spacing:
self._env_spacing = 2.0
self.last_update_time = time.time()
# Lab Setup:
self._lab_setup_position = np.array([0.0, 0.0, 0.0]) # Gf.Vec3f(0.5, 0.0, 0.0)
self._lab_setup_orientation = np.array([0, 0, 0, 1])
self._lab_setup_scale = 1.0
# Shuttles Grid:
self._grid_position = np.array([1.2877, -1.0415, 0.0])
shuttle_orientation = np.pi/2
self._grid_orientation = np.array([np.cos(shuttle_orientation/2), 0, 0, np.sin(shuttle_orientation/2)]) #Rotates 90 degrees around z-axis
# Shuttles:
self._number_shuttles = 4
# self._shuttle_position = np.array([1.2277, -0.9815, 1.07])
self._shuttle_position = np.array([0.06, 0.06, 1.07]) #([0.06, 0.06, 1.07])
self._platform_limits = np.array([0.0, 0.0, 0.832, 0.596]) # x_min, y_min, x_max, y_max
self._shuttle_scale = 0.01
# self.xbot_ids = [1, 2, 3, 4, 5, 6, 7, 8]
self.xbot_ids = [i for i in range(1, self._number_shuttles + 1)]
self.targets_x = []
self.targets_y = []
# Trays
self._number_tray_vial = 1
self._tray_vial_position = np.array([0.35992, -0.15884, 1.063]) #([0.06, 0.06, 1.10])
# self._tray_vial_position = np.array([1.2277, -1.2, 1])
self._tray_vial_scale = 0.0098
self._number_tray_beaker = 1
# self._tray_beaker_position = np.array([0.30, 0.06, 1.090])
self._tray_beaker_position = np.array([0.57916, -0.15884, 1.063])
self._tray_beaker_scale = 0.0099
# Flyways:
# DEFINE FLYWAYS MATRIX
self.flyways_matrix = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
# Flyway offsets
self._flyway_position = np.array([1.165, -0.92398, 0.99302])
self._flyway_orientation = np.array([0, 0, 0, 1])
self._flyway_scale = 0.01
# Grid for BFS Algorithm
self.grid = []
for row in self.flyways_matrix:
grid_row = []
for cell in row:
grid_row.extend([cell]*2) # each cell in flyways_matrix is 2 cells in grid
for _ in range(2): # each cell in flyways_matrix is 2 cells in grid
self.grid.append(grid_row)
# Magnetic Stirrer
self._stirrer_position = np.array([-0.15554, 0.71716, 1.0049])
self._stirrer_orientation = np.array(euler_angles_to_quat([np.pi/2, 0, 0]))
self._stirrer_scale = 1.0
# HPLC
#self._hplc_position = np.array([1.05725, -0.10274, 0.0369])
self._hplc_position = np.array([-1.03033, 0.15418, 1.0049])
self._hplc_orientation = np.array(euler_angles_to_quat([0, 0, 0]))
self._hplc_scale = 0.01
# Loading station
#self._loading_station_position = np.array([1.42345, -0.53634, 0.0369])
self._loading_station_position = np.array([-1.47442, 0.58184, 1.0049])
self._loading_station_orientation = np.array(euler_angles_to_quat([0, 0, np.pi/2]))
self._loading_station_scale = 0.01
# Removing station
#self._removing_station_position = np.array([1.15523, -1.15596, 0.0369])
self._removing_station_position = np.array([-1.04649, 1.23841, 1.0049])
self._removing_station_orientation = np.array(euler_angles_to_quat([0, 0, 0]))
self._removing_station_scale = 0.01
# Kuka Multiple Arms:
self._kuka_arms_position = np.array([0.0, 0.0, 1.0])
self._kuka_arms_orientation = np.array(euler_angles_to_quat([0, 0, 0]))
self._kuka_arms_scale = 1.0
# Repository path:
# self.repo_folder = "/home/andrei/P10-MAP/"
self.repo_folder = "/home/robotlab/Documents/Github/P10-MAP/"
# USD asset paths:
# self.asset_folder = "omniverse://localhost/Projects/MAPs-AAU/Assets/"
self.asset_folder = self.repo_folder + "assets/"
self.asset_paths = {
#"kr3": self.asset_folder + "kr3r540/kr3r540_v3/kr3r540_v3.usd",
#"kr3": self.asset_folder + "kr3r540/kr3r540_v4/kr3r540_v4.usd", # Schunk Kr3
"kr3": self.asset_folder + "kr3r540_v4/kr3r540_v4g.usd", # Schunk Kr3
"kr4": self.asset_folder + "kr4r600/kr4r600_v2.usd",
"kuka_multiple": self.asset_folder + "kuka_multiple_arms/kuka_multiple_arms_5.usd",
"franka": "omniverse://localhost/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Robots/Franka/franka_alt_fingers.usd",
"flyway": self.asset_folder + "flyways/flyway_segment.usd",
# "shuttle": self.asset_folder + "120x120x10/acopos_shuttle_120.usd", # Basic shuttle
"shuttle": self.asset_folder + "120x120x10/shuttle_wh.usd",
"tray_vial" : self.asset_folder + "Trays/Tray_vial_w.usd",
"tray_flask" : self.asset_folder + "Trays/Tray_beaker_w.usd",
"vial" : self.asset_folder + "vials/vial.usd",
"stirrer" : self.asset_folder + "Magnetic_stirrer/Magnetic_stirrer.usd",
#"lab_setup": self.asset_folder + "Lab_setup_v2.usd" # Lab Setup with robots
#"lab_setup": self.asset_folder + "Lab_setup_v1.usd" # Lab Setup without robots
"lab_setup": self.asset_folder + "Lab_setup_v0.usd", # Lab Setup without robots or Acopos Matrix
"hplc": self.asset_folder + "Loading_station/Loading_station.usd",
"loading_station": self.asset_folder + "Loading_station/Loading_station.usd",
"removing_station": self.asset_folder + "Loading_station/Loading_station.usd"
}
# Prim paths Dictionaries:
self.shuttles_prim_dict = {} # Dictionary to store shuttle prim paths
self.items_prim_dict = {} # Dictionary to store tray vial prim paths
self.eef_link_prim_dict = {} # Dictionary to store eef link prim paths for each robot
self.gripper_prim_dict = {} # Dictionary to store gripper prim paths for each robot
self.current_pos_dict = {} # Dictionary to store shuttle current positions
# Get dictionary with planning group, joints and eef link for each robot
self.filename = self.repo_folder + "src/kuka_config_multiple/config/simple_moveit_controllers.yaml"
self.joints_loader = ControllerJointsLoader(self.filename)
self.robot_joints_data = self.joints_loader.get_controller_data()
print(self.robot_joints_data)
# Load recipe with experiment instructions
self.actions_file = self.repo_folder + "recipe/recipe_v2.yaml"
self.actions_loader = RecipeLoader(self.actions_file)
self.recipe = self.actions_loader.read_instructions_from_yaml()
# Ros topics messages
self.planning_group = String() # ROS topic name for move group
self.joint_state_request = JointState()
self.pose_request = Pose()
self.cartesian_path_request = PoseArray()
self.action_completed = False
self.start_time = 0
self.action_times = {}
self.control_switch = 0 # 0: Sim, 1: PMC
return
# This function is called to setup the assets in the scene for the first time
# Class variables should not be assigned here, since this function is not called
# after a hot-reload, its only called to load the world starting from an EMPTY stage
def setup_scene(self):
# Check if ROS master is running
if not rosgraph.is_master_online():
carb.log_error("Please run roscore before executing this script")
# A world is defined in the BaseSample, can be accessed everywhere EXCEPT __init__
world = self.get_world()
world = World.instance()
# stage.SetDefaultPrim(world)
world.scene.add_default_ground_plane() # adds a default ground plane to the scene
# Add physics context
physx_context = PhysicsContext()
# Enable GPU dynamics
physx_context.enable_gpu_dynamics(True)
# Reload recipe
self.recipe = self.actions_loader.read_instructions_from_yaml()
# Add Xform reference for the shuttles
world.scene.add(XFormPrim(prim_path="/World/LabSetup", name=f"LabSetup"))
# Add Xform reference for the shuttles
world.scene.add(XFormPrim(prim_path="/World/LabSetup/Grid", name=f"Grid"))
# Add Xform reference for the flyways
for i in range(len(self.flyways_matrix)):
for j in range(len(self.flyways_matrix[i])):
if self.flyways_matrix[i][j] == 1:
add_reference_to_stage(usd_path=self.asset_paths["flyway"],
prim_path="/World/LabSetup/Grid/flyway_{}{}".format((i+1),(j+1)))
world.scene.add(GeometryPrim(prim_path="/World/LabSetup/Grid/flyway_{}{}".format((i+1),(j+1)),
name="flyway_{}{}_ref_geom".format(i+1, j+1), collision=True))
# Add shuttles references
for i in range(self._number_shuttles):
add_reference_to_stage(usd_path=self.asset_paths["shuttle"], prim_path="/World/LabSetup/Grid/shuttle_{}".format(i+1))
world.scene.add(RigidPrim(prim_path="/World/LabSetup/Grid/shuttle_{}".format(i+1),
name="shuttle_{}_ref_geom".format(i+1),
position= self._shuttle_position + np.array([0.12 *i, 0, 0]),
scale = np.full((3,), self._shuttle_scale),
mass = 0.30))
self.targets_x = np.append(self.targets_x, self._shuttle_position[0] + np.array([0.12 *i]))
self.targets_y = np.append(self.targets_y, self._shuttle_position[1])
# Add Trays
for i in range(self._number_tray_vial):
add_reference_to_stage(usd_path=self.asset_paths["tray_vial"], prim_path="/World/LabSetup/Grid/tray_vial_{}".format(i+1))
world.scene.add(RigidPrim(prim_path="/World/LabSetup/Grid/tray_vial_{}".format(i+1),
name="tray_vial_{}_ref_geom".format(i+1),
position= self._tray_vial_position + np.array([0.12 *i, 0, 0]),
scale = np.full((3,), self._tray_vial_scale),
mass = 0.15))
for i in range(self._number_tray_beaker):
add_reference_to_stage(usd_path=self.asset_paths["tray_flask"], prim_path="/World/LabSetup/Grid/tray_beaker_{}".format(i+1))
world.scene.add(RigidPrim(prim_path="/World/LabSetup/Grid/tray_beaker_{}".format(i+1),
name="tray_beaker_{}_ref_geom".format(i+1),
position= self._tray_beaker_position + np.array([0.12 *i, 0, 0]),
scale = np.full((3,), self._tray_beaker_scale),
mass = 0.15))
# Add Magnetic Stirrer
add_reference_to_stage(usd_path=self.asset_paths["stirrer"],
prim_path="/World/LabSetup/Stirrer")
world.scene.add(RigidPrim(prim_path ="/World/LabSetup/Stirrer",
name="magnetic_stirrer",
position = self._stirrer_position,
orientation = self._stirrer_orientation,
mass = 3))
# Add HPLC
add_reference_to_stage(usd_path=self.asset_paths["hplc"],
prim_path="/World/LabSetup/hplc")
world.scene.add(RigidPrim(prim_path ="/World/LabSetup/hplc",
name="hplc",
position = self._hplc_position,
orientation = self._hplc_orientation,
mass = 20))
# Add Loading station
add_reference_to_stage(usd_path=self.asset_paths["loading_station"],
prim_path="/World/LabSetup/loading_station")
world.scene.add(RigidPrim(prim_path ="/World/LabSetup/loading_station",
name="loading_station",
position = self._loading_station_position,
orientation = self._loading_station_orientation,
mass = 20))
# Add Remove station
add_reference_to_stage(usd_path=self.asset_paths["removing_station"],
prim_path="/World/LabSetup/removing_station")
world.scene.add(RigidPrim(prim_path ="/World/LabSetup/removing_station",
name="removing_station",
position = self._removing_station_position,
orientation = self._removing_station_orientation,
mass = 20))
# Add Robots references
add_reference_to_stage(usd_path=self.asset_paths["kuka_multiple"],
prim_path="/World/Kuka_Multiple_Arms")
self.kukas = world.scene.add(Articulation(prim_path ="/World/Kuka_Multiple_Arms",
name="Kuka_Multiple_Arms",
position = self._kuka_arms_position,
orientation = self._kuka_arms_orientation))
return
# Here we assign the class's variables this function is called after load button is pressed
# regardless starting from an empty stage or not this is called after setup_scene and after
# one physics time step to propagate appropriate physics handles which are needed to retrieve
# many physical properties of the different objects
async def setup_post_load(self):
# Load World and Assets --CHECK
self._world = self.get_world()
self._world.scene.enable_bounding_boxes_computations()
# Camera Initial Viewport
viewports.set_camera_view(eye=np.array([3.3, -0.7, 2.2]), target=np.array([0.8, -0.7, 1.05]))
# Add USD Assets
await self._add_lab_setup()
await self._add_shuttles_grid()
for i in range(len(self.flyways_matrix)):
for j in range(len(self.flyways_matrix[i])):
if self.flyways_matrix[i][j] == 1:
await self._add_flyway(i, j)
# Shuttles Prim Dictionary
stage = omni.usd.get_context().get_stage()
for shuttle_number in range(self._number_shuttles):
shuttle_path = "/World/LabSetup/Grid/shuttle_{}".format(shuttle_number + 1)
prim = stage.GetPrimAtPath(shuttle_path)
if prim:
key_name = "prim_{}".format(shuttle_number + 1)
self.shuttles_prim_dict[key_name] = prim
else:
print("Error: shuttle prim not found at path {}".format(shuttle_path))
# Items Prim Dictionary
for tray_vial in range(self._number_tray_vial):
tray_vial_path = "/World/LabSetup/Grid/tray_vial_{}".format(tray_vial + 1)
prim = stage.GetPrimAtPath(tray_vial_path)
if prim:
key_name = "prim_tray_vial_{}".format(tray_vial + 1)
self.items_prim_dict[key_name] = prim
for tray_beaker in range(self._number_tray_beaker):
tray_beaker_path = "/World/LabSetup/Grid/tray_beaker_{}".format(tray_beaker + 1)
prim = stage.GetPrimAtPath(tray_beaker_path)
if prim:
key_name = "prim_tray_beaker_{}".format(tray_beaker + 1)
while key_name in self.items_prim_dict: # Check if the key already exists in the dictionary
tray_beaker += self._number_tray_vial # Increment the index by the number of vials
tray_beaker_path = "/World/LabSetup/Grid/tray_beaker_{}".format(tray_beaker + 1)
prim = stage.GetPrimAtPath(tray_beaker_path)
key_name = "prim_{}_beaker".format(tray_beaker + 1)
self.items_prim_dict[key_name] = prim
print("ITEMS DICT: ", self.items_prim_dict)
# Iterate over each robot
for robot_name, robot_data in self.robot_joints_data.items():
eef_link = robot_data['eef_link']
eef_link_path = "/World/Kuka_Multiple_Arms/{}".format(eef_link)
prim = stage.GetPrimAtPath(eef_link_path)
if prim:
self.eef_link_prim_dict[robot_name] = prim
else:
print("Error: eef link prim not found at path {}".format(eef_link_path))
print("EEF DICT: ", self.eef_link_prim_dict)
# Create rospy node to publish requested joint positions
rospy.init_node('isaac_joint_request_publisher')
self.pub_group = rospy.Publisher('/joint_move_group_isaac', String, queue_size=10)
self.pub_joints = rospy.Publisher('/joint_command_isaac', JointState, queue_size=10)
self.pub_pose = rospy.Publisher('/pose_command_isaac', Pose, queue_size=10)
self.pub_cartesian_path = rospy.Publisher('/cartesian_path_command_isaac', PoseArray, queue_size=10)
# Creating a action graph with ROS component nodes
try:
og.Controller.edit(
{"graph_path": "/World/Kuka_Multiple_Arms/ActionGraph", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("PublishJointState", "omni.isaac.ros_bridge.ROS1PublishJointState"),
("SubscribeJointState", "omni.isaac.ros_bridge.ROS1SubscribeJointState"),
("ArticulationController", "omni.isaac.core_nodes.IsaacArticulationController"),
("PublishTF", "omni.isaac.ros_bridge.ROS1PublishTransformTree"),
("PublishClock", "omni.isaac.ros_bridge.ROS1PublishClock"),
],
og.Controller.Keys.CONNECT: [
("OnImpulseEvent.outputs:execOut", "PublishJointState.inputs:execIn"),
("OnImpulseEvent.outputs:execOut", "SubscribeJointState.inputs:execIn"),
("OnImpulseEvent.outputs:execOut", "PublishTF.inputs:execIn"),
("OnImpulseEvent.outputs:execOut", "PublishClock.inputs:execIn"),
("OnImpulseEvent.outputs:execOut", "ArticulationController.inputs:execIn"),
("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
("ReadSimTime.outputs:simulationTime", "PublishTF.inputs:timeStamp"),
("SubscribeJointState.outputs:jointNames", "ArticulationController.inputs:jointNames"),
("SubscribeJointState.outputs:positionCommand", "ArticulationController.inputs:positionCommand"),
("SubscribeJointState.outputs:velocityCommand", "ArticulationController.inputs:velocityCommand"),
("SubscribeJointState.outputs:effortCommand", "ArticulationController.inputs:effortCommand"),
],
og.Controller.Keys.SET_VALUES: [
# Setting the /Kuka target prim to Articulation Controller node
("SubscribeJointState.inputs:topicName", "joint_command"),
("ArticulationController.inputs:usePath", False),
("ArticulationController.inputs:robotPath", ""),
],
},
)
except Exception as e:
print(e)
# Setting the /Kuka target prim to Publish JointState node
set_targets(
prim = stage.GetPrimAtPath("/World/Kuka_Multiple_Arms/ActionGraph/PublishJointState"),
attribute="inputs:targetPrim",
target_prim_paths=["/World/Kuka_Multiple_Arms"]
)
# Setting the /Kuka target prim to Articulation Controller node
set_targets(
prim = stage.GetPrimAtPath("/World/Kuka_Multiple_Arms/ActionGraph/ArticulationController"),
attribute="inputs:targetPrim",
target_prim_paths=["/World/Kuka_Multiple_Arms"]
)
# Setting the /Kuka target prim to Publish Transform Tree node
set_targets(
prim = stage.GetPrimAtPath("/World/Kuka_Multiple_Arms/ActionGraph/PublishTF"),
attribute = "inputs:targetPrims",
target_prim_paths=["/World/Kuka_Multiple_Arms"]
)
# Control Switch
if self.control_switch == 0:
# self._world.add_physics_callback("sim_step_shuttles", callback_fn=self.sim_xbots_movement_2)
# rospy.init_node('isaac_test', anonymous=True)
# self.pub_joints = rospy.Publisher("/joint_command_desired", queue_size=1)
#self.on_impulse_event()
self._world.add_physics_callback("sim_step_impulse", callback_fn=self.on_impulse_event)
# self._world.add_physics_callback("sim_step_shuttles", self.sim_xbots_movement)
elif self.control_switch == 1:
self._connect_pmc() # Connect to PMC
self._world.add_physics_callback("sim_step_read_acopos", callback_fn=self.read_xbots_positions) #callback names have to be unique
self._world.add_physics_callback("sim_step_move_acopos", callback_fn=self.send_xbots_positions)
return
# Add Lab Setup reference
async def _add_lab_setup(self):
self._lab_setup_ref_geom = self._world.scene.get_object(f"LabSetup")
# self._lab_setup_ref_geom.set_local_scale(np.array([self._lab_setup_scale]))
self._lab_setup_ref_geom.set_world_pose(position=self._lab_setup_position,
orientation=self._lab_setup_orientation)
self._lab_setup_ref_geom.set_default_state(position=self._lab_setup_position,
orientation=self._lab_setup_orientation)
# self._lab_setup_ref_geom.set_collision_approximation("none")
# self._convexIncludeRel.AddTarget(self._table_ref_geom.prim_path)
# Add flyways to the scene
async def _add_flyway(self, x, y):
self._flyway_ref_geom = self._world.scene.get_object(f"flyway_{x+1}{y+1}_ref_geom")
self._flyway_ref_geom.set_local_scale(np.array([self._flyway_scale]))
self._flyway_ref_geom.set_world_pose(position = self._flyway_position + (-0.24 * (x), +0.24 * (y), 0))
self._flyway_ref_geom.set_default_state(position = self._flyway_position)
self._flyway_ref_geom.set_collision_approximation("none")
# Add xForm shuttles reference
async def _add_shuttles_grid(self):
self._shuttles_grid_ref_geom = self._world.scene.get_object(f"Grid")
self._shuttles_grid_ref_geom.set_world_pose(position=self._grid_position,
orientation=self._grid_orientation)
self._shuttles_grid_ref_geom.set_default_state(position=self._grid_position,
orientation=self._grid_orientation)
## Interface Functions:
async def _on_sim_control_event_async(self):
world = self.get_world()
self.targets_x, self.targets_y = self.create_random_coordinates(self._number_shuttles)
if world.physics_callback_exists("sim_step_read_acopos"):
world.remove_physics_callback("sim_step_read_acopos")
# world.add_physics_callback("sim_step_shuttles", self.sim_xbots_movement)
await world.play_async()
return
async def _on_real_control_event_async(self):
world = self.get_world()
if world.physics_callback_exists("sim_step_shuttles"):
world.remove_physics_callback("sim_step_shuttles")
self._world.add_physics_callback("sim_step_read_acopos", callback_fn=self.read_xbots_positions) #callback names have to be unique
#self._world.add_physics_callback("sim_step_move_acopos", callback_fn=self.send_xbots_positions) ## Random positions right now
await world.play_async()
return
## CONTROL FUNCTIONS
# Function to move selected robot to desired joints position
def move_to_joint_state(self, planning_group, joint_state_request):
moveit_planning_group = self.robot_joints_data[planning_group]["planning_group"]
self.planning_group = planning_group
self.joint_state_request.position = joint_state_request
self.pub_group.publish(moveit_planning_group)
self.pub_joints.publish(self.joint_state_request)
if len(joint_state_request) == 6:
# Add a physics callback to check when the action has been completed
callback_fn = functools.partial(self.on_sim_step_check, planning_group, joint_state_request)
self._world.add_physics_callback("sim_step_check", callback_fn)
return
# Function to move selected robot to desired pose
def move_to_pose(self, planning_group, position, orientation = [0.0, np.pi/2, 0.0]):
moveit_planning_group = self.robot_joints_data[planning_group]["planning_group"]
self.planning_group = planning_group
quaternion = euler_angles_to_quat(orientation) # reverse the order of the angles to be rxyz as in ROS
self.pose_request = self.create_pose_msg(position, quaternion)
self.pub_group.publish(moveit_planning_group)
self.pub_pose.publish(self.pose_request)
# Add a physics callback to check when the action has been completed
callback_fn = functools.partial(self.on_sim_step_check, planning_group, position)
self._world.add_physics_callback("sim_step_check", callback_fn)
return
# Function to move selected robot to desired pose using cartesian path
def move_along_cartesian_path(self, planning_group, waypoints):
moveit_planning_group = self.robot_joints_data[planning_group]["planning_group"]
self.planning_group = planning_group
self.cartesian_path_request.header.stamp = rospy.Time.now()
self.cartesian_path_request.header.frame_id = 'world' # or whatever frame_id you are using
for waypoint in waypoints:
position, orientation = waypoint
quaternion = euler_angles_to_quat(orientation) # convert euler to quaternion
pose = self.create_pose_msg(position, quaternion)
self.cartesian_path_request.poses.append(pose)
print("Cartesian path request: ", self.cartesian_path_request)
self.pub_group.publish(moveit_planning_group)
self.pub_cartesian_path.publish(self.cartesian_path_request)
# Add a physics callback to check when the action has been completed
self._world.add_physics_callback("sim_step_check", lambda arg: self.on_sim_step_check(planning_group, position))
return
# Function to move selected selected shuttle to desired position
def move_shuttle_to_target(self, xbot_id: int , target_x, target_y):
# Check if the xbot_id exists in xbot_ids
if xbot_id in self.xbot_ids:
# Update the corresponding target_x and target_y values
self.targets_x[xbot_id - 1] = target_x
self.targets_y[xbot_id - 1] = target_y
else:
# If the xbot_id doesn't exist in xbot_ids, raise an exception
raise ValueError(f"xbot_id {xbot_id} not found in xbot_ids")
desired_position = [target_x, target_y]
print("xbot_id_function: ", xbot_id)
print("desired_position: ", desired_position)
# Add physics callback to move the selected shuttle to the desired position
# and to check when the action has been completed
self._world.add_physics_callback("sim_step_shuttles", self.sim_xbots_movement)
callback_fn = functools.partial(self.on_sim_step_check, xbot_id, desired_position)
self._world.add_physics_callback("sim_step_check", callback_fn)
# self._world.add_physics_callback("sim_step_check", lambda xbot_id=xbot_id, desired_position=desired_position: self.on_sim_step_check(xbot_id, desired_position))
def attach_object(self, planning_group, state, item):
# Attach the shuttle to the robot arm
callback_fn = functools.partial(self.on_sim_attach_object, planning_group, state, item)
self._world.add_physics_callback("sim_attach_object", callback_fn)
def on_sim_attach_object(self, planning_group, state, item, step_size = 0.01):
# Get prim of item
prim_item = self.items_prim_dict['prim_{}'.format(item)]
# Get prim of robot arm
offset = 0.02
if isinstance(planning_group, int):
if state == True:
shuttle_pos = self.get_shuttle_position(planning_group)
prim_item.GetAttribute('xformOp:translate').Set(( shuttle_pos[0], shuttle_pos[1] , shuttle_pos[2] + offset ))
elif isinstance(planning_group, str):
# eef_pos, eef_orient = self.get_eef_link_position(planning_group)
print("Not working")
# # Set the position of the item
# item_pos = prim_item.GetAttribute('xformOp:translate').Get()
# prim_item.GetAttribute('xformOp:translate').Set(( eef_pos[1] + 1.03443 , -eef_pos[0] +1.46063 -0.18, eef_pos[2] + 1 ))
# # CHECK Maybe create a fake point in between both grippers to attach the item to the robot arm
# # Convert orientation from GfQuatd to GfQuatf
# # eef_orient_f = Gf.Quatf(eef_orient)
# # print(eef_orient_f)
# # prim_item.GetAttribute('xformOp:orient').Set(eef_orient_f)
# # Transform orientation from euler angles to quaternion
# quat_prim = euler_angles_to_quat([0.0, 0.0, 0.0])
# quat = Gf.Quatf(*quat_prim)
# # Set Orientation of item
# prim_item.GetAttribute('xformOp:orient').Set(quat)
# Function to open and close the gripper
def gripper_control(self, planning_group, state):
if state == "open":
self.move_to_joint_state(planning_group, [0.0 , 0.0])
elif state == "close":
self.move_to_joint_state(planning_group, [-0.0030 , -0.0030])
else:
raise ValueError(f"state {state} not found in gripper_control")
desired_position = state
callback_fn = functools.partial(self.on_sim_step_check, planning_group, desired_position)
self._world.add_physics_callback("sim_step_check", callback_fn)
## GET DATA FUNCTIONS
def get_eef_link_position(self, robot_arm):
# Collect end effector position
prim_eef_link = self.eef_link_prim_dict[robot_arm] # Robot arm is a string (e.g. "robot_arm_1"")
eef_pos = prim_eef_link.GetAttribute('xformOp:translate').Get()
eef_orient = prim_eef_link.GetAttribute('xformOp:orient').Get()
return eef_pos[0], eef_pos[1], eef_pos[2], eef_orient
# return eef_pos, eef_orient
def get_shuttle_position(self, xbot_id):
# Retrieve the shuttle position
shuttle_prim = self.shuttles_prim_dict["prim_{}".format(xbot_id)]
shuttle_pos = shuttle_prim.GetAttribute('xformOp:translate').Get()
return shuttle_pos[0], shuttle_pos[1], shuttle_pos[2]
def get_gripper_joints_position(self, robot_hand):
""" Get the current joint positions of the robot gripper """
# Create an ArticulationSubset instance
articulation_subset = ArticulationSubset(articulation=self.kukas, joint_names=self.robot_joints_data[robot_hand]['joints'])
# Get the joint positions
joint_pos_left, joint_pos_right = articulation_subset.get_joint_positions()
return joint_pos_left, joint_pos_right
def get_joints_position(self, robot_arm):
""" Get the current joint positions of the robot arm """
articulation_subset = ArticulationSubset(articulation=self.kukas, joint_names=self.robot_joints_data[robot_arm]['joints'])
current_joint_values = articulation_subset.get_joint_positions()
# # Debugging:
# current_joint_states = self.get_joints_position("robot_arm_1")
# carb.log_warn("Current joint states {}: {}".format("robot_arm_1" ,repr(current_joint_states)))
# current_joint_states = self.get_joints_position("robot_arm_2")
# carb.log_warn("Current joint states {}: {}".format("robot_arm_2" ,repr(current_joint_states)))
# current_joint_states = self.get_joints_position("robot_arm_3")
# carb.log_warn("Current joint states {}: {}".format("robot_arm_3" ,repr(current_joint_states)))
# current_joint_states = self.get_joints_position("robot_arm_4")
# carb.log_warn("Current joint states {}: {}".format("robot_arm_4" ,repr(current_joint_states)))
# current_joint_states = self.get_joints_position("robot_arm_5")
# carb.log_warn("Current joint states {}: {}".format("robot_arm_5" ,repr(current_joint_states)))
return current_joint_values
def has_reached_position(self, planning_group, desired_position, tolerance=0.01):
"""
Check if the robot/shuttle has reached the desired position
planning_group: string (Robot Arm) or integer (Shuttle)
desired_position: list of 3 floats [x, y, z] in Isaac Sim coordinates or string ("open" or "close") for gripper
"""
if isinstance(desired_position, str) and desired_position in ["open", "close"]:
# Get the gripper joint positions
joint_pos_left, joint_pos_right = self.get_gripper_joints_position(planning_group)
print("Joint positions: ", joint_pos_left, joint_pos_right)
# Check if the gripper is open or closed
if (desired_position == "close" and (joint_pos_left < -0.0010 or joint_pos_right < -0.0010)) or \
(desired_position == "open" and (joint_pos_left > -0.0001 and joint_pos_right > -0.0001)):
elapsed_time = time.time() - self.start_time
action_name = "{} gripper {}".format(planning_group, desired_position)
self.action_times.setdefault(action_name, []).append(elapsed_time)
carb.log_warn("{} completed in {:.3f} seconds".format(action_name, elapsed_time))
self.action_completed = True # Set the action_completed flag to True
return True
else:
print("Current gripper position: ", joint_pos_left, joint_pos_right)
return False
elif isinstance(planning_group, str): # Get current position of the robot
if len(desired_position) == 3: # Move to Pose checking (eef position)
current_position = self.get_eef_link_position(planning_group)
# Compute the distance between the current position and the desired position
distance = math.sqrt((current_position[0] - desired_position[0])**2 +
(current_position[1] - desired_position[1])**2 +
(current_position[2] - desired_position[2])**2)
# Check if the distance is within the tolerance
if distance <= tolerance:
elapsed_time = time.time() - self.start_time
action_name = "{} moved to target".format(planning_group)
self.action_times.setdefault(action_name, []).append(elapsed_time)
carb.log_warn("{} completed in {:.3f} seconds".format(action_name, elapsed_time))
self.action_completed = True # Set the action_completed flag to True
current_joint_states = self.get_joints_position(planning_group)
carb.log_warn("Current joint states: {}".format(repr(current_joint_states)))
return True
else:
print("Current position: ", current_position)
print("Distance: ", distance)
return False
elif len(desired_position) == 6: # Move to Joint States checking (joint positions)
current_joint_states = self.get_joints_position(planning_group)
# Compute the distance between the current position and the desired position
distance = math.sqrt((current_joint_states[0] - desired_position[0])**2 +
(current_joint_states[1] - desired_position[1])**2 +
(current_joint_states[2] - desired_position[2])**2 +
(current_joint_states[3] - desired_position[3])**2 +
(current_joint_states[4] - desired_position[4])**2 +
(current_joint_states[5] - desired_position[5])**2)
# Check if the distance is within the tolerance
if distance <= tolerance:
elapsed_time = time.time() - self.start_time
action_name = "{} moved to joint states".format(planning_group)
self.action_times.setdefault(action_name, []).append(elapsed_time)
carb.log_warn("{} completed in {:.3f} seconds".format(action_name, elapsed_time))
self.action_completed = True
else:
print("Current position: ", current_joint_states)
print("Distance: ", distance)
return False
else:
print("Invalid desired position")
return False
if isinstance(planning_group, int):
# Get current position of the shuttle
current_position = self.get_shuttle_position(planning_group)
# Compute the distance between the current position and the desired position
distance = math.sqrt((current_position[0] - desired_position[0])**2 +
(current_position[1] - desired_position[1])**2)
# Check if the distance is within the tolerance
if distance <= tolerance:
elapsed_time = time.time() - self.start_time
action_name = "Shuttle {} moved to target".format(planning_group)
self.action_times.setdefault(action_name, []).append(elapsed_time)
carb.log_warn("{} completed in {:.3f} seconds".format(action_name, elapsed_time))
self.action_completed = True # Set the action_completed flag to True
return True
else:
print("Current position: ", current_position)
print("Distance: ", distance)
return False
else:
print("Invalid planning group type. Must be a string for a robot arm or integer for a shuttle.")
return False
def print_action_times_summary(self):
# Print the sum of times for each action, ordered by the number of actions
for action, times in sorted(self.action_times.items(), key=lambda item: len(item[1])):
carb.log_warn("Action '{}': completed {} times, total time {:.3f} seconds".format(action, len(times), sum(times)))
def execute_actions(self):
if len(self.recipe) > 0:
if self.action_completed:
action = self.recipe.pop(0) # Retrieve the first action in the list
action_name = action['action']
parameters = action['parameters']
self.start_time = time.time() # Record the start time for each action
# Print the action to be executed with its parameters
carb.log_warn("Executing action: " + action_name + ": " + str(parameters))
world= self.get_world()
if world.physics_callback_exists("sim_step_check"):
world.remove_physics_callback("sim_step_check")
if world.physics_callback_exists("sim_step_shuttles"):
world.remove_physics_callback("sim_step_shuttles")
self.action_completed = False # Set the action_completed flag to False
if action_name == 'MOVE_TO_JOINT_STATE':
self.move_to_joint_state(**parameters) # The ** operator is used to unpack the dictionary into keyword arguments
elif action_name == 'MOVE_TO_POSE_MOVEIT':
self.move_to_pose(**parameters) # The ** operator is used to unpack the dictionary into keyword arguments
elif action_name == 'MOVE_TO_POSE_IN_PLATFORM':
position_xy = self.platform_pos_to_coordinates(parameters['position'][0],parameters['position'][1], moveit_offset = True)
self.move_to_pose(parameters['planning_group'], [position_xy[0],position_xy[1],parameters['position'][2]], parameters['orientation'])
elif action_name == 'MOVE_ALONG_CARTESIAN_PATH':
self.move_along_cartesian_path(**parameters)
elif action_name == 'MOVE_SHUTTLE_TO_TARGET':
position_xy = self.platform_pos_to_coordinates(parameters['target_x'],parameters['target_y'], moveit_offset = False)
xbot_id = int(parameters['xbot_id'])
self.move_shuttle_to_target(xbot_id, position_xy[0], position_xy[1])
elif action_name == 'GRIPPER_CONTROL':
self.gripper_control(**parameters)
elif action_name == 'ATTACH_OBJECT':
if parameters['state'] == True:
self.attach_object(**parameters)
elif parameters['state'] == False:
world= self.get_world()
if world.physics_callback_exists("sim_attach_object"):
world.remove_physics_callback("sim_attach_object") # Remove the physics callback
self.action_completed = True
else:
print("Invalid action name: ", action_name)
else:
world= self.get_world()
if world.physics_callback_exists("sim_step_auto_play"):
world.remove_physics_callback("sim_step_auto_play")
if world.physics_callback_exists("sim_step_check"):
world.remove_physics_callback("sim_step_check")
if world.physics_callback_exists("sim_step_shuttles"):
world.remove_physics_callback("sim_step_shuttles")
carb.log_warn("Recipe completed!")
self.print_action_times_summary()
async def _on_start_experiment_event_async(self):
self.action_completed = True
self._world.add_physics_callback("sim_step_auto_play", callback_fn=self.on_automatic_execution)
#self.execute_actions()
return
def on_impulse_event(self, step_size):
# Tick the Publish/Subscribe JointState, Publish TF and Publish Clock nodes each frame
og.Controller.set(og.Controller.attribute("/World/Kuka_Multiple_Arms/ActionGraph/OnImpulseEvent.state:enableImpulse"), True)
def on_sim_step_check(self, planning_group, desired_position, step_size=1):
# Check if the robot has reached the desired position
self.has_reached_position(planning_group, desired_position)
def on_automatic_execution(self, step_size=1):
# Execute the actions in the recipe
self.execute_actions()
async def setup_pre_reset(self):
# world = self.get_world()
# if world.physics_callback_exists("sim_step"):
# world.remove_physics_callback("sim_step")
return
async def setup_post_reset(self):
# await self._world.play_async()
return
def world_cleanup(self):
return
# Move xbots in simulation (No collision detection)
def sim_xbots_movement(self, step_size):
max_speed = 1.0 # m/s
move_increment = step_size * max_speed
for shuttle_number in range(self._number_shuttles):
prim = self.shuttles_prim_dict["prim_{}".format(shuttle_number + 1)]
current_pos = prim.GetAttribute('xformOp:translate').Get()
#Move shuttle up
if (self.targets_y[shuttle_number]) > current_pos[1]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], current_pos[1] + move_increment, current_pos[2]))
if (current_pos[1] + move_increment) > self.targets_y[shuttle_number]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], self.targets_y[shuttle_number], current_pos[2]))
# Move shuttle down
elif (self.targets_y[shuttle_number]) < current_pos[1]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], current_pos[1] - move_increment, current_pos[2]))
if (current_pos[1] - move_increment) < self.targets_y[shuttle_number]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], self.targets_y[shuttle_number], current_pos[2]))
# check if we reached the target in y axis, then start moving in x direction.
if abs(current_pos[1] - self.targets_y[shuttle_number]) < move_increment:
# Move shuttle right
if (self.targets_x[shuttle_number]) > current_pos[0]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0] + move_increment, current_pos[1], current_pos[2]))
if (current_pos[0] + move_increment) > self.targets_x[shuttle_number]:
prim.GetAttribute('xformOp:translate').Set((self.targets_x[shuttle_number], current_pos[1], current_pos[2]))
# Move shuttle left
elif (self.targets_x[shuttle_number]) < current_pos[0]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0] - move_increment, current_pos[1], current_pos[2]))
if (current_pos[0] - move_increment) < self.targets_x[shuttle_number]:
prim.GetAttribute('xformOp:translate').Set((self.targets_x[shuttle_number], current_pos[1], current_pos[2]))
# Move xbots in simulation (Checking other shuttles in the path)
def sim_xbots_movement_collision(self, step_size):
max_speed = 1.0 # m/s
move_increment = step_size * max_speed
for xbot in range(self._number_shuttles):
prim = self.shuttles_prim_dict["prim_{}".format(xbot + 1)]
current_pos = prim.GetAttribute('xformOp:translate').Get()
x_pos_control = []
y_pos_control = []
# Collect all shuttles positions
for shuttle_number in range(self._number_shuttles):
prim_others = self.shuttles_prim_dict["prim_{}".format(shuttle_number + 1)]
shuttles_pos = prim_others.GetAttribute('xformOp:translate').Get()
x_pos_control.append(shuttles_pos[0])
y_pos_control.append(shuttles_pos[1])
# Decide which direction to move in
dx = self.targets_x[xbot] - current_pos[0]
dy = self.targets_y[xbot] - current_pos[1]
for shuttle in range(self._number_shuttles):
continue_flag = False
if xbot != shuttle and ((current_pos[1] > (y_pos_control[shuttle] - 0.0602 - move_increment) and current_pos[1] < (y_pos_control[shuttle] + 0.0602 + move_increment)) or (current_pos[0] > (x_pos_control[shuttle] - 0.0602 - move_increment) and current_pos[0] < (x_pos_control[shuttle] + 0.0602 + move_increment))):
continue_flag = True
if continue_flag:
continue
# if moving right is safe
if dx > 0:
prim.GetAttribute('xformOp:translate').Set((current_pos) + (move_increment, 0.0, 0.0))
if (current_pos[0] + move_increment) > self.targets_x[xbot]:
prim.GetAttribute('xformOp:translate').Set((self.targets_x[xbot], current_pos[1], current_pos[2]))
break
# if moving left is safe
elif dx < 0:
prim.GetAttribute('xformOp:translate').Set((current_pos) - (move_increment, 0.0 , 0.0))
if (current_pos[0] - move_increment) < self.targets_x[xbot]:
prim.GetAttribute('xformOp:translate').Set((self.targets_x[xbot], current_pos[1], current_pos[2]))
break
# if moving up is safe
if dy > 0:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], current_pos[1] + move_increment, current_pos[2]))
if (current_pos[1] + move_increment) > self.targets_y[xbot]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], self.targets_y[xbot], current_pos[2]))
break
# if moving down is safe
elif dy < 0:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], current_pos[1] - move_increment, current_pos[2]))
if (current_pos[1] - move_increment) < self.targets_y[xbot]:
prim.GetAttribute('xformOp:translate').Set((current_pos[0], self.targets_y[xbot], current_pos[2]))
break
# Read shuttles position and orientation from physical setup
def read_xbots_positions(self, step_size):
# Read info for every shuttle
xbot_list = bot.get_all_xbot_info(1)
xbot_positions = [(xbot.x_pos, xbot.y_pos, xbot.z_pos,
xbot.rx_pos, xbot.ry_pos, xbot.rz_pos,
xbot.xbot_state) for xbot in xbot_list]
# Set position and orientation of shuttles
for shuttle_number in range(self._number_shuttles):
prim = self.shuttles_prim_dict["prim_{}".format(shuttle_number + 1)]
# Set position of shuttle
prim.GetAttribute('xformOp:translate').Set((xbot_positions[shuttle_number][0],
xbot_positions[shuttle_number][1] ,
xbot_positions[shuttle_number][2] + 1.06))
# Transform orientation from euler angles to quaternion
quat_prim = (euler_angles_to_quat([xbot_positions[shuttle_number][3],
xbot_positions[shuttle_number][4],
xbot_positions[shuttle_number][5]]))
# quat = Gf.Quatd(*quat_prim)
quat = Gf.Quatf(*quat_prim)
# Set Orientation of shuttle
prim.GetAttribute('xformOp:orient').Set(quat)
def send_xbots_positions(self, step_size):
"""Send commands to the Xbots to move them to the next target position.
Planning is done using PMC algorithm."""
# Only update the Xbots if at least some time (s) have passed since the last update
if time.time() - self.last_update_time >= 0.5:
#print(bot.get_xbot_status(xbot_id=xid).xbot_state)
xbot_list = bot.get_all_xbot_info(1)
xbot_positions = [(xbot.x_pos, xbot.y_pos, xbot.z_pos,
xbot.rx_pos, xbot.ry_pos, xbot.rz_pos,
xbot.xbot_state) for xbot in xbot_list]
# Don't send commands while the xbots are moving
if all(xbot_state[6] == pmc_types.XbotState.XBOT_IDLE for xbot_state in xbot_positions): #xbot_state[6] --> xbot_state
# Get random unique targets for each shuttle
targets_x, targets_y = self.create_random_coordinates(self._number_shuttles)
print("target_x ", targets_x)
print("target_y ", targets_y)
bot.auto_driving_motion_si(self._number_shuttles, xbot_ids=self.xbot_ids, targets_x=targets_x, targets_y=targets_y)
else:
print("Xbots are moving")
self.last_update_time = time.time()
# if bot.get_xbot_status(xbot_id=xid).xbot_state is pmc_types.XbotState.XBOT_IDLE:
# #self.sample_motions(input_id=xid)
# bot.auto_driving_motion_si(8, xbot_ids=xbot_ids, targets_x=targets_x, targets_y=targets_y)
# # Recover Disabled xbot
# elif bot.get_xbot_status(xbot_id=xid).xbot_state is pmc_types.XbotState.XBOT_DISABLED:
# bot.recover_accident_xbot(xbot_id=xid)
# print("Recovering xbot: ", xid)
def create_random_coordinates(self, num_shuttles):
"""Create random coordinates for each shuttle in num_shuttles"""
x_coords = []
y_coords = []
coords_dict = {}
for i in range(num_shuttles):
while True:
x = random.randint(0, 5) * 0.12 + 0.06
y = random.randint(0, 7) * 0.12 + 0.06
if (x, y) not in coords_dict:
coords_dict[(x, y)] = 1
break
x_coords.append(x)
y_coords.append(y)
return x_coords, y_coords
def sample_motions(self, input_id):
max_speed = 1.0
max_accel = 10.0
bot.linear_motion_si(xbot_id=input_id, target_x=0.18, target_y=0.06,
max_speed=max_speed, max_accel=max_accel)
bot.linear_motion_si(xbot_id=input_id, target_x=0.18, target_y=0.90,
max_speed=max_speed, max_accel=max_accel)
bot.linear_motion_si(xbot_id=input_id, target_x=0.66, target_y=0.90,
max_speed=max_speed, max_accel=max_accel)
bot.linear_motion_si(xbot_id=input_id, target_x=0.66, target_y=0.06,
max_speed=max_speed, max_accel=max_accel)
# bot.rotary_motion_timed_spin(xbot_id=input_id,rot_time=3, target_rz=3.14,
# max_speed=3.0, max_accel=max_accel)
# bot.linear_motion_si(xbot_id=input_id, target_x=0.60, target_y=0.36,
# max_speed=max_speed, max_accel=max_accel)
# bot.rotary_motion_timed_spin(xbot_id=input_id,rot_time=3, target_rz=3.14,
# max_speed=3.0, max_accel=max_accel)
def wait_for_xbot_done(xid):
while bot.get_xbot_status(xbot_id=xid).xbot_state is not pmc_types.XbotState.XBOT_IDLE:
time.sleep(0.5)
def _connect_pmc(self):
"""Connect to PMC and gain mastership"""
# Connect to PMC
sys.auto_connect_to_pmc()
if not sys.auto_connect_to_pmc():
sys.connect_to_pmc("192.168.10.100") #sys.auto_connect_to_pmc()
carb.log_warn("Connected: " + str(sys.auto_connect_to_pmc()))
carb.log_warn("Status: " + str(sys.get_pmc_status()))
# Gain mastership
if not sys.is_master():
sys.gain_mastership()
carb.log_warn("Master: " + str(sys.is_master()))
# Activate xBots
bot.activate_xbots()
def create_pose_msg(self, position, orientation, frame_id=''):
"""Create a ROS Pose message object from a position and orientation"""
# Create a new Pose object
pose = Pose()
# Given a position and orientation as lists and a frame id as string, return a PoseStamped message object.
header = Header()
header.frame_id = frame_id
header.stamp = rospy.Time.now()
# Set the position field of the Pose object
position_obj = Point()
position_obj.x = position[0]
position_obj.y = position[1]
position_obj.z = position[2]
pose.position = position_obj
# Set the orientation field of the Pose object (rxyz)
orientation_obj = Quaternion()
orientation_obj.x = orientation[1]
orientation_obj.y = orientation[2]
orientation_obj.z = orientation[3]
orientation_obj.w = orientation[0]
pose.orientation = orientation_obj
pose_stamped = PoseStamped(header=header, pose=pose)
return pose
def platform_pos_to_coordinates(self, x_pos, y_pos, moveit_offset=False, robot_arm=None):
"""
Description: Converts the acopos platform positions to the platform coordinates.
Origin of the matrix is at the bottom left corner (0,0)
Limits of the acopos matrix are (5,7)
Use moveit_offset to convert the coordinates to the moveit frame --> Robot arms EEF Poses.
"""
## TBD - Add robot end effector offsets
if robot_arm is None:
robot_arm = self.planning_group #if self.planning_group is not None else None
lim_x = self.flyways_matrix.shape[1] * 2
lim_y = self.flyways_matrix.shape[0] * 2
# Moveit offset
offset = [1.275, -1.04, 0.0]
if moveit_offset:
x_coord = -(y_pos * 0.12 + 0.06) + offset[0]
y_coord = (x_pos * 0.12 + 0.06) + offset[1]
else:
x_coord = x_pos * 0.12 + 0.06
y_coord = y_pos * 0.12 + 0.06
if x_pos > (lim_x - 1):
raise ValueError("x_pos exceeds the size of the platform.")
if y_pos > (lim_y - 1):
raise ValueError("y_pos exceeds the size of the platform.")
return x_coord, y_coord
##############################################################################################################
########################################## BFS Algortihm #####################################################
##############################################################################################################
def sim_xbots_movement_bfs(self, step_size):
max_speed = 1.0 # m/s
move_increment = step_size * max_speed
for xbot in range(self._number_shuttles):
prim = self.shuttles_prim_dict["prim_{}".format(xbot + 1)]
current_pos = prim.GetAttribute('xformOp:translate').Get()
# Convert current_pos and target to grid coordinates
start = (int((current_pos[0] + 0.06)/0.12), len(self.grid) - 1 - int((current_pos[1] + 0.06)/0.12))
end = (int((self.targets_x[xbot] + (0.06 if self.targets_x[xbot] % 0.12 != 0 else 0))/0.12),
len(self.grid) - 1 - int((self.targets_y[xbot] + (0.06 if self.targets_y[xbot] % 0.12 != 0 else 0))/0.12))
path = self.bfs(self.grid, start, end)
if path is not None and len(path) > 1:
next_step = path[1] # Take the second step in the path (first is current position)
# Convert next_step from grid coordinates back to simulation's coordinates
next_step_sim = ((next_step[0]*0.12) + (0.06 if next_step[0] % 1 != 0 else 0),
((len(self.grid) - 1 - next_step[1])*0.12) + (0.06 if (len(self.grid) - 1 - next_step[1]) % 1 != 0 else 0))
prim.GetAttribute('xformOp:translate').Set((next_step_sim[0], next_step_sim[1], current_pos[2]))
print("Moving xbot {} to {}".format(xbot + 1, next_step_sim))
# BFS algorithm
def bfs(self, grid, start, end):
queue = []
queue.append([start]) # Wrap the start tuple in a list
visited = set(start) # Create a set to store visited nodes
while queue:
path = queue.pop(0)
node = path[-1] # Get the last node in this path
if node == end:
return path
for direction in [(0, 1), (0, -1), (1, 0), (-1, 0)]: # Right, Left, Down, Up
new_node = (node[0] + direction[0], node[1] + direction[1])
if (new_node[0] >= 0 and new_node[0] < len(grid) and # Check grid boundaries
new_node[1] >= 0 and new_node[1] < len(grid[0]) and
grid[new_node[0]][new_node[1]] == 1 and # Check if new_node is walkable
new_node not in visited): # Check if the node has not been visited
new_path = list(path)
new_path.append(new_node)
queue.append(new_path)
visited.add(new_node) # Add the new node to the visited set
print("No valid path found.")
return None | 63,928 | Python | 49.417192 | 344 | 0.580184 |
AndreiVoica/P10-MAP/user_examples/acopos_extension.py | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.user_examples import Acopos
class AcoposExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="",
submenu_name="",
name="Acopos",
title="My Awesome Example",
doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=Acopos(),
)
return
| 1,188 | Python | 41.464284 | 135 | 0.702862 |
AndreiVoica/P10-MAP/user_examples/__init__.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 omni.isaac.examples.user_examples.acopos import Acopos
from omni.isaac.examples.user_examples.acopos_extension import AcoposExtension
| 568 | Python | 46.416663 | 78 | 0.820423 |
AndreiVoica/P10-MAP/user_examples/acopos.py | # Copyright (c) 2020-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 omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core import World
from omni.isaac.core.prims import GeometryPrim, XFormPrim
import omni.kit.commands
from pxr import Sdf, Gf, UsdPhysics
from omni.isaac.core.utils.rotations import euler_angles_to_quat
import numpy as np
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_server_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils.types import ArticulationAction
import carb
from pmclib import system_commands as sys # PMC System related commands
from pmclib import xbot_commands as bot # PMC Mover related commands
from pmclib import pmc_types # PMC API Types
import time
import random
class Acopos(BaseSample):
def __init__(self) -> None:
super().__init__()
# SCENE GEOMETRY
# env (group) spacing:
self._env_spacing = 2.0
self.last_update_time = time.time()
# Lab Setup:
self._lab_setup_position = np.array([0.0, 0.0, 0.0]) # Gf.Vec3f(0.5, 0.0, 0.0)
self._lab_setup_orientation = np.array([0, 0, 0, 1])
self._lab_setup_scale = 1.0
# Shuttles:
self._number_shuttles = 8
self._shuttle_position = np.array([1.2277, -0.9815, 1.07]) # Gf.Vec3f(0.5, 0.0, 0.0)
self._platform_limits = np.array([0.0, 0.0, 0.832, 0.596]) # x_min, y_min, x_max, y_max
self._target = np.array([0.8, 0.52])
self._shuttle_scale = 0.01
# Shuttles Grid:
self._grid_position = np.array([1.2877, -1.0415, 0.0]) # Gf.Vec3f(0.5, 0.0, 0.0)
shuttle_orientation = np.pi/2
self._grid_orientation = np.array([np.cos(shuttle_orientation/2), 0, 0, np.sin(shuttle_orientation/2)]) #Rotates 90 degrees around z-axis
# USD asset paths:
self.asset_folder = "omniverse://localhost/Projects/MAPs-AAU/Assets/"
self.asset_paths = {
"shuttle": self.asset_folder + "120x120x10/acopos_shuttle_120.usd",
"lab_setup": self.asset_folder + "Lab_setup_v2.usd"
}
self.prim_dict = {}
self.control_switch = 1 # 0: Sim, 1: PMC
return
# This function is called to setup the assets in the scene for the first time
# Class variables should not be assigned here, since this function is not called
# after a hot-reload, its only called to load the world starting from an EMPTY stage
def setup_scene(self):
# A world is defined in the BaseSample, can be accessed everywhere EXCEPT __init__
world = self.get_world()
world = World.instance()
world.scene.add_default_ground_plane() # adds a default ground plane to the scene
# Add Lab Setup Reference
add_reference_to_stage(usd_path=self.asset_paths["lab_setup"], prim_path="/World")
world.scene.add(GeometryPrim(prim_path="/World", name=f"lab_setup_ref_geom", collision=True))
# Add Xform reference for the shuttles
world.scene.add(XFormPrim(prim_path="/World/LabSetup/Grid", name=f"Grid"))
# Add shuttles references
for i in range(self._number_shuttles):
add_reference_to_stage(usd_path=self.asset_paths["shuttle"], prim_path="/World/LabSetup/Grid/shuttle_{}".format(i+1))
world.scene.add(GeometryPrim(prim_path="/World/LabSetup/Grid/shuttle_{}".format(i+1),
name="shuttle_{}_ref_geom".format(i+1), collision=True))
# world.scene.add(Robot(prim_path="/World/LabSetup/Grid/shuttle_{}".format(i+1),
# name="shuttle_{}_ref_geom".format(i+1)))
return
# Here we assign the class's variables this function is called after load button is pressed
# regardless starting from an empty stage or not this is called after setup_scene and after
# one physics time step to propagate appropriate physics handles which are needed to retrieve
# many physical properties of the different objects
async def setup_post_load(self):
# Load World and Assets
self._world = self.get_world()
self._world.scene.enable_bounding_boxes_computations()
# Add USD Assets
await self._add_lab_setup()
await self._add_shuttles_grid()
for i in range(self._number_shuttles):
await self._add_shuttle(i)
# Shuttles Prim Dictionary
stage = omni.usd.get_context().get_stage()
for shuttle_number in range(self._number_shuttles):
shuttle_path = "/World/LabSetup/Grid/shuttle_{}".format(shuttle_number + 1)
prim = stage.GetPrimAtPath(shuttle_path)
if prim:
key_name = "prim_{}".format(shuttle_number + 1)
self.prim_dict[key_name] = prim
else:
print("Error: shuttle prim not found at path {}".format(shuttle_path))
# Control Switch
if self.control_switch == 0:
self._world.add_physics_callback("sim_step", callback_fn=self.sim_xbots_movement)
elif self.control_switch == 1:
self.connect_pmc() # Connect to PMC
self._world.add_physics_callback("sim_step", callback_fn=self.read_xbots_positions) #callback names have to be unique
self._world.add_physics_callback("sim_step_move", callback_fn=self.send_xbots_positions)
return
# Add Lab Setup reference
async def _add_lab_setup(self):
self._lab_setup_ref_geom = self._world.scene.get_object(f"lab_setup_ref_geom")
self._lab_setup_ref_geom.set_local_scale(np.array([self._lab_setup_scale]))
self._lab_setup_ref_geom.set_world_pose(position=self._lab_setup_position,
orientation=self._lab_setup_orientation)
self._lab_setup_ref_geom.set_default_state(position=self._lab_setup_position,
orientation=self._lab_setup_orientation)
# lb = self._world.scene.compute_object_AABB(name=f"lab_setup_ref_geom")
# zmin = lb[0][2]
# zmax = lb[1][2]
# self._lab_setup_position[2] = -zmin
# self._lab_setup_height = zmax
self._lab_setup_ref_geom.set_collision_approximation("none")
#self._convexIncludeRel.AddTarget(self._table_ref_geom.prim_path)
# Add xForm shuttles reference
async def _add_shuttles_grid(self):
self._shuttles_grid_ref_geom = self._world.scene.get_object(f"Grid")
self._shuttles_grid_ref_geom.set_world_pose(position=self._grid_position,
orientation=self._grid_orientation)
self._shuttles_grid_ref_geom.set_default_state(position=self._grid_position,
orientation=self._grid_orientation)
# Add shuttles to the scene
async def _add_shuttle(self, shuttle_number):
self._shuttle_ref_geom = self._world.scene.get_object(f"shuttle_{shuttle_number+1}_ref_geom")
self._shuttle_ref_geom.set_local_scale(np.array([self._shuttle_scale]))
self._shuttle_ref_geom.set_world_pose(position= self._shuttle_position + (-0.121 * (shuttle_number), 0, 0))
self._shuttle_ref_geom.set_default_state(position=self._shuttle_position)
self._shuttle_ref_geom.set_collision_approximation("none")
#self._shuttle_articulation_controller = self._shuttle.get_articulation_controller()
async def on_sim_control_event_async(self):
world = self.get_world()
world.add_physics_callback("sim_step", self.sim_xbots_movement)
await world.play_async()
return
# def on_pmc_connection_event(self):
# self.connect_pmc()
# return
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
return
def world_cleanup(self):
return
def sim_xbots_movement(self, step_size):
#print("step_size: ", step_size)
#print(self.translate)
#stage = omni.usd.get_context().get_stage()
max_speed = 3.0 # m/s
max_accel = 10.0 # m/s^2
for shuttle_number in range(1):
# for shuttle_number in range(self._number_shuttles):
prim = self.prim_dict["prim_{}".format(shuttle_number + 1)]
current_pos = prim.GetAttribute('xformOp:translate').Get()
# Move cube to the right
if (self._target[1] + 0.1) < current_pos[0]:
prim.GetAttribute('xformOp:translate').Set((current_pos)-(step_size*max_speed, 0.0, 0.0))
continue
# Move cube to the left
elif (self._target[1] - 0.1) > current_pos[0]:
prim.GetAttribute('xformOp:translate').Set((current_pos)+(step_size*max_speed, 0.0, 0.0))
continue
#current_pos = prim.GetAttribute('xformOp:translate').Get()
# Move cube up
if (self._target[0] + 0.1) > current_pos[1]:
prim.GetAttribute('xformOp:translate').Set((current_pos)+(0.0, step_size*max_speed, 0.0))
continue
# Move cube down
elif (self._target[0] - 0.1) < current_pos[1]:
prim.GetAttribute('xformOp:translate').Set((current_pos)-(0.0, step_size*max_speed, 0.0))
continue
# Read shuttles position and orientation from physical setup
def read_xbots_positions(self, step_size):
# Read info for every shuttle
xbot_list = bot.get_all_xbot_info(1)
xbot_positions = [(xbot.x_pos, xbot.y_pos, xbot.z_pos,
xbot.rx_pos, xbot.ry_pos, xbot.rz_pos,
xbot.xbot_state) for xbot in xbot_list]
# Set position and orientation of shuttles
for shuttle_number in range(self._number_shuttles):
prim = self.prim_dict["prim_{}".format(shuttle_number + 1)]
# Set position of shuttle
prim.GetAttribute('xformOp:translate').Set((xbot_positions[shuttle_number][0],
xbot_positions[shuttle_number][1] ,
xbot_positions[shuttle_number][2] + 1.06))
# Transform orientation from euler angles to quaternion
quat_prim = (euler_angles_to_quat([xbot_positions[shuttle_number][3],
xbot_positions[shuttle_number][4],
xbot_positions[shuttle_number][5]]))
quat = Gf.Quatd(*quat_prim)
# Set Orientation of shuttle
prim.GetAttribute('xformOp:orient').Set(quat)
def send_xbots_positions(self, step_size):
xbot_ids = [1, 2, 3, 4, 5, 6, 7, 8]
# Only update the Xbots if at least 2 seconds have passed since the last update
if time.time() - self.last_update_time >= 2:
#print(bot.get_xbot_status(xbot_id=xid).xbot_state)
xbot_list = bot.get_all_xbot_info(1)
xbot_positions = [(xbot.x_pos, xbot.y_pos, xbot.z_pos,
xbot.rx_pos, xbot.ry_pos, xbot.rz_pos,
xbot.xbot_state) for xbot in xbot_list]
# Don't send commands while the xbots are moving
if all(xbot_state[6] == pmc_types.XbotState.XBOT_IDLE for xbot_state in xbot_positions):
# Get random unique targets for each shuttle
targets_x, targets_y = self.create_random_coordinates(self._number_shuttles)
print("target_x ", targets_x)
print("target_y ", targets_y)
bot.auto_driving_motion_si(8, xbot_ids=xbot_ids, targets_x=targets_x, targets_y=targets_y)
else:
print("Xbots are moving")
self.last_update_time = time.time()
# if bot.get_xbot_status(xbot_id=xid).xbot_state is pmc_types.XbotState.XBOT_IDLE:
# #self.sample_motions(input_id=xid)
# bot.auto_driving_motion_si(8, xbot_ids=xbot_ids, targets_x=targets_x, targets_y=targets_y)
# # Recover Disabled xbot
# elif bot.get_xbot_status(xbot_id=xid).xbot_state is pmc_types.XbotState.XBOT_DISABLED:
# bot.recover_accident_xbot(xbot_id=xid)
# print("Recovering xbot: ", xid)
def create_random_coordinates(self, num_shuttles):
x_coords = []
y_coords = []
coords_dict = {}
for i in range(num_shuttles):
while True:
x = random.randint(0, 6) * 0.12 + 0.06
y = random.randint(0, 8) * 0.12 + 0.06
if (x, y) not in coords_dict:
coords_dict[(x, y)] = 1
break
x_coords.append(x)
y_coords.append(y)
return x_coords, y_coords
def sample_motions(self, input_id):
max_speed = 1.0
max_accel = 10.0
bot.linear_motion_si(xbot_id=input_id, target_x=0.18, target_y=0.06,
max_speed=max_speed, max_accel=max_accel)
bot.linear_motion_si(xbot_id=input_id, target_x=0.18, target_y=0.90,
max_speed=max_speed, max_accel=max_accel)
bot.linear_motion_si(xbot_id=input_id, target_x=0.66, target_y=0.90,
max_speed=max_speed, max_accel=max_accel)
bot.linear_motion_si(xbot_id=input_id, target_x=0.66, target_y=0.06,
max_speed=max_speed, max_accel=max_accel)
# bot.rotary_motion_timed_spin(xbot_id=input_id,rot_time=3, target_rz=3.14,
# max_speed=3.0, max_accel=max_accel)
# bot.linear_motion_si(xbot_id=input_id, target_x=0.60, target_y=0.36,
# max_speed=max_speed, max_accel=max_accel)
# bot.rotary_motion_timed_spin(xbot_id=input_id,rot_time=3, target_rz=3.14,
# max_speed=3.0, max_accel=max_accel)
def wait_for_xbot_done(xid):
while bot.get_xbot_status(xbot_id=xid).xbot_state is not pmc_types.XbotState.XBOT_IDLE:
time.sleep(0.5)
def connect_pmc(self):
# Connect to PMC
if not sys.auto_connect_to_pmc():
sys.connect_to_pmc("192.168.10.100") #sys.auto_connect_to_pmc()
print("Connected: ", sys.auto_connect_to_pmc())
print("Status: ", sys.get_pmc_status())
# Gain mastership
if not sys.is_master():
sys.gain_mastership()
print("Master: ", sys.is_master())
# Activate xBots
bot.activate_xbots()
############################################################################################################
def print_cube_info(self, step_size):
position, orientation = self._cube.get_world_pose()
linear_velocity = self._cube.get_linear_velocity()
# will be shown on terminal
print("Cube position is : " + str(position))
print("Cube's orientation is : " + str(orientation))
print("Cube's linear velocity is : " + str(linear_velocity))
def _change_property(self, prim_path: str, attribute_name:str, value:float):
usd_path = Sdf.Path(prim_path + "." + attribute_name)
omni.kit.commands.execute(
"ChangeProperty",
prop_path=usd_path,
value=value,
prev=self._get_property(prim_path, attribute_name),
)
def _get_property(self, prim_path: str, attribute: str):
prim = self.stage.GetPrimAtPath(prim_path)
prim_property = prim.GetAttribute(attribute)
return prim_property.Get() | 16,317 | Python | 40.734015 | 145 | 0.585953 |
AndreiVoica/P10-MAP/scripts/TestScripts/avoid_obstacles.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 omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
from omni.isaac.motion_generation.lula import RmpFlow
from omni.isaac.motion_generation import ArticulationMotionPolicy
from omni.isaac.core.robots import Robot
from omni.isaac.core.objects import cuboid
from omni.isaac.core import World
from omni.isaac.core.utils.stage import open_stage
import numpy as np
import os
import argparse
#TODO: Fill in tutorial directory with absolute path to this file
TUTORIAL_DIRECTORY = "/home/robotlab/Documents/Github/P10-MAP/"
rmp_config_dir = os.path.join(TUTORIAL_DIRECTORY,"Assets/kr3r540/")
parser = argparse.ArgumentParser()
parser.add_argument("--urdf_path",type=str,default="kr3r540.urdf")
parser.add_argument("--rmpflow_config_path",type=str,default="kr3r540_rmpflow_config.yaml")
parser.add_argument("--end_effector_frame_name",type=str,default="gripper_base_link")
args = parser.parse_args()
open_stage(usd_path=os.path.join(rmp_config_dir,"kr3r540.usd"))
my_world = World(stage_units_in_meters=1.0)
robot = my_world.scene.add(Robot(prim_path="/kuka_kr3r540", name="Kr3r540"))
#Initialize an RmpFlow object
rmpflow = RmpFlow(
robot_description_path = os.path.join(rmp_config_dir,"kr3_description_v1.0.yaml"),
urdf_path = os.path.join(rmp_config_dir,args.urdf_path),
rmpflow_config_path = os.path.join(rmp_config_dir,args.rmpflow_config_path),
end_effector_frame_name = args.end_effector_frame_name, #This frame name must be present in the URDF
maximum_substep_size = .0034
)
physics_dt = 1/60.
articulation_rmpflow = ArticulationMotionPolicy(robot,rmpflow,physics_dt)
articulation_controller = robot.get_articulation_controller()
#Make a target to follow
target_cube = cuboid.VisualCuboid("/World/target",position = np.array([.5,0,.5]),color = np.array([1.,0,0]),size = .1)
#Make an obstacle to avoid
obstacle = cuboid.VisualCuboid("/World/obstacle",position = np.array([.8,0,.5]),color = np.array([0,1.,0]), size = .1)
rmpflow.add_obstacle(obstacle)
my_world.reset()
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
#Set rmpflow target to be the current position of the target cube.
rmpflow.set_end_effector_target(
target_position=target_cube.get_world_pose()[0],
#target_orientation=target_cube.get_world_pose()[1]
)
#Query the current obstacle position
rmpflow.update_world()
actions = articulation_rmpflow.get_next_articulation_action()
articulation_controller.apply_action(actions)
simulation_app.close()
| 3,123 | Python | 37.567901 | 118 | 0.741274 |
AndreiVoica/P10-MAP/scripts/TestScripts/test.py | from omni.isaac.manipulators import SingleManipulator
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.core.utils.types import ArticulationAction
import numpy as np
from omni.isaac.dynamic_control import _dynamic_control
dc = _dynamic_control.acquire_dynamic_control_interface()
articulation1 = dc.get_articulation("/World/kr3_01")
# Call this each frame of simulation step if the state of the articulation is changing.
dc.wake_up_articulation(articulation1)
joint_angles1 = [np.random.rand(9) * 2 - 1]
dc.set_articulation_dof_position_targets(articulation1, joint_angles1)
dc = _dynamic_control.acquire_dynamic_control_interface()
articulation2 = dc.get_articulation("/World/kr3_02")
# Call this each frame of simulation step if the state of the articulation is changing.
dc.wake_up_articulation(articulation2)
joint_angles2 = [np.random.rand(9) * 2 - 1]
dc.set_articulation_dof_position_targets(articulation2, joint_angles2)
dc = _dynamic_control.acquire_dynamic_control_interface()
articulation3 = dc.get_articulation("/World/kr3_03")
# Call this each frame of simulation step if the state of the articulation is changing.
dc.wake_up_articulation(articulation3)
joint_angles3 = [np.random.rand(9) * 2 - 1]
dc.set_articulation_dof_position_targets(articulation3, joint_angles3)
dc = _dynamic_control.acquire_dynamic_control_interface()
articulation4 = dc.get_articulation("/World/kr3_04")
# Call this each frame of simulation step if the state of the articulation is changing.
dc.wake_up_articulation(articulation4)
joint_angles4 = [np.random.rand(9) * 2 - 1]
dc.set_articulation_dof_position_targets(articulation4, joint_angles4)
dc = _dynamic_control.acquire_dynamic_control_interface()
articulation5 = dc.get_articulation("/World/kr4")
# Call this each frame of simulation step if the state of the articulation is changing.
dc.wake_up_articulation(articulation5)
joint_angles5 = [np.random.rand(9) * 2 - 1]
dc.set_articulation_dof_position_targets(articulation5, joint_angles5)
'''
dc = _dynamic_control.acquire_dynamic_control_interface()
articulationGrip = dc.get_articulation("/World/kr3_03/tool0")
# Call this each frame of simulation step if the state of the articulation is changing.
dc.wake_up_articulation(articulationGrip)
joint_anglesGrip = [np.random.rand(9) * 2 - 1]
dc.set_articulation_dof_position_targets(articulationGrip, joint_anglesGrip)
'''
'''
dc = _dynamic_control.acquire_dynamic_control_interface()
articulation1 = dc.get_articulation("/World/kr3_01")
dc.wake_up_articulation(articulation1)
dof_ptr1 = dc.find_articulation_dof(articulation1, "joint_a2")
dc.set_dof_position_target(dof_ptr1, -1)
articulation2 = dc.get_articulation("/World/kr3_02")
dc.wake_up_articulation(articulation2)
dof_ptr2 = dc.find_articulation_dof(articulation2, "joint_a2")
dc.set_dof_position_target(dof_ptr2, -1)
'''
| 2,857 | Python | 45.852458 | 87 | 0.782989 |
AndreiVoica/P10-MAP/scripts/TestScripts/planar_motors_basic.py |
def _change_property(self, prim_path: str, attribute_name:str, value:float):
usd_path = Sdf.Path(prim_path + "." + attribute_name)
omni.kit.commands.execute(
"ChangeProperty",
prop_path=usd_path,
value=value,
prev=self._get_property(prim_path, attribute_name),
)
def _get_property(self, prim_path: str, attribute: str):
prim= self.stage.GetPrimAtPath(prim_path)
prim_property = prim.GetAttribute(attribute)
return prim_property.Get() | 492 | Python | 31.866665 | 76 | 0.664634 |
AndreiVoica/P10-MAP/scripts/TestScripts/pipettetest.py | from omni.isaac.manipulators import SingleManipulator
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.core.utils.types import ArticulationAction
import numpy as np
from omni.isaac.dynamic_control import _dynamic_control
def home():
dc = _dynamic_control.acquire_dynamic_control_interface()
joint1 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint1)
dof_ptr1 = dc.find_articulation_dof(joint1, "joint_a1")
dc.set_dof_position_target(dof_ptr1, 0)
joint2 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint2)
dof_ptr2 = dc.find_articulation_dof(joint2, "joint_a2")
dc.set_dof_position_target(dof_ptr2, 0)
joint3 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint3)
dof_ptr3 = dc.find_articulation_dof(joint3, "joint_a3")
dc.set_dof_position_target(dof_ptr3, 0)
joint4 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint4)
dof_ptr4 = dc.find_articulation_dof(joint4, "joint_a4")
dc.set_dof_position_target(dof_ptr4, 0)
joint5 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint5)
dof_ptr5 = dc.find_articulation_dof(joint5, "joint_a5")
dc.set_dof_position_target(dof_ptr5, 0)
joint6 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint6)
dof_ptr6 = dc.find_articulation_dof(joint1, "joint_a6")
dc.set_dof_position_target(dof_ptr6, 0)
def position1():
dc = _dynamic_control.acquire_dynamic_control_interface()
joint1 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint1)
dof_ptr1 = dc.find_articulation_dof(joint1, "joint_a1")
dc.set_dof_position_target(dof_ptr1, 0)
joint2 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint2)
dof_ptr2 = dc.find_articulation_dof(joint2, "joint_a2")
dc.set_dof_position_target(dof_ptr2, -0.33)
joint3 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint3)
dof_ptr3 = dc.find_articulation_dof(joint3, "joint_a3")
dc.set_dof_position_target(dof_ptr3, 0.342)
joint4 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint4)
dof_ptr4 = dc.find_articulation_dof(joint4, "joint_a4")
dc.set_dof_position_target(dof_ptr4, 0)
joint5 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint5)
dof_ptr5 = dc.find_articulation_dof(joint5, "joint_a5")
dc.set_dof_position_target(dof_ptr5, 0)
joint6 = dc.get_articulation("/World/kr3")
dc.wake_up_articulation(joint6)
dof_ptr6 = dc.find_articulation_dof(joint1, "joint_a6")
dc.set_dof_position_target(dof_ptr6, 0)
home()
position1() | 2,686 | Python | 35.808219 | 61 | 0.699926 |
AndreiVoica/P10-MAP/scripts/TestScripts/basic_follow_target.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 omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
from omni.isaac.motion_generation.lula import RmpFlow
from omni.isaac.motion_generation import ArticulationMotionPolicy
from omni.isaac.core.robots import Robot
from omni.isaac.core.objects import cuboid
from omni.isaac.core import World
from omni.isaac.core.utils.stage import open_stage
import numpy as np
import os
import argparse
#TODO: Fill in tutorial directory with absolute path to this file
TUTORIAL_DIRECTORY = "E:/Stuff/Faculta/P10/Assets/P10-MAP"
rmp_config_dir = os.path.join(TUTORIAL_DIRECTORY,"Assets/kr3r540")
parser = argparse.ArgumentParser()
parser.add_argument("--urdf_path",type=str,default="kr3r540.urdf")
parser.add_argument("--rmpflow_config_path",type=str,default="kr3r540_rmpflow_config.yaml")
parser.add_argument("--end_effector_frame_name",type=str,default="gripper_base_link")
args = parser.parse_args()
open_stage(usd_path=os.path.join(rmp_config_dir,"kr3r540.usd"))
my_world = World(stage_units_in_meters=0.01)
robot = my_world.scene.add(Robot(prim_path="/kr3r540", name="Kr3r540"))
#Initialize an RmpFlow object
rmpflow = RmpFlow(
robot_description_path = os.path.join(rmp_config_dir,"kr3_description_v1.0.yaml"),
urdf_path = os.path.join(rmp_config_dir,args.urdf_path),
rmpflow_config_path = os.path.join(rmp_config_dir,args.rmpflow_config_path),
end_effector_frame_name = args.end_effector_frame_name, #This frame name must be present in the URDF
maximum_substep_size = .0034
)
#Uncomment this line to visualize the collision spheres in the robot_description YAML file
#rmpflow.visualize_collision_spheres()
physics_dt = 1/60.
articulation_rmpflow = ArticulationMotionPolicy(robot,rmpflow,physics_dt)
articulation_controller = robot.get_articulation_controller()
#Make a target to follow
target_cube = cuboid.VisualCuboid("/World/target",position = np.array([0.,0,1.5]),color=np.array([1.,0,0]),size = .1)
my_world.reset()
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
#Set rmpflow target to be the current position of the target cube.
rmpflow.set_end_effector_target(
target_position=target_cube.get_world_pose()[0],
#target_orientation=target_cube.get_world_pose()[1]
)
actions = articulation_rmpflow.get_next_articulation_action()
articulation_controller.apply_action(actions)
simulation_app.close()
| 2,988 | Python | 37.818181 | 117 | 0.750669 |
AndreiVoica/P10-MAP/docs/installation/planar_motor_control_API/basic_example.py | """
Planar Motor Python API Basic Example
(c) Planar Motor Inc 2022
"""
from pmclib import system_commands as sys # PMC System related commands
from pmclib import xbot_commands as bot # PMC Mover related commands
from pmclib import pmc_types # PMC API Types
import time
# %% Connect to the PMC
# To start sending commands to the system, the library must
# first connect to the Planar Motor Controller (PMC) via TCP/IP.
# this can be done by explicitly connecting to a known PMC IP
# address, or by scanning the network using an auto-connect
# command. By default, the PMC IP address is 192.168.10.100.
sys.connect_to_pmc("192.168.10.100")
# or
# sys.auto_connect_to_pmc()
# %% Activating the system
# On bootup, all the movers within the system will be in a
# "Deactivated" state. Which means that they are not actively
# position controlled. To start controlling the system, the
# "activate" command must be sent.
bot.activate_xbots()
# Now we wait for the movers to be levitated and fully controlled.
# This can be done by periodically polling for the PMC status.
maxTime = time.time() + 60 # Set timeout of 60s
while sys.get_pmc_status() is not pmc_types.PmcStatus.PMC_FULLCTRL:
time.sleep(0.5)
if time.time() > maxTime:
raise TimeoutError("PMC Activation timeout")
# %% Basic mover commands
# Now that the mover are levitated, they are now ready to receive
# motion commands.
bot.linear_motion_si(xbot_id=1, target_x=0.06, target_y=0.06,
max_speed=1.0, max_accel=10.0)
# The commands will return as soon the PMC receives and acknowledges
# that the command is valid/invalid. Multiple motion commands can be
# buffered to the same mover, and they will execute continuously in the
# order that the command was sent. Let's define a simple sample motion:
def sample_motions(input_id):
bot.linear_motion_si(xbot_id=input_id, target_x=0.18, target_y=0.06,
max_speed=1.0, max_accel=10.0)
bot.linear_motion_si(xbot_id=input_id, target_x=0.18, target_y=0.18,
max_speed=1.0, max_accel=10.0)
bot.linear_motion_si(xbot_id=input_id, target_x=0.06, target_y=0.18,
max_speed=1.0, max_accel=10.0)
bot.linear_motion_si(xbot_id=input_id, target_x=0.06, target_y=0.06,
max_speed=1.0, max_accel=10.0)
# Sending all commands, will buffer into the movers "Motion Buffer"
sample_motions(input_id=1)
# To check if all buffered motions are complete, we poll for
# the xbot information, and check that it's state is IDLE.
# Let's define a helper function for this:
def wait_for_xbot_done(xid):
while bot.get_xbot_status(xbot_id=xid).xbot_state is not pmc_types.XbotState.XBOT_IDLE:
time.sleep(0.5)
# Now we can wait for all motions buffered to an mover to be
# complete
wait_for_xbot_done(xid=1)
# %% Macros
# We can also save a series of motion commands as a "macro", which
# can be re-used for different movers. Macros are programmed by sending
# commands to mover ID 128 - 191
# First we clear the macro
bot.edit_motion_macro(
option=pmc_types.MotionMacroOptions.CLEAR_MACRO, macro_id=128)
# The the commands can be programmed to the macro
sample_motions(input_id=128)
# Then the macro can be saved,and run
bot.edit_motion_macro(
option=pmc_types.MotionMacroOptions.SAVE_MACRO, macro_id=128)
bot.run_motion_macro(macro_id=128, xbot_id=1)
wait_for_xbot_done(xid=1)
# Macros can be infinitely looped/ chained together by sending
# run_motion_macro commands to macro IDs. i.e. to run macro id
# 128 in a loop:
# First clear the macro so we can edit it again
bot.edit_motion_macro(
option=pmc_types.MotionMacroOptions.CLEAR_MACRO, macro_id=128)
# Send some motion commands
sample_motions(input_id=128)
# Then send run_macro 128 to macro ID 128
bot.run_motion_macro(macro_id=128, xbot_id=128)
bot.edit_motion_macro(
option=pmc_types.MotionMacroOptions.SAVE_MACRO, macro_id=128)
# Now when we run, the macro will infinitely loop
bot.run_motion_macro(macro_id=128, xbot_id=1)
time.sleep(5)
# To stop the motion, we can send the stop motion command
bot.stop_motion(xbot_id=1)
| 4,179 | Python | 34.423729 | 91 | 0.714286 |
AndreiVoica/P10-MAP/docs/installation/planar_motor_control_API/README.md | # PMI_Python_Lib
Python API for interfacing with the Planar Motor Controller
It is highly recommended to create a conda virtual environment when using the API with Isaac Sim. To see how to create conda environment for Isaac Sim check [Isaac Sim Python Environment](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html)
## Installing the library on Windows
First install wheel and pythonnet.
```
# install pythonnet
pip install wheel
pip install pythonnet==2.5.2
```
The library can be installed using `pip install /path/to/.whl/file/`
## Installing the library on Ubuntu
Installing the library on linux is a little bit trickier, since dotnet and some required libraries needs to be installed before installing pythonnet. If these libraries aren't installed beforehand, the installation of pythonnet will fail. Run the following commands:
Replace VERSION with the Ubuntu version. (i.e. bionic 18.04) or focal (20.04))
```
sudo apt-get update
# install mono (.NET implementation)
sudo apt install gnupg ca-certificates
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb https://download.mono-project.com/repo/ubuntu stable-VERSION main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list
sudo apt update
sudo apt install mono-devel
```
Before installing the needed python libraries
```
# install pythonnet
pip install wheel
pip install pythonnet==2.5.2
```
If building the wheel for pythonnet fails, try installing the following libaries
```
# install libraries needed to build pythonnet
sudo apt-get install clang
sudo apt-get install libglib2.0-dev
```
Finally, the library can be installed using `pip install /path/to/.whl/file/`
## Using the library
Once installed, it can be used like any other python library, i.e:
```
from pmclib import system_commands as sys
from pmclib import xbot_commands as bot
if not sys.is_master():
sys.gain_mastership()
sys.auto_connect_to_pmc()
bot.activate_xbots()
bot.linear_motion_si(1, 0.18, 0.18, 0.5, 10)
```
## VS Code Security settings
```
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell",
"args": ["-ExecutionPolicy", "Bypass"]
}
}
```
| 2,302 | Markdown | 29.706666 | 268 | 0.752824 |
AndreiVoica/P10-MAP/docs/installation/Nvidia Isaac Sim ROS2/README.md | # Nvidia Isaac Sim
Nvidia Isaac Sim is a simulation software developed by Nvidia. In the first instance, the project was intended to be developed using ROS2, these steps may be useful for implementation with ROS2.
## Installing Nvidia Isaac Sim on Ubuntu 20.04
Follow the [Workstation Installation](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_workstation.html) tutorial.
# ROS 2 Foxy
Nvidia Isaac Sim is currently compatible with ROS 2 Foxy (Ubuntu 20.04) due to ROS 2 bridge.
Follow the [ROS2 Foxy installation method](https://docs.ros.org/en/foxy/Installation/Ubuntu-Install-Debians.html).
# ROS 2 Humble in Docker
ROS 2 Humble is used only for Moveit2 assistant, since it is not available on Foxy.
1. Install Docker following [this tutorial](https://docs.docker.com/engine/install/ubuntu/);
2. Open a terminal and run
```docker pull ubuntu:jammy```
3. In the terminal run ```docker images``` and copy the IMAGE ID
4. Run the docker image using ```docker run -it IMAGE ID```
5. Start installing ROS 2 Humble following [this tutorial](https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html)
6. Install moveit2 setup assistant ```sudo apt install ros-humble-moveit```
7. Create a colcon workspace ```source /opt/ros/humble/setup.bash```
```
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws/src
```
8. Clone the repo (TBD)
9.
```
cd ..
rosdep install -i --from-path src --rosdistro humble -y
```
# Converting ROS1 packages to ROS2
To be able to build using colcon, the packages have to be converted to support it.
# Using Moveit2
# Connecting Moveit2 to Isaac using a custom robot configuration
# Troubleshooting
## QT unable to find display in while trying to launch a GUI application (such as rviz2 or moveit setup assistant)
If you encounter an error related to QT5 not being able to find a display (this will be needed if you are going to use any application with a GUI in docker) run ```xhost local:root``` in the terminal and after run the docker image by using the command below and skip step 4. Recommended to add ```xhost local:root``` in your .bashrc.
```
docker run -it --rm \
--network host \
-e DISPLAY=$DISPLAY \
-v /tmp/.X11-unix/:/tmp/.X11-unix \
IMAGE ID
```
## URDF files require double
If you have for example velocity = 2.0, try velocity = 2.00001
| 2,327 | Markdown | 39.842105 | 333 | 0.743017 |
AndreiVoica/P10-MAP/docs/installation/MAPs_Extension/README.md | ## How to install MAPs Extension
1. Copy the *maps* folder into the Isaac Sim extensions folder. The default path in Ubuntu (Isaac Sim 2022.2.1) is:
```
/home/$USER$/.local/share/ov/pkg/isaac_sim-2022.2.1/exts/omni.isaac.examples/omni/isaac/examples/maps
```
2. In the *extensions.toml* file, add the following lines:
```
PATH:
/home/$USER$/.local/share/ov/pkg/isaac_sim-2022.2.1/exts/omni.isaac.examples/config/extensions.toml
TO ADD:
[[python.module]]
name = "omni.isaac.examples.maps"
```
3. Once the extension is installed, it is necessary to launch the ROS master in a terminal using `roscore` before opening Isaac Sim GUI.
4. Then you can run the MAPs extension from the Isaac Examples tab in the Isaac Sim GUI:

### Known Issues
The first time you load the Isaac Sim GUI, the MAPs extension doesn't appear, to fix this just go to the *maps.py* file and save it again. This will load the files and allow you to launch it from the GUI.
```
/home/$USER$/.local/share/ov/pkg/isaac_sim-2022.2.1/exts/omni.isaac.examples/omni/isaac/examples/maps/maps.py
```
| 1,123 | Markdown | 34.124999 | 204 | 0.738201 |
Ngochuy2137/omni_isaac_examples/README.md | # omni_isaac_examples
| 22 | Markdown | 10.499995 | 21 | 0.772727 |
Ngochuy2137/omni_isaac_examples/path_planning/__init__.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.path_planning.path_planning import PathPlanning
from omni.isaac.examples.path_planning.path_planning_controller import PathPlannerController
from omni.isaac.examples.path_planning.path_planning_extension import PathPlanningExtension
from omni.isaac.examples.path_planning.path_planning_task import PathPlanningTask
| 772 | Python | 54.214282 | 92 | 0.838083 |
Ngochuy2137/omni_isaac_examples/path_planning/path_planning.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from .path_planning_controller import FrankaRrtController
from .path_planning_task import FrankaPathPlanningTask
class PathPlanning(BaseSample):
def __init__(self) -> None:
super().__init__()
self._controller = None
self._articulation_controller = None
def setup_scene(self):
world = self.get_world()
world.add_task(FrankaPathPlanningTask("Plan To Target Task"))
return
async def setup_pre_reset(self):
world = self.get_world()
if world.physics_callback_exists("sim_step"):
world.remove_physics_callback("sim_step")
self._controller.reset()
return
def world_cleanup(self):
self._controller = None
return
async def setup_post_load(self):
self._franka_task = list(self._world.get_current_tasks().values())[0]
self._task_params = self._franka_task.get_params()
my_franka = self._world.scene.get_object(self._task_params["robot_name"]["value"])
my_franka.disable_gravity()
self._controller = FrankaRrtController(name="franka_rrt_controller", robot_articulation=my_franka)
self._articulation_controller = my_franka.get_articulation_controller()
return
async def _on_follow_target_event_async(self):
world = self.get_world()
self._pass_world_state_to_controller()
await world.play_async()
if not world.physics_callback_exists("sim_step"):
world.add_physics_callback("sim_step", self._on_follow_target_simulation_step)
def _pass_world_state_to_controller(self):
self._controller.reset()
for wall in self._franka_task.get_obstacles():
self._controller.add_obstacle(wall)
def _on_follow_target_simulation_step(self, step_size):
observations = self._world.get_observations()
actions = self._controller.forward(
target_end_effector_position=observations[self._task_params["target_name"]["value"]]["position"],
target_end_effector_orientation=observations[self._task_params["target_name"]["value"]]["orientation"],
)
kps, kds = self._franka_task.get_custom_gains()
self._articulation_controller.set_gains(kps, kds)
self._articulation_controller.apply_action(actions)
return
def _on_add_wall_event(self):
world = self.get_world()
current_task = list(world.get_current_tasks().values())[0]
cube = current_task.add_obstacle()
return
def _on_remove_wall_event(self):
world = self.get_world()
current_task = list(world.get_current_tasks().values())[0]
obstacle_to_delete = current_task.get_obstacle_to_delete()
current_task.remove_obstacle()
return
def _on_logging_event(self, val):
world = self.get_world()
data_logger = world.get_data_logger()
if not world.get_data_logger().is_started():
robot_name = self._task_params["robot_name"]["value"]
target_name = self._task_params["target_name"]["value"]
def frame_logging_func(tasks, scene):
return {
"joint_positions": scene.get_object(robot_name).get_joint_positions().tolist(),
"applied_joint_positions": scene.get_object(robot_name)
.get_applied_action()
.joint_positions.tolist(),
"target_position": scene.get_object(target_name).get_world_pose()[0].tolist(),
}
data_logger.add_data_frame_logging_func(frame_logging_func)
if val:
data_logger.start()
else:
data_logger.pause()
return
def _on_save_data_event(self, log_path):
world = self.get_world()
data_logger = world.get_data_logger()
data_logger.save(log_path=log_path)
data_logger.reset()
return
| 4,416 | Python | 38.4375 | 115 | 0.634511 |
Ngochuy2137/omni_isaac_examples/path_planning/path_planning_task.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from collections import OrderedDict
from typing import List, Optional, Tuple
import numpy as np
from omni.isaac.core.objects import FixedCuboid, VisualCuboid
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.scenes.scene import Scene
from omni.isaac.core.tasks import BaseTask
from omni.isaac.core.utils.prims import is_prim_path_valid
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.core.utils.stage import get_stage_units
from omni.isaac.core.utils.string import find_unique_string_name
from omni.isaac.franka import Franka
class PathPlanningTask(BaseTask):
def __init__(
self,
name: str,
target_prim_path: Optional[str] = None,
target_name: Optional[str] = None,
target_position: Optional[np.ndarray] = None,
target_orientation: Optional[np.ndarray] = None,
offset: Optional[np.ndarray] = None,
) -> None:
BaseTask.__init__(self, name=name, offset=offset)
self._robot = None
self._target_name = target_name
self._target = None
self._target_prim_path = target_prim_path
self._target_position = target_position
self._target_orientation = target_orientation
self._target_visual_material = None
self._obstacle_walls = OrderedDict()
if self._target_position is None:
self._target_position = np.array([0.8, 0.3, 0.4]) / get_stage_units()
return
def set_up_scene(self, scene: Scene) -> None:
"""[summary]
Args:
scene (Scene): [description]
"""
super().set_up_scene(scene)
scene.add_default_ground_plane()
if self._target_orientation is None:
self._target_orientation = euler_angles_to_quat(np.array([-np.pi, 0, np.pi]))
if self._target_prim_path is None:
self._target_prim_path = find_unique_string_name(
initial_name="/World/TargetCube", is_unique_fn=lambda x: not is_prim_path_valid(x)
)
if self._target_name is None:
self._target_name = find_unique_string_name(
initial_name="target", is_unique_fn=lambda x: not self.scene.object_exists(x)
)
self.set_params(
target_prim_path=self._target_prim_path,
target_position=self._target_position,
target_orientation=self._target_orientation,
target_name=self._target_name,
)
self._robot = self.set_robot()
scene.add(self._robot)
self._task_objects[self._robot.name] = self._robot
self._move_task_objects_to_their_frame()
return
def set_params(
self,
target_prim_path: Optional[str] = None,
target_name: Optional[str] = None,
target_position: Optional[np.ndarray] = None,
target_orientation: Optional[np.ndarray] = None,
) -> None:
"""[summary]
Args:
target_prim_path (Optional[str], optional): [description]. Defaults to None.
target_name (Optional[str], optional): [description]. Defaults to None.
target_position (Optional[np.ndarray], optional): [description]. Defaults to None.
target_orientation (Optional[np.ndarray], optional): [description]. Defaults to None.
"""
if target_prim_path is not None:
if self._target is not None:
del self._task_objects[self._target.name]
if is_prim_path_valid(target_prim_path):
self._target = self.scene.add(
XFormPrim(
prim_path=target_prim_path,
position=target_position,
orientation=target_orientation,
name=target_name,
)
)
else:
self._target = self.scene.add(
VisualCuboid(
name=target_name,
prim_path=target_prim_path,
position=target_position,
orientation=target_orientation,
color=np.array([1, 0, 0]),
size=1.0,
scale=np.array([0.03, 0.03, 0.03]) / get_stage_units(),
)
)
self._task_objects[self._target.name] = self._target
self._target_visual_material = self._target.get_applied_visual_material()
if self._target_visual_material is not None:
if hasattr(self._target_visual_material, "set_color"):
self._target_visual_material.set_color(np.array([1, 0, 0]))
else:
self._target.set_local_pose(position=target_position, orientation=target_orientation)
return
def get_params(self) -> dict:
"""[summary]
Returns:
dict: [description]
"""
params_representation = dict()
params_representation["target_prim_path"] = {"value": self._target.prim_path, "modifiable": True}
params_representation["target_name"] = {"value": self._target.name, "modifiable": True}
position, orientation = self._target.get_local_pose()
params_representation["target_position"] = {"value": position, "modifiable": True}
params_representation["target_orientation"] = {"value": orientation, "modifiable": True}
params_representation["robot_name"] = {"value": self._robot.name, "modifiable": False}
return params_representation
def get_task_objects(self) -> dict:
"""[summary]
Returns:
dict: [description]
"""
return self._task_objects
def get_observations(self) -> dict:
"""[summary]
Returns:
dict: [description]
"""
joints_state = self._robot.get_joints_state()
target_position, target_orientation = self._target.get_local_pose()
return {
self._robot.name: {
"joint_positions": np.array(joints_state.positions),
"joint_velocities": np.array(joints_state.velocities),
},
self._target.name: {"position": np.array(target_position), "orientation": np.array(target_orientation)},
}
def target_reached(self) -> bool:
"""[summary]
Returns:
bool: [description]
"""
end_effector_position, _ = self._robot.end_effector.get_world_pose()
target_position, _ = self._target.get_world_pose()
if np.mean(np.abs(np.array(end_effector_position) - np.array(target_position))) < (0.035 / get_stage_units()):
return True
else:
return False
def pre_step(self, time_step_index: int, simulation_time: float) -> None:
"""[summary]
Args:
time_step_index (int): [description]
simulation_time (float): [description]
"""
if self._target_visual_material is not None:
if hasattr(self._target_visual_material, "set_color"):
if self.target_reached():
self._target_visual_material.set_color(color=np.array([0, 1.0, 0]))
else:
self._target_visual_material.set_color(color=np.array([1.0, 0, 0]))
return
def add_obstacle(self, position: np.ndarray = None, orientation=None):
"""[summary]
Args:
position (np.ndarray, optional): [description]. Defaults to np.array([0.1, 0.1, 1.0]).
"""
# TODO: move to task frame if there is one
cube_prim_path = find_unique_string_name(
initial_name="/World/WallObstacle", is_unique_fn=lambda x: not is_prim_path_valid(x)
)
cube_name = find_unique_string_name(initial_name="wall", is_unique_fn=lambda x: not self.scene.object_exists(x))
if position is None:
position = np.array([0.6, 0.1, 0.3]) / get_stage_units()
if orientation is None:
orientation = euler_angles_to_quat(np.array([0, 0, np.pi / 3]))
cube = self.scene.add(
VisualCuboid(
name=cube_name,
position=position + self._offset,
orientation=orientation,
prim_path=cube_prim_path,
size=1.0,
scale=np.array([0.1, 0.5, 0.6]) / get_stage_units(),
color=np.array([0, 0, 1.0]),
)
)
self._obstacle_walls[cube.name] = cube
return cube
def remove_obstacle(self, name: Optional[str] = None) -> None:
"""[summary]
Args:
name (Optional[str], optional): [description]. Defaults to None.
"""
if name is not None:
self.scene.remove_object(name)
del self._obstacle_walls[name]
else:
obstacle_to_delete = list(self._obstacle_walls.keys())[-1]
self.scene.remove_object(obstacle_to_delete)
del self._obstacle_walls[obstacle_to_delete]
return
def get_obstacles(self) -> List:
return list(self._obstacle_walls.values())
def get_obstacle_to_delete(self) -> None:
"""[summary]
Returns:
[type]: [description]
"""
obstacle_to_delete = list(self._obstacle_walls.keys())[-1]
return self.scene.get_object(obstacle_to_delete)
def obstacles_exist(self) -> bool:
"""[summary]
Returns:
bool: [description]
"""
if len(self._obstacle_walls) > 0:
return True
else:
return False
def cleanup(self) -> None:
"""[summary]"""
obstacles_to_delete = list(self._obstacle_walls.keys())
for obstacle_to_delete in obstacles_to_delete:
self.scene.remove_object(obstacle_to_delete)
del self._obstacle_walls[obstacle_to_delete]
return
def get_custom_gains(self) -> Tuple[np.array, np.array]:
return None, None
class FrankaPathPlanningTask(PathPlanningTask):
def __init__(
self,
name: str,
target_prim_path: Optional[str] = None,
target_name: Optional[str] = None,
target_position: Optional[np.ndarray] = None,
target_orientation: Optional[np.ndarray] = None,
offset: Optional[np.ndarray] = None,
franka_prim_path: Optional[str] = None,
franka_robot_name: Optional[str] = None,
) -> None:
PathPlanningTask.__init__(
self,
name=name,
target_prim_path=target_prim_path,
target_name=target_name,
target_position=target_position,
target_orientation=target_orientation,
offset=offset,
)
self._franka_prim_path = franka_prim_path
self._franka_robot_name = franka_robot_name
self._franka = None
return
def set_robot(self) -> Franka:
"""[summary]
Returns:
Franka: [description]
"""
if self._franka_prim_path is None:
self._franka_prim_path = find_unique_string_name(
initial_name="/World/Franka", is_unique_fn=lambda x: not is_prim_path_valid(x)
)
if self._franka_robot_name is None:
self._franka_robot_name = find_unique_string_name(
initial_name="my_franka", is_unique_fn=lambda x: not self.scene.object_exists(x)
)
self._franka = Franka(prim_path=self._franka_prim_path, name=self._franka_robot_name)
return self._franka
def get_custom_gains(self) -> Tuple[np.array, np.array]:
return (1e15 * np.ones(9), 1e13 * np.ones(9))
| 12,187 | Python | 37.206896 | 120 | 0.576024 |
Ngochuy2137/omni_isaac_examples/path_planning/path_planning_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import carb
import omni.ui as ui
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.path_planning import PathPlanning
from omni.isaac.ui.ui_utils import btn_builder, state_btn_builder, str_builder
class PathPlanningExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Manipulation",
submenu_name="",
name="Path Planning",
title="Path Planning Task",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_motion_generation_rrt.html#isaac-sim-app-tutorial-motion-generation-rrt",
overview="This Example shows how to plan a path through a complicated static environment with the Franka robot in Isaac Sim.\n\nPress the 'Open in IDE' button to view the source code.",
sample=PathPlanning(),
file_path=os.path.abspath(__file__),
number_of_extra_frames=2,
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
frame = self.get_frame(index=1)
self.build_data_logging_ui(frame)
return
def _on_follow_target_button_event(self):
asyncio.ensure_future(self.sample._on_follow_target_event_async())
return
def _on_add_wall_button_event(self):
self.sample._on_add_wall_event()
self.task_ui_elements["Remove Wall"].enabled = True
return
def _on_remove_wall_button_event(self):
self.sample._on_remove_wall_event()
world = self.sample.get_world()
current_task = list(world.get_current_tasks().values())[0]
if not current_task.obstacles_exist():
self.task_ui_elements["Remove Wall"].enabled = False
return
def _on_logging_button_event(self, val):
self.sample._on_logging_event(val)
self.task_ui_elements["Save Data"].enabled = True
return
def _on_save_data_button_event(self):
self.sample._on_save_data_event(self.task_ui_elements["Output Directory"].get_value_as_string())
return
def post_reset_button_event(self):
self.task_ui_elements["Move To Target"].enabled = True
self.task_ui_elements["Remove Wall"].enabled = False
self.task_ui_elements["Add Wall"].enabled = True
self.task_ui_elements["Start Logging"].enabled = True
self.task_ui_elements["Save Data"].enabled = False
return
def post_load_button_event(self):
self.task_ui_elements["Move To Target"].enabled = True
self.task_ui_elements["Add Wall"].enabled = True
self.task_ui_elements["Start Logging"].enabled = True
self.task_ui_elements["Save Data"].enabled = False
return
def post_clear_button_event(self):
self.task_ui_elements["Move To Target"].enabled = False
self.task_ui_elements["Remove Wall"].enabled = False
self.task_ui_elements["Add Wall"].enabled = False
self.task_ui_elements["Start Logging"].enabled = False
self.task_ui_elements["Save Data"].enabled = False
return
def shutdown_cleanup(self):
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Move To Target",
"type": "button",
"text": "Move To Target",
"tooltip": "Plan a Path and Move to Target",
"on_clicked_fn": self._on_follow_target_button_event,
}
self.task_ui_elements["Move To Target"] = btn_builder(**dict)
self.task_ui_elements["Move To Target"].enabled = False
dict = {
"label": "Add Wall",
"type": "button",
"text": "ADD",
"tooltip": "Add a Wall",
"on_clicked_fn": self._on_add_wall_button_event,
}
self.task_ui_elements["Add Wall"] = btn_builder(**dict)
self.task_ui_elements["Add Wall"].enabled = False
dict = {
"label": "Remove Wall",
"type": "button",
"text": "REMOVE",
"tooltip": "Remove Wall",
"on_clicked_fn": self._on_remove_wall_button_event,
}
self.task_ui_elements["Remove Wall"] = btn_builder(**dict)
self.task_ui_elements["Remove Wall"].enabled = False
def build_data_logging_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
frame.title = "Data Logging"
frame.visible = True
dict = {
"label": "Output Directory",
"type": "stringfield",
"default_val": os.path.join(os.getcwd(), "output_data.json"),
"tooltip": "Output Directory",
"on_clicked_fn": None,
"use_folder_picker": False,
"read_only": False,
}
self.task_ui_elements["Output Directory"] = str_builder(**dict)
dict = {
"label": "Start Logging",
"type": "button",
"a_text": "START",
"b_text": "PAUSE",
"tooltip": "Start Logging",
"on_clicked_fn": self._on_logging_button_event,
}
self.task_ui_elements["Start Logging"] = state_btn_builder(**dict)
self.task_ui_elements["Start Logging"].enabled = False
dict = {
"label": "Save Data",
"type": "button",
"text": "Save Data",
"tooltip": "Save Data",
"on_clicked_fn": self._on_save_data_button_event,
}
self.task_ui_elements["Save Data"] = btn_builder(**dict)
self.task_ui_elements["Save Data"].enabled = False
return
| 6,822 | Python | 39.135294 | 197 | 0.557021 |
Ngochuy2137/omni_isaac_examples/path_planning/path_planning_controller.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import Optional
import carb
import numpy as np
import omni.isaac.core.objects
import omni.isaac.motion_generation.interface_config_loader as interface_config_loader
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.controllers.base_controller import BaseController
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.motion_generation import ArticulationTrajectory
from omni.isaac.motion_generation.lula import RRT
from omni.isaac.motion_generation.lula.trajectory_generator import LulaCSpaceTrajectoryGenerator
from omni.isaac.motion_generation.path_planner_visualizer import PathPlannerVisualizer
from omni.isaac.motion_generation.path_planning_interface import PathPlanner
class PathPlannerController(BaseController):
def __init__(
self,
name: str,
path_planner_visualizer: PathPlannerVisualizer,
cspace_trajectory_generator: LulaCSpaceTrajectoryGenerator,
physics_dt=1 / 60.0,
rrt_interpolation_max_dist=0.01,
):
BaseController.__init__(self, name)
self._robot = path_planner_visualizer.get_robot_articulation()
self._cspace_trajectory_generator = cspace_trajectory_generator
self._path_planner = path_planner_visualizer.get_path_planner()
self._path_planner_visualizer = path_planner_visualizer
self._last_solution = None
self._action_sequence = None
self._physics_dt = physics_dt
self._rrt_interpolation_max_dist = rrt_interpolation_max_dist
def _convert_rrt_plan_to_trajectory(self, rrt_plan):
# This example uses the LulaCSpaceTrajectoryGenerator to convert RRT waypoints to a cspace trajectory.
# In general this is not theoretically guaranteed to work since the trajectory generator uses spline-based
# interpolation and RRT only guarantees that the cspace position of the robot can be linearly interpolated between
# waypoints. For this example, we verified experimentally that a dense interpolation of cspace waypoints with a maximum
# l2 norm of .01 between waypoints leads to a good enough approximation of the RRT path by the trajectory generator.
interpolated_path = self._path_planner_visualizer.interpolate_path(rrt_plan, self._rrt_interpolation_max_dist)
trajectory = self._cspace_trajectory_generator.compute_c_space_trajectory(interpolated_path)
art_trajectory = ArticulationTrajectory(self._robot, trajectory, self._physics_dt)
return art_trajectory.get_action_sequence()
def _make_new_plan(
self, target_end_effector_position: np.ndarray, target_end_effector_orientation: Optional[np.ndarray] = None
) -> None:
self._path_planner.set_end_effector_target(target_end_effector_position, target_end_effector_orientation)
self._path_planner.update_world()
path_planner_visualizer = PathPlannerVisualizer(self._robot, self._path_planner)
active_joints = path_planner_visualizer.get_active_joints_subset()
if self._last_solution is None:
start_pos = active_joints.get_joint_positions()
else:
start_pos = self._last_solution
self._rrt_plan = self._path_planner.compute_path(start_pos, np.array([]))
if self._rrt_plan is None or self._rrt_plan == []:
carb.log_warn("No plan could be generated to target pose: " + str(target_end_effector_position))
self._action_sequence = []
return
self._action_sequence = self._convert_rrt_plan_to_trajectory(self._rrt_plan)
self._last_solution = self._action_sequence[-1].joint_positions
def forward(
self, target_end_effector_position: np.ndarray, target_end_effector_orientation: Optional[np.ndarray] = None
) -> ArticulationAction:
if self._action_sequence is None:
# This will only happen the first time the forward function is used
self._make_new_plan(target_end_effector_position, target_end_effector_orientation)
if len(self._action_sequence) == 0:
# The plan is completed; return null action to remain in place
return ArticulationAction()
if len(self._action_sequence) == 1:
final_positions = self._action_sequence[0].joint_positions
# print("Steady State Error: ", np.linalg.norm(self._robot.get_joint_positions()[:7]-final_positions[:7]))
return ArticulationAction(
final_positions, np.zeros_like(final_positions), joint_indices=self._action_sequence[0].joint_indices
)
return self._action_sequence.pop(0)
def add_obstacle(self, obstacle: omni.isaac.core.objects, static: bool = False) -> None:
self._path_planner.add_obstacle(obstacle, static)
def remove_obstacle(self, obstacle: omni.isaac.core.objects) -> None:
self._path_planner.remove_obstacle(obstacle)
def reset(self) -> None:
# PathPlannerController will make one plan per reset
self._path_planner.reset()
self._action_sequence = None
self._last_solution = None
def get_path_planner(self) -> PathPlanner:
return self._path_planner
class FrankaRrtController(PathPlannerController):
def __init__(
self,
name,
robot_articulation: Articulation,
):
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.isaac.examples")
examples_extension_path = ext_manager.get_extension_path(ext_id)
# Load default RRT config files stored in the omni.isaac.motion_generation extension
rrt_config = interface_config_loader.load_supported_path_planner_config("Franka", "RRT")
# Replace the default robot description file with a copy that has inflated collision spheres
rrt_config["robot_description_path"] = os.path.join(
examples_extension_path,
"omni",
"isaac",
"examples",
"path_planning",
"path_planning_example_assets",
"franka_conservative_spheres_robot_description.yaml",
)
rrt = RRT(**rrt_config)
# Create a trajectory generator to convert RRT cspace waypoints to trajectories
cspace_trajectory_generator = LulaCSpaceTrajectoryGenerator(
rrt_config["robot_description_path"], rrt_config["urdf_path"]
)
# It is important that the Robot Description File includes optional Jerk and Acceleration limits so that the generated trajectory
# can be followed closely by the simulated robot Articulation
assert cspace_trajectory_generator._lula_kinematics.has_c_space_acceleration_limits()
assert cspace_trajectory_generator._lula_kinematics.has_c_space_jerk_limits()
visualizer = PathPlannerVisualizer(robot_articulation, rrt)
PathPlannerController.__init__(self, name, visualizer, cspace_trajectory_generator)
| 7,463 | Python | 45.943396 | 137 | 0.7028 |
Ngochuy2137/omni_isaac_examples/base_sample/base_sample.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import gc
from abc import abstractmethod
from omni.isaac.core import World
from omni.isaac.core.scenes.scene import Scene
from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async
class BaseSample(object):
def __init__(self) -> None:
self._world = None
self._current_tasks = None
self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0}
# self._logging_info = ""
return
def get_world(self):
return self._world
def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None):
if physics_dt is not None:
self._world_settings["physics_dt"] = physics_dt
if stage_units_in_meters is not None:
self._world_settings["stage_units_in_meters"] = stage_units_in_meters
if rendering_dt is not None:
self._world_settings["rendering_dt"] = rendering_dt
return
async def load_world_async(self):
"""Function called when clicking load buttton"""
if World.instance() is None:
await create_new_stage_async()
self._world = World(**self._world_settings)
await self._world.initialize_simulation_context_async()
self.setup_scene()
else:
self._world = World.instance()
self._current_tasks = self._world.get_current_tasks()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_load()
if len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
async def reset_async(self):
"""Function called when clicking reset buttton"""
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.remove_physics_callback("tasks_step")
await self._world.play_async()
await update_stage_async()
await self.setup_pre_reset()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_reset()
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
@abstractmethod
def setup_scene(self, scene: Scene) -> None:
"""used to setup anything in the world, adding tasks happen here for instance.
Args:
scene (Scene): [description]
"""
return
@abstractmethod
async def setup_post_load(self):
"""called after first reset of the world when pressing load,
intializing provate variables happen here.
"""
return
@abstractmethod
async def setup_pre_reset(self):
"""called in reset button before resetting the world
to remove a physics callback for instance or a controller reset
"""
return
@abstractmethod
async def setup_post_reset(self):
"""called in reset button after resetting the world which includes one step with rendering"""
return
@abstractmethod
async def setup_post_clear(self):
"""called after clicking clear button
or after creating a new stage and clearing the instance of the world with its callbacks
"""
return
# def log_info(self, info):
# self._logging_info += str(info) + "\n"
# return
def _world_cleanup(self):
self._world.stop()
self._world.clear_all_callbacks()
self._current_tasks = None
self.world_cleanup()
return
def world_cleanup(self):
"""Function called when extension shutdowns and starts again, (hot reloading feature)"""
return
async def clear_async(self):
"""Function called when clicking clear buttton"""
await create_new_stage_async()
if self._world is not None:
self._world_cleanup()
self._world.clear_instance()
self._world = None
gc.collect()
await self.setup_post_clear()
return
| 4,600 | Python | 34.945312 | 115 | 0.631957 |
Ngochuy2137/omni_isaac_examples/base_sample/base_sample_extension.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import weakref
from abc import abstractmethod
import omni.ext
import omni.ui as ui
from omni.isaac.core import World
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import btn_builder, get_style, scrolling_frame_builder, setup_ui_headers
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
class BaseSampleExtension(omni.ext.IExt):
def on_startup(self, ext_id: str):
self._menu_items = None
self._buttons = None
self._ext_id = ext_id
self._sample = None
self._extra_frames = []
return
def start_extension(
self,
menu_name: str,
submenu_name: str,
name: str,
title: str,
doc_link: str,
overview: str,
file_path: str,
sample=None,
number_of_extra_frames=1,
window_width=350,
keep_window_open=False,
):
if sample is None:
self._sample = BaseSample()
else:
self._sample = sample
menu_items = [make_menu_item_description(self._ext_id, name, lambda a=weakref.proxy(self): a._menu_callback())]
if menu_name == "" or menu_name is None:
self._menu_items = menu_items
elif submenu_name == "" or submenu_name is None:
self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)]
else:
self._menu_items = [
MenuItemDescription(
name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)]
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._buttons = dict()
self._build_ui(
name=name,
title=title,
doc_link=doc_link,
overview=overview,
file_path=file_path,
number_of_extra_frames=number_of_extra_frames,
window_width=window_width,
keep_window_open=keep_window_open,
)
return
@property
def sample(self):
return self._sample
def get_frame(self, index):
if index >= len(self._extra_frames):
raise Exception("there were {} extra frames created only".format(len(self._extra_frames)))
return self._extra_frames[index]
def get_world(self):
return World.instance()
def get_buttons(self):
return self._buttons
def _build_ui(
self, name, title, doc_link, overview, file_path, number_of_extra_frames, window_width, keep_window_open
):
self._window = omni.ui.Window(
name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
self._main_stack = ui.VStack(spacing=5, height=0)
with self._main_stack:
setup_ui_headers(self._ext_id, file_path, title, doc_link, overview)
self._controls_frame = ui.CollapsableFrame(
title="World Controls",
width=ui.Fraction(1),
height=0,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with ui.VStack(style=get_style(), spacing=5, height=0):
for i in range(number_of_extra_frames):
self._extra_frames.append(
ui.CollapsableFrame(
title="",
width=ui.Fraction(0.33),
height=0,
visible=False,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
)
with self._controls_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
dict = {
"label": "Load World",
"type": "button",
"text": "Load",
"tooltip": "Load World and Task",
"on_clicked_fn": self._on_load_world,
}
self._buttons["Load World"] = btn_builder(**dict)
self._buttons["Load World"].enabled = True
dict = {
"label": "Reset",
"type": "button",
"text": "Reset",
"tooltip": "Reset robot and environment",
"on_clicked_fn": self._on_reset,
}
self._buttons["Reset"] = btn_builder(**dict)
self._buttons["Reset"].enabled = False
return
def _set_button_tooltip(self, button_name, tool_tip):
self._buttons[button_name].set_tooltip(tool_tip)
return
def _on_load_world(self):
async def _on_load_world_async():
await self._sample.load_world_async()
await omni.kit.app.get_app().next_update_async()
self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event)
self._enable_all_buttons(True)
self._buttons["Load World"].enabled = False
self.post_load_button_event()
self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event)
asyncio.ensure_future(_on_load_world_async())
return
def _on_reset(self):
async def _on_reset_async():
await self._sample.reset_async()
await omni.kit.app.get_app().next_update_async()
self.post_reset_button_event()
asyncio.ensure_future(_on_reset_async())
return
@abstractmethod
def post_reset_button_event(self):
return
@abstractmethod
def post_load_button_event(self):
return
@abstractmethod
def post_clear_button_event(self):
return
def _enable_all_buttons(self, flag):
for btn_name, btn in self._buttons.items():
if isinstance(btn, omni.ui._ui.Button):
btn.enabled = flag
return
def _menu_callback(self):
self._window.visible = not self._window.visible
return
def _on_window(self, status):
# if status:
return
def on_shutdown(self):
self._extra_frames = []
if self._sample._world is not None:
self._sample._world_cleanup()
if self._menu_items is not None:
self._sample_window_cleanup()
if self._buttons is not None:
self._buttons["Load World"].enabled = True
self._enable_all_buttons(False)
self.shutdown_cleanup()
return
def shutdown_cleanup(self):
return
def _sample_window_cleanup(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
self._menu_items = None
self._buttons = None
return
def on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSED):
if World.instance() is not None:
self.sample._world_cleanup()
self.sample._world.clear_instance()
if hasattr(self, "_buttons"):
if self._buttons is not None:
self._enable_all_buttons(False)
self._buttons["Load World"].enabled = True
return
def _reset_on_stop_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self._buttons["Load World"].enabled = False
self._buttons["Reset"].enabled = True
self.post_clear_button_event()
return
| 8,761 | Python | 35.815126 | 119 | 0.543659 |
Ngochuy2137/omni_isaac_examples/base_sample/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample.base_sample import BaseSample
from omni.isaac.examples.base_sample.base_sample_extension import BaseSampleExtension
| 585 | Python | 47.833329 | 85 | 0.823932 |
Ngochuy2137/omni_isaac_examples/unitree_quadruped/quadruped_example.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import numpy as np
import omni
import omni.appwindow # Contains handle to keyboard
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.quadruped.robots import Unitree
class QuadrupedExample(BaseSample):
def __init__(self) -> None:
super().__init__()
self._world_settings["stage_units_in_meters"] = 1.0
self._world_settings["physics_dt"] = 1.0 / 400.0
self._world_settings["rendering_dt"] = 5.0 / 400.0
self._enter_toggled = 0
self._base_command = [0.0, 0.0, 0.0, 0]
self._event_flag = False
# bindings for keyboard to command
self._input_keyboard_mapping = {
# forward command
"NUMPAD_8": [5, 0.0, 0.0],
"UP": [5, 0.0, 0.0],
# back command
"NUMPAD_2": [-5, 0.0, 0.0],
"DOWN": [-5, 0.0, 0.0],
# left command
"NUMPAD_6": [0.0, -4.0, 0.0],
"RIGHT": [0.0, -4.0, 0.0],
# right command
"NUMPAD_4": [0.0, 4.0, 0.0],
"LEFT": [0.0, 4.0, 0.0],
# yaw command (positive)
"NUMPAD_7": [0.0, 0.0, 1.0],
"N": [0.0, 0.0, 1.0],
# yaw command (negative)
"NUMPAD_9": [0.0, 0.0, -1.0],
"M": [0.0, 0.0, -1.0],
}
return
def setup_scene(self) -> None:
world = self.get_world()
self._world.scene.add_default_ground_plane(
z_position=0,
name="default_ground_plane",
prim_path="/World/defaultGroundPlane",
static_friction=0.2,
dynamic_friction=0.2,
restitution=0.01,
)
self._a1 = world.scene.add(
Unitree(
prim_path="/World/A1",
name="A1",
position=np.array([0, 0, 0.400]),
physics_dt=self._world_settings["physics_dt"],
)
)
timeline = omni.timeline.get_timeline_interface()
self._event_timer_callback = timeline.get_timeline_event_stream().create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.STOP), self._timeline_timer_callback_fn
)
return
async def setup_post_load(self) -> None:
self._world = self.get_world()
self._appwindow = omni.appwindow.get_default_app_window()
self._input = carb.input.acquire_input_interface()
self._keyboard = self._appwindow.get_keyboard()
self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event)
self._world.add_physics_callback("sending_actions", callback_fn=self.on_physics_step)
await self._world.play_async()
return
async def setup_pre_reset(self) -> None:
self._event_flag = False
return
async def setup_post_reset(self) -> None:
await self._world.play_async()
self._a1.set_state(self._a1._default_a1_state)
self._a1.post_reset()
return
def on_physics_step(self, step_size) -> None:
if self._event_flag:
self._a1._qp_controller.switch_mode()
self._event_flag = False
self._a1.advance(step_size, self._base_command)
def _sub_keyboard_event(self, event, *args, **kwargs) -> bool:
"""Subscriber callback to when kit is updated."""
# reset event
self._event_flag = False
# when a key is pressedor released the command is adjusted w.r.t the key-mapping
if event.type == carb.input.KeyboardEventType.KEY_PRESS:
# on pressing, the command is incremented
if event.input.name in self._input_keyboard_mapping:
self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name])
self._event_flag = True
# enter, toggle the last command
if event.input.name == "ENTER" and self._enter_toggled is False:
self._enter_toggled = True
if self._base_command[3] == 0:
self._base_command[3] = 1
else:
self._base_command[3] = 0
self._event_flag = True
elif event.type == carb.input.KeyboardEventType.KEY_RELEASE:
# on release, the command is decremented
if event.input.name in self._input_keyboard_mapping:
self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name])
self._event_flag = True
# enter, toggle the last command
if event.input.name == "ENTER":
self._enter_toggled = False
# since no error, we are fine :)
return True
def _timeline_timer_callback_fn(self, event) -> None:
self._a1.post_reset()
return
| 5,275 | Python | 38.373134 | 111 | 0.570237 |
Ngochuy2137/omni_isaac_examples/unitree_quadruped/__init__.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# NOTE: Import here your extension examples to be propagated to ISAAC SIM Extensions startup
from omni.isaac.examples.unitree_quadruped.quadruped_example import QuadrupedExample
from omni.isaac.examples.unitree_quadruped.quadruped_example_extension import QuadrupedExampleExtension
| 715 | Python | 50.142854 | 103 | 0.830769 |
Ngochuy2137/omni_isaac_examples/unitree_quadruped/quadruped_example_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.unitree_quadruped import QuadrupedExample
class QuadrupedExampleExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
overview = "This Example shows quadruped simulation in Isaac Sim. Currently there is a performance issue with "
overview += (
"the quadruped gait controller; it's being investigated and will be improved in an upcoming release."
)
overview += "\n\tKeybord Input:"
overview += "\n\t\tup arrow / numpad 8: Move Forward"
overview += "\n\t\tdown arrow/ numpad 2: Move Reverse"
overview += "\n\t\tleft arrow/ numpad 4: Move Left"
overview += "\n\t\tright arrow / numpad 6: Move Right"
overview += "\n\t\tN / numpad 7: Spin Counterclockwise"
overview += "\n\t\tM / numpad 9: Spin Clockwise"
overview += "\n\nPress the 'Open in IDE' button to view the source code."
super().start_extension(
menu_name="",
submenu_name="",
name="Quadruped",
title="Unitree A1 Quadruped Example",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/features/robots_simulation/ext_omni_isaac_quadruped.html",
overview=overview,
file_path=os.path.abspath(__file__),
sample=QuadrupedExample(),
)
return
| 1,908 | Python | 41.422221 | 130 | 0.672432 |
Ngochuy2137/omni_isaac_examples/franka_nut_and_bolt/nut_bolt_controller.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import typing
import numpy as np
from omni.isaac.core.controllers.base_controller import BaseController
from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles
from omni.isaac.core.utils.stage import get_stage_units
from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController
from omni.isaac.franka.franka import Franka
from omni.isaac.manipulators.controllers.pick_place_controller import PickPlaceController
from .nut_vibra_table_controller import VibraFSM
from .screw_controller import ScrewController
class NutBoltController(BaseController):
"""
A state machine to tie nuts onto bolts with a vibrating table feeding the nuts
- State 0: Pick and Place from pickup location on vibration table to different bolts
- State 1: Screw nut onto bolt
Args:
name (str): Name id of the controller
franka (Franka): Franka Robot
"""
def __init__(self, name: str, franka: Franka) -> None:
BaseController.__init__(self, name=name)
self._event = 0
self._franka = franka
self._gripper = self._franka.gripper
self._end_effector_initial_height = self._franka.get_world_pose()[0][2] + (0.4 / get_stage_units())
self._pause = False
self._cspace_controller = RMPFlowController(name="pickplace_cspace_controller", robot_articulation=self._franka)
pick_place_events_dt = [0.008, 0.005, 1, 0.1, 0.05, 0.01, 0.0025]
self._pick_place_controller = PickPlaceController(
name="pickplace_controller",
cspace_controller=self._cspace_controller,
gripper=self._gripper,
end_effector_initial_height=self._end_effector_initial_height,
events_dt=pick_place_events_dt,
)
self._screw_controller = ScrewController(
name=f"screw_controller", cspace_controller=self._cspace_controller, gripper=self._gripper
)
self._vibraSM = VibraFSM()
self._i = self._vibraSM._i
self._vibraSM.stop_feed_after_delay(delay_sec=5.0)
return
def is_paused(self) -> bool:
"""
Returns:
bool: True if the state machine is paused. Otherwise False.
"""
return self._pause
def get_current_event(self) -> int:
"""
Returns:
int: Current event/ phase of the state machine
"""
return self._event
def forward(
self,
initial_picking_position: np.ndarray,
bolt_top: np.ndarray,
gripper_to_nut_offset: np.ndarray,
x_offset: np.ndarray,
) -> np.ndarray:
"""Runs the controller one step.
Args:
initial_picking_position (np.ndarray): initial nut position at table feeder
bolt_top (np.ndarray): bolt target position
#"""
_vibra_table_transforms = np.array([0.0, 0.0, 0.0])
if self.is_paused():
return _vibra_table_transforms
offsetPos = self._vibraSM.update()
_vibra_table_transforms = np.array(offsetPos, dtype=float)
if self._vibraSM._state == "stop" and self._event == 0:
initial_effector_orientation = quat_to_euler_angles(self._gripper.get_world_pose()[1])
initial_effector_orientation[2] = np.pi / 2
initial_end_effector_orientation = euler_angles_to_quat(initial_effector_orientation)
actions = self._pick_place_controller.forward(
picking_position=initial_picking_position + gripper_to_nut_offset,
placing_position=bolt_top + np.array([x_offset, 0.0, 0.0]),
current_joint_positions=self._franka.get_joint_positions(),
end_effector_orientation=initial_end_effector_orientation,
)
self._franka.apply_action(actions)
if self._pick_place_controller.is_done():
self._vibraSM._set_delayed_state_change(delay_sec=1.0, nextState="backward")
self._event = 1
if self._event == 1:
actions2 = self._screw_controller.forward(
franka_art_controller=self._franka.get_articulation_controller(),
bolt_position=bolt_top,
current_joint_positions=self._franka.get_joint_positions(),
current_joint_velocities=self._franka.get_joint_velocities(),
)
self._franka.apply_action(actions2)
if self._screw_controller.is_paused():
self.pause()
self._i += 1
return _vibra_table_transforms
def reset(self, franka: Franka) -> None:
"""Resets the state machine to start from the first phase/ event
Args:
franka (Franka): Franka Robot
"""
BaseController.reset(self)
self._event = 0
self._pause = False
self._franka = franka
self._gripper = self._franka.gripper
self._end_effector_initial_height = self._franka.get_world_pose()[0][2] + (0.4 / get_stage_units())
self._pick_place_controller.reset(end_effector_initial_height=self._end_effector_initial_height)
self._screw_controller.reset()
return
def pause(self) -> None:
"""Pauses the state machine's time and phase."""
self._pause = True
return
def resume(self) -> None:
"""Resumes the state machine's time and phase."""
self._pause = False
return
| 5,896 | Python | 38.313333 | 120 | 0.633311 |
Ngochuy2137/omni_isaac_examples/franka_nut_and_bolt/screw_controller.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import typing
import numpy as np
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.controllers.articulation_controller import ArticulationController
from omni.isaac.core.controllers.base_controller import BaseController
from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles
from omni.isaac.core.utils.stage import get_stage_units
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.manipulators.grippers.gripper import Gripper
class ScrewController(BaseController):
"""
A state machine for screwing nuts on bolts
Each phase runs for 1 second, which is the internal time of the state machine
Dt of each phase/ event step is defined
- State 0: Lower end_effector down to encircle the nut
- State 1: Close grip
- State 2: Re-Center end-effector grip with that of the nut and bolt
- State 3: Screw Clockwise
- State 4: Open grip (initiates at this state and cycles until limit)
- State 5: Screw counter-clockwise
Args:
name (str): Name id of the controller
cspace_controller (BaseController): a cartesian space controller that returns an ArticulationAction type
gripper (Gripper): a gripper controller for open/ close actions.
events_dt (typing.Optional[typing.List[float]], optional): Dt of each phase/ event step. 10 phases dt has to be defined. Defaults to None.
Raises:
Exception: events dt need to be list or numpy array
Exception: events dt need have length of 5 or less
"""
def __init__(
self,
name: str,
cspace_controller: BaseController,
gripper: Gripper,
events_dt: typing.Optional[typing.List[float]] = None,
) -> None:
BaseController.__init__(self, name=name)
self._event = 4
self._t = 0
self._events_dt = events_dt
if self._events_dt is None:
self._events_dt = [0.01, 0.1, 0.1, 0.025, 0.1, 0.05]
else:
if not isinstance(self._events_dt, np.ndarray) and not isinstance(self._events_dt, list):
raise Exception("events dt need to be list or numpy array")
elif isinstance(self._events_dt, np.ndarray):
self._events_dt = self._events_dt.tolist()
if len(self._events_dt) > 5:
raise Exception("events dt need have length of 5 or less")
self._cspace_controller = cspace_controller
self._gripper = gripper
self._pause = False
self._start = True
self._screw_position = np.array([0.0, 0.0, 0.0])
self._final_position = np.array([0.0, 0.0, 0.0])
self._screw_speed = 360.0 / 180.0 * np.pi
self._screw_speed_back = 720.0 / 180.0 * np.pi
return
def is_paused(self) -> bool:
"""
Returns:
bool: True if the state machine is paused. Otherwise False.
"""
return self._pause
def get_current_event(self) -> int:
"""
Returns:
int: Current event/ phase of the state machine
"""
return self._event
def forward(
self,
franka_art_controller: ArticulationController,
bolt_position: np.ndarray,
current_joint_positions: np.ndarray,
current_joint_velocities: np.ndarray,
) -> ArticulationAction:
"""Runs the controller one step.
Args:
franka_art_controller (ArticulationController): Robot's Articulation Controller.
bolt_position (np.ndarray): bolt position to reference for screwing position.
current_joint_positions (np.ndarray): Current joint positions of the robot.
current_joint_velocities (np.ndarray): Current joint velocities of the robot.
Returns:
ArticulationAction: action to be executed by the ArticulationController
"""
if self._pause or self._event >= len(self._events_dt):
target_joints = [None] * current_joint_positions.shape[0]
return ArticulationAction(joint_positions=target_joints)
if self._event == 0 and self._start:
self._screw_position = np.copy(bolt_position)
self._final_position = np.copy(bolt_position)
self._start = False
self._target_end_effector_orientation = self._gripper.get_world_pose()[1]
if self._event == 0:
franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position")
orientation_quat = self._gripper.get_world_pose()[1]
self.orientation_euler = quat_to_euler_angles(orientation_quat)
target_orientation_euler = np.array([self.orientation_euler[0], self.orientation_euler[1], -np.pi / 2])
target_orientation_quat = euler_angles_to_quat(target_orientation_euler)
target_joints = self._cspace_controller.forward(
target_end_effector_position=self._screw_position,
target_end_effector_orientation=target_orientation_quat,
)
if self._event == 1:
self._lower = False
franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position")
target_joints = self._gripper.forward(action="close")
if self._event == 2:
franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position")
orientation_quat = self._gripper.get_world_pose()[1]
self.orientation_euler = quat_to_euler_angles(orientation_quat)
target_orientation_euler = np.array([self.orientation_euler[0], self.orientation_euler[1], -np.pi / 2])
target_orientation_quat = euler_angles_to_quat(target_orientation_euler)
finger_pos = current_joint_positions[-2:]
positive_x_offset = finger_pos[1] - finger_pos[0]
target_joints = self._cspace_controller.forward(
target_end_effector_position=self._screw_position + np.array([positive_x_offset, 0.0, -0.001]),
target_end_effector_orientation=target_orientation_quat,
)
if self._event == 3:
franka_art_controller.switch_dof_control_mode(dof_index=6, mode="velocity")
target_joint_velocities = [None] * current_joint_velocities.shape[0]
target_joint_velocities[6] = self._screw_speed
if current_joint_positions[6] > 2.7:
target_joint_velocities[6] = 0.0
target_joints = ArticulationAction(joint_velocities=target_joint_velocities)
if self._event == 4:
franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position")
target_joints = self._gripper.forward(action="open")
if self._event == 5:
franka_art_controller.switch_dof_control_mode(dof_index=6, mode="velocity")
target_joint_velocities = [None] * current_joint_velocities.shape[0]
target_joint_velocities[6] = -self._screw_speed_back
if current_joint_positions[6] < -0.4:
target_joint_velocities[6] = 0.0
target_joints = ArticulationAction(joint_velocities=target_joint_velocities)
self._t += self._events_dt[self._event]
if self._t >= 1.0:
self._event = (self._event + 1) % 6
self._t = 0
if self._event == 5:
if not self._start and (bolt_position[2] - self._final_position[2] > 0.0198):
self.pause()
return ArticulationAction(joint_positions=[None] * current_joint_positions.shape[0])
if self._start:
self._screw_position[2] -= 0.001
self._final_position[2] -= 0.001
if bolt_position[2] - self._screw_position[2] < 0.013:
self._screw_position[2] -= 0.0018
self._final_position[2] -= 0.0018
return target_joints
def reset(self, events_dt: typing.Optional[typing.List[float]] = None) -> None:
"""Resets the state machine to start from the first phase/ event
Args:
events_dt (typing.Optional[typing.List[float]], optional): Dt of each phase/ event step. Defaults to None.
Raises:
Exception: events dt need to be list or numpy array
Exception: events dt need have length of 5 or less
"""
BaseController.reset(self)
self._cspace_controller.reset()
self._event = 4
self._t = 0
self._pause = False
self._start = True
self._screw_position = np.array([0.0, 0.0, 0.0])
self._final_position = np.array([0.0, 0.0, 0.0])
self._screw_speed = 360.0 / 180.0 * np.pi
self._screw_speed_back = 720.0 / 180.0 * np.pi
# self._gripper = gripper
if events_dt is not None:
self._events_dt = events_dt
if not isinstance(self._events_dt, np.ndarray) and not isinstance(self._events_dt, list):
raise Exception("events dt need to be list or numpy array")
elif isinstance(self._events_dt, np.ndarray):
self._events_dt = self._events_dt.tolist()
if len(self._events_dt) > 5:
raise Exception("events dt need have length of 5 or less")
return
def is_done(self) -> bool:
"""
Returns:
bool: True if the state machine reached the last phase. Otherwise False.
"""
if self._event >= len(self._events_dt):
return True
else:
return False
def pause(self) -> None:
"""Pauses the state machine's time and phase."""
self._pause = True
return
def resume(self) -> None:
"""Resumes the state machine's time and phase."""
self._pause = False
return
| 10,293 | Python | 42.434599 | 146 | 0.61605 |
Ngochuy2137/omni_isaac_examples/franka_nut_and_bolt/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.franka_nut_and_bolt.franka_nut_and_bolt import FrankaNutAndBolt
from omni.isaac.examples.franka_nut_and_bolt.franka_nut_and_bolt_extension import FrankaNutAndBoltExtension
| 629 | Python | 51.499996 | 107 | 0.823529 |
Ngochuy2137/omni_isaac_examples/franka_nut_and_bolt/franka_nut_and_bolt.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
from omni.isaac.core.materials.physics_material import PhysicsMaterial
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.franka.franka import Franka
from pxr import Gf, PhysxSchema, Usd, UsdPhysics, UsdShade
from .nut_bolt_controller import NutBoltController
# Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html
class FrankaNutAndBolt(BaseSample):
def __init__(self) -> None:
super().__init__()
# SCENE GEOMETRY
# env (group) spacing:
self._env_spacing = 2.0
# franka
self._stool_height = 0.15
self._franka_position = np.array([0.269, 0.1778, 0.0]) # Gf.Vec3f(0.269, 0.1778, 0.0)
# table and vibra table:
self._table_position = np.array([0.5, 0.0, 0.0]) # Gf.Vec3f(0.5, 0.0, 0.0)
self._table_scale = 0.01
self._tooling_plate_offset = np.array([0.0, 0.0, 0.0])
self._vibra_table_position_offset = np.array([0.157, -0.1524, 0.0])
self._vibra_top_offset = np.array([0.0, 0.0, 0.15])
self._vibra_table_top_to_collider_offset = np.array([0.05, 2.5, -0.59]) * 0.01
# xyz relative to the vibra table where the nut should be picked up
self._vibra_table_nut_pickup_pos_offset = np.array([0.124, 0.24, 0.158])
# nut
self._nut_height = 0.016
self._nut_spiral_center_vibra_offset = np.array([-0.04, -0.17, 0.01])
# randomize initial nut and bolt positions
self._nut_radius = 0.055
self._nut_height_delta = 0.03
self._nut_dist_delta = 0.03
self._mass_nut = 0.065
# pipe and bolt parameters
self._bolt_length = 0.1
self._bolt_radius = 0.11
self._pipe_pos_on_table = np.array([0.2032, 0.381, 0.0])
self._bolt_z_offset_to_pipe = 0.08
self._gripper_to_nut_offset = np.array([0.0, 0.0, 0.003])
self._top_of_bolt = (
np.array([0.0, 0.0, self._bolt_length + (self._nut_height / 2)]) + self._gripper_to_nut_offset
)
# randomization
self._randomize_nut_positions = True
self._nut_position_noise_minmax = 0.005
self._rng_seed = 8
# states
self._reset_hydra_instancing_on_shutdown = False
self._time = 0.0
self._fsm_time = 0.0
# some global sim options:
self._time_steps_per_second = 240 # 4.167ms aprx
self._fsm_update_rate = 60
self._solverPositionIterations = 4
self._solverVelocityIterations = 1
self._solver_type = "TGS"
self._ik_damping = 0.1
self._num_bolts = 6
self._num_nuts = 12
self._sim_dt = 1.0 / self._time_steps_per_second
self._fsm_update_dt = 1.0 / self._fsm_update_rate
return
def setup_scene(self):
# setup asset paths:
self.nucleus_server = get_assets_root_path()
self.asset_folder = self.nucleus_server + "/Isaac/Samples/Examples/FrankaNutBolt/"
self.asset_paths = {
"shop_table": self.asset_folder + "SubUSDs/Shop_Table/Shop_Table.usd",
"tooling_plate": self.asset_folder + "SubUSDs/Tooling_Plate/Tooling_Plate.usd",
"nut": self.asset_folder + "SubUSDs/Nut/M20_Nut_Tight_R256_Franka_SI.usd",
"bolt": self.asset_folder + "SubUSDs/Bolt/M20_Bolt_Tight_R512_Franka_SI.usd",
"vibra_table_top": self.asset_folder + "SubUSDs/VibrationTable_Top/VibrationTable_Top.usd",
"vibra_table_bot": self.asset_folder + "SubUSDs/VibrationTable_Base/VibrationTable_Base.usd",
"vibra_table_collision": self.asset_folder + "SubUSDs/VibrationTable_Top_collision.usd",
"vibra_table_clamps": self.asset_folder + "SubUSDs/Clamps/Clamps.usd",
"pipe": self.asset_folder + "SubUSDs/Pipe/Pipe.usd",
}
world = self.get_world()
world.scene.add_default_ground_plane()
world.scene.add(XFormPrim(prim_path="/World/collisionGroups", name="collision_groups_xform"))
self._setup_simulation()
# add_table_assets
add_reference_to_stage(usd_path=self.asset_paths["shop_table"], prim_path="/World/env/table")
world.scene.add(GeometryPrim(prim_path="/World/env/table", name=f"table_ref_geom", collision=True))
add_reference_to_stage(usd_path=self.asset_paths["tooling_plate"], prim_path="/World/env/tooling_plate")
world.scene.add(GeometryPrim(prim_path="/World/env/tooling_plate", name=f"tooling_plate_geom", collision=True))
add_reference_to_stage(usd_path=self.asset_paths["pipe"], prim_path="/World/env/pipe")
world.scene.add(GeometryPrim(prim_path="/World/env/pipe", name=f"pipe_geom", collision=True))
# add_vibra_table_assets
add_reference_to_stage(usd_path=self.asset_paths["vibra_table_bot"], prim_path="/World/env/vibra_table_bottom")
world.scene.add(GeometryPrim(prim_path="/World/env/vibra_table_bottom", name=f"vibra_table_bottom_geom"))
add_reference_to_stage(
usd_path=self.asset_paths["vibra_table_clamps"], prim_path="/World/env/vibra_table_clamps"
)
world.scene.add(
GeometryPrim(prim_path="/World/env/vibra_table_clamps", name=f"vibra_table_clamps_geom", collision=True)
)
world.scene.add(XFormPrim(prim_path="/World/env/vibra_table", name=f"vibra_table_xform"))
add_reference_to_stage(usd_path=self.asset_paths["vibra_table_top"], prim_path="/World/env/vibra_table/visual")
add_reference_to_stage(
usd_path=self.asset_paths["vibra_table_collision"], prim_path="/World/env/vibra_table/collision"
)
world.scene.add(XFormPrim(prim_path="/World/env/vibra_table/visual", name=f"vibra_table_visual_xform"))
world.scene.add(
GeometryPrim(
prim_path="/World/env/vibra_table/collision", name=f"vibra_table_collision_ref_geom", collision=True
)
)
# add_nuts_bolts_assets
for bolt in range(self._num_bolts):
add_reference_to_stage(usd_path=self.asset_paths["bolt"], prim_path=f"/World/env/bolt{bolt}")
world.scene.add(GeometryPrim(prim_path=f"/World/env/bolt{bolt}", name=f"bolt{bolt}_geom"))
for nut in range(self._num_nuts):
add_reference_to_stage(usd_path=self.asset_paths["nut"], prim_path=f"/World/env/nut{nut}")
world.scene.add(GeometryPrim(prim_path=f"/World/env/nut{nut}", name=f"nut{nut}_geom"))
# add_franka_assets
world.scene.add(Franka(prim_path="/World/env/franka", name=f"franka"))
return
async def setup_post_load(self):
self._world = self.get_world()
self._rng = np.random.default_rng(self._rng_seed)
self._world.scene.enable_bounding_boxes_computations()
await self._setup_materials()
# next four functions are for setting up the right positions and orientations for all assets
await self._add_table()
await self._add_vibra_table()
await self._add_nuts_and_bolt(add_debug_nut=self._num_nuts == 2)
await self._add_franka()
self._controller = NutBoltController(name="nut_bolt_controller", franka=self._franka)
self._franka.gripper.open()
self._rbApi2 = UsdPhysics.RigidBodyAPI.Apply(self._vibra_table_xform.prim.GetPrim())
self._world.add_physics_callback(f"sim_step", callback_fn=self.physics_step)
await self._world.play_async()
return
def physics_step(self, step_size):
if self._controller.is_paused():
if self._controller._i >= min(self._num_nuts, self._num_bolts):
self._rbApi2.CreateVelocityAttr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
return
self._controller.reset(self._franka)
if self._controller._i < min(self._num_nuts, self._num_bolts):
initial_position = self._vibra_table_nut_pickup_pos_offset + self._vibra_table_position
self._bolt_geom = self._world.scene.get_object(f"bolt{self._controller._i}_geom")
finger_pos = self._franka.get_joint_positions()[-2:]
positive_x_offset = finger_pos[1] - finger_pos[0]
bolt_position, _ = self._bolt_geom.get_world_pose()
placing_position = bolt_position + self._top_of_bolt
_vibra_table_transforms = self._controller.forward(
initial_picking_position=initial_position,
bolt_top=placing_position,
gripper_to_nut_offset=self._gripper_to_nut_offset,
x_offset=positive_x_offset,
)
self._rbApi2.CreateVelocityAttr().Set(
Gf.Vec3f(_vibra_table_transforms[0], _vibra_table_transforms[1], _vibra_table_transforms[2])
)
return
async def _setup_materials(self):
self._bolt_physics_material = PhysicsMaterial(
prim_path="/World/PhysicsMaterials/BoltMaterial",
name="bolt_material_physics",
static_friction=0.2,
dynamic_friction=0.2,
)
self._nut_physics_material = PhysicsMaterial(
prim_path="/World/PhysicsMaterials/NutMaterial",
name="nut_material_physics",
static_friction=0.2,
dynamic_friction=0.2,
)
self._vibra_table_physics_material = PhysicsMaterial(
prim_path="/World/PhysicsMaterials/VibraTableMaterial",
name="vibra_table_material_physics",
static_friction=0.2,
dynamic_friction=0.2,
)
self._franka_finger_physics_material = PhysicsMaterial(
prim_path="/World/PhysicsMaterials/FrankaFingerMaterial",
name="franka_finger_material_physics",
static_friction=0.7,
dynamic_friction=0.7,
)
await self._world.reset_async()
async def _add_table(self):
##shop_table
self._table_ref_geom = self._world.scene.get_object(f"table_ref_geom")
self._table_ref_geom.set_local_scale(np.array([self._table_scale]))
self._table_ref_geom.set_world_pose(position=self._table_position)
self._table_ref_geom.set_default_state(position=self._table_position)
lb = self._world.scene.compute_object_AABB(name=f"table_ref_geom")
zmin = lb[0][2]
zmax = lb[1][2]
self._table_position[2] = -zmin
self._table_height = zmax
self._table_ref_geom.set_collision_approximation("none")
self._convexIncludeRel.AddTarget(self._table_ref_geom.prim_path)
##tooling_plate
self._tooling_plate_geom = self._world.scene.get_object(f"tooling_plate_geom")
self._tooling_plate_geom.set_local_scale(np.array([self._table_scale]))
lb = self._world.scene.compute_object_AABB(name=f"tooling_plate_geom")
zmin = lb[0][2]
zmax = lb[1][2]
tooling_transform = self._tooling_plate_offset
tooling_transform[2] = -zmin + self._table_height
tooling_transform = tooling_transform + self._table_position
self._tooling_plate_geom.set_world_pose(position=tooling_transform)
self._tooling_plate_geom.set_default_state(position=tooling_transform)
self._tooling_plate_geom.set_collision_approximation("boundingCube")
self._table_height += zmax - zmin
self._convexIncludeRel.AddTarget(self._tooling_plate_geom.prim_path)
##pipe
self._pipe_geom = self._world.scene.get_object(f"pipe_geom")
self._pipe_geom.set_local_scale(np.array([self._table_scale]))
lb = self._world.scene.compute_object_AABB(name=f"pipe_geom")
zmin = lb[0][2]
zmax = lb[1][2]
self._pipe_height = zmax - zmin
pipe_transform = self._pipe_pos_on_table
pipe_transform[2] = -zmin + self._table_height
pipe_transform = pipe_transform + self._table_position
self._pipe_geom.set_world_pose(position=pipe_transform, orientation=np.array([0, 0, 0, 1]))
self._pipe_geom.set_default_state(position=pipe_transform, orientation=np.array([0, 0, 0, 1]))
self._pipe_geom.set_collision_approximation("none")
self._convexIncludeRel.AddTarget(self._pipe_geom.prim_path)
await self._world.reset_async()
async def _add_vibra_table(self):
self._vibra_table_bottom_geom = self._world.scene.get_object(f"vibra_table_bottom_geom")
self._vibra_table_bottom_geom.set_local_scale(np.array([self._table_scale]))
lb = self._world.scene.compute_object_AABB(name=f"vibra_table_bottom_geom")
zmin = lb[0][2]
bot_part_pos = self._vibra_table_position_offset
bot_part_pos[2] = -zmin + self._table_height
bot_part_pos = bot_part_pos + self._table_position
self._vibra_table_bottom_geom.set_world_pose(position=bot_part_pos)
self._vibra_table_bottom_geom.set_default_state(position=bot_part_pos)
self._vibra_table_bottom_geom.set_collision_approximation("none")
self._convexIncludeRel.AddTarget(self._vibra_table_bottom_geom.prim_path)
# clamps
self._vibra_table_clamps_geom = self._world.scene.get_object(f"vibra_table_clamps_geom")
self._vibra_table_clamps_geom.set_collision_approximation("none")
self._convexIncludeRel.AddTarget(self._vibra_table_clamps_geom.prim_path)
# vibra_table
self._vibra_table_xform = self._world.scene.get_object(f"vibra_table_xform")
self._vibra_table_position = bot_part_pos
vibra_kinematic_prim = self._vibra_table_xform.prim
rbApi = UsdPhysics.RigidBodyAPI.Apply(vibra_kinematic_prim.GetPrim())
rbApi.CreateRigidBodyEnabledAttr(True)
rbApi.CreateKinematicEnabledAttr(True)
# visual
self._vibra_table_visual_xform = self._world.scene.get_object(f"vibra_table_visual_xform")
self._vibra_table_visual_xform.set_world_pose(position=self._vibra_top_offset)
self._vibra_table_visual_xform.set_default_state(position=self._vibra_top_offset)
self._vibra_table_visual_xform.set_local_scale(np.array([self._table_scale]))
# not clear why this makes a difference for the position (new bug although no change to code)
self._vibra_table_visual_xform.prim.SetInstanceable(True)
# collision
self._vibra_table_collision_ref_geom = self._world.scene.get_object(f"vibra_table_collision_ref_geom")
offset = self._vibra_top_offset + self._vibra_table_top_to_collider_offset
self._vibra_table_collision_ref_geom.set_local_scale(np.array([1.0]))
self._vibra_table_collision_ref_geom.set_world_pose(position=offset)
self._vibra_table_collision_ref_geom.set_default_state(position=offset)
self._vibra_table_collision_ref_geom.apply_physics_material(self._vibra_table_physics_material)
self._convexIncludeRel.AddTarget(self._vibra_table_collision_ref_geom.prim_path)
self._vibra_table_collision_ref_geom.set_collision_approximation("convexHull")
vibra_kinematic_prim.SetInstanceable(True)
self._vibra_table_xform.set_world_pose(position=self._vibra_table_position, orientation=np.array([0, 0, 0, 1]))
self._vibra_table_xform.set_default_state(
position=self._vibra_table_position, orientation=np.array([0, 0, 0, 1])
)
self._vibra_table_visual_xform.set_default_state(
position=self._vibra_table_visual_xform.get_world_pose()[0],
orientation=self._vibra_table_visual_xform.get_world_pose()[1],
)
self._vibra_table_collision_ref_geom.set_default_state(
position=self._vibra_table_collision_ref_geom.get_world_pose()[0],
orientation=self._vibra_table_collision_ref_geom.get_world_pose()[1],
)
await self._world.reset_async()
async def _add_nuts_and_bolt(self, add_debug_nut=False):
angle_delta = np.pi * 2.0 / self._num_bolts
for j in range(self._num_bolts):
self._bolt_geom = self._world.scene.get_object(f"bolt{j}_geom")
self._bolt_geom.prim.SetInstanceable(True)
bolt_pos = np.array(self._pipe_pos_on_table) + self._table_position
bolt_pos[0] += np.cos(j * angle_delta) * self._bolt_radius
bolt_pos[1] += np.sin(j * angle_delta) * self._bolt_radius
bolt_pos[2] = self._bolt_z_offset_to_pipe + self._table_height
self._bolt_geom.set_world_pose(position=bolt_pos)
self._bolt_geom.set_default_state(position=bolt_pos)
self._boltMeshIncludeRel.AddTarget(self._bolt_geom.prim_path)
self._bolt_geom.apply_physics_material(self._bolt_physics_material)
await self._generate_nut_initial_poses()
for nut_idx in range(self._num_nuts):
nut_pos = self._nut_init_poses[nut_idx, :3].copy()
if add_debug_nut and nut_idx == 0:
nut_pos[0] = 0.78
nut_pos[1] = self._vibra_table_nut_pickup_pos_offset[1] + self._vibra_table_position[1] # 0.0264
if add_debug_nut and nut_idx == 1:
nut_pos[0] = 0.78
nut_pos[1] = 0.0264 - 0.04
self._nut_geom = self._world.scene.get_object(f"nut{nut_idx}_geom")
self._nut_geom.prim.SetInstanceable(True)
self._nut_geom.set_world_pose(position=np.array(nut_pos.tolist()))
self._nut_geom.set_default_state(position=np.array(nut_pos.tolist()))
physxRBAPI = PhysxSchema.PhysxRigidBodyAPI.Apply(self._nut_geom.prim)
physxRBAPI.CreateSolverPositionIterationCountAttr().Set(self._solverPositionIterations)
physxRBAPI.CreateSolverVelocityIterationCountAttr().Set(self._solverVelocityIterations)
self._nut_geom.apply_physics_material(self._nut_physics_material)
self._convexIncludeRel.AddTarget(self._nut_geom.prim_path + "/M20_Nut_Tight_Convex")
self._nutMeshIncludeRel.AddTarget(self._nut_geom.prim_path + "/M20_Nut_Tight_SDF")
rbApi3 = UsdPhysics.RigidBodyAPI.Apply(self._nut_geom.prim.GetPrim())
rbApi3.CreateRigidBodyEnabledAttr(True)
physxAPI = PhysxSchema.PhysxRigidBodyAPI.Apply(self._nut_geom.prim.GetPrim())
physxAPI.CreateSleepThresholdAttr().Set(0.0)
massAPI = UsdPhysics.MassAPI.Apply(self._nut_geom.prim.GetPrim())
massAPI.CreateMassAttr().Set(self._mass_nut)
await self._world.reset_async()
async def _generate_nut_initial_poses(self):
self._nut_init_poses = np.zeros((self._num_nuts, 7), dtype=np.float32)
self._nut_init_poses[:, -1] = 1 # quat to identity
nut_spiral_center = self._vibra_table_position + self._nut_spiral_center_vibra_offset
nut_spiral_center += self._vibra_top_offset
for nut_idx in range(self._num_nuts):
self._nut_init_poses[nut_idx, :3] = np.array(nut_spiral_center)
self._nut_init_poses[nut_idx, 0] += self._nut_radius * np.sin(
np.pi / 3.0 * nut_idx
) + self._nut_dist_delta * (nut_idx // 6)
self._nut_init_poses[nut_idx, 1] += self._nut_radius * np.cos(
np.pi / 3.0 * nut_idx
) + self._nut_dist_delta * (nut_idx // 6)
self._nut_init_poses[nut_idx, 2] += self._nut_height_delta * (nut_idx // 6)
if self._randomize_nut_positions:
self._nut_init_poses[nut_idx, 0] += self._rng.uniform(
-self._nut_position_noise_minmax, self._nut_position_noise_minmax
)
self._nut_init_poses[nut_idx, 1] += self._rng.uniform(
-self._nut_position_noise_minmax, self._nut_position_noise_minmax
)
await self._world.reset_async()
async def _add_franka(self):
self._franka = self._world.scene.get_object(f"franka")
franka_pos = np.array(self._franka_position)
franka_pos[2] = franka_pos[2] + self._table_height
self._franka.set_world_pose(position=franka_pos)
self._franka.set_default_state(position=franka_pos)
self._franka.gripper.open()
kps = np.array([6000000.0, 600000.0, 6000000.0, 600000.0, 25000.0, 15000.0, 25000.0, 15000.0, 15000.0])
kds = np.array([600000.0, 60000.0, 300000.0, 30000.0, 3000.0, 3000.0, 3000.0, 6000.0, 6000.0])
self._franka.get_articulation_controller().set_gains(kps=kps, kds=kds, save_to_usd=True)
self._frankaHandIncludeRel.AddTarget(self._franka.prim_path + "/panda_leftfinger")
self._frankaHandIncludeRel.AddTarget(self._franka.prim_path + "/panda_rightfinger")
franka_left_finger = self._world.stage.GetPrimAtPath(
"/World/env/franka/panda_leftfinger/geometry/panda_leftfinger"
)
x = UsdShade.MaterialBindingAPI.Apply(franka_left_finger)
x.Bind(
self._franka_finger_physics_material.material,
bindingStrength="weakerThanDescendants",
materialPurpose="physics",
)
franka_right_finger = self._world.stage.GetPrimAtPath(
"/World/env/franka/panda_rightfinger/geometry/panda_rightfinger"
)
x2 = UsdShade.MaterialBindingAPI.Apply(franka_right_finger)
x2.Bind(
self._franka_finger_physics_material.material,
bindingStrength="weakerThanDescendants",
materialPurpose="physics",
)
await self._world.reset_async()
def _setup_simulation(self):
self._scene = PhysicsContext()
self._scene.set_solver_type(self._solver_type)
self._scene.set_broadphase_type("GPU")
self._scene.enable_gpu_dynamics(flag=True)
self._scene.set_friction_offset_threshold(0.01)
self._scene.set_friction_correlation_distance(0.0005)
self._scene.set_gpu_total_aggregate_pairs_capacity(10 * 1024)
self._scene.set_gpu_found_lost_pairs_capacity(10 * 1024)
self._scene.set_gpu_heap_capacity(64 * 1024 * 1024)
self._scene.set_gpu_found_lost_aggregate_pairs_capacity(10 * 1024)
# added because of new errors regarding collisionstacksize
physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(get_prim_at_path("/physicsScene"))
physxSceneAPI.CreateGpuCollisionStackSizeAttr().Set(76000000) # or whatever min is needed
# group to include SDF mesh of nut only
self._meshCollisionGroup = UsdPhysics.CollisionGroup.Define(
self._world.scene.stage, "/World/collisionGroups/meshColliders"
)
collectionAPI = Usd.CollectionAPI.Apply(self._meshCollisionGroup.GetPrim(), "colliders")
self._nutMeshIncludeRel = collectionAPI.CreateIncludesRel()
# group to include all convex collision (nut convex, pipe, table, vibrating table, other small assets on the table)
self._convexCollisionGroup = UsdPhysics.CollisionGroup.Define(
self._world.scene.stage, "/World/collisionGroups/convexColliders"
)
collectionAPI = Usd.CollectionAPI.Apply(self._convexCollisionGroup.GetPrim(), "colliders")
self._convexIncludeRel = collectionAPI.CreateIncludesRel()
# group to include bolt prim only (only has SDF mesh)
self._boltCollisionGroup = UsdPhysics.CollisionGroup.Define(
self._world.scene.stage, "/World/collisionGroups/boltColliders"
)
collectionAPI = Usd.CollectionAPI.Apply(self._boltCollisionGroup.GetPrim(), "colliders")
self._boltMeshIncludeRel = collectionAPI.CreateIncludesRel()
# group to include the franka hands prims only
self._frankaHandCollisionGroup = UsdPhysics.CollisionGroup.Define(
self._world.scene.stage, "/World/collisionGroups/frankaHandColliders"
)
collectionAPI = Usd.CollectionAPI.Apply(self._frankaHandCollisionGroup.GetPrim(), "colliders")
self._frankaHandIncludeRel = collectionAPI.CreateIncludesRel()
# invert group logic so only groups that filter each-other will collide:
self._scene.set_invert_collision_group_filter(True)
# # the SDF mesh collider nuts should only collide with the bolts
filteredRel = self._meshCollisionGroup.CreateFilteredGroupsRel()
filteredRel.AddTarget("/World/collisionGroups/boltColliders")
# # the convex hull nuts should collide with other nuts, the vibra table, table, pipe and small assets on the table.
# It should also collide with the franka grippers
filteredRel = self._convexCollisionGroup.CreateFilteredGroupsRel()
filteredRel.AddTarget("/World/collisionGroups/convexColliders")
filteredRel.AddTarget("/World/collisionGroups/frankaHandColliders")
# # the SDF mesh bolt only collides with the SDF mesh nut colliders
# and with the franka grippers
filteredRel = self._boltCollisionGroup.CreateFilteredGroupsRel()
filteredRel.AddTarget("/World/collisionGroups/meshColliders")
filteredRel.AddTarget("/World/collisionGroups/frankaHandColliders")
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
self._controller._vibraSM.reset()
self._controller._vibraSM._i = 2
self._controller.reset(franka=self._franka)
self._controller._i = self._controller._vibraSM._i
self._franka.gripper.open()
self._controller._vibraSM.start_feed()
await self._world.play_async()
return
def world_cleanup(self):
self._controller = None
return
| 26,377 | Python | 50.721569 | 124 | 0.646851 |
Ngochuy2137/omni_isaac_examples/franka_nut_and_bolt/franka_nut_and_bolt_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.franka_nut_and_bolt import FrankaNutAndBolt
class FrankaNutAndBoltExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Manipulation",
submenu_name="",
name="Franka Nut and Bolt",
title="Franka Nut and Bolt",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_sdf_nut_and_bolt.html#franka-nut-and-bolt-tutorial",
overview="Franka robot arms picking and screwing nuts onto bolts",
file_path=os.path.abspath(__file__),
sample=FrankaNutAndBolt(),
)
return
| 1,241 | Python | 40.399999 | 161 | 0.713135 |
Ngochuy2137/omni_isaac_examples/franka_nut_and_bolt/nut_vibra_table_controller.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
class VibraFSM:
_amplitudes = {
"stop": np.array((0.0, 0.0, 0.0), dtype=np.float32), # [m]
"run_feed": np.array((0.000, 0.03, 0.02), dtype=np.float32), # [m]
"backward": np.array((0.000, -0.03, 0.02), dtype=np.float32), # [m]
"realign": np.array((-0.03, 0.0, 0.02), dtype=np.float32), # [m]
}
_motion_frequency = 60.0 # [Hz]
# configure unblock-cycle:
_feed_time = 3.5
_stop_time = 5.0
_backward_time = 0.75
_realign_time = 0.75
def __init__(self, dt=None):
self.reset()
self._i = 2
if dt is not None:
self._dt = dt
def reset(self):
self._dt = 1.0 / 240.0
self._time = 0.0
self.state = "stop"
self._after_delay_state = None
def start_feed(self):
self.state = "run_feed"
# kick off unblock cycle
self._set_delayed_state_change(delay_sec=self._feed_time, nextState="backward")
def stop_feed_after_delay(self, delay_sec: float):
self.state = "run_feed"
self._set_delayed_state_change(delay_sec=delay_sec, nextState="stop")
def _set_delayed_state_change(self, delay_sec: float, nextState: str):
self._after_delay_state = nextState
self._wait_end_time = self._time + delay_sec
def update(self):
self._time += self._dt
# process wait if necessary
if self._after_delay_state is not None and self._time > self._wait_end_time:
self.state = self._after_delay_state
# auto-unblock cycle
if self._state == "run_feed":
self.stop_feed_after_delay(self._stop_time)
elif self._state == "backward":
self._set_delayed_state_change(delay_sec=self._backward_time, nextState="realign")
elif self._state == "realign":
self._set_delayed_state_change(delay_sec=self._realign_time, nextState="run_feed")
else:
self._after_delay_state = None
return self._motion_amplitude
def is_stopped(self):
return self._state == "stop"
def is_stopping(self):
return self.is_stopped() or self._after_delay_state == "stop"
@property
def state(self):
return self._state
@state.setter
def state(self, newState):
self._state = newState
if self._state in self._amplitudes:
self._motion_amplitude = self._amplitudes[self._state]
else:
self._motion_amplitude = self._amplitudes["stop"]
| 2,983 | Python | 34.105882 | 98 | 0.601408 |
Ngochuy2137/omni_isaac_examples/omnigraph_keyboard/omnigraph_keyboard_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.omnigraph_keyboard import OmnigraphKeyboard
class OmnigraphKeyboardExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
overview = "This Example shows how to change the size of a cube using the keyboard through omnigraph progrmaming in Isaac Sim."
overview += "\n\tKeybord Input:"
overview += "\n\t\ta: Grow"
overview += "\n\t\td: Shrink"
overview += "\n\nPress the 'Open in IDE' button to view the source code."
overview += "\nOpen Visual Scripting Window to see Omnigraph"
super().start_extension(
menu_name="Input Devices",
submenu_name="",
name="Omnigraph Keyboard",
title="NVIDIA Omnigraph Scripting Example",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/gui_tutorials/tutorial_advanced_input_devices.html",
overview=overview,
file_path=os.path.abspath(__file__),
sample=OmnigraphKeyboard(),
)
| 1,562 | Python | 42.416665 | 135 | 0.697183 |
Ngochuy2137/omni_isaac_examples/omnigraph_keyboard/omnigraph_keyboard.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
import omni.ext
import omni.graph.core as og
from omni.isaac.core.objects import VisualCuboid
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.examples.base_sample import BaseSample
class OmnigraphKeyboard(BaseSample):
def __init__(self) -> None:
super().__init__()
self._gamepad_gains = (40.0, 40.0, 2.0)
self._gamepad_deadzone = 0.15
def setup_scene(self):
world = self.get_world()
world.scene.add(
VisualCuboid(
prim_path="/Cube", # The prim path of the cube in the USD stage
name="cube", # The unique name used to retrieve the object from the scene later on
position=np.array([0, 0, 1.0]), # Using the current stage units which is cms by default.
size=1.0, # most arguments accept mainly numpy arrays.
color=np.array([0, 1.0, 1.0]), # RGB channels, going from 0-1
)
)
world.scene.add_default_ground_plane()
set_camera_view(eye=np.array([5, 5, 3]), target=np.array([0, 0, 0]))
# setup graph
keys = og.Controller.Keys
og.Controller.edit(
{"graph_path": "/controller_graph", "evaluator_name": "execution"},
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("A", "omni.graph.nodes.ReadKeyboardState"),
("D", "omni.graph.nodes.ReadKeyboardState"),
("ToDouble1", "omni.graph.nodes.ToDouble"),
("ToDouble2", "omni.graph.nodes.ToDouble"),
("Negate", "omni.graph.nodes.Multiply"),
("DeltaAdd", "omni.graph.nodes.Add"),
("SizeAdd", "omni.graph.nodes.Add"),
("NegOne", "omni.graph.nodes.ConstantInt"),
("ScaleDown", "omni.graph.nodes.Multiply"),
("ScaleFactor", "omni.graph.nodes.ConstantDouble"),
("CubeWrite", "omni.graph.nodes.WritePrimAttribute"), # write prim property translate
("CubeRead", "omni.graph.nodes.ReadPrimAttribute"),
],
keys.SET_VALUES: [
("A.inputs:key", "A"),
("D.inputs:key", "D"),
("OnTick.inputs:onlyPlayback", True), # only tick when simulator is playing
("NegOne.inputs:value", -1),
("ScaleFactor.inputs:value", 0.1),
("CubeWrite.inputs:name", "size"),
("CubeWrite.inputs:primPath", "/Cube"),
("CubeWrite.inputs:usePath", True),
("CubeRead.inputs:name", "size"),
("CubeRead.inputs:primPath", "/Cube"),
("CubeRead.inputs:usePath", True),
],
keys.CONNECT: [
("OnTick.outputs:tick", "CubeWrite.inputs:execIn"),
("A.outputs:isPressed", "ToDouble1.inputs:value"),
("D.outputs:isPressed", "ToDouble2.inputs:value"),
("ToDouble2.outputs:converted", "Negate.inputs:a"),
("NegOne.inputs:value", "Negate.inputs:b"),
("ToDouble1.outputs:converted", "DeltaAdd.inputs:a"),
("Negate.outputs:product", "DeltaAdd.inputs:b"),
("DeltaAdd.outputs:sum", "ScaleDown.inputs:a"),
("CubeRead.outputs:value", "SizeAdd.inputs:b"),
("SizeAdd.outputs:sum", "CubeWrite.inputs:value"),
("ScaleFactor.inputs:value", "ScaleDown.inputs:b"),
("ScaleDown.outputs:product", "SizeAdd.inputs:a"),
],
},
)
def world_cleanup(self):
pass
| 4,293 | Python | 46.186813 | 106 | 0.541113 |
Ngochuy2137/omni_isaac_examples/omnigraph_keyboard/__init__.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.omnigraph_keyboard.omnigraph_keyboard import OmnigraphKeyboard
from omni.isaac.examples.omnigraph_keyboard.omnigraph_keyboard_extension import OmnigraphKeyboardExtension
| 627 | Python | 51.333329 | 106 | 0.835726 |
Ngochuy2137/omni_isaac_examples/surface_gripper/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.surface_gripper.surface_gripper import *
| 498 | Python | 44.363632 | 76 | 0.813253 |
Ngochuy2137/omni_isaac_examples/surface_gripper/surface_gripper.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import weakref
import numpy as np
import omni
import omni.ext
import omni.kit.commands
import omni.kit.usd
import omni.physx as _physx
import omni.ui as ui
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.dynamic_control import _dynamic_control as dc
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.surface_gripper._surface_gripper import Surface_Gripper, Surface_Gripper_Properties
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import (
add_separator,
btn_builder,
combo_floatfield_slider_builder,
get_style,
setup_ui_headers,
state_btn_builder,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdPhysics
EXTENSION_NAME = "Surface Gripper"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
"""Initialize extension and UI elements"""
self._ext_id = ext_id
# Loads interfaces
self._timeline = omni.timeline.get_timeline_interface()
self._dc = dc.acquire_dynamic_control_interface()
self._usd_context = omni.usd.get_context()
self._window = None
self._models = {}
# Creates UI window with default size of 600x300
# self._window = omni.ui.Window(
# title=EXTENSION_NAME, width=300, height=200, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
# )
menu_items = [
make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback())
]
self._menu_items = [MenuItemDescription(name="Manipulation", sub_menu=menu_items)]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
self.surface_gripper = None
self.cone = None
self.box = None
self._stage_id = -1
def _build_ui(self):
if not self._window:
self._window = ui.Window(
title=EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Surface Gripper Example"
doc_link = "https://docs.omniverse.nvidia.com/isaacsim/latest/features/robots_simulation/ext_omni_isaac_surface_gripper.html"
overview = "This Example shows how to simulate a suction-cup gripper in Isaac Sim. "
overview += "It simulates suction by creating a Joint between two bodies when the parent and child bodies are close at the gripper's point of contact."
overview += "\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
args = {
"label": "Load Scene",
"type": "button",
"text": "Load",
"tooltip": "Load a gripper into the Scene",
"on_clicked_fn": self._on_create_scenario_button_clicked,
}
self._models["create_button"] = btn_builder(**args)
args = {
"label": "Gripper State",
"type": "button",
"a_text": "Close",
"b_text": "Open",
"tooltip": "Open and Close the Gripper",
"on_clicked_fn": self._on_toggle_gripper_button_clicked,
}
self._models["toggle_button"] = state_btn_builder(**args)
add_separator()
args = {
"label": "Gripper Force (UP)",
"default_val": 0,
"min": 0,
"max": 1.0e2,
"step": 1,
"tooltip": ["Force in ()", "Force in ()"],
}
self._models["force_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Force",
"type": "button",
"text": "APPLY",
"tooltip": "Apply the Gripper Force to the Z-Axis of the Cone",
"on_clicked_fn": self._on_force_button_clicked,
}
self._models["force_button"] = btn_builder(**args)
args = {
"label": "Gripper Speed (UP)",
"default_val": 0,
"min": 0,
"max": 5.0e1,
"step": 1,
"tooltip": ["Speed in ()", "Speed in ()"],
}
add_separator()
self._models["speed_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Speed",
"type": "button",
"text": "APPLY",
"tooltip": "Apply Cone Velocity in the Z-Axis",
"on_clicked_fn": self._on_speed_button_clicked,
}
self._models["speed_button"] = btn_builder(**args)
ui.Spacer()
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._physx_subs = None
self._window = None
def _on_window(self, status):
if status:
self._usd_context = omni.usd.get_context()
if self._usd_context is not None:
self._stage_event_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update_ui)
)
else:
self._stage_event_sub = None
self._physx_subs = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_update_ui(self, widget):
self._models["create_button"].enabled = self._timeline.is_playing()
self._models["toggle_button"].enabled = self._timeline.is_playing()
self._models["force_button"].enabled = self._timeline.is_playing()
self._models["speed_button"].enabled = self._timeline.is_playing()
# If the scene has been reloaded, reset UI to create Scenario
if self._usd_context.get_stage_id() != self._stage_id:
self._models["create_button"].enabled = True
# self._models["create_button"].text = "Create Scenario"
self._models["create_button"].set_tooltip("Creates a new scenario with the cone on top of the Cube")
self._models["create_button"].set_clicked_fn(self._on_create_scenario_button_clicked)
self.cone = None
self.box = None
self._stage_id = -1
def _toggle_gripper_button_ui(self):
# Checks if the surface gripper has been created
if self.surface_gripper is not None:
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
pass
def _on_simulation_step(self, step):
# Checks if the simulation is playing, and if the stage has been loaded
if self._timeline.is_playing() and self._stage_id != -1:
# Check if the handles for cone and box have been loaded
if self.cone is None:
self.cone = self._dc.get_rigid_body("/GripperCone")
self.box = self._dc.get_rigid_body("/Box")
# If the surface Gripper has been created, update wheter it has been broken or not
if self.surface_gripper is not None:
self.surface_gripper.update()
if self.surface_gripper.is_closed():
self.coneGeom.GetDisplayColorAttr().Set([self.color_closed])
else:
self.coneGeom.GetDisplayColorAttr().Set([self.color_open])
self._toggle_gripper_button_ui()
def _on_reset_scenario_button_clicked(self):
if self._timeline.is_playing() and self._stage_id != -1:
if self.surface_gripper is not None:
self.surface_gripper.open()
self._dc.set_rigid_body_linear_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_linear_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_pose(self.cone, self.gripper_start_pose)
self._dc.set_rigid_body_pose(self.box, self.box_start_pose)
async def _create_scenario(self, task):
done, pending = await asyncio.wait({task})
if task in done:
# Repurpose button to reset Scene
# self._models["create_button"].text = "Reset Scene"
self._models["create_button"].set_tooltip("Resets scenario with the cone on top of the Cube")
# Get Handle for stage and stage ID to check if stage was reloaded
self._stage = self._usd_context.get_stage()
self._stage_id = self._usd_context.get_stage_id()
self._timeline.stop()
self._models["create_button"].set_clicked_fn(self._on_reset_scenario_button_clicked)
# Adds a light to the scene
distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
distantLight.AddOrientOp().Set(Gf.Quatf(-0.3748, -0.42060, -0.0716, 0.823))
# Set up stage with Z up, treat units as cm, set up gravity and ground plane
UsdGeom.SetStageUpAxis(self._stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(self._stage, 1.0)
self.scene = UsdPhysics.Scene.Define(self._stage, Sdf.Path("/physicsScene"))
self.scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
self.scene.CreateGravityMagnitudeAttr().Set(9.81)
omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=self._stage,
planePath="/groundPlane",
axis="Z",
size=10.000,
position=Gf.Vec3f(0),
color=Gf.Vec3f(0.5),
)
# Colors to represent when gripper is open or closed
self.color_closed = Gf.Vec3f(1.0, 0.2, 0.2)
self.color_open = Gf.Vec3f(0.2, 1.0, 0.2)
# Cone that will represent the gripper
self.gripper_start_pose = dc.Transform([0, 0, 0.301], [1, 0, 0, 0])
self.coneGeom = self.createRigidBody(
UsdGeom.Cone,
"/GripperCone",
0.100,
[0.10, 0.10, 0.10],
self.gripper_start_pose.p,
self.gripper_start_pose.r,
self.color_open,
)
# Box to be picked
self.box_start_pose = dc.Transform([0, 0, 0.10], [1, 0, 0, 0])
self.boxGeom = self.createRigidBody(
UsdGeom.Cube, "/Box", 0.10, [0.1, 0.1, 0.1], self.box_start_pose.p, self.box_start_pose.r, [0.2, 0.2, 1]
)
# Reordering the quaternion to follow DC convention for later use.
self.gripper_start_pose = dc.Transform([0, 0, 0.301], [0, 0, 0, 1])
self.box_start_pose = dc.Transform([0, 0, 0.10], [0, 0, 0, 1])
# Gripper properties
self.sgp = Surface_Gripper_Properties()
self.sgp.d6JointPath = "/GripperCone/SurfaceGripper"
self.sgp.parentPath = "/GripperCone"
self.sgp.offset = dc.Transform()
self.sgp.offset.p.x = 0
self.sgp.offset.p.z = -0.1001
self.sgp.offset.r = [0.7071, 0, 0.7071, 0] # Rotate to point gripper in Z direction
self.sgp.gripThreshold = 0.02
self.sgp.forceLimit = 1.0e2
self.sgp.torqueLimit = 1.0e3
self.sgp.bendAngle = np.pi / 4
self.sgp.stiffness = 1.0e4
self.sgp.damping = 1.0e3
self.surface_gripper = Surface_Gripper(self._dc)
self.surface_gripper.initialize(self.sgp)
# Set camera to a nearby pose and looking directly at the Gripper cone
set_camera_view(
eye=[4.00, 4.00, 4.00], target=self.gripper_start_pose.p, camera_prim_path="/OmniverseKit_Persp"
)
self._physx_subs = _physx.get_physx_interface().subscribe_physics_step_events(self._on_simulation_step)
self._timeline.play()
def _on_create_scenario_button_clicked(self):
# wait for new stage before creating scenario
task = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._create_scenario(task))
def _on_toggle_gripper_button_clicked(self, val=False):
if self._timeline.is_playing():
if self.surface_gripper.is_closed():
self.surface_gripper.open()
else:
self.surface_gripper.close()
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
def _on_speed_button_clicked(self):
if self._timeline.is_playing():
self._dc.set_rigid_body_linear_velocity(
self.cone, [0, 0, self._models["speed_slider"].get_value_as_float()]
)
def _on_force_button_clicked(self):
if self._timeline.is_playing():
self._dc.apply_body_force(
self.cone, [0, 0, self._models["force_slider"].get_value_as_float()], [0, 0, 0], True
)
def createRigidBody(self, bodyType, boxActorPath, mass, scale, position, rotation, color):
p = Gf.Vec3f(position[0], position[1], position[2])
orientation = Gf.Quatf(rotation[0], rotation[1], rotation[2], rotation[3])
scale = Gf.Vec3f(scale[0], scale[1], scale[2])
bodyGeom = bodyType.Define(self._stage, boxActorPath)
bodyPrim = self._stage.GetPrimAtPath(boxActorPath)
bodyGeom.AddTranslateOp().Set(p)
bodyGeom.AddOrientOp().Set(orientation)
bodyGeom.AddScaleOp().Set(scale)
bodyGeom.CreateDisplayColorAttr().Set([color])
UsdPhysics.CollisionAPI.Apply(bodyPrim)
if mass > 0:
massAPI = UsdPhysics.MassAPI.Apply(bodyPrim)
massAPI.CreateMassAttr(mass)
UsdPhysics.RigidBodyAPI.Apply(bodyPrim)
UsdPhysics.CollisionAPI(bodyPrim)
print(bodyPrim.GetPath().pathString)
return bodyGeom
| 16,637 | Python | 44.583562 | 171 | 0.542586 |
Ngochuy2137/omni_isaac_examples/bin_filling/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.bin_filling.bin_filling import BinFilling
from omni.isaac.examples.bin_filling.bin_filling_extension import BinFillingExtension
| 585 | Python | 47.833329 | 85 | 0.823932 |
Ngochuy2137/omni_isaac_examples/bin_filling/bin_filling_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.ui as ui
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.bin_filling import BinFilling
from omni.isaac.ui.ui_utils import btn_builder
class BinFillingExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Manipulation",
submenu_name="",
name="Bin Filling",
title="Bin Filling",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_adding_manipulator.html",
overview="This Example shows how to do bin filling using UR10 robot in Isaac Sim.\n It showcases a realistic surface gripper that breaks with heavy bin load.\nPress the 'Open in IDE' button to view the source code.",
sample=BinFilling(),
file_path=os.path.abspath(__file__),
number_of_extra_frames=1,
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
return
def _on_fill_bin_button_event(self):
asyncio.ensure_future(self.sample.on_fill_bin_event_async())
self.task_ui_elements["Start Bin Filling"].enabled = False
return
def post_reset_button_event(self):
self.task_ui_elements["Start Bin Filling"].enabled = True
return
def post_load_button_event(self):
self.task_ui_elements["Start Bin Filling"].enabled = True
return
def post_clear_button_event(self):
self.task_ui_elements["Start Bin Filling"].enabled = False
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Start Bin Filling",
"type": "button",
"text": "Start Bin Filling",
"tooltip": "Start Bin Filling",
"on_clicked_fn": self._on_fill_bin_button_event,
}
self.task_ui_elements["Start Bin Filling"] = btn_builder(**dict)
self.task_ui_elements["Start Bin Filling"].enabled = False
| 2,800 | Python | 38.450704 | 228 | 0.632857 |
Ngochuy2137/omni_isaac_examples/bin_filling/bin_filling.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController
from omni.isaac.universal_robots.tasks import BinFilling as BinFillingTask
class BinFilling(BaseSample):
def __init__(self) -> None:
super().__init__()
self._controller = None
self._articulation_controller = None
self._added_screws = False
def setup_scene(self):
world = self.get_world()
world.add_task(BinFillingTask(name="bin_filling"))
return
async def setup_post_load(self):
self._ur10_task = self._world.get_task(name="bin_filling")
self._task_params = self._ur10_task.get_params()
my_ur10 = self._world.scene.get_object(self._task_params["robot_name"]["value"])
self._controller = PickPlaceController(
name="pick_place_controller", gripper=my_ur10.gripper, robot_articulation=my_ur10
)
self._articulation_controller = my_ur10.get_articulation_controller()
return
def _on_fill_bin_physics_step(self, step_size):
observations = self._world.get_observations()
actions = self._controller.forward(
picking_position=observations[self._task_params["bin_name"]["value"]]["position"],
placing_position=observations[self._task_params["bin_name"]["value"]]["target_position"],
current_joint_positions=observations[self._task_params["robot_name"]["value"]]["joint_positions"],
end_effector_offset=np.array([0, -0.098, 0.03]),
end_effector_orientation=euler_angles_to_quat(np.array([np.pi, 0, np.pi / 2.0])),
)
if not self._added_screws and self._controller.get_current_event() == 6 and not self._controller.is_paused():
self._controller.pause()
self._ur10_task.add_screws(screws_number=20)
self._added_screws = True
if self._controller.is_done():
self._world.pause()
self._articulation_controller.apply_action(actions)
return
async def on_fill_bin_event_async(self):
world = self.get_world()
world.add_physics_callback("sim_step", self._on_fill_bin_physics_step)
await world.play_async()
return
async def setup_pre_reset(self):
world = self.get_world()
if world.physics_callback_exists("sim_step"):
world.remove_physics_callback("sim_step")
self._controller.reset()
self._added_screws = False
return
def world_cleanup(self):
self._controller = None
self._added_screws = False
return
| 3,174 | Python | 41.333333 | 117 | 0.664146 |
Ngochuy2137/omni_isaac_examples/user_examples/__init__.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# NOTE: Import here your extension examples to be propagated to ISAAC SIM Extensions startup
from omni.isaac.examples.user_examples.hello_world import HelloWorld
from omni.isaac.examples.user_examples.hello_world_extension import HelloWorldExtension
| 684 | Python | 44.666664 | 92 | 0.821637 |
Ngochuy2137/omni_isaac_examples/user_examples/hello_world.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
import numpy as np
# Can be used to create a new cube or to point to an already existing cube in stage.
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.dynamic_control import _dynamic_control
from pxr import UsdLux, Gf
from omni.usd import get_context
# Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html
class HelloWorld(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
fancy_cube = world.scene.add(
DynamicCuboid(
prim_path="/World/my_fancy_cube", # The prim path of the cube in the USD stage
name="fancy_cube", # The unique name used to retrieve the object from the scene later on
position=np.array([0, 0, 1.0]), # Using the current stage units which is in meters by default.
scale=np.array([0.5015, 0.5015, 0.5015]), # most arguments accept mainly numpy arrays.
color=np.array([0, 0, 1.0]), # RGB channels, going from 0-1
))
# Create a dome light
stage = get_context().get_stage()
light_path = "/World/fancy_dome_light"
light_prim = UsdLux.DomeLight.Define(stage, light_path)
light_prim.CreateIntensityAttr().Set(1.0)
light_prim.CreateColorAttr().Set(Gf.Vec3f(1.0, 1.0, 1.0))
return
async def setup_post_load(self):
self._world = self.get_world()
self._cube = self._world.scene.get_object("fancy_cube")
# "sim_step" is the name of the event
# "callback_fn" is the callback function
self._world.add_physics_callback("sim_step", callback_fn=self.print_cube_info) #callback names have to be unique
return
# here we define the physics callback to be called before each physics step, all physics callbacks must take
# step_size as an argument
# Tham số này thường là kích thước bước thời gian (time step) của mỗi bước vật lý trong mô phỏng.
# Tuy nhiên, trong ví dụ này, step_size không được sử dụng trực tiếp trong hàm.
def print_cube_info(self, step_size):
position, orientation = self._cube.get_world_pose()
linear_velocity = self._cube.get_linear_velocity()
# will be shown on terminal
print("Cube position is : " + str(position))
print("Cube's orientation is : " + str(orientation))
print("Cube's linear velocity is : " + str(linear_velocity))
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
return
def world_cleanup(self):
return
| 3,231 | Python | 41.526315 | 120 | 0.665429 |
Ngochuy2137/omni_isaac_examples/user_examples/my_application.py | #launch Isaac Sim before any other imports
#default first two lines in any standalone application
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False}) # we can also run as headless.
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicCuboid
import numpy as np
world = World()
world.scene.add_default_ground_plane()
fancy_cube = world.scene.add(
DynamicCuboid(
prim_path="/World/random_cube",
name="fancy_cube",
position=np.array([0, 0, 1.0]),
scale=np.array([0.5015, 0.5015, 0.5015]),
color=np.array([0, 0, 1.0]),
))
# Resetting the world needs to be called before querying anything related to an articulation specifically.
# Its recommended to always do a reset after adding your assets, for physics handles to be propagated properly
world.reset()
for i in range(500):
position, orientation = fancy_cube.get_world_pose()
linear_velocity = fancy_cube.get_linear_velocity()
# will be shown on terminal
print("Cube position is : " + str(position))
print("Cube's orientation is : " + str(orientation))
print("Cube's linear velocity is : " + str(linear_velocity))
# we have control over stepping physics and rendering in this workflow
# things run in sync
world.step(render=True) # execute one physics step and one rendering step
simulation_app.close() # close Isaac Sim | 1,419 | Python | 40.764705 | 110 | 0.714588 |
Ngochuy2137/omni_isaac_examples/user_examples/hello_world_extension.py | import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.user_examples import HelloWorld
class HelloWorldExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="",
submenu_name="",
name="My Awesome Example",
title="My Awesome Example",
doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=HelloWorld(),
)
return | 779 | Python | 40.052629 | 135 | 0.650834 |
Ngochuy2137/omni_isaac_examples/replay_follow_target/replay_follow_target_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.ui as ui
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.replay_follow_target import ReplayFollowTarget
from omni.isaac.ui.ui_utils import btn_builder, str_builder
class ReplayFollowTargetExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Manipulation",
submenu_name="",
name="Replay Follow Target",
title="Replay Follow Target Task",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_advanced_data_logging.html",
overview="This Example shows how to use data logging to replay data collected\n\n from the follow target extension example.\n\n Press the 'Open in IDE' button to view the source code.",
sample=ReplayFollowTarget(),
file_path=os.path.abspath(__file__),
number_of_extra_frames=2,
window_width=700,
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_data_logging_ui(frame)
return
def _on_replay_trajectory_button_event(self):
asyncio.ensure_future(
self.sample._on_replay_trajectory_event_async(self.task_ui_elements["Data File"].get_value_as_string())
)
self.task_ui_elements["Replay Trajectory"].enabled = False
self.task_ui_elements["Replay Scene"].enabled = False
return
def _on_replay_scene_button_event(self):
asyncio.ensure_future(
self.sample._on_replay_scene_event_async(self.task_ui_elements["Data File"].get_value_as_string())
)
self.task_ui_elements["Replay Trajectory"].enabled = False
self.task_ui_elements["Replay Scene"].enabled = False
return
def post_reset_button_event(self):
self.task_ui_elements["Replay Trajectory"].enabled = True
self.task_ui_elements["Replay Scene"].enabled = True
return
def post_load_button_event(self):
self.task_ui_elements["Replay Trajectory"].enabled = True
self.task_ui_elements["Replay Scene"].enabled = True
return
def post_clear_button_event(self):
self.task_ui_elements["Replay Trajectory"].enabled = False
self.task_ui_elements["Replay Scene"].enabled = False
return
def build_data_logging_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
frame.title = "Data Replay"
frame.visible = True
example_data_file = os.path.abspath(
os.path.join(os.path.abspath(__file__), "../../../../../data/example_data_file.json")
)
dict = {
"label": "Data File",
"type": "stringfield",
"default_val": example_data_file,
"tooltip": "Data File",
"on_clicked_fn": None,
"use_folder_picker": False,
"read_only": False,
}
self.task_ui_elements["Data File"] = str_builder(**dict)
dict = {
"label": "Replay Trajectory",
"type": "button",
"text": "Replay Trajectory",
"tooltip": "Replay Trajectory",
"on_clicked_fn": self._on_replay_trajectory_button_event,
}
self.task_ui_elements["Replay Trajectory"] = btn_builder(**dict)
self.task_ui_elements["Replay Trajectory"].enabled = False
dict = {
"label": "Replay Scene",
"type": "button",
"text": "Replay Scene",
"tooltip": "Replay Scene",
"on_clicked_fn": self._on_replay_scene_button_event,
}
self.task_ui_elements["Replay Scene"] = btn_builder(**dict)
self.task_ui_elements["Replay Scene"].enabled = False
return
| 4,574 | Python | 40.972477 | 197 | 0.587232 |
Ngochuy2137/omni_isaac_examples/replay_follow_target/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.replay_follow_target.replay_follow_target import ReplayFollowTarget
from omni.isaac.examples.replay_follow_target.replay_follow_target_extension import ReplayFollowTargetExtension
| 637 | Python | 52.166662 | 111 | 0.832025 |
Ngochuy2137/omni_isaac_examples/replay_follow_target/replay_follow_target.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.franka.tasks import FollowTarget as FollowTargetTask
class ReplayFollowTarget(BaseSample):
def __init__(self) -> None:
super().__init__()
self._articulation_controller = None
def setup_scene(self):
world = self.get_world()
world.add_task(FollowTargetTask())
return
async def setup_pre_reset(self):
world = self.get_world()
if world.physics_callback_exists("replay_trajectory"):
world.remove_physics_callback("replay_trajectory")
if world.physics_callback_exists("replay_scene"):
world.remove_physics_callback("replay_scene")
return
async def setup_post_load(self):
self._franka_task = list(self._world.get_current_tasks().values())[0]
self._task_params = self._franka_task.get_params()
my_franka = self._world.scene.get_object(self._task_params["robot_name"]["value"])
self._articulation_controller = my_franka.get_articulation_controller()
self._data_logger = self._world.get_data_logger()
return
async def _on_replay_trajectory_event_async(self, data_file):
self._data_logger.load(log_path=data_file)
world = self.get_world()
await world.play_async()
world.add_physics_callback("replay_trajectory", self._on_replay_trajectory_step)
return
async def _on_replay_scene_event_async(self, data_file):
self._data_logger.load(log_path=data_file)
world = self.get_world()
await world.play_async()
world.add_physics_callback("replay_scene", self._on_replay_scene_step)
return
def _on_replay_trajectory_step(self, step_size):
if self._world.current_time_step_index < self._data_logger.get_num_of_data_frames():
data_frame = self._data_logger.get_data_frame(data_frame_index=self._world.current_time_step_index)
self._articulation_controller.apply_action(
ArticulationAction(joint_positions=data_frame.data["applied_joint_positions"])
)
return
def _on_replay_scene_step(self, step_size):
if self._world.current_time_step_index < self._data_logger.get_num_of_data_frames():
target_name = self._task_params["target_name"]["value"]
data_frame = self._data_logger.get_data_frame(data_frame_index=self._world.current_time_step_index)
self._articulation_controller.apply_action(
ArticulationAction(joint_positions=data_frame.data["applied_joint_positions"])
)
self._world.scene.get_object(target_name).set_world_pose(
position=np.array(data_frame.data["target_position"])
)
return
| 3,300 | Python | 43.013333 | 111 | 0.671212 |
Ngochuy2137/omni_isaac_examples/robo_factory/robo_factory.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.franka.controllers.stacking_controller import StackingController
from omni.isaac.franka.tasks import Stacking
class RoboFactory(BaseSample):
def __init__(self) -> None:
super().__init__()
self._tasks = []
self._controllers = []
self._articulation_controllers = []
self._robots = []
self._num_of_tasks = 4
return
def setup_scene(self):
world = self.get_world()
for i in range(self._num_of_tasks):
task = Stacking(name="task" + str(i), offset=np.array([0, (i * 2) - 3, 0]))
world.add_task(task)
return
async def setup_post_load(self):
for i in range(self._num_of_tasks):
self._tasks.append(self._world.get_task(name="task" + str(i)))
for i in range(self._num_of_tasks):
self._robots.append(self._world.scene.get_object(self._tasks[i].get_params()["robot_name"]["value"]))
self._controllers.append(
StackingController(
name="stacking_controller",
gripper=self._robots[i].gripper,
robot_articulation=self._robots[i],
picking_order_cube_names=self._tasks[i].get_cube_names(),
robot_observation_name=self._robots[i].name,
)
)
for i in range(self._num_of_tasks):
self._articulation_controllers.append(self._robots[i].get_articulation_controller())
return
def _on_start_factory_physics_step(self, step_size):
observations = self._world.get_observations()
for i in range(self._num_of_tasks):
actions = self._controllers[i].forward(observations=observations, end_effector_offset=np.array([0, 0, 0]))
self._articulation_controllers[i].apply_action(actions)
return
async def _on_start_stacking_event_async(self):
world = self.get_world()
world.add_physics_callback("sim_step", self._on_start_factory_physics_step)
await world.play_async()
return
async def setup_pre_reset(self):
world = self.get_world()
if world.physics_callback_exists("sim_step"):
world.remove_physics_callback("sim_step")
for i in range(len(self._controllers)):
self._controllers[i].reset()
return
def world_cleanup(self):
self._tasks = []
self._controllers = []
self._articulation_controllers = []
self._robots = []
return
| 3,052 | Python | 38.141025 | 118 | 0.616972 |
Ngochuy2137/omni_isaac_examples/robo_factory/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.robo_factory.robo_factory import RoboFactory
from omni.isaac.examples.robo_factory.robo_factory_extension import RoboFactoryExtension
| 591 | Python | 48.333329 | 88 | 0.825719 |
Ngochuy2137/omni_isaac_examples/robo_factory/robo_factory_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.ui as ui
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.robo_factory import RoboFactory
from omni.isaac.ui.ui_utils import btn_builder
class RoboFactoryExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Multi-Robot",
submenu_name="",
name="RoboFactory",
title="RoboFactory",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_adding_multiple_robots.html",
overview="This Example shows how to run multiple tasks in the same scene.\n\nPress the 'Open in IDE' button to view the source code.",
sample=RoboFactory(),
file_path=os.path.abspath(__file__),
number_of_extra_frames=1,
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
return
def _on_start_stacking_button_event(self):
asyncio.ensure_future(self.sample._on_start_stacking_event_async())
self.task_ui_elements["Start Stacking"].enabled = False
return
def post_reset_button_event(self):
self.task_ui_elements["Start Stacking"].enabled = True
return
def post_load_button_event(self):
self.task_ui_elements["Start Stacking"].enabled = True
return
def post_clear_button_event(self):
self.task_ui_elements["Start Stacking"].enabled = False
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Start Stacking",
"type": "button",
"text": "Start Stacking",
"tooltip": "Start Stacking",
"on_clicked_fn": self._on_start_stacking_button_event,
}
self.task_ui_elements["Start Stacking"] = btn_builder(**dict)
self.task_ui_elements["Start Stacking"].enabled = False
| 2,717 | Python | 37.28169 | 146 | 0.630107 |
Ngochuy2137/omni_isaac_examples/robo_party/robo_party_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.ui as ui
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.robo_party import RoboParty
from omni.isaac.ui.ui_utils import btn_builder
class RoboPartyExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Multi-Robot",
submenu_name="",
name="RoboParty",
title="RoboParty",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_adding_multiple_robots.html",
overview="This Example shows how to run multiple tasks in the same scene.\n\nPress the 'Open in IDE' button to view the source code.",
sample=RoboParty(),
file_path=os.path.abspath(__file__),
number_of_extra_frames=1,
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
return
def _on_start_party_button_event(self):
asyncio.ensure_future(self.sample._on_start_party_event_async())
self.task_ui_elements["Start Party"].enabled = False
return
def post_reset_button_event(self):
self.task_ui_elements["Start Party"].enabled = True
return
def post_load_button_event(self):
self.task_ui_elements["Start Party"].enabled = True
return
def post_clear_button_event(self):
self.task_ui_elements["Start Party"].enabled = False
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Start Party",
"type": "button",
"text": "Start Party",
"tooltip": "Start Party",
"on_clicked_fn": self._on_start_party_button_event,
}
self.task_ui_elements["Start Party"] = btn_builder(**dict)
self.task_ui_elements["Start Party"].enabled = False
| 2,669 | Python | 36.605633 | 146 | 0.623454 |
Ngochuy2137/omni_isaac_examples/robo_party/robo_party.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import numpy as np
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.dofbot.controllers import PickPlaceController
from omni.isaac.dofbot.tasks import PickPlace
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.franka.controllers.stacking_controller import StackingController as FrankaStackingController
from omni.isaac.franka.tasks import Stacking as FrankaStacking
from omni.isaac.universal_robots.controllers import StackingController as UR10StackingController
from omni.isaac.universal_robots.tasks import Stacking as UR10Stacking
from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.wheeled_robots.robots.holonomic_robot_usd_setup import HolonomicRobotUsdSetup
class RoboParty(BaseSample):
def __init__(self) -> None:
super().__init__()
self._tasks = []
self._controllers = []
self._articulation_controllers = []
self._pick_place_task_params = None
self._robots = []
return
def setup_scene(self):
world = self.get_world()
self._tasks.append(FrankaStacking(name="task_0", offset=np.array([0, -2, 0])))
world.add_task(self._tasks[-1])
self._tasks.append(UR10Stacking(name="task_1", offset=np.array([0.5, 0.5, 0])))
world.add_task(self._tasks[-1])
self._tasks.append(PickPlace(name="task_2", offset=np.array([0, -1, 0])))
world.add_task(self._tasks[-1])
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
return
kaya_asset_path = assets_root_path + "/Isaac/Robots/Kaya/kaya.usd"
world.scene.add(
WheeledRobot(
prim_path="/World/Kaya",
name="my_kaya",
wheel_dof_names=["axle_0_joint", "axle_1_joint", "axle_2_joint"],
create_robot=True,
usd_path=kaya_asset_path,
position=np.array([-1, 0, 0]),
)
)
jetbot_asset_path = assets_root_path + "/Isaac/Robots/Jetbot/jetbot.usd"
world.scene.add(
WheeledRobot(
prim_path="/World/Jetbot",
name="my_jetbot",
wheel_dof_names=["left_wheel_joint", "right_wheel_joint"],
create_robot=True,
usd_path=jetbot_asset_path,
position=np.array([-1.5, -1.5, 0]),
)
)
return
async def setup_post_load(self):
self._tasks = [
self._world.get_task(name="task_0"),
self._world.get_task(name="task_1"),
self._world.get_task(name="task_2"),
]
for i in range(3):
self._robots.append(self._world.scene.get_object(self._tasks[i].get_params()["robot_name"]["value"]))
self._robots.append(self._world.scene.get_object("my_kaya"))
self._robots.append(self._world.scene.get_object("my_jetbot"))
self._pick_place_task_params = self._tasks[2].get_params()
self._controllers.append(
FrankaStackingController(
name="stacking_controller",
gripper=self._robots[0].gripper,
robot_articulation=self._robots[0],
picking_order_cube_names=self._tasks[0].get_cube_names(),
robot_observation_name=self._robots[0].name,
)
)
self._controllers.append(
UR10StackingController(
name="pick_place_controller",
gripper=self._robots[1].gripper,
robot_articulation=self._robots[1],
picking_order_cube_names=self._tasks[1].get_cube_names(),
robot_observation_name=self._robots[1].name,
)
)
self._controllers.append(
PickPlaceController(
name="pick_place_controller", gripper=self._robots[2].gripper, robot_articulation=self._robots[2]
)
)
kaya_setup = HolonomicRobotUsdSetup(
robot_prim_path="/World/Kaya", com_prim_path="/World/Kaya/base_link/control_offset"
)
(
wheel_radius,
wheel_positions,
wheel_orientations,
mecanum_angles,
wheel_axis,
up_axis,
) = kaya_setup.get_holonomic_controller_params()
self._controllers.append(
HolonomicController(
name="holonomic_controller",
wheel_radius=wheel_radius,
wheel_positions=wheel_positions,
wheel_orientations=wheel_orientations,
mecanum_angles=mecanum_angles,
wheel_axis=wheel_axis,
up_axis=up_axis,
)
)
self._controllers.append(DifferentialController(name="simple_control", wheel_radius=0.03, wheel_base=0.1125))
for i in range(5):
self._articulation_controllers.append(self._robots[i].get_articulation_controller())
return
def _on_start_party_physics_step(self, step_size):
observations = self._world.get_observations()
actions = self._controllers[0].forward(observations=observations, end_effector_offset=np.array([0, 0, 0]))
self._articulation_controllers[0].apply_action(actions)
actions = self._controllers[1].forward(observations=observations, end_effector_offset=np.array([0, 0, 0.02]))
self._articulation_controllers[1].apply_action(actions)
actions = self._controllers[2].forward(
picking_position=observations[self._pick_place_task_params["cube_name"]["value"]]["position"],
placing_position=observations[self._pick_place_task_params["cube_name"]["value"]]["target_position"],
current_joint_positions=observations[self._pick_place_task_params["robot_name"]["value"]][
"joint_positions"
],
end_effector_offset=np.array([0, -0.06, 0]),
)
self._articulation_controllers[2].apply_action(actions)
if self._world.current_time_step_index >= 0 and self._world.current_time_step_index < 500:
self._robots[3].apply_wheel_actions(self._controllers[3].forward(command=[0.2, 0.0, 0.0]))
self._robots[4].apply_wheel_actions(self._controllers[4].forward(command=[0.1, 0]))
elif self._world.current_time_step_index >= 500 and self._world.current_time_step_index < 1000:
self._robots[3].apply_wheel_actions(self._controllers[3].forward(command=[0, 0.2, 0.0]))
self._robots[4].apply_wheel_actions(self._controllers[4].forward(command=[0.0, np.pi / 10]))
elif self._world.current_time_step_index >= 1000 and self._world.current_time_step_index < 1500:
self._robots[3].apply_wheel_actions(self._controllers[3].forward(command=[0, 0.0, 0.06]))
self._robots[4].apply_wheel_actions(self._controllers[4].forward(command=[0.1, 0]))
return
async def _on_start_party_event_async(self):
world = self.get_world()
world.add_physics_callback("sim_step", self._on_start_party_physics_step)
await world.play_async()
return
async def setup_pre_reset(self):
world = self.get_world()
if world.physics_callback_exists("sim_step"):
world.remove_physics_callback("sim_step")
for i in range(len(self._controllers)):
self._controllers[i].reset()
return
def world_cleanup(self):
self._tasks = []
self._controllers = []
self._articulation_controllers = []
self._pick_place_task_params = None
self._robots = []
return
| 8,421 | Python | 44.27957 | 117 | 0.620116 |
Ngochuy2137/omni_isaac_examples/robo_party/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.robo_party.robo_party import RoboParty
from omni.isaac.examples.robo_party.robo_party_extension import RoboPartyExtension
| 579 | Python | 47.333329 | 82 | 0.822107 |
Ngochuy2137/omni_isaac_examples/ur10_palletizing/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.ur10_palletizing.ur10_palletizing_extension import BinStackingExtension
| 529 | Python | 47.181814 | 96 | 0.824197 |
Ngochuy2137/omni_isaac_examples/ur10_palletizing/ur10_palletizing.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import random
import numpy as np
import omni
import omni.isaac.cortex.math_util as math_util
from omni.isaac.core.objects.capsule import VisualCapsule
from omni.isaac.core.objects.sphere import VisualSphere
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.tasks.base_task import BaseTask
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.cortex.cortex_rigid_prim import CortexRigidPrim
from omni.isaac.cortex.cortex_utils import get_assets_root_path
from omni.isaac.cortex.robot import CortexUr10
from omni.isaac.cortex.sample_behaviors.ur10 import bin_stacking_behavior as behavior
from omni.isaac.examples.cortex.cortex_base import CortexBase
class Ur10Assets:
def __init__(self):
self.assets_root_path = get_assets_root_path()
self.ur10_table_usd = (
self.assets_root_path + "/Isaac/Samples/Leonardo/Stage/ur10_bin_stacking_short_suction.usd"
)
self.small_klt_usd = self.assets_root_path + "/Isaac/Props/KLT_Bin/small_KLT.usd"
self.background_usd = self.assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse.usd"
self.rubiks_cube_usd = self.assets_root_path + "/Isaac/Props/Rubiks_Cube/rubiks_cube.usd"
def random_bin_spawn_transform():
x = random.uniform(-0.15, 0.15)
y = 1.5
z = -0.15
position = np.array([x, y, z])
z = random.random() * 0.02 - 0.01
w = random.random() * 0.02 - 0.01
norm = np.sqrt(z**2 + w**2)
quat = math_util.Quaternion([w / norm, 0, 0, z / norm])
if random.random() > 0.5:
print("<flip>")
# flip the bin so it's upside down
quat = quat * math_util.Quaternion([0, 0, 1, 0])
else:
print("<no flip>")
return position, quat.vals
class BinStackingTask(BaseTask):
def __init__(self, env_path, assets) -> None:
super().__init__("bin_stacking")
self.assets = assets
self.env_path = env_path
self.bins = []
self.stashed_bins = []
self.on_conveyor = None
def _spawn_bin(self, rigid_bin):
x, q = random_bin_spawn_transform()
rigid_bin.set_world_pose(position=x, orientation=q)
rigid_bin.set_linear_velocity(np.array([0, -0.30, 0]))
rigid_bin.set_visibility(True)
def post_reset(self) -> None:
if len(self.bins) > 0:
for rigid_bin in self.bins:
self.scene.remove_object(rigid_bin.name)
self.bins.clear()
self.on_conveyor = None
def pre_step(self, time_step_index, simulation_time) -> None:
"""Spawn a new randomly oriented bin if the previous bin has been placed."""
spawn_new = False
if self.on_conveyor is None:
spawn_new = True
else:
(x, y, z), _ = self.on_conveyor.get_world_pose()
is_on_conveyor = y > 0.0 and -0.4 < x and x < 0.4
if not is_on_conveyor:
spawn_new = True
if spawn_new:
name = "bin_{}".format(len(self.bins))
prim_path = self.env_path + "/bins/{}".format(name)
add_reference_to_stage(usd_path=self.assets.small_klt_usd, prim_path=prim_path)
self.on_conveyor = self.scene.add(CortexRigidPrim(name=name, prim_path=prim_path))
self._spawn_bin(self.on_conveyor)
self.bins.append(self.on_conveyor)
def world_cleanup(self):
self.bins = []
self.stashed_bins = []
self.on_conveyor = None
return
class BinStacking(CortexBase):
def __init__(self, monitor_fn=None):
super().__init__()
self._monitor_fn = monitor_fn
self.robot = None
def setup_scene(self):
world = self.get_world()
env_path = "/World/Ur10Table"
ur10_assets = Ur10Assets()
add_reference_to_stage(usd_path=ur10_assets.ur10_table_usd, prim_path=env_path)
add_reference_to_stage(usd_path=ur10_assets.background_usd, prim_path="/World/Background")
background_prim = XFormPrim(
"/World/Background", position=[10.00, 2.00, -1.18180], orientation=[0.7071, 0, 0, 0.7071]
)
self.robot = world.add_robot(CortexUr10(name="robot", prim_path="{}/ur10".format(env_path)))
obs = world.scene.add(
VisualSphere(
"/World/Ur10Table/Obstacles/FlipStationSphere",
name="flip_station_sphere",
position=np.array([0.73, 0.76, -0.13]),
radius=0.2,
visible=False,
)
)
self.robot.register_obstacle(obs)
obs = world.scene.add(
VisualSphere(
"/World/Ur10Table/Obstacles/NavigationDome",
name="navigation_dome_obs",
position=[-0.031, -0.018, -1.086],
radius=1.1,
visible=False,
)
)
self.robot.register_obstacle(obs)
az = np.array([1.0, 0.0, -0.3])
ax = np.array([0.0, 1.0, 0.0])
ay = np.cross(az, ax)
R = math_util.pack_R(ax, ay, az)
quat = math_util.matrix_to_quat(R)
obs = world.scene.add(
VisualCapsule(
"/World/Ur10Table/Obstacles/NavigationBarrier",
name="navigation_barrier_obs",
position=[0.471, 0.276, -0.463 - 0.1],
orientation=quat,
radius=0.5,
height=0.9,
visible=False,
)
)
self.robot.register_obstacle(obs)
obs = world.scene.add(
VisualCapsule(
"/World/Ur10Table/Obstacles/NavigationFlipStation",
name="navigation_flip_station_obs",
position=np.array([0.766, 0.755, -0.5]),
radius=0.5,
height=0.5,
visible=False,
)
)
self.robot.register_obstacle(obs)
async def setup_post_load(self):
world = self.get_world()
env_path = "/World/Ur10Table"
ur10_assets = Ur10Assets()
if not self.robot:
self.robot = world._robots["robot"]
world._current_tasks.clear()
world._behaviors.clear()
world._logical_state_monitors.clear()
self.task = BinStackingTask(env_path, ur10_assets)
print(world.scene)
self.task.set_up_scene(world.scene)
world.add_task(self.task)
self.decider_network = behavior.make_decider_network(self.robot, self._on_monitor_update)
world.add_decider_network(self.decider_network)
return
def _on_monitor_update(self, diagnostics):
decision_stack = ""
if self.decider_network._decider_state.stack:
decision_stack = "\n".join(
[
"{0}{1}".format(" " * i, element)
for i, element in enumerate(str(i) for i in self.decider_network._decider_state.stack)
]
)
if self._monitor_fn:
self._monitor_fn(diagnostics, decision_stack)
def _on_physics_step(self, step_size):
world = self.get_world()
world.step(False, False)
return
async def on_event_async(self):
world = self.get_world()
await omni.kit.app.get_app().next_update_async()
world.reset_cortex()
world.add_physics_callback("sim_step", self._on_physics_step)
await world.play_async()
return
async def setup_pre_reset(self):
world = self.get_world()
if world.physics_callback_exists("sim_step"):
world.remove_physics_callback("sim_step")
return
def world_cleanup(self):
return
| 8,211 | Python | 34.860262 | 106 | 0.590427 |
Ngochuy2137/omni_isaac_examples/ur10_palletizing/ur10_palletizing_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.ui as ui
from omni.isaac.cortex.cortex_world import CortexWorld
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.ur10_palletizing.ur10_palletizing import BinStacking
from omni.isaac.ui.ui_utils import btn_builder, cb_builder, get_style, str_builder
class BinStackingExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Cortex",
submenu_name="",
name="UR10 Palletizing",
title="UR10 Palletizing",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/replicator_tutorials/tutorial_replicator_ur10_palletizing.html#isaac-sim-app-tutorial-replicator-ur10-palletizing",
overview="This Example shows how to do Palletizing using UR10 robot and Cortex behaviors in Isaac Sim.\n\nPress the 'Open in IDE' button to view the source code.",
sample=BinStacking(self.on_diagnostics),
file_path=os.path.abspath(__file__),
number_of_extra_frames=2,
)
self.decision_stack = ""
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
return
def on_diagnostics(self, diagnostic, decision_stack):
if self.decision_stack != decision_stack:
self.decision_stack = decision_stack
if decision_stack:
decision_stack = "\n".join(
[
"{0}{1}".format(" " * (i + 1) if i > 0 else "", element)
for i, element in enumerate(decision_stack.replace("]", "").split("["))
]
)
self.state_model.set_value(decision_stack)
if diagnostic.bin_name:
self.selected_bin.set_value(str(diagnostic.bin_name))
self.bin_base.set_value(str(diagnostic.bin_base.prim_path))
self.grasp_reached.set_value((diagnostic.grasp_reached))
self.is_attached.set_value((diagnostic.attached))
self.needs_flip.set_value((diagnostic.needs_flip))
else:
self.selected_bin.set_value(str("No Bin Selected"))
self.bin_base.set_value("")
self.grasp_reached.set_value(False)
self.is_attached.set_value(False)
self.needs_flip.set_value(False)
def get_world(self):
return CortexWorld.instance()
def _on_start_button_event(self):
asyncio.ensure_future(self.sample.on_event_async())
self.task_ui_elements["Start Palletizing"].enabled = False
return
def post_reset_button_event(self):
self.task_ui_elements["Start Palletizing"].enabled = True
return
def post_load_button_event(self):
self.task_ui_elements["Start Palletizing"].enabled = True
return
def post_clear_button_event(self):
self.task_ui_elements["Start Palletizing"].enabled = False
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Start Palletizing",
"type": "button",
"text": "Start Palletizing",
"tooltip": "Start Palletizing",
"on_clicked_fn": self._on_start_button_event,
}
self.task_ui_elements["Start Palletizing"] = btn_builder(**dict)
self.task_ui_elements["Start Palletizing"].enabled = False
# with self._main_stack:
with self.get_frame(index=1):
self.get_frame(index=1).title = "Diagnostics"
self.get_frame(index=1).visible = True
self._diagnostics = ui.VStack(spacing=5)
# self._diagnostics.enabled = False
with self._diagnostics:
ui.Label("Decision Stack", height=20)
self.state_model = ui.SimpleStringModel()
ui.StringField(self.state_model, multiline=True, height=120)
self.selected_bin = str_builder("Selected Bin", "<No Bin Selected>", read_only=True)
self.bin_base = str_builder("Bin Base", "", read_only=True)
self.grasp_reached = cb_builder("Grasp Reached", False)
self.is_attached = cb_builder("Is Attached", False)
self.needs_flip = cb_builder("Needs Flip", False)
| 5,063 | Python | 43.034782 | 187 | 0.609125 |
Ngochuy2137/omni_isaac_examples/follow_target/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.follow_target.follow_target import FollowTarget
from omni.isaac.examples.follow_target.follow_target_extension import FollowTargetExtension
| 597 | Python | 48.833329 | 91 | 0.827471 |
Ngochuy2137/omni_isaac_examples/follow_target/follow_target.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController
from omni.isaac.franka.tasks import FollowTarget as FollowTargetTask
class FollowTarget(BaseSample):
def __init__(self) -> None:
super().__init__()
self._controller = None
self._articulation_controller = None
def setup_scene(self):
world = self.get_world()
world.add_task(FollowTargetTask())
return
async def setup_pre_reset(self):
world = self.get_world()
if world.physics_callback_exists("sim_step"):
world.remove_physics_callback("sim_step")
self._controller.reset()
return
def world_cleanup(self):
self._controller = None
return
async def setup_post_load(self):
self._franka_task = list(self._world.get_current_tasks().values())[0]
self._task_params = self._franka_task.get_params()
my_franka = self._world.scene.get_object(self._task_params["robot_name"]["value"])
self._controller = RMPFlowController(name="target_follower_controller", robot_articulation=my_franka)
self._articulation_controller = my_franka.get_articulation_controller()
return
async def _on_follow_target_event_async(self, val):
world = self.get_world()
if val:
await world.play_async()
world.add_physics_callback("sim_step", self._on_follow_target_simulation_step)
else:
world.remove_physics_callback("sim_step")
return
def _on_follow_target_simulation_step(self, step_size):
observations = self._world.get_observations()
actions = self._controller.forward(
target_end_effector_position=observations[self._task_params["target_name"]["value"]]["position"],
target_end_effector_orientation=observations[self._task_params["target_name"]["value"]]["orientation"],
)
self._articulation_controller.apply_action(actions)
return
def _on_add_obstacle_event(self):
world = self.get_world()
current_task = list(world.get_current_tasks().values())[0]
cube = current_task.add_obstacle()
self._controller.add_obstacle(cube)
return
def _on_remove_obstacle_event(self):
world = self.get_world()
current_task = list(world.get_current_tasks().values())[0]
obstacle_to_delete = current_task.get_obstacle_to_delete()
self._controller.remove_obstacle(obstacle_to_delete)
current_task.remove_obstacle()
return
def _on_logging_event(self, val):
world = self.get_world()
data_logger = world.get_data_logger()
if not world.get_data_logger().is_started():
robot_name = self._task_params["robot_name"]["value"]
target_name = self._task_params["target_name"]["value"]
def frame_logging_func(tasks, scene):
return {
"joint_positions": scene.get_object(robot_name).get_joint_positions().tolist(),
"applied_joint_positions": scene.get_object(robot_name)
.get_applied_action()
.joint_positions.tolist(),
"target_position": scene.get_object(target_name).get_world_pose()[0].tolist(),
}
data_logger.add_data_frame_logging_func(frame_logging_func)
if val:
data_logger.start()
else:
data_logger.pause()
return
def _on_save_data_event(self, log_path):
world = self.get_world()
data_logger = world.get_data_logger()
data_logger.save(log_path=log_path)
data_logger.reset()
return
| 4,208 | Python | 38.336448 | 115 | 0.633555 |
Ngochuy2137/omni_isaac_examples/follow_target/follow_target_extension.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import carb
import omni.ui as ui
from omni.isaac.examples.base_sample import BaseSampleExtension
from omni.isaac.examples.follow_target import FollowTarget
from omni.isaac.ui.ui_utils import btn_builder, state_btn_builder, str_builder
class FollowTargetExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Manipulation",
submenu_name="",
name="Follow Target",
title="Follow Target Task",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_adding_new_manipulator.html",
overview="This Example shows how to follow a target using Franka robot in Isaac Sim.\n\nPress the 'Open in IDE' button to view the source code.",
sample=FollowTarget(),
file_path=os.path.abspath(__file__),
number_of_extra_frames=2,
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
frame = self.get_frame(index=1)
self.build_data_logging_ui(frame)
return
def _on_follow_target_button_event(self, val):
asyncio.ensure_future(self.sample._on_follow_target_event_async(val))
return
def _on_add_obstacle_button_event(self):
self.sample._on_add_obstacle_event()
self.task_ui_elements["Remove Obstacle"].enabled = True
return
def _on_remove_obstacle_button_event(self):
self.sample._on_remove_obstacle_event()
world = self.sample.get_world()
current_task = list(world.get_current_tasks().values())[0]
if not current_task.obstacles_exist():
self.task_ui_elements["Remove Obstacle"].enabled = False
return
def _on_logging_button_event(self, val):
self.sample._on_logging_event(val)
self.task_ui_elements["Save Data"].enabled = True
return
def _on_save_data_button_event(self):
self.sample._on_save_data_event(self.task_ui_elements["Output Directory"].get_value_as_string())
return
def post_reset_button_event(self):
self.task_ui_elements["Follow Target"].enabled = True
self.task_ui_elements["Remove Obstacle"].enabled = False
self.task_ui_elements["Add Obstacle"].enabled = True
self.task_ui_elements["Start Logging"].enabled = True
self.task_ui_elements["Save Data"].enabled = False
if self.task_ui_elements["Follow Target"].text == "STOP":
self.task_ui_elements["Follow Target"].text = "START"
return
def post_load_button_event(self):
self.task_ui_elements["Follow Target"].enabled = True
self.task_ui_elements["Add Obstacle"].enabled = True
self.task_ui_elements["Start Logging"].enabled = True
self.task_ui_elements["Save Data"].enabled = False
return
def post_clear_button_event(self):
self.task_ui_elements["Follow Target"].enabled = False
self.task_ui_elements["Remove Obstacle"].enabled = False
self.task_ui_elements["Add Obstacle"].enabled = False
self.task_ui_elements["Start Logging"].enabled = False
self.task_ui_elements["Save Data"].enabled = False
if self.task_ui_elements["Follow Target"].text == "STOP":
self.task_ui_elements["Follow Target"].text = "START"
return
def shutdown_cleanup(self):
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Follow Target",
"type": "button",
"a_text": "START",
"b_text": "STOP",
"tooltip": "Follow Target",
"on_clicked_fn": self._on_follow_target_button_event,
}
self.task_ui_elements["Follow Target"] = state_btn_builder(**dict)
self.task_ui_elements["Follow Target"].enabled = False
dict = {
"label": "Add Obstacle",
"type": "button",
"text": "ADD",
"tooltip": "Add Obstacle",
"on_clicked_fn": self._on_add_obstacle_button_event,
}
self.task_ui_elements["Add Obstacle"] = btn_builder(**dict)
self.task_ui_elements["Add Obstacle"].enabled = False
dict = {
"label": "Remove Obstacle",
"type": "button",
"text": "REMOVE",
"tooltip": "Remove Obstacle",
"on_clicked_fn": self._on_remove_obstacle_button_event,
}
self.task_ui_elements["Remove Obstacle"] = btn_builder(**dict)
self.task_ui_elements["Remove Obstacle"].enabled = False
def build_data_logging_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
frame.title = "Data Logging"
frame.visible = True
dict = {
"label": "Output Directory",
"type": "stringfield",
"default_val": os.path.join(os.getcwd(), "output_data.json"),
"tooltip": "Output Directory",
"on_clicked_fn": None,
"use_folder_picker": False,
"read_only": False,
}
self.task_ui_elements["Output Directory"] = str_builder(**dict)
dict = {
"label": "Start Logging",
"type": "button",
"a_text": "START",
"b_text": "PAUSE",
"tooltip": "Start Logging",
"on_clicked_fn": self._on_logging_button_event,
}
self.task_ui_elements["Start Logging"] = state_btn_builder(**dict)
self.task_ui_elements["Start Logging"].enabled = False
dict = {
"label": "Save Data",
"type": "button",
"text": "Save Data",
"tooltip": "Save Data",
"on_clicked_fn": self._on_save_data_button_event,
}
self.task_ui_elements["Save Data"] = btn_builder(**dict)
self.task_ui_elements["Save Data"].enabled = False
return
| 7,114 | Python | 39.890804 | 157 | 0.55946 |
Ngochuy2137/omni_isaac_examples/tests/test_replay_follow_target.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.kit
import omni.kit.test
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
from omni.isaac.core.utils.extensions import get_extension_path_from_name
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.replay_follow_target import ReplayFollowTarget
class TestReplayFollowTargetExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = ReplayFollowTarget()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
pass
async def test_replay_trajectory(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_replay_trajectory_event_async(
os.path.abspath(
os.path.join(get_extension_path_from_name("omni.isaac.examples"), "data/example_data_file.json")
)
)
await update_stage_async()
# run for 2500 frames and print time
for i in range(500):
await update_stage_async()
pass
async def test_replay_scene(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_replay_scene_event_async(
os.path.abspath(
os.path.join(get_extension_path_from_name("omni.isaac.examples"), "data/example_data_file.json")
)
)
await update_stage_async()
# run for 2500 frames and print time
for i in range(500):
await update_stage_async()
pass
| 3,296 | Python | 36.465909 | 119 | 0.668386 |
Ngochuy2137/omni_isaac_examples/tests/test_path_planning.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import numpy as np
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.path_planning import PathPlanning
class TestPathPlanningExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = PathPlanning()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
# Run all functions with simulation enabled
async def test_follow_target(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_follow_target_event_async()
await update_stage_async()
# run for 2500 frames and print time
for i in range(500):
await update_stage_async()
pass
# Run all functions with simulation enabled
async def test_add_obstacle(self):
await self._sample.reset_async()
await update_stage_async()
# run for 2500 frames and print time
for i in range(500):
await update_stage_async()
if i % 50 == 0:
self._sample._on_add_wall_event()
await update_stage_async()
await self._sample._on_follow_target_event_async()
await update_stage_async()
await self._sample.reset_async()
await update_stage_async()
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
pass
| 3,025 | Python | 35.457831 | 119 | 0.669091 |
Ngochuy2137/omni_isaac_examples/tests/test_nut_bolt.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
from math import isclose
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.franka_nut_and_bolt import FrankaNutAndBolt
class NutBoltExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = FrankaNutAndBolt()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
# Run all functions with simulation enabled
async def test_nut_bolt(self):
world = self._sample.get_world()
await update_stage_async()
# run for 4000 frames
for i in range(3500):
await update_stage_async()
nut_on_bolt = False
bolt = world.scene.get_object(f"bolt2_geom")
bolt_pos, _ = bolt.get_world_pose()
for j in range(self._sample._num_nuts):
nut = world.scene.get_object(f"nut{j}_geom")
nut_pos, _ = nut.get_world_pose()
if (
isclose(nut_pos[0], bolt_pos[0], abs_tol=0.0009)
and isclose(nut_pos[1], bolt_pos[1], abs_tol=0.0009)
and isclose(nut_pos[2], bolt_pos[2] + 0.09, abs_tol=0.015)
):
nut_on_bolt = True
self.assertTrue(nut_on_bolt)
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
world = self._sample.get_world()
await update_stage_async()
for i in range(3500):
await update_stage_async()
nut_on_bolt = False
bolt = world.scene.get_object(f"bolt2_geom")
bolt_pos, _ = bolt.get_world_pose()
for j in range(self._sample._num_nuts):
nut = world.scene.get_object(f"nut{j}_geom")
nut_pos, _ = nut.get_world_pose()
if (
isclose(nut_pos[0], bolt_pos[0], abs_tol=0.0009)
and isclose(nut_pos[1], bolt_pos[1], abs_tol=0.0009)
and isclose(nut_pos[2], bolt_pos[2] + 0.09, abs_tol=0.015)
):
nut_on_bolt = True
self.assertTrue(nut_on_bolt)
pass
| 3,659 | Python | 36.731958 | 119 | 0.626401 |
Ngochuy2137/omni_isaac_examples/tests/__init__.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_bin_filling import *
from .test_follow_target import *
from .test_hello_world import *
from .test_kaya_gamepad import *
from .test_nut_bolt import *
from .test_omnigraph_keyboard import *
from .test_path_planning import *
from .test_replay_follow_target import *
from .test_robo_factory import *
from .test_robo_party import *
from .test_simple_stack import *
| 803 | Python | 37.285713 | 76 | 0.787049 |
Ngochuy2137/omni_isaac_examples/tests/test_bin_filling.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import carb
import numpy as np
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.bin_filling import BinFilling
class TestBinFillingExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = BinFilling()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
settings = carb.settings.get_settings()
settings.set("/app/player/useFixedTimeStepping", False)
settings.set("/app/runLoops/main/rateLimitEnabled", False)
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
# Run all functions with simulation enabled
async def test_bin_filling(self):
await self._sample.reset_async()
await update_stage_async()
world = self._sample.get_world()
ur10_task = world.get_task(name="bin_filling")
task_params = ur10_task.get_params()
my_ur10 = world.scene.get_object(task_params["robot_name"]["value"])
bin = world.scene.get_object(task_params["bin_name"]["value"])
await self._sample.on_fill_bin_event_async()
await update_stage_async()
# run for 1500 frames and print time
for i in range(1500):
await update_stage_async()
my_ur10.gripper.update()
if self._sample._controller.get_current_event() in [4, 5]:
self.assertTrue(my_ur10.gripper.is_closed())
if self._sample._controller.get_current_event() == 5:
self.assertGreater(bin.get_world_pose()[0][-1], 0.15)
if self._sample._controller.get_current_event() > 5:
if not my_ur10.gripper.is_closed():
break
if my_ur10.gripper.is_closed():
bin.set_linear_velocity(np.array([0.0, 0.0, -15.0]))
for i in range(100):
await update_stage_async()
self.assertTrue(not my_ur10.gripper.is_closed())
self.assertLess(bin.get_world_pose()[0][-1], 0.15)
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample.on_fill_bin_event_async()
await update_stage_async()
for i in range(2500):
await update_stage_async()
await self._sample.reset_async()
await update_stage_async()
await self._sample.on_fill_bin_event_async()
await update_stage_async()
for i in range(2500):
await update_stage_async()
pass
| 4,027 | Python | 39.686868 | 119 | 0.650112 |
Ngochuy2137/omni_isaac_examples/tests/test_robo_factory.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import numpy as np
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.robo_factory import RoboFactory
class TestRoboFactoryExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = RoboFactory()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
# Run all functions with simulation enabled
async def test_stacking(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_start_stacking_event_async()
await update_stage_async()
# run for 2500 frames and print time
for i in range(2000):
await update_stage_async()
cube_names = self._sample._tasks[0].get_cube_names()
task_observations = self._sample._tasks[0].get_observations()
for cube_name in cube_names:
self.assertTrue(
np.isclose(task_observations[cube_name]["position"][0:2], np.array([0.5, -2.5]), atol=1e-2).all()
)
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
pass
| 2,898 | Python | 37.653333 | 119 | 0.675293 |
Ngochuy2137/omni_isaac_examples/tests/test_robo_party.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.robo_party import RoboParty
class TestRoboPartyExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = RoboParty()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
# Run all functions with simulation enabled
async def test_stacking(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_start_party_event_async()
await update_stage_async()
# run for 2500 frames and print time
for i in range(500):
await update_stage_async()
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
pass
| 2,542 | Python | 36.397058 | 119 | 0.686861 |
Ngochuy2137/omni_isaac_examples/tests/test_simple_stack.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.simple_stack import SimpleStack
class TestSimpleStackExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = SimpleStack()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
# Run all functions with simulation enabled
async def test_stacking(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_stacking_event_async()
await update_stage_async()
# run for 2500 frames and print time
for i in range(1000):
await update_stage_async()
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
await self._sample.reset_async()
await update_stage_async()
await update_stage_async()
pass
| 2,548 | Python | 36.485294 | 119 | 0.687991 |
Ngochuy2137/omni_isaac_examples/tests/test_follow_target.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.follow_target import FollowTarget
class TestFollowTargetExampleExtension(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
await update_stage_async()
self._sample = FollowTarget()
self._sample.set_world_settings(physics_dt=1.0 / 60.0, stage_units_in_meters=1.0)
await self._sample.load_world_async()
await update_stage_async()
while is_stage_loading():
await update_stage_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await self._sample.clear_async()
await update_stage_async()
self._sample = None
pass
# Run all functions with simulation enabled
async def test_follow_target(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_follow_target_event_async(True)
await update_stage_async()
# run for 2500 frames and print time
for i in range(500):
await update_stage_async()
pass
# Run all functions with simulation enabled
async def test_add_obstacle(self):
await self._sample.reset_async()
await update_stage_async()
await self._sample._on_follow_target_event_async(True)
await update_stage_async()
# run for 2500 frames and print time
for i in range(500):
await update_stage_async()
if i % 50 == 0:
self._sample._on_add_obstacle_event()
await update_stage_async()
await self._sample.reset_async()
await update_stage_async()
pass
async def test_reset(self):
await self._sample.reset_async()
await update_stage_async()
pass
| 3,000 | Python | 36.5125 | 119 | 0.673667 |
Ngochuy2137/omni_isaac_examples/tests/test_kaya_gamepad.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import carb
import omni.kit
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async
from omni.isaac.core.world.world import World
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.examples.kaya_gamepad import KayaGamepad
class TestKayaGamepadSample(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await create_new_stage_async()
self._physics_rate = 60
self._provider = carb.input.acquire_input_provider()
self._gamepad = self._provider.create_gamepad("test", "0")
carb.settings.get_settings().set_int("/app/runLoops/main/rateLimitFrequency", int(self._physics_rate))
carb.settings.get_settings().set_bool("/app/runLoops/main/rateLimitEnabled", True)
carb.settings.get_settings().set_int("/persistent/simulation/minFrameRate", int(self._physics_rate))
omni.usd.get_context().get_stage().SetTimeCodesPerSecond(self._physics_rate)
omni.timeline.get_timeline_interface().set_target_framerate(self._physics_rate)
await update_stage_async()
self._sample = KayaGamepad()
World.clear_instance()
self._sample.set_world_settings(physics_dt=1.0 / self._physics_rate, stage_units_in_meters=1.0)
await self._sample.load_world_async()
return
# After running each test
async def tearDown(self):
# In some cases the test will end before the asset is loaded, in this case wait for assets to load
while is_stage_loading():
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await omni.kit.app.get_app().next_update_async()
self._sample._world_cleanup()
self._sample = None
await update_stage_async()
self._provider.destroy_gamepad(self._gamepad)
await update_stage_async()
World.clear_instance()
pass
# # Run all functions with simulation enabled
# async def test_simulation(self):
# await update_stage_async()
# while is_stage_loading():
# await update_stage_async()
# self._provider.set_gamepad_connected(self._gamepad, True)
# self.assertLess(self._sample._kaya.get_world_pose()[0][1], 1)
# await update_stage_async()
# for i in range(100):
# self._provider.buffer_gamepad_event(self._gamepad, carb.input.GamepadInput.LEFT_STICK_UP, 1.0)
# await update_stage_async()
# self._provider.set_gamepad_connected(self._gamepad, False)
# await update_stage_async()
# self.assertGreater(self._sample._kaya.get_world_pose()[0][1], 64.0)
# pass
| 3,468 | Python | 44.644736 | 119 | 0.689735 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.