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
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.debug_draw/docs/ogn.rst
DebugDrawPointCloud ------------------- ['Take a point cloud as input and display it in the scene.'] **Inputs** - **execIn** (*execution*): The input execution port. - **depthTest** (*bool*): If true, the points will not render when behind other objects. Default to True. - **transform** (*matrixd[4]*): The matrix to transform the points by. - **pointCloudData** (*pointf[3][]*): Buffer of 3d points containing point cloud data. Default to []. - **color** (*colorf[4]*): Color of points. Default to [0.75, 0.75, 1, 1]. - **width** (*float*): Size of points. Default to 0.02.
608
reStructuredText
39.599997
109
0.616776
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.debug_draw/docs/CHANGELOG.md
# Changelog ## [0.2.3] - 2023-01-19 ### Fixed - crash when trying to draw without a valid renderer ## [0.2.2] - 2022-12-14 ### Fixed - crash when deleting ## [0.2.1] - 2022-10-18 ### Changed - Debug Draw Point Cloud takes transform - PrimitiveDrawingHelper::setVertices with poistion only ## [0.2.0] - 2022-10-06 ### Added - Debug Draw Point Cloud node - PrimitiveDrawingHelper::setVertices with constant color and width ### Changed - antialiasingWidth to 1 in PrimitiveDrawingHelper::draw() ## [0.1.4] - 2022-10-02 ### Fixed - Crash when stage was not ready ## [0.1.3] - 2022-09-07 ### Fixed - Fixes for kit 103.5 ## [0.1.2] - 2022-03-07 ### Added - Added flag to disable depth check ## [0.1.1] - 2021-08-20 ### Added - world space flag to specify if width value is in world coordinates. ## [0.1.0] - 2021-07-27 ### Added - Initial version of extension
869
Markdown
17.913043
71
0.667434
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.debug_draw/docs/README.md
# Usage To enable this extension, go to the Extension Manager menu and enable omni.isaac.debug_draw extension.
113
Markdown
21.799996
102
0.787611
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.debug_draw/docs/index.rst
Debug Drawing [omni.isaac.debug_draw] ########################################### .. automodule:: omni.isaac.debug_draw._debug_draw :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: Omnigraph Nodes ======================= .. include:: ogn.rst
344
reStructuredText
20.562499
49
0.543605
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/PACKAGE-LICENSES/omni.isaac.benchmark_environments-LICENSE.md
Copyright (c) 2020, 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.
412
Markdown
57.999992
74
0.839806
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/config/extension.toml
[core] reloadable = true order = 0 [package] version = "0.4.0" category = "Simulation" title = "Simulated Environments for use in Isaac Sim" description = "Extension for programming simple environments for robots" authors = ["NVIDIA"] repository = "" keywords = ["isaac", "samples", "environments"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" icon = "data/icon.png" [dependencies] "omni.isaac.core" = {} [[python.module]] name = "omni.isaac.benchmark_environments" [[python.module]] name = "omni.isaac.benchmark_environments.tests"
550
TOML
21.039999
72
0.72
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/omni/isaac/benchmark_environments/extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext from .environments import *
473
Python
38.499997
76
0.805497
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/omni/isaac/benchmark_environments/__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 .extension import *
454
Python
40.363633
76
0.803965
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/omni/isaac/benchmark_environments/objects.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 pxr import Gf import numpy as np from scipy.spatial.transform import Rotation as R from .object_interface import Object """ An Object allows the manipulation of a group of prims as a single unit. A subclass of Object must implement the construct() method to specify what prims comprise an object, and what their relative positions are. When an Object is created, the base pose is specified in the constructor. Inside the construct() method, the position of each prim in the object is specified relative to that base pose. For example, the Cubby Object is constructed from a set of blocks that have translations specified relative to the base of the Cubby. The relative rotation is not specified, and so is assumed to be the identity. Target, Block, Sphere, and Capsule are the most basic possible variants of Object, as they are comprised of just a single prim. """ class Target(Object): def construct(self, **kwargs): size = kwargs.get("size", 0.05) target_color = kwargs.get("target_color", np.array([1.0, 0, 0])) self.create_target(target_size=size, target_color=target_color) def get_target(self, make_visible=True): target = self.targets[0] target.set_visibility(make_visible) return target class Block(Object): def construct(self, **kwargs): self.size = kwargs.get("size", 0.10 * np.ones(3)) # self.scales = kwargs.get("scales", np.array([1.0, 1.0, 1.0])) self.create_block(self.size) def get_component(self): return self.components[0] class Sphere(Object): def construct(self, **kwargs): self.radius = kwargs.get("radius", 0.10) self.create_sphere(self.radius) def get_geom(self): return self.components[0] class Capsule(Object): def construct(self, **kwargs): self.radius = kwargs.get("radius", 0.05) self.height = kwargs.get("height", 0.10) self.create_capsule(self.radius, self.height) def get_geom(self): return self.components[0] class Cubbies(Object): def construct(self, **kwargs): self.size = kwargs.get("size", 1) self.num_rows = kwargs.get("num_rows", 3) self.num_cols = kwargs.get("num_cols", 3) self.height = kwargs.get("height", 1.00) # z axis self.width = kwargs.get("width", 1.00) # y axis self.depth = kwargs.get("depth", 0.30) # x axis self.target_depth = kwargs.get("target_depth", self.depth / 2) self.cub_height = self.height / self.num_rows self.cub_width = self.width / self.num_cols back = self.create_block( self.size * np.array([0.01, self.width, self.height]), relative_translation=np.array([self.depth / 2, 0, self.height / 2]), ) for i in range(self.num_rows + 1): shelf = self.create_block( self.size * np.array([self.depth, self.width, 0.01]), relative_translation=np.array([0, 0, self.cub_height * i]), ) for i in range(self.num_cols + 1): shelf = self.create_block( self.size * np.array([self.depth, 0.01, self.height]), relative_translation=np.array([0, self.cub_width * i - self.width / 2, self.height / 2]), ) # Put a target in each shelf. target_x_offset = self.target_depth - self.depth / 2 target_start = np.array([target_x_offset, -self.width / 2 + self.cub_width / 2, self.cub_height / 2]) target_rot = R.from_rotvec([0, np.pi / 2, 0]).as_matrix() for i in range(self.num_rows): for j in range(self.num_cols): pos = target_start + np.array([0, self.cub_width * j, self.cub_height * i]) target = self.create_target(relative_translation=pos, relative_rotation=target_rot) class Cage(Object): def construct(self, **kwargs): self.ceiling_height = kwargs.get("ceiling_height", 0.75) self.ceiling_thickenss = kwargs.get("ceiling_thickness", 0.01) self.cage_width = kwargs.get("cage_width", 0.3) self.cage_length = kwargs.get("cage_length", 0.3) self.num_pillars = kwargs.get("num_pillars", 3) self.pillar_thickness = kwargs.get("pillar_thickness", 0.1) self.target_scalar = kwargs.get("target_scalar", 1.15) ceiling = self.create_block( np.array([2 * self.cage_width, 2 * self.cage_length, self.ceiling_thickenss]), np.array([0, 0, self.ceiling_height]), np.eye(3), ) for i in range(self.num_pillars): angle = 2 * (i + 0.5) * np.pi / self.num_pillars pillar_x = self.cage_width * np.cos(angle) pillar_y = self.cage_length * np.sin(angle) pillar = self.create_block( np.array([self.pillar_thickness, self.pillar_thickness, self.ceiling_height]), np.array([pillar_x, pillar_y, self.ceiling_height / 2]), np.eye(3), ) for angle in np.arange(0, 2 * np.pi, 0.1): target_x = (self.cage_width + self.pillar_thickness) * self.target_scalar * np.cos(angle) target_y = (self.cage_length + self.pillar_thickness) * self.target_scalar * np.sin(angle) self.create_target(np.array([target_x, target_y, self.ceiling_height / 2])) class Windmill(Object): def construct(self, **kwargs): self.size = kwargs.get("size", 1) # scales entire windmill self.num_blades = kwargs.get("num_blades", 2) self.blade_width = kwargs.get("blade_width", 0.01) # y axis self.blade_height = kwargs.get("blade_height", 1.00) # z axis self.blade_depth = kwargs.get("blade_depth", 0.01) # x axis for i in range(self.num_blades): rot = R.from_rotvec([i * np.pi / self.num_blades, 0, 0]) blade = self.create_block( self.size * np.array([self.blade_depth, self.blade_width, self.blade_height]), relative_rotation=rot.as_matrix(), ) class Window(Object): def construct(self, **kwargs): self.width = kwargs.get("width", 1.00) # y axis self.depth = kwargs.get("depth", 0.05) # x axis self.height = kwargs.get("height", 1.00) # z axis self.size = kwargs.get("size", 1) # scales entire window self.window_width = kwargs.get("window_width", 0.50) self.window_height = kwargs.get("window_height", 0.50) side_width = (self.width - self.window_width) / 2 side = self.create_block( self.size * np.array([self.depth, side_width, self.height]), relative_translation=np.array([0, -self.width / 2 + side_width / 2, 0]), ) side = self.create_block( self.size * np.array([self.depth, side_width, self.height]), relative_translation=np.array([0, +self.width / 2 - side_width / 2, 0]), ) top_height = (self.height - self.window_height) / 2 top = self.create_block( self.size * np.array([self.depth, self.width, top_height]), relative_translation=np.array([0, 0, self.height / 2 - top_height / 2]), ) bottom = self.create_block( self.size * np.array([self.depth, self.width, top_height]), relative_translation=np.array([0, 0, -self.height / 2 + top_height / 2]), ) self.center_target = self.create_target() # in center of window self.behind_target = self.create_target(relative_translation=np.array([self.depth, 0, 0])) self.front_target = self.create_target(relative_translation=np.array([-self.depth, 0, 0]))
8,135
Python
37.928229
111
0.613645
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/omni/isaac/benchmark_environments/environment_interface.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import numpy as np import omni.usd from pxr import UsdPhysics, PhysxSchema """ Environments have a set of Objects in them that can move or change over time. The default environment doesn't have any objects in it. Subclasses of Environment implement build_environment: instantiate all objects/targets in the environment according to **kwargs update: called every frame, update moves all moving elements of the environment and does any necessary maintainence get_new_scenario: return a series of targets that the robot should follow Environments have random seeds to ensure repeatability. This means that all randomness in the environment should be achieved through numpy's random module. As a convention, environments are displaced from the robot along the positive x axis, and mostly centered about the y axis. Some robots (such as the UR10) may need the environment to be rotated about the robot. The UR10's environment config file rotates each environment by pi/2 about the z axis. """ class Environment: def __init__(self, random_seed=0, **kwargs): self._stage = omni.usd.get_context().get_stage() self.objects = [] self.targetable_objects = [] self.random_seed = random_seed np.random.seed(random_seed) # get the frequency in Hz of the simulation physxSceneAPI = None for prim in self._stage.Traverse(): if prim.IsA(UsdPhysics.Scene): physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(prim) if physxSceneAPI is not None: self.fps = physxSceneAPI.GetTimeStepsPerSecondAttr().Get() else: self.fps = 60 self.timeout = 10 # simulated seconds before a test times out self.camera_position = [-2.00, -1.00, 1.00] self.camera_target = [0.50, 0, 0.50] # Set thresholds for robot reaching translation/rotation targets self.target_translation_thresh = 0.03 self.target_rotation_thresh = 0.1 self.name = "" self.initial_robot_cspace_position = None self.build_environment(**kwargs) def get_timeout(self): return self.timeout def build_environment(self, **kwargs): pass def update(self): # update positions of moving obstacles/targets in environment as a function of time pass def get_new_scenario(self): """ Returns start_config (USD Geom): desired starting position of the robot (should be easy to reach to start the test) if None, the robot should ignore this scenario waypoints (USD Geom): desired goal position of the robot if None, the robot will follow the start_target until timeout is reached timeout (float): stop trial when timeout (seconds) have passes """ return None, [], self.timeout def enable_collisions(self): for obj in self.objects: obj.set_enable_collisions(True) def disable_collisions(self): for obj in self.objects: obj.set_enable_collisions(False) def get_all_obstacles(self): prims = [] for obj in self.objects: prims.extend(obj.get_all_components()) return prims def get_random_target(self, make_visible=True): if len(self.targetable_objects) == 0: return None obj = np.random.choice(self.targetable_objects) return obj.get_random_target(make_visible=make_visible) def reset(self, new_seed=None): if new_seed is not None: self.random_seed = new_seed self.first_update = True np.random.seed(self.random_seed) for obj in self.objects: obj.reset() def delete_all_objects(self): for obj in self.targetable_objects: obj.delete() for obj in self.objects: obj.delete() def get_initial_robot_cspace_position(self): return self.initial_robot_cspace_position def get_target_thresholds(self): return self.target_translation_thresh, self.target_rotation_thresh def set_target_translation_threshold(self, thresh): self.target_translation_thresh = thresh def set_target_rotation_threshold(self, thresh): self.target_rotation_thresh = thresh
4,765
Python
34.834586
126
0.670724
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/omni/isaac/benchmark_environments/object_interface.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.client import delete from pxr import UsdGeom, Gf, UsdPhysics import numpy as np import asyncio import uuid import omni.kit.app from omni.isaac.core.utils.prims import delete_prim from omni.isaac.core.utils.rotations import matrix_to_euler_angles, euler_angles_to_quat from omni.isaac.core.objects import cuboid, sphere, capsule from omni.isaac.core.prims import XFormPrim, GeometryPrimView def matrix_to_quat(rot_mat): return euler_angles_to_quat(matrix_to_euler_angles(rot_mat)) class Object: """ An Object is a collection of prims that move and change their properties together. A base Object has no prims in it by default because the construct method is empty. The Object Class is inherited by specific types of objects in objects.py and the construct function is implemented Objects have a base translation and rotation. All prims that form the object have a (fixed) translation and rotation that is relative to the base. The base pose can be updated with set_base_pose, and the world coordinate positions of every prim will be updated by their relative position to the base. Objects have two lists of prims: self.components, and self.targets self.components: prims that for the object that the robot must avoid self.targets: possible targets to make a robot seek. Ex. the cubby object has possible targets in each cubby that are transformed along with the base. A random target can be retrieved with self.get_random_target() Objects are made up of three primitives: capsules, spheres, and rectangular prisms TODO: allow meshes to be loaded for an object """ def __init__(self, base_translation, base_rotation, color=np.array([1.0, 1.0, 0]), **kwargs): self.initial_base_trans = base_translation self.initial_base_rotation = base_rotation self.components = [] self.color = color self.targets = [] self.last_target = None # make a random USD path for all the prims in this object object_id = str(uuid.uuid4()) self.base_path = ("/scene/object-" + object_id).replace("-", "_") self.base_xform = XFormPrim(self.base_path) self.base_xform.set_world_pose(base_translation, matrix_to_quat(base_rotation)) self.construct(**kwargs) self._geometry_view = GeometryPrimView(self.base_path + "/.*") self._geometry_view.apply_collision_apis() self.set_enable_collisions(False) def construct(self, **kwargs): pass def get_random_target(self, make_visible=True): if self.last_target is not None: self.last_target.set_visibility(False) if len(self.targets) > 0: target = np.random.choice(self.targets) target.set_visibility(make_visible) self.last_target = target return target def get_all_components(self): # get all prims that the robot should avoid return self.components def create_target( self, relative_translation=np.zeros(3), relative_rotation=np.eye(3), target_color=np.array([1.0, 0, 0]), target_size=0.05, ): path = self.base_path + "/target_" + str(len(self.targets)) target = cuboid.VisualCuboid(path, size=target_size, color=target_color) target.set_local_pose(relative_translation, matrix_to_quat(relative_rotation)) target.set_visibility(False) self.targets.append(target) return target def create_block(self, size, relative_translation=np.zeros(3), relative_rotation=np.eye(3)): path = self.base_path + "/cuboid_" + str(len(self.components)) cube = cuboid.FixedCuboid(path, size=1.0, scale=size, color=self.color) cube.set_local_pose(relative_translation, matrix_to_quat(relative_rotation)) self.components.append(cube) return cube def create_sphere(self, radius, relative_translation=np.zeros(3), relative_rotation=np.eye(3)): path = self.base_path + "/sphere_" + str(len(self.components)) sphere = sphere.FixedSphere(path, radius=radius, color=self.color) sphere.set_local_pose(relative_translation, matrix_to_quat(relative_rotation)) self.components.append(sphere) return sphere def create_capsule(self, radius, height, relative_translation=np.zeros(3), relative_rotation=np.eye(3)): path = self.base_path + "/capsule_" + str(len(self.components)) capsule = capsule.FixedCapsule(path, radius=radius, height=height, color=self.color) capsule.set_local_pose(relative_translation, matrix_to_quat(relative_rotation)) self.components.append(capsule) return capsule def set_base_pose(self, translation=np.zeros(3), rotation=np.eye(3)): self.base_xform.set_world_pose(translation, matrix_to_quat(rotation)) def set_visibility(self, on=True): for component in self.components: component.set_visibility(on) def set_enable_collisions(self, collisions_enabled=True): if collisions_enabled: self._geometry_view.enable_collision() else: self._geometry_view.disable_collision() def delete(self): for component in self.components: delete_prim(component.prim_path) self.components = [] for target in self.targets: delete_prim(target.prim_path) self.targets = [] def reset(self): self.set_base_pose(self.initial_base_trans, self.initial_base_rotation) for target in self.targets: target.set_visibility(False)
6,127
Python
37.3
114
0.679615
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/omni/isaac/benchmark_environments/environments.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import numpy as np from scipy.spatial.transform import Rotation as R from .environment_interface import Environment from .objects import * """ The environment creator is used by the UI in Isaac Sim for the automatic discovery of environments that appear in a drop down menu. Some environments may not be available for certain robots, and the environment creator stores any relevant excluding of robots per environment. The creator is also used to validate the choice of environment when testing from a standalone script. """ class EnvironmentCreator: def __init__(self): self.environments = ["Static Cage", "Cubby", "Window", "Evasion", "Guillotine"] self.robot_exclusion_lists = {"Windmill": ["UR10"]} self.policy_exclusion_list = {} def create_environment(self, env_name, random_seed=0, **kwargs): if env_name == "Cubby": return CubbyEnv(random_seed=random_seed, **kwargs) elif env_name == "Evasion": return EvasionEnv(random_seed=random_seed, **kwargs) elif env_name == "Window": return WindowEnv(random_seed=random_seed, **kwargs) elif env_name == "Windmill": return WindmillEnv(random_seed=random_seed, **kwargs) elif env_name == "Guillotine": return GuillotineEnv(random_seed=random_seed, **kwargs) elif env_name == "Static Cage": return CageEnv(random_seed=random_seed, **kwargs) elif env_name == "Empty": return EmptyEnv(random_seed=random_seed, **kwargs) else: return None def has_environment(self, env_name): return env_name in self.environments def get_environment_names(self): return self.environments def get_robot_exclusion_list(self, env_name): # some robots should not be used in certain environments return self.robot_exclusion_lists.get(env_name, []) def get_motion_policy_exclusion_list(self, env_name): # some motion policies should not be used in certain environments # For example, global motion policies with slow update rates may not make sense # for environments with quickly moving obstacles or targets. return self.policy_exclusion_list.get(env_name, []) """ See comments above the Environment class in ./template_classes.py for information about the general behavior of all environments. These comments explain some implementation details when implementing the Environment class. Different environments are implemented below. Each environment has **kwargs that it can accept as an argument. Each robot has an environment config file with the desired kwargs for each environment. Any kwargs that are explicitly listed in the environment config file override the default kwargs seen in the kwargs.get() lines. There is not a rigid style for naming kwargs or deciding what kwargs are in a certain environment. The environments are not made with the assumption that every possible detail will be specified by a kwarg. Most position information can be passed in as a kwarg, but the relative positions of some objects may not be changeable. There are some magic numbers in the placement of certain objects when it would overcomplicate things to use kwargs and it is not likely that the param will need to change. Most parameters that are chosen arbitrarily, such as the speed of moving obstacles, are given as kwargs. As a convention, environments are displaced from the robot along the positive x axis, and mostly centered about the y axis. Some robots (such as the UR10) may need the environment to be rotated about the robot. The UR10's environment config file rotates each environment by pi/2 about the z axis. In general, the code for these environments are not written with the expectation that the user will never need to touch the code for their desired custom behavior. The code serves as more of an example for how to create different behaviors in different environments as needed. """ class CubbyEnv(Environment): def build_environment(self, **kwargs): """ Kwargs: name: human-readable name of this environment (default: "Cubby") initial_robot_cspace_position: If specified, this parameter can be accessed to determine a good starting cspace position for a robot in this environment timeout: simulated time (in seconds) before a test times out (default: 10) collidable: turn on collision detection for the cubby (default: False) target_translation_thresh: threshold for how close the robot end effector must be to translation targets in meters (default: .03) target_rotation_thresh: threshold for how close the robot end effector must be to rotation targets in radians (default: .1) base_rotation: axis-angle rotation of the cubby base (default: [0,0,0]) base_offset: 3d translation of the cubby base (default [45.0,0,0]) depth: The depth of the cubby shelves (default 30) target_depth: how deep the target is into the cubby (default half the depth) """ self.name = kwargs.get("name", "Cubby") self.initial_robot_cspace_position = kwargs.get("initial_robot_cspace_position", None) self.timeout = kwargs.get("timeout", 20) self.target_translation_thresh = kwargs.get("target_translation_thresh", 0.03) self.target_rotation_thresh = kwargs.get("target_rotation_thresh", 0.1) cub_rot = R.from_rotvec(kwargs.get("base_rotation", [0, 0, 0])) base_offset = np.array(kwargs.get("base_offset", [0.45, 0.0, 0])) depth = kwargs.get("depth", 0.30) target_depth = kwargs.get("target_depth", depth / 2) self.require_orientation = kwargs.get("require_orientation", True) # add an orientation target cub_pos = base_offset + np.array([0, 0, 0.20]) c = Cubbies(cub_pos, cub_rot.as_matrix(), require_orientation=False, depth=depth, target_depth=target_depth) target_pos = cub_pos / 2 + np.array([0.0, 0.0, c.height / 2]) self.start_target = Target( target_pos, R.from_rotvec([0, np.pi, 0]).as_matrix(), target_color=np.array([0, 0, 1.0]), require_orientation=True, ) base_pos = base_offset + np.array([0, 0, 0.10]) cubby_base = Block(base_pos, cub_rot.as_matrix(), size=np.array([c.depth, c.width, 0.20])) self.objects.append(c) self.objects.append(cubby_base) self.targetable_objects.append(c) def get_new_scenario(self): t1 = self.get_random_target(make_visible=False) t2 = self.get_random_target(make_visible=False) while t2 == t1: t2 = self.get_random_target(make_visible=False) waypoints = [t1, t2] return self.start_target.get_target(make_visible=True), waypoints, self.timeout class EvasionEnv(Environment): def build_environment(self, **kwargs): """ Kwargs: name: human-readable name of this environment (default: "Evasion") timeout: simulated time (in seconds) before a test times out (default: 300) target_translation_thresh: threshold for how close the robot end effector must be to translation targets in meters (default: .03) target_rotation_thresh: threshold for how close the robot end effector must be to rotation targets in radians (default: .1) target_speed: speed of the target along a sinusoidal path in rad/sec (default: .2) block_speeds: 6d vector of speeds for the blocks moving along sinusoidal paths in rad/sec (default: np.linspace(.1, .3, num=6)) block_sizes: 6d vector of the sizes of each block (default [15,15,15,15,15,15]) frames_per_update: number of frames that should pass before obstacle/target positions are updated (default: 1) -- This approximates lag in perception target_position_std_dev: standard deviation of target position offset from the set path on every frame (default: 0) obstacle_position_std_dev: standard deviation of obstacle positions offset from their set path on every frame (default: 0) height: height of target/average heights of obstacles off the ground """ self.name = kwargs.get("name", "Evasion") self.initial_robot_cspace_position = kwargs.get("initial_robot_cspace_position", None) self.timeout = kwargs.get("timeout", 300) self.target_translation_thresh = kwargs.get("target_translation_thresh", 0.03) self.target_rotation_thresh = kwargs.get("target_rotation_thresh", 0.1) self.target_speed = kwargs.get("target_speed", 0.2) # rad/sec # blocks move sinusoidally with the given frequencies self.block_speeds = np.array(kwargs.get("block_speeds", np.linspace(0.1, 0.3, num=6))) self.block_sizes = np.array(kwargs.get("block_sizes", [0.15] * 6), dtype=int) # the size of each block # Update postions once every frame by default. self.frames_per_update = kwargs.get("frames_per_update", 1) # std_dev of gaussian noise to target position self.target_position_std_dev = kwargs.get("target_position_std_dev", 0) self.obstacle_position_std_dev = kwargs.get("obstacle_position_std_dev", 0) height = kwargs.get("height", 0.50) self.target = Target(np.array([0.60, 0.0, height]), np.eye(3)) self.objects.append(self.target) self.blocks = [] for i, position in enumerate(np.linspace([0.40, -0.50, height], [0.40, 0.50, height], num=6)): self.blocks.append(Block(position, np.eye(3), size=0.150 * np.ones(3))) self.objects.extend(self.blocks) self.first_update = True def get_new_scenario(self): self.first_update = True return self.target.get_target(make_visible=True), [], self.timeout def update(self): if self.first_update: self.frame_number = 0 self.first_update = False else: self.frame_number += 1 # Because robot perception can be slow, this slows down the world updates by a factor of self.frames_per_update. t = (self.frame_number // self.frames_per_update) * self.frames_per_update pos = ( self.target.initial_base_trans + np.array([0, 0.50 * np.sin(self.target_speed / self.fps * t), 0]) + np.random.normal(0, self.target_position_std_dev) ) self.target.set_base_pose(translation=pos) for block, speed in zip(self.blocks, self.block_speeds): pos = ( block.initial_base_trans + np.array([0, 0, 0.40 * np.sin(speed / self.fps * t)]) + np.random.normal(0, self.obstacle_position_std_dev) ) block.set_base_pose(translation=pos) class WindmillEnv(Environment): def build_environment(self, **kwargs): """ Kwargs: name: human-readable name of this environment (default: "Windmill") timeout: simulated time (in seconds) before a test times out (default: 300) target_translation_thresh: threshold for how close the robot end effector must be to translation targets in meters (default: .03) target_rotation_thresh: threshold for how close the robot end effector must be to rotation targets in radians (default: .1) windmill_1_speed: rotational speed of windmill 1 in rad/sec (default: pi/15) windmill_2_speed: rotational speed of windmill 2 in rad/sec (default: pi/15) windmill_1_translation: translational position of windmill 1 (default [35,0,50]) windmill_2_translation: translational position of windmill 1 (default [40,0,50]) target_pos: position of target behind windmills (default [50,0,70]) env_rotation: axis rotation of environmnet at the world origin (default [0,0,0]) """ self.name = kwargs.get("name", "Windmill") self.timeout = kwargs.get("timeout", 300) self.initial_robot_cspace_position = kwargs.get("initial_robot_cspace_position", None) self.target_translation_thresh = kwargs.get("target_translation_thresh", 0.03) self.target_rotation_thresh = kwargs.get("target_rotation_thresh", 0.1) self.speed1 = kwargs.get("windmill_1_speed", np.pi / 15) self.speed2 = kwargs.get("windmill_2_speed", np.pi / 25) self.bt1 = np.array(kwargs.get("windmill_1_translation", [0.40, 0, 0.50])) self.bt2 = np.array(kwargs.get("windmill_2_translation", [0.45, 0, 0.50])) self.br1 = np.eye(3) self.br2 = np.eye(3) self.t_pos = np.array(kwargs.get("target_pos", [0.50, 0, 0.70])) self.env_rotation = R.from_rotvec( np.array(kwargs.get("env_rotation", [0, 0, 0])) ).as_matrix() # Rotate the entire environment about the robot. self.bt1 = self.env_rotation @ self.bt1 self.bt2 = self.env_rotation @ self.bt2 self.br1 = self.env_rotation @ self.br1 self.br2 = self.env_rotation @ self.br2 self.t_pos = self.env_rotation @ self.t_pos self.rot_axs = self.env_rotation @ np.array([1, 0, 0]) self.w1 = Windmill(self.bt1, self.br1) self.w2 = Windmill(self.bt2, self.br2, num_blades=3) self.objects.append(self.w1) self.objects.append(self.w2) self.target = Target(self.t_pos, np.eye(3)) self.start_target = Target(self.w1.initial_base_trans / 2, np.eye(3), target_color=np.array([0, 0, 1.0])) self.mid_target = Target(self.w1.initial_base_trans / 2, np.eye(3)) self.frame_number = 0 def update(self): self.frame_number += 1 t = self.frame_number p1 = self.w1.initial_base_trans p2 = self.w2.initial_base_trans rot1 = R.from_rotvec(self.speed1 / self.fps * t * self.rot_axs).as_matrix() @ self.w1.initial_base_rotation rot2 = R.from_rotvec(self.speed2 / self.fps * t * self.rot_axs).as_matrix() @ self.w2.initial_base_rotation self.w1.set_base_pose(p1, rot1) self.w2.set_base_pose(p2, rot2) def get_new_scenario(self): sg = self.start_target.get_target(make_visible=True) mg = self.mid_target.get_target() tg = self.target.get_target() return sg, [tg, mg, tg], self.timeout class WindowEnv(Environment): def build_environment(self, **kwargs): """ Kwargs: name: human-readable name of this environment (default: "Window") timeout: simulated time (in seconds) before a test times out (default: 20) target_translation_thresh: threshold for how close the robot end effector must be to translation targets in meters (default: .03) target_rotation_thresh: threshold for how close the robot end effector must be to rotation targets in radians (default: .1) window_translation: translational position of window (default [45,-30, 50]) env_rotation: axis rotation of environmnet at the world origin (default [0,0,0]) """ self.name = kwargs.get("name", "Window") self.timeout = kwargs.get("timeout", 20) self.initial_robot_cspace_position = kwargs.get("initial_robot_cspace_position", None) self.target_translation_thresh = kwargs.get("target_translation_thresh", 0.03) self.target_rotation_thresh = kwargs.get("target_rotation_thresh", 0.1) self.window_trans = np.array(kwargs.get("window_translation", [0.45, -0.30, 0.50])) self.window_rotation = np.eye(3) env_rotation = R.from_rotvec( np.array(kwargs.get("env_rotation", [0, 0, 0])) ).as_matrix() # Rotate the entire environment about the robot. self.window_trans = env_rotation @ self.window_trans self.window_rotation = env_rotation @ self.window_rotation self.window = Window(self.window_trans, self.window_rotation, window_width=0.30, window_height=0.30) self.start_target = Target(self.window_trans / 2, self.window_rotation, target_color=np.array([0, 0, 1.0])) self.objects.append(self.window) self.end_target = Target(np.array([*1.3 * self.window_trans[:2], self.window_trans[2]]), self.window_rotation) def get_new_scenario(self): return ( self.start_target.get_target(), [ self.window.front_target, self.window.center_target, self.window.behind_target, self.end_target.get_target(make_visible=False), ], self.timeout, ) class GuillotineEnv(Environment): def build_environment(self, **kwargs): """ Kwargs: name: human-readable name of this environment (default: "Guillotine") timeout: simulated time (in seconds) before a test times out (default: 20) target_translation_thresh: threshold for how close the robot end effector must be to translation targets in meters (default: .03) target_rotation_thresh: threshold for how close the robot end effector must be to rotation targets in radians (default: .1) wall_height: height of wall the robot has to reach through (default: 100) windmill_speed: speed of windmill embedded in wall in rad/sec (default: pi/15) window_translation: translational position of window embedded in wall (default [50,0, wall_height/2]) windmill_translation: translational position of windmill (default: [55,0,wall_height/2+30]) env_rotation: axis rotation of environmnet at the world origin (default [0,0,0]) """ self.name = kwargs.get("name", "Guillotine") self.timeout = kwargs.get("timeout", 20) self.initial_robot_cspace_position = kwargs.get("initial_robot_cspace_position", None) self.target_translation_thresh = kwargs.get("target_translation_thresh", 0.03) self.target_rotation_thresh = kwargs.get("target_rotation_thresh", 0.1) self.wall_height = kwargs.get("wall_height", 1.00) self.speed = kwargs.get("windmill_speed", np.pi / 15) self.window_trans = np.array(kwargs.get("window_translation", [0.50, 0, self.wall_height / 2])) end_target_trans = np.array([1.5 * self.window_trans[0], 0, self.wall_height / 2]) self.window_rotation = np.eye(3) self.windmill_trans = np.array(kwargs.get("windmill_translation", [0.55, 0, self.wall_height / 2 + 0.30])) self.windmill_rot_axs = np.array([1, 0, 0]) self.windmill_rotation = self.window_rotation self.env_rotation = R.from_rotvec( np.array(kwargs.get("env_rotation", [0, 0, 0])) ).as_matrix() # Rotate the entire environment about the robot. self.window_trans = self.env_rotation @ self.window_trans self.window_rotation = self.env_rotation @ self.window_rotation self.windmill_trans = self.env_rotation @ self.windmill_trans self.windmill_rotation = self.env_rotation @ self.windmill_rotation self.windmill_rot_axs = self.env_rotation @ self.windmill_rot_axs self.window = Window( self.window_trans, self.window_rotation, height=self.wall_height, window_width=0.30, window_height=0.30, depth=0.20, ) self.windmill = Windmill(self.windmill_trans, self.windmill_rotation, blade_width=0.10) self.start_target = Target(self.window_trans / 2, self.window_rotation, target_color=np.array([0, 0, 1.0])) self.objects.append(self.window) self.objects.append(self.windmill) self.end_target = Target(self.env_rotation @ end_target_trans, self.window_rotation) self.frame_number = 0 self.camera_position = self.env_rotation @ np.array([2.00, -1.00, 1.00]) self.camera_target = self.env_rotation @ np.array([0, 0, 0.50]) def update(self): self.frame_number += 1 t = self.frame_number rot = ( R.from_rotvec(self.speed / self.fps * t * self.windmill_rot_axs).as_matrix() @ self.windmill.initial_base_rotation ) self.windmill.set_base_pose(self.windmill.initial_base_trans, rot) end_tgt = self.end_target.initial_base_trans + self.env_rotation @ ( 10 * np.array([0, np.cos(t * self.speed / self.fps), np.sin(t * self.speed / self.fps)]) ) self.end_target.set_base_pose(end_tgt, self.window_rotation) def get_new_scenario(self): return ( self.start_target.get_target(), [ self.window.front_target, self.window.center_target, self.window.behind_target, self.end_target.get_target(make_visible=True), ], self.timeout, ) class CageEnv(Environment): def build_environment(self, **kwargs): """ Kwargs: name: human-readable name of this environment (default: "Cage") timeout: simulated time (in seconds) before a test times out (default: 20) target_translation_thresh: threshold for how close the robot end effector must be to translation targets in meters (default: .03) target_rotation_thresh: threshold for how close the robot end effector must be to rotation targets in radians (default: .1) ceiling_height: height of ceiling of cage (default .75 m) ceiling_thickness: thickness (along z axis) of ceiling (default .01 m) cage_width: width (along x axis) of cage (default .35 m) cage_length: length (along y axis) of cage (default .35 m) num_pillars: number of pillars defining the "bars" of the cage. The pillars will be evenly spaced by angle around the elipse defined by cage_width and cage_length pillar_thickness: thickness of pillars (default .1 m) target_scalar: a scalar defining the distance from the robot to the targets. Potential targets are arranged in an ovoid around the robot with a width of target_scalar*cage_width and a length of target_scalar*cage_length. A value of 1 would place some targets inside the pillars (default 1.15) """ self.name = kwargs.get("name", "Cage") self.timeout = kwargs.get("timeout", 20) self.initial_robot_cspace_position = kwargs.get("initial_robot_cspace_position", None) self.target_translation_thresh = kwargs.get("target_translation_thresh", 0.03) self.target_rotation_thresh = kwargs.get("target_rotation_thresh", 0.1) self.ceiling_height = kwargs.get("ceiling_height", 0.75) self.ceiling_thickenss = kwargs.get("ceiling_thickness", 0.01) self.cage_width = kwargs.get("cage_width", 0.35) self.cage_length = kwargs.get("cage_length", 0.35) self.num_pillars = kwargs.get("num_pillars", 4) self.pillar_thickness = kwargs.get("pillar_thickness", 0.1) self.target_scalar = kwargs.get("target_scalar", 1.15) self.objects = [] self.cage = Cage( np.zeros(3), np.eye(3), ceiling_height=self.ceiling_height, ceiling_thickness=self.ceiling_thickenss, cage_width=self.cage_width, cage_length=self.cage_length, num_pillars=self.num_pillars, pillar_thickness=self.pillar_thickness, target_scalar=self.target_scalar, ) self.objects.append(self.cage) self.start_target = Target( np.array([(self.cage_width - self.pillar_thickness / 2) / 1.25, 0, self.ceiling_height / 2]), np.eye(3), target_color=np.array([0, 0, 1.0]), ) def get_new_scenario(self): return ( self.start_target.get_target(), [ self.cage.get_random_target(False), self.cage.get_random_target(False), self.cage.get_random_target(False), ], self.timeout, ) class EmptyEnv(Environment): def build_environment(self, **kwargs): self.name = "Empty" def get_new_scenario(self): return None, [], self.timeout
25,286
Python
43.363158
148
0.635371
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/omni/isaac/benchmark_environments/tests/__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. #
428
Python
46.666661
76
0.808411
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/docs/CHANGELOG.md
# Changelog ## [0.4.0] - 2022-07-06 ### Added - Added Cage environment ## [0.3.0] - 2022-05-09 ### Changed - Updated all hard coded USD object values to meters ## [0.2.0] - 2022-02-10 ### Changed - updated object instantiation to use Core API ## [0.1.2] - 2021-10-22 ### Changed - use delete_prim from omni.isaac.core ## [0.1.1] - 2021-10-09 ### Changed - Folder structure reorganized ## [0.1.0] - 2021-08-10 ### Added - Initial version of Isaac Sim Benchmark Environments Extension
494
Markdown
14.967741
63
0.653846
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.benchmark_environments/docs/README.md
# Usage To enable this extension, go to the Extension Manager menu and enable omni.isaac.benchmark_environments extension.
125
Markdown
24.199995
114
0.808
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/PACKAGE-LICENSES/omni.isaac.urdf-LICENSE.md
Copyright (c) 2020, 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.
412
Markdown
57.999992
74
0.839806
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/config/extension.toml
[core] reloadable = true order = 0 [package] version = "0.5.9" category = "Simulation" title = "Isaac Sim URDF Importer" description = "URDF Importer for Isaac Sim" authors = ["NVIDIA"] repository = "" keywords = ["isaac", "urdf", "import"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" icon = "data/icon.png" writeTarget.kit = true [dependencies] "omni.kit.uiapp" = {} "omni.isaac.ui" = {} "omni.kit.window.filepicker" = {} "omni.kit.window.content_browser" = {} "omni.kit.viewport.utility" = {} "omni.kit.pip_archive" = {} # pulls in pillow "omni.physx" = {} [[python.module]] name = "omni.isaac.urdf" [[python.module]] name = "omni.isaac.urdf.tests" [[python.module]] name = "omni.isaac.urdf.scripts.samples.import_carter" [[python.module]] name = "omni.isaac.urdf.scripts.samples.import_franka" [[python.module]] name = "omni.isaac.urdf.scripts.samples.import_kaya" [[python.module]] name = "omni.isaac.urdf.scripts.samples.import_ur10" [[native.plugin]] path = "bin/*.plugin" recursive = false [[test]] # this is to catch issues where our assimp is out of sync with the one that comes with # asset importer as this can cause segfaults due to binary incompatibility. dependencies = ["omni.kit.tool.asset_importer"] stdoutFailPatterns.exclude = [ "*extension object is still alive, something holds a reference on it*", # exclude warning as failure ]
1,384
TOML
22.87931
104
0.70448
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/__init__.py
# Copyright (c) 2018-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 .scripts.extension import * from .scripts.commands import *
499
Python
40.666663
76
0.803607
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/commands.py
# Copyright (c) 2018-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 omni.kit.commands import omni.kit.utils from omni.isaac.urdf import _urdf import os from pxr import Usd from omni.client._omniclient import Result import omni.client class URDFCreateImportConfig(omni.kit.commands.Command): """ Returns an ImportConfig object that can be used while parsing and importing. Should be used with `URDFParseFile` and `URDFParseAndImportFile` commands Returns: :obj:`omni.isaac.urdf._urdf.ImportConfig`: Parsed URDF stored in an internal structure. """ def __init__(self) -> None: pass def do(self) -> _urdf.ImportConfig: return _urdf.ImportConfig() def undo(self) -> None: pass class URDFParseFile(omni.kit.commands.Command): """ This command parses a given urdf and returns a UrdfRobot object Args: arg0 (:obj:`str`): The absolute path to where the urdf file is arg1 (:obj:`omni.isaac.urdf._urdf.ImportConfig`): Import Configuration Returns: :obj:`omni.isaac.urdf._urdf.UrdfRobot`: Parsed URDF stored in an internal structure. """ def __init__(self, urdf_path: str = "", import_config: _urdf.ImportConfig = _urdf.ImportConfig()) -> None: self._root_path, self._filename = os.path.split(os.path.abspath(urdf_path)) self._import_config = import_config self._urdf_interface = _urdf.acquire_urdf_interface() pass def do(self) -> _urdf.UrdfRobot: return self._urdf_interface.parse_urdf(self._root_path, self._filename, self._import_config) def undo(self) -> None: pass class URDFParseAndImportFile(omni.kit.commands.Command): """ This command parses and imports a given urdf and returns a UrdfRobot object Args: arg0 (:obj:`str`): The absolute path to where the urdf file is arg1 (:obj:`omni.isaac.urdf._urdf.ImportConfig`): Import Configuration arg2 (:obj:`str`): destination path for robot usd. Default is "" which will load the robot in-memory on the open stage. Returns: :obj:`str`: Path to the robot on the USD stage. """ def __init__(self, urdf_path: str = "", import_config=_urdf.ImportConfig(), dest_path: str = "") -> None: self.dest_path = dest_path self._urdf_path = urdf_path self._root_path, self._filename = os.path.split(os.path.abspath(urdf_path)) self._import_config = import_config self._urdf_interface = _urdf.acquire_urdf_interface() pass def do(self) -> str: status, imported_robot = omni.kit.commands.execute( "URDFParseFile", urdf_path=self._urdf_path, import_config=self._import_config ) if self.dest_path: self.dest_path = self.dest_path.replace( "\\", "/" ) # Omni client works with both slashes cross platform, making it standard to make it easier later on result = omni.client.read_file(self.dest_path) if result[0] != Result.OK: stage = Usd.Stage.CreateNew(self.dest_path) stage.Save() return self._urdf_interface.import_robot( self._root_path, self._filename, imported_robot, self._import_config, self.dest_path ) def undo(self) -> None: pass omni.kit.commands.register_all_commands_in_module(__name__)
3,772
Python
33.614679
127
0.659332
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/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 os import omni.ext import omni.ui as ui import weakref import gc import carb import asyncio from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription from omni.isaac.ui.menu import make_menu_item_description from pxr import Usd, UsdGeom, Sdf, UsdPhysics import omni.client from omni.isaac.urdf import _urdf from omni.isaac.ui.ui_utils import ( float_builder, dropdown_builder, btn_builder, cb_builder, str_builder, get_style, setup_ui_headers, ) EXTENSION_NAME = "URDF Importer" def is_urdf_file(path: str): _, ext = os.path.splitext(path.lower()) return ext in [".urdf", ".URDF"] def on_filter_item(item) -> bool: if not item or item.is_folder: return not (item.name == "Omniverse" or item.path.startswith("omniverse:")) return is_urdf_file(item.path) def on_filter_folder(item) -> bool: if item and item.is_folder: return True else: return False class Extension(omni.ext.IExt): def on_startup(self, ext_id): self._ext_id = ext_id self._urdf_interface = _urdf.acquire_urdf_interface() self._usd_context = omni.usd.get_context() self._window = omni.ui.Window( EXTENSION_NAME, width=400, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) self._window.set_visibility_changed_fn(self._on_window) menu_items = [ make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback()) ] self._menu_items = [MenuItemDescription(name="Workflows", sub_menu=menu_items)] add_menu_items(self._menu_items, "Isaac Utils") self._file_picker = None self._models = {} result, self._config = omni.kit.commands.execute("URDFCreateImportConfig") self._filepicker = None self._last_folder = None self._content_browser = None self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) self._imported_robot = None # Set defaults self._config.set_merge_fixed_joints(False) self._config.set_convex_decomp(False) self._config.set_fix_base(True) self._config.set_import_inertia_tensor(False) self._config.set_distance_scale(1.0) self._config.set_density(0.0) self._config.set_default_drive_type(1) self._config.set_default_drive_strength(1e7) self._config.set_default_position_drive_damping(1e5) self._config.set_self_collision(False) self._config.set_up_vector(0, 0, 1) self._config.set_make_default_prim(True) self._config.set_create_physics_scene(True) def build_ui(self): with self._window.frame: with ui.VStack(spacing=5, height=0): self._build_info_ui() self._build_options_ui() self._build_import_ui() stage = self._usd_context.get_stage() if stage: if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y: self._config.set_up_vector(0, 1, 0) if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z: self._config.set_up_vector(0, 0, 1) units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage) self._models["scale"].set_value(units_per_meter) async def dock_window(): await omni.kit.app.get_app().next_update_async() def dock(space, name, location, pos=0.5): window = omni.ui.Workspace.get_window(name) if window and space: window.dock_in(space, location, pos) return window tgt = ui.Workspace.get_window("Viewport") dock(tgt, EXTENSION_NAME, omni.ui.DockPosition.LEFT, 0.33) await omni.kit.app.get_app().next_update_async() self._task = asyncio.ensure_future(dock_window()) def _build_info_ui(self): title = EXTENSION_NAME doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This utility is used to import URDF representations of robots into Isaac Sim. " overview += "URDF is an XML format for representing a robot model in ROS." overview += "\n\nPress the 'Open in IDE' button to view the source code." setup_ui_headers(self._ext_id, __file__, title, doc_link, overview) def _build_options_ui(self): frame = ui.CollapsableFrame( title="Import Options", 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, height=0): cb_builder( label="Merge Fixed Joints", tooltip="Consolidate links that are connected by fixed joints.", on_clicked_fn=lambda m, config=self._config: config.set_merge_fixed_joints(m), ) cb_builder( "Fix Base Link", tooltip="Fix the robot base robot to where it's imported in world coordinates.", default_val=True, on_clicked_fn=lambda m, config=self._config: config.set_fix_base(m), ) cb_builder( "Import Inertia Tensor", tooltip="Load inertia tensor directly from the URDF.", on_clicked_fn=lambda m, config=self._config: config.set_import_inertia_tensor(m), ) self._models["scale"] = float_builder( "Stage Units Per Meter", default_val=1.0, tooltip="Sets the scaling factor to match the units used in the URDF. Default Stage units are (cm).", ) self._models["scale"].add_value_changed_fn( lambda m, config=self._config: config.set_distance_scale(m.get_value_as_float()) ) self._models["density"] = float_builder( "Link Density", default_val=0.0, tooltip="Density value to compute mass based on link volume. Use 0.0 to automatically compute density.", ) self._models["density"].add_value_changed_fn( lambda m, config=self._config: config.set_density(m.get_value_as_float()) ) dropdown_builder( "Joint Drive Type", items=["None", "Position", "Velocity"], default_val=1, on_clicked_fn=lambda i, config=self._config: config.set_default_drive_type( 0 if i == "None" else (1 if i == "Position" else 2) ), tooltip="Default Joint drive type.", ) self._models["drive_strength"] = float_builder( "Joint Drive Strength", default_val=1e4, tooltip="Joint stiffness for position drive, or damping for velocity driven joints. Set to -1 to prevent this parameter from getting used.", ) self._models["drive_strength"].add_value_changed_fn( lambda m, config=self._config: config.set_default_drive_strength(m.get_value_as_float()) ) self._models["position_drive_damping"] = float_builder( "Joint Position Damping", default_val=1e3, tooltip="Default damping value when drive type is set to Position. Set to -1 to prevent this parameter from getting used.", ) self._models["position_drive_damping"].add_value_changed_fn( lambda m, config=self._config: config.set_default_position_drive_damping(m.get_value_as_float()) ) self._models["clean_stage"] = cb_builder( label="Clear Stage", tooltip="Clear the Stage prior to loading the URDF." ) dropdown_builder( "Normals Subdivision", items=["catmullClark", "loop", "bilinear", "none"], default_val=2, on_clicked_fn=lambda i, dict={ "catmullClark": 0, "loop": 1, "bilinear": 2, "none": 3, }, config=self._config: config.set_subdivision_scheme(dict[i]), tooltip="Mesh surface normal subdivision scheme. Use `none` to avoid overriding authored values.", ) cb_builder( "Convex Decomposition", tooltip="Decompose non-convex meshes into convex collision shapes. If false, convex hull will be used.", on_clicked_fn=lambda m, config=self._config: config.set_convex_decomp(m), ) cb_builder( "Self Collision", tooltip="Enables self collision between adjacent links.", on_clicked_fn=lambda m, config=self._config: config.set_self_collision(m), ) cb_builder( "Create Physics Scene", tooltip="Creates a default physics scene on the stage on import.", default_val=True, on_clicked_fn=lambda m, config=self._config: config.set_create_physics_scene(m), ) cb_builder( "Create Instanceable Asset", tooltip="If true, creates an instanceable version of the asset. Meshes will be saved in a separate USD file", default_val=False, on_clicked_fn=lambda m, config=self._config: config.set_make_instanceable(m), ) self._models["instanceable_usd_path"] = str_builder( "Instanceable USD Path", tooltip="USD file to store instanceable meshes in", default_val="./instanceable_meshes.usd", use_folder_picker=True, folder_dialog_title="Select Output File", folder_button_title="Select File", ) self._models["instanceable_usd_path"].add_value_changed_fn( lambda m, config=self._config: config.set_instanceable_usd_path(m.get_value_as_string()) ) def _build_import_ui(self): frame = ui.CollapsableFrame( title="Import", 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, height=0): def check_file_type(model=None): path = model.get_value_as_string() if is_urdf_file(path) and "omniverse:" not in path.lower(): self._models["import_btn"].enabled = True else: carb.log_warn(f"Invalid path to URDF: {path}") kwargs = { "label": "Input File", "default_val": "", "tooltip": "Click the Folder Icon to Set Filepath", "use_folder_picker": True, "item_filter_fn": on_filter_item, "bookmark_label": "Built In URDF Files", "bookmark_path": f"{self._extension_path}/data/urdf", "folder_dialog_title": "Select URDF File", "folder_button_title": "Select URDF", } self._models["input_file"] = str_builder(**kwargs) self._models["input_file"].add_value_changed_fn(check_file_type) kwargs = { "label": "Output Directory", "type": "stringfield", "default_val": self.get_dest_folder(), "tooltip": "Click the Folder Icon to Set Filepath", "use_folder_picker": True, } self.dest_model = str_builder(**kwargs) # btn_builder("Import URDF", text="Select and Import", on_clicked_fn=self._parse_urdf) self._models["import_btn"] = btn_builder("Import", text="Import", on_clicked_fn=self._load_robot) self._models["import_btn"].enabled = False def get_dest_folder(self): stage = omni.usd.get_context().get_stage() if stage: path = stage.GetRootLayer().identifier if not path.startswith("anon"): basepath = path[: path.rfind("/")] if path.rfind("/") < 0: basepath = path[: path.rfind("\\")] return basepath return "(same as source)" def _menu_callback(self): self._window.visible = not self._window.visible def _on_window(self, visible): if self._window.visible: self.build_ui() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="urdf importer stage event" ) else: self._events = None self._stage_event_sub = None def _on_stage_event(self, event): stage = self._usd_context.get_stage() if event.type == int(omni.usd.StageEventType.OPENED) and stage: if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y: self._config.set_up_vector(0, 1, 0) if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z: self._config.set_up_vector(0, 0, 1) units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage) self._models["scale"].set_value(units_per_meter) self.dest_model.set_value(self.get_dest_folder()) def _load_robot(self, path=None): path = self._models["input_file"].get_value_as_string() if path: dest_path = self.dest_model.get_value_as_string() base_path = path[: path.rfind("/")] basename = path[path.rfind("/") + 1 :] basename = basename[: basename.rfind(".")] if path.rfind("/") < 0: base_path = path[: path.rfind("\\")] basename = path[path.rfind("\\") + 1] if dest_path != "(same as source)": base_path = dest_path # + "/" + basename dest_path = "{}/{}/{}.usd".format(base_path, basename, basename) # counter = 1 # while result[0] == Result.OK: # dest_path = "{}/{}_{:02}.usd".format(base_path, basename, counter) # result = omni.client.read_file(dest_path) # counter +=1 # result = omni.client.read_file(dest_path) # if # stage = Usd.Stage.Open(dest_path) # else: # stage = Usd.Stage.CreateNew(dest_path) # UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=path, import_config=self._config, dest_path=dest_path ) # print("Created file, instancing it now") stage = Usd.Stage.Open(dest_path) prim_name = str(stage.GetDefaultPrim().GetName()) # print(prim_name) # stage.Save() def add_reference_to_stage(): current_stage = omni.usd.get_context().get_stage() if current_stage: prim_path = omni.usd.get_stage_next_free_path( current_stage, str(current_stage.GetDefaultPrim().GetPath()) + "/" + prim_name, False ) robot_prim = current_stage.OverridePrim(prim_path) if "anon:" in current_stage.GetRootLayer().identifier: robot_prim.GetReferences().AddReference(dest_path) else: robot_prim.GetReferences().AddReference( omni.client.make_relative_url(current_stage.GetRootLayer().identifier, dest_path) ) if self._config.create_physics_scene: UsdPhysics.Scene.Define(current_stage, Sdf.Path("/physicsScene")) async def import_with_clean_stage(): await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() add_reference_to_stage() await omni.kit.app.get_app().next_update_async() if self._models["clean_stage"].get_value_as_bool(): asyncio.ensure_future(import_with_clean_stage()) else: add_reference_to_stage() def on_shutdown(self): _urdf.release_urdf_interface(self._urdf_interface) remove_menu_items(self._menu_items, "Isaac Utils") if self._window: self._window = None gc.collect()
18,204
Python
43.511002
160
0.546968
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/__init__.py
# Copyright (c) 2018-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. #
433
Python
47.222217
76
0.808314
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/samples/common.py
# Copyright (c) 2018-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 import carb.tokens import omni from pxr import UsdGeom, PhysxSchema, UsdPhysics def set_drive_parameters(drive, target_type, target_value, stiffness=None, damping=None, max_force=None): """Enable velocity drive for a given joint""" if target_type == "position": if not drive.GetTargetPositionAttr(): drive.CreateTargetPositionAttr(target_value) else: drive.GetTargetPositionAttr().Set(target_value) elif target_type == "velocity": if not drive.GetTargetVelocityAttr(): drive.CreateTargetVelocityAttr(target_value) else: drive.GetTargetVelocityAttr().Set(target_value) if stiffness is not None: if not drive.GetStiffnessAttr(): drive.CreateStiffnessAttr(stiffness) else: drive.GetStiffnessAttr().Set(stiffness) if damping is not None: if not drive.GetDampingAttr(): drive.CreateDampingAttr(damping) else: drive.GetDampingAttr().Set(damping) if max_force is not None: if not drive.GetMaxForceAttr(): drive.CreateMaxForceAttr(max_force) else: drive.GetMaxForceAttr().Set(max_force)
1,653
Python
34.191489
105
0.69147
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/samples/import_franka.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 omni import asyncio import math import weakref import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription from omni.isaac.ui.menu import make_menu_item_description from .common import set_drive_parameters from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysxSchema from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder from omni.kit.viewport.utility.camera_state import ViewportCameraState EXTENSION_NAME = "Import Franka" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "Franka URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a Franka Panda via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = ( "This Example shows you import a URDF.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a UR10 Robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Joint Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Move to Pose", "type": "button", "text": "move", "tooltip": "Drive the Robot to a specific pose", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_franka(load_stage)) async def _load_franka(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.fix_base = True import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(1.22, -1.24, 1.13), True) camera_state.set_target_world(Gf.Vec3d(-0.96, 1.08, 0.0), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) result, plane_path = omni.kit.commands.execute( "AddGroundPlaneCommand", stage=stage, planePath="/groundPlane", axis="Z", size=1500.0, position=Gf.Vec3f(0), color=Gf.Vec3f(0.5), ) # make sure the ground plane is under root prim and not robot omni.kit.commands.execute( "MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True ) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() # Set the solver parameters on the articulation PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverPositionIterationCountAttr(64) PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverVelocityIterationCountAttr(64) self.joint_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link0/panda_joint1"), "angular") self.joint_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link1/panda_joint2"), "angular") self.joint_3 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link2/panda_joint3"), "angular") self.joint_4 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link3/panda_joint4"), "angular") self.joint_5 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link4/panda_joint5"), "angular") self.joint_6 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link5/panda_joint6"), "angular") self.joint_7 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link6/panda_joint7"), "angular") self.finger_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint1"), "linear") self.finger_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint2"), "linear") # Set the drive mode, target, stiffness, damping and max force for each joint set_drive_parameters(self.joint_1, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_2, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_3, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_4, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_5, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_6, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_7, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.finger_1, "position", 0, 1e7, 1e6) set_drive_parameters(self.finger_2, "position", 0, 1e7, 1e6) def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first # Set the drive mode, target, stiffness, damping and max force for each joint set_drive_parameters(self.joint_1, "position", math.degrees(0.012)) set_drive_parameters(self.joint_2, "position", math.degrees(-0.57)) set_drive_parameters(self.joint_3, "position", math.degrees(0)) set_drive_parameters(self.joint_4, "position", math.degrees(-2.81)) set_drive_parameters(self.joint_5, "position", math.degrees(0)) set_drive_parameters(self.joint_6, "position", math.degrees(3.037)) set_drive_parameters(self.joint_7, "position", math.degrees(0.741)) set_drive_parameters(self.finger_1, "position", 4) set_drive_parameters(self.finger_2, "position", 4)
9,399
Python
49
119
0.601021
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/samples/import_kaya.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 omni import omni.kit.commands import asyncio import math import weakref import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription from omni.isaac.ui.menu import make_menu_item_description from .common import set_drive_parameters from pxr import UsdLux, Sdf, Gf, UsdPhysics from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder from omni.kit.viewport.utility.camera_state import ViewportCameraState EXTENSION_NAME = "Import Kaya" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "Kaya URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a Kaya Robot via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This Example shows you import an NVIDIA Kaya robot via URDF.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a UR10 Robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Joint Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Spin Robot", "type": "button", "text": "move", "tooltip": "Spin the Robot in Place", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_kaya(load_stage)) async def _load_kaya(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True import_config.import_inertia_tensor = False # import_config.distance_scale = 1.0 import_config.fix_base = False import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(-1.0, 1.5, 0.5), True) camera_state.set_target_world(Gf.Vec3d(0.0, 0.0, 0.0), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) result, plane_path = omni.kit.commands.execute( "AddGroundPlaneCommand", stage=stage, planePath="/groundPlane", axis="Z", size=1500.0, position=Gf.Vec3f(0, 0, -0.25), color=Gf.Vec3f(0.5), ) # make sure the ground plane is under root prim and not robot omni.kit.commands.execute( "MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True ) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() # Make all rollers spin freely by removing extra drive API for axle in range(0, 2 + 1): for ring in range(0, 1 + 1): for roller in range(0, 4 + 1): prim_path = ( "/kaya/axle_" + str(axle) + "/roller_" + str(axle) + "_" + str(ring) + "_" + str(roller) + "_joint" ) prim = stage.GetPrimAtPath(prim_path) omni.kit.commands.execute( "UnapplyAPISchemaCommand", api=UsdPhysics.DriveAPI, prim=prim, api_prefix="drive", multiple_api_token="angular", ) def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first stage = omni.usd.get_context().get_stage() # set each axis to spin at a rate of 1 rad/s axle_0 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_0_joint"), "angular") axle_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_1_joint"), "angular") axle_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_2_joint"), "angular") set_drive_parameters(axle_0, "velocity", math.degrees(1), 0, math.radians(1e7)) set_drive_parameters(axle_1, "velocity", math.degrees(1), 0, math.radians(1e7)) set_drive_parameters(axle_2, "velocity", math.degrees(1), 0, math.radians(1e7))
8,034
Python
41.967914
148
0.538835
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/samples/import_carter.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 omni import math import omni.kit.commands import asyncio import weakref import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription from omni.isaac.ui.menu import make_menu_item_description from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder from omni.kit.viewport.utility.camera_state import ViewportCameraState from .common import set_drive_parameters from pxr import UsdLux, Sdf, Gf, UsdPhysics EXTENSION_NAME = "Import Carter" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "Carter URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a UR10 via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This Example shows how to import a URDF in Isaac Sim.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a NVIDIA Carter robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Wheel Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Move to Pose", "type": "button", "text": "move", "tooltip": "Drive the Robot to a specific pose", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_carter(load_stage)) async def _load_carter(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.fix_base = False import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/carter/urdf/carter.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(3.00, -3.50, 1.13), True) camera_state.set_target_world(Gf.Vec3d(-0.96, 1.08, -0.20), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) result, plane_path = omni.kit.commands.execute( "AddGroundPlaneCommand", stage=stage, planePath="/groundPlane", axis="Z", size=1500.0, position=Gf.Vec3f(0, 0, -0.50), color=Gf.Vec3f(0.5), ) # make sure the ground plane is under root prim and not robot omni.kit.commands.execute( "MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True ) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() # Remove drive from rear wheel and pivot prim = stage.GetPrimAtPath("/carter/chassis_link/rear_pivot") omni.kit.commands.execute( "UnapplyAPISchemaCommand", api=UsdPhysics.DriveAPI, prim=prim, api_prefix="drive", multiple_api_token="angular", ) prim = stage.GetPrimAtPath("/carter/rear_pivot_link/rear_axle") omni.kit.commands.execute( "UnapplyAPISchemaCommand", api=UsdPhysics.DriveAPI, prim=prim, api_prefix="drive", multiple_api_token="angular", ) def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first stage = omni.usd.get_context().get_stage() left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular") right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular") # Drive forward set_drive_parameters(left_wheel_drive, "velocity", math.degrees(2.5), 0, math.radians(1e8)) set_drive_parameters(right_wheel_drive, "velocity", math.degrees(2.5), 0, math.radians(1e8))
7,495
Python
40.877095
141
0.566111
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/scripts/samples/import_ur10.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 omni import asyncio import math import weakref import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription from omni.isaac.ui.menu import make_menu_item_description from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder from omni.kit.viewport.utility.camera_state import ViewportCameraState from .common import set_drive_parameters from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysxSchema EXTENSION_NAME = "Import UR10" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): """Initialize extension and UI elements""" ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "UR10 URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a UR10 via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This Example shows you import a UR10 robot arm via URDF.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a UR10 Robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Joint Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Move to Pose", "type": "button", "text": "move", "tooltip": "Drive the Robot to a specific pose", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_robot(load_stage)) async def _load_robot(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.fix_base = True import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/ur10/urdf/ur10.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(2.0, -2.0, 0.5), True) camera_state.set_target_world(Gf.Vec3d(0.0, 0.0, 0.0), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() PhysxSchema.PhysxArticulationAPI.Get(stage, "/ur10").CreateSolverPositionIterationCountAttr(64) PhysxSchema.PhysxArticulationAPI.Get(stage, "/ur10").CreateSolverVelocityIterationCountAttr(64) self.joint_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/base_link/shoulder_pan_joint"), "angular") self.joint_2 = UsdPhysics.DriveAPI.Get( stage.GetPrimAtPath("/ur10/shoulder_link/shoulder_lift_joint"), "angular" ) self.joint_3 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/upper_arm_link/elbow_joint"), "angular") self.joint_4 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/forearm_link/wrist_1_joint"), "angular") self.joint_5 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/wrist_1_link/wrist_2_joint"), "angular") self.joint_6 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/wrist_2_link/wrist_3_joint"), "angular") # Set the drive mode, target, stiffness, damping and max force for each joint set_drive_parameters(self.joint_1, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_2, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_3, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_4, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_5, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_6, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first set_drive_parameters(self.joint_1, "position", 45) set_drive_parameters(self.joint_2, "position", 45) set_drive_parameters(self.joint_3, "position", 45) set_drive_parameters(self.joint_4, "position", 45) set_drive_parameters(self.joint_5, "position", 45) set_drive_parameters(self.joint_6, "position", 45)
7,837
Python
46.216867
144
0.596019
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/tests/test_urdf.py
# Copyright (c) 2018-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. # # 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 import omni.kit.commands import os from pxr import Sdf, Gf, UsdShade, PhysicsSchemaTools, UsdGeom, UsdPhysics import pxr import asyncio import numpy as np # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class TestUrdf(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._timeline = omni.timeline.get_timeline_interface() ext_manager = omni.kit.app.get_app().get_extension_manager() ext_id = ext_manager.get_enabled_extension_id("omni.isaac.urdf") self._extension_path = ext_manager.get_extension_path(ext_id) self.dest_path = os.path.abspath(self._extension_path + "/tests_out") await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() pass # After running each test async def tearDown(self): # _urdf.release_urdf_interface(self._urdf_interface) await omni.kit.app.get_app().next_update_async() pass # Tests to make sure visual mesh names are incremented async def test_urdf_mesh_naming(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_names.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) prim = stage.GetPrimAtPath("/test_names/cube/visuals") prim_range = prim.GetChildren() # There should be a total of 6 visual meshes after import self.assertEqual(len(prim_range), 6) # basic urdf test: joints and links are imported correctly async def test_urdf_basic(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() prim = stage.GetPrimAtPath("/test_basic") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_basic/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint") self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint") self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08) fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2") self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0) self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) pass async def test_urdf_save_to_file(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") dest_path = os.path.abspath(self.dest_path + "/test_basic.usd") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() stage = pxr.Usd.Stage.Open(dest_path) prim = stage.GetPrimAtPath("/test_basic") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_basic/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint") self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint") self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08) fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2") self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0) self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3) self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) stage = None pass async def test_urdf_textured_obj(self): base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf" basename = "cube_obj" dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename) mats_path = "{}/{}/materials".format(self.dest_path, basename) omni.client.create_folder("{}/{}".format(self.dest_path, basename)) omni.client.create_folder(mats_path) urdf_path = "{}/{}.urdf".format(base_path, basename) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() result = omni.client.list(mats_path) self.assertEqual(result[0], omni.client._omniclient.Result.OK) self.assertEqual(len(result[1]), 4) # Metallic texture is unsuported by assimp on OBJ pass async def test_urdf_textured_in_memory(self): base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf" basename = "cube_obj" urdf_path = "{}/{}.urdf".format(base_path, basename) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() pass async def test_urdf_textured_dae(self): base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf" basename = "cube_dae" dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename) mats_path = "{}/{}/materials".format(self.dest_path, basename) omni.client.create_folder("{}/{}".format(self.dest_path, basename)) omni.client.create_folder(mats_path) urdf_path = "{}/{}.urdf".format(base_path, basename) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() result = omni.client.list(mats_path) self.assertEqual(result[0], omni.client._omniclient.Result.OK) self.assertEqual(len(result[1]), 1) # only albedo is supported for Collada pass async def test_urdf_overwrite_file(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") dest_path = os.path.abspath(self._extension_path + "/data/urdf/tests/tests_out/test_basic.usd") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() stage = pxr.Usd.Stage.Open(dest_path) prim = stage.GetPrimAtPath("/test_basic") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_basic/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint") self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint") self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08) fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2") self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0) self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) stage = None pass # advanced urdf test: test for all the categories of inputs that an urdf can hold async def test_urdf_advanced(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_advanced.urdf") stage = omni.usd.get_context().get_stage() # enable merging fixed joints status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True import_config.default_position_drive_damping = -1 # ignore this setting by making it -1 omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() # check if object is there prim = stage.GetPrimAtPath("/test_advanced") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # check color are imported mesh = stage.GetPrimAtPath("/test_advanced/link_1/visuals") self.assertNotEqual(mesh.GetPath(), Sdf.Path.emptyPath) mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial() shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader")) self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0, 0.8, 0), 1e-5)) # check joint properties elbowPrim = stage.GetPrimAtPath("/test_advanced/link_1/elbow_joint") self.assertNotEqual(elbowPrim.GetPath(), Sdf.Path.emptyPath) self.assertAlmostEqual(elbowPrim.GetAttribute("physxJoint:jointFriction").Get(), 0.1) self.assertAlmostEqual(elbowPrim.GetAttribute("drive:angular:physics:damping").Get(), 0.1) # check position of a link joint_pos = elbowPrim.GetAttribute("physics:localPos0").Get() self.assertTrue(Gf.IsClose(joint_pos, Gf.Vec3f(0, 0, 0.40), 1e-5)) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass # test for importing urdf where fixed joints are merged async def test_urdf_merge_joints(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_merge_joints.urdf") stage = omni.usd.get_context().get_stage() # enable merging fixed joints status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # the merged link shouldn't be there prim = stage.GetPrimAtPath("/test_merge_joints/link_2") self.assertEqual(prim.GetPath(), Sdf.Path.emptyPath) pass async def test_urdf_mtl(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) mesh = stage.GetPrimAtPath("/test_mtl/cube/visuals") self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None) mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial() shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader")) print(shader) self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5)) async def test_urdf_mtl_stl(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl_stl.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) mesh = stage.GetPrimAtPath("/test_mtl_stl/cube/visuals") self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None) mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial() shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader")) print(shader) self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5)) async def test_urdf_carter(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/carter/urdf/carter.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False status, path = omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config ) self.assertTrue(path, "/carter") # TODO add checks here async def test_urdf_franka(self): urdf_path = os.path.abspath( self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf" ) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # TODO add checks here' async def test_urdf_ur10(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/ur10/urdf/ur10.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # TODO add checks here' async def test_urdf_kaya(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # TODO add checks here async def test_missing(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_missing.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # This sample corresponds to the example in the docs, keep this and the version in the docs in sync async def test_doc_sample(self): import omni.kit.commands from pxr import UsdLux, Sdf, Gf, UsdPhysics # setting up import configuration: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.convex_decomp = False import_config.import_inertia_tensor = True import_config.fix_base = False # Get path to extension data: ext_manager = omni.kit.app.get_app().get_extension_manager() ext_id = ext_manager.get_enabled_extension_id("omni.isaac.urdf") extension_path = ext_manager.get_extension_path(ext_id) # import URDF omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=extension_path + "/data/urdf/robots/carter/urdf/carter.urdf", import_config=import_config, ) # get stage handle stage = omni.usd.get_context().get_stage() # enable physics scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) # set gravity scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) # add ground plane PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 1500, Gf.Vec3f(0, 0, -50), Gf.Vec3f(0.5)) # add lighting distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) #### #### Next Docs section #### # get handle to the Drive API for both wheels left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular") right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular") # Set the velocity drive target in degrees/second left_wheel_drive.GetTargetVelocityAttr().Set(150) right_wheel_drive.GetTargetVelocityAttr().Set(150) # Set the drive damping, which controls the strength of the velocity drive left_wheel_drive.GetDampingAttr().Set(15000) right_wheel_drive.GetDampingAttr().Set(15000) # Set the drive stiffness, which controls the strength of the position drive # In this case because we want to do velocity control this should be set to zero left_wheel_drive.GetStiffnessAttr().Set(0) right_wheel_drive.GetStiffnessAttr().Set(0) # Make sure that a urdf with more than 63 links imports async def test_64(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_large.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/test_large") self.assertTrue(prim) # basic urdf test: joints and links are imported correctly async def test_urdf_floating(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_floating.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() prim = stage.GetPrimAtPath("/test_floating") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_floating/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) link_1 = stage.GetPrimAtPath("/test_floating/link_1") self.assertNotEqual(link_1.GetPath(), Sdf.Path.emptyPath) link_1_trans = np.array(omni.usd.utils.get_world_transform_matrix(link_1).ExtractTranslation()) self.assertAlmostEqual(np.linalg.norm(link_1_trans - np.array([0, 0, 0.45])), 0, delta=0.03) floating_link = stage.GetPrimAtPath("/test_floating/floating_link") self.assertNotEqual(floating_link.GetPath(), Sdf.Path.emptyPath) floating_link_trans = np.array(omni.usd.utils.get_world_transform_matrix(floating_link).ExtractTranslation()) self.assertAlmostEqual(np.linalg.norm(floating_link_trans - np.array([0, 0, 1.450])), 0, delta=0.03) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass async def test_urdf_scale(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.distance_scale = 1.0 omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) pass async def test_urdf_drive_none(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") from omni.isaac.urdf._urdf import UrdfJointTargetType import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() self.assertFalse(stage.GetPrimAtPath("/test_basic/root_joint").HasAPI(UsdPhysics.DriveAPI)) self.assertTrue(stage.GetPrimAtPath("/test_basic/link_1/elbow_joint").HasAPI(UsdPhysics.DriveAPI)) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass async def test_urdf_usd(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_usd.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") from omni.isaac.urdf._urdf import UrdfJointTargetType import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_0/Cylinder"), Sdf.Path.emptyPath) self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_1/Torus"), Sdf.Path.emptyPath) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass # test negative joint limits async def test_urdf_limits(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_limits.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() # ensure the import completed. prim = stage.GetPrimAtPath("/test_limits") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # ensure the joint limits are set on the elbow elbowJoint = stage.GetPrimAtPath("/test_limits/link_1/elbow_joint") self.assertNotEqual(elbowJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(elbowJoint.GetTypeName(), "PhysicsRevoluteJoint") self.assertTrue(elbowJoint.HasAPI(UsdPhysics.DriveAPI)) # ensure the joint limits are set on the wrist wristJoint = stage.GetPrimAtPath("/test_limits/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") self.assertTrue(wristJoint.HasAPI(UsdPhysics.DriveAPI)) # ensure the joint limits are set on the finger1 finger1Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_1_joint") self.assertNotEqual(finger1Joint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(finger1Joint.GetTypeName(), "PhysicsPrismaticJoint") self.assertTrue(finger1Joint.HasAPI(UsdPhysics.DriveAPI)) # ensure the joint limits are set on the finger2 finger2Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_2_joint") self.assertNotEqual(finger2Joint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(finger2Joint.GetTypeName(), "PhysicsPrismaticJoint") self.assertTrue(finger2Joint.HasAPI(UsdPhysics.DriveAPI)) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass
27,453
Python
46.171821
142
0.679671
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/omni/isaac/urdf/tests/__init__.py
# Copyright (c) 2018-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 .test_urdf import *
459
Python
40.818178
76
0.801743
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/docs/CHANGELOG.md
# Changelog ## [0.5.9] - 2023-02-28 ### Fixed - Appearance of carb warnings when setting the joint damping and stiffness to 0 for `NONE` drive type ## [0.5.8] - 2023-02-22 ### Fixed - removed max joint effort scaling by 60 during import - removed custom collision api when the shape is a cylinder ## [0.5.7] - 2023-02-17 ### Added - Unit test for joint limits. - URDF data file for joint limit unit test (test_limits.urdf) ## [0.5.6] - 2023-02-14 ### Fixed - Imported negative URDF effort and velocity joint constraints set the physics constraint value to infinity. ## [0.5.5] - 2023-01-06 ### Fixed - onclick_fn warning when creating UI ## [0.5.4] - 2022-10-13 ### Fixed - Fixes materials on instanceable imports ## [0.5.3] - 2022-10-13 ### Fixed - Added Test for import stl with custom material ## [0.5.2] - 2022-09-07 ### Fixed - Fixes for kit 103.5 ## [0.5.1] - 2022-01-02 ### Changed - Use omni.kit.viewport.utility when setting camera ## [0.5.0] - 2022-08-30 ### Changed - Remove direct legacy viewport calls ## [0.4.1] - 2022-08-30 ### Changed - Modified default gains in URDF -> USD converter to match gains for Franka and UR10 robots ## [0.4.0] - 2022-08-09 ### Added - Cobotta 900 urdf data files ## [0.3.1] - 2022-08-08 ### Fixed - Missing argument in example docstring ## [0.3.0] - 2022-07-09 ### Added - Add instanceable option to importer ## [0.2.2] - 2022-06-02 ### Changed - Fix title for file picker ## [0.2.1] - 2022-05-23 ### Changed - Fix units for samples ## [0.2.0] - 2022-05-17 ### Changed - Add joint values API ## [0.1.16] - 2022-04-19 ### Changed - Add Texture import compatibility for Windows. ## [0.1.16] - 2022-02-08 ### Changed - Revamped UI ## [0.1.15] - 2021-12-20 ### Changed - Fixed bug where missing mesh on part with urdf material assigned would crash on material binding in a non-existing prim. ## [0.1.14] - 2021-12-20 ### Changed - Fix bug where material was indexed by name and removing false duplicates. - Add Normal subdivision group import parameter. ## [0.1.13] - 2021-12-10 ### Changed - Texture support for OBJ and Collada assets. - Remove bug where an invalid link on a joint would stop importing the remainder of the urdf. raises an error message instead. ## [0.1.12] - 2021-12-03 ### Changed - Default to save Imported assets on a new USD and reference it on open stage. - Change base robot prim to also use orientOP instead of rotateOP - Change behavior where any stage event (e.g selection changed) was resetting some options on the UI ## [0.1.11] - 2021-11-29 ### Changed - Use double precision for xform ops to match isaac sim defaults ## [0.1.10] - 2021-11-04 ### Changed - create physics scene is false for import config - create physics scene will not create a scene if one exists - set default prim is false for import config ## [0.1.9] - 2021-10-25 ### Added - Support to specify usd paths for urdf meshes. ### Changed - distance_scale sets the stage to the same units for consistency - None drive mode still applies DriveAPI, but keeps the stiffness/damping at zero - rootJoint prim is renamed to root_joint for consistency with other joint names. ### Fixed - warnings when setting attributes as double when they should have been float ## [0.1.8] - 2021-10-18 ### Added - Floating joints are ignored but place any child links at the correct location. ### Fixed - Crash when urdf contained a floating joint ## [0.1.7] - 2021-09-23 ### Added - Default position drive damping to UI ### Fixed - Default config parameters are now respected ## [0.1.6] - 2021-08-31 ### Changed - Updated to New UI - Spheres and Cubes are treated as shapes - Cylinders are by default imported with custom geometry enabled - Joint drives are default force instead of acceleration ### Fixed - Meshes were not imported correctly, fixed subdivision scheme setting ### Removed - Parsing URDF is not a separate step with its own UI ## [0.1.5] - 2021-07-30 ### Fixed - Zero joint velocity issue - Artifact when dragging URDF file due to transform matrix ## [0.1.4] - 2021-06-09 ### Added - Fixed bugs with default density ## [0.1.3] - 2021-05-26 ### Added - Fixed bugs with import units - Streamlined UI and fixed missing elements - Fixed issues with creating new stage on import ## [0.1.2] - 2020-12-11 ### Added - Unit tests to extension - Add test urdf files - Fix unit issues with samples - Fix unit conversion issue with import ## [0.1.1] - 2020-12-03 ### Added - Sample URDF files for carter, franka ur10 and kaya ## [0.1.0] - 2020-12-03 ### Added - Initial version of URDF importer extension
4,600
Markdown
21.334951
126
0.697174
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/docs/README.md
# Usage To enable this extension, go to the Extension Manager menu and enable omni.isaac.urdf extension.
107
Markdown
20.599996
96
0.785047
swadaskar/Isaac_Sim_Folder/exts/omni.isaac.urdf/docs/index.rst
URDF Import Extension [omni.isaac.urdf] ####################################### URDF Import Commands ==================== The following commands can be used to simplify the import process. Below is a sample demonstrating how to import the Carter URDF included with this extension .. code-block:: python :linenos: import omni.kit.commands from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysicsSchemaTools # setting up import configuration: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.convex_decomp = False import_config.import_inertia_tensor = True import_config.fix_base = False # Get path to extension data: ext_manager = omni.kit.app.get_app().get_extension_manager() ext_id = ext_manager.get_enabled_extension_id("omni.isaac.urdf") extension_path = ext_manager.get_extension_path(ext_id) # import URDF omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=extension_path + "/data/urdf/robots/carter/urdf/carter.urdf", import_config=import_config, ) # get stage handle stage = omni.usd.get_context().get_stage() # enable physics scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) # set gravity scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) # add ground plane PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 1500, Gf.Vec3f(0, 0, -50), Gf.Vec3f(0.5)) # add lighting distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) .. automodule:: omni.isaac.urdf.scripts.commands :members: :undoc-members: :exclude-members: do, undo .. automodule:: omni.isaac.urdf._urdf .. autoclass:: omni.isaac.urdf._urdf.Urdf :members: :undoc-members: :no-show-inheritance: .. autoclass:: omni.isaac.urdf._urdf.ImportConfig :members: :undoc-members: :no-show-inheritance:
2,088
reStructuredText
30.651515
113
0.681034
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/isaac_tutorials/scripts/ros2_publisher.py
#!/usr/bin/env python3 # Copyright (c) 2020-2022, 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 rclpy from rclpy.node import Node from sensor_msgs.msg import JointState import numpy as np import time class TestROS2Bridge(Node): def __init__(self): super().__init__("test_ros2bridge") # Create the publisher. This publisher will publish a JointState message to the /joint_command topic. self.publisher_ = self.create_publisher(JointState, "joint_command", 10) # Create a JointState message self.joint_state = JointState() self.joint_state.name = [ "panda_joint1", "panda_joint2", "panda_joint3", "panda_joint4", "panda_joint5", "panda_joint6", "panda_joint7", "panda_finger_joint1", "panda_finger_joint2", ] num_joints = len(self.joint_state.name) # make sure kit's editor is playing for receiving messages self.joint_state.position = np.array([0.0] * num_joints, dtype=np.float64).tolist() self.default_joints = [0.0, -1.16, -0.0, -2.3, -0.0, 1.6, 1.1, 0.4, 0.4] # limiting the movements to a smaller range (this is not the range of the robot, just the range of the movement self.max_joints = np.array(self.default_joints) + 0.5 self.min_joints = np.array(self.default_joints) - 0.5 # position control the robot to wiggle around each joint self.time_start = time.time() timer_period = 0.05 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) def timer_callback(self): self.joint_state.header.stamp = self.get_clock().now().to_msg() joint_position = ( np.sin(time.time() - self.time_start) * (self.max_joints - self.min_joints) * 0.5 + self.default_joints ) self.joint_state.position = joint_position.tolist() # Publish the message to the topic self.publisher_.publish(self.joint_state) def main(args=None): rclpy.init(args=args) ros2_publisher = TestROS2Bridge() rclpy.spin(ros2_publisher) # Destroy the node explicitly ros2_publisher.destroy_node() rclpy.shutdown() if __name__ == "__main__": main()
2,662
Python
31.084337
119
0.644252
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/carter_navigation/launch/carter_navigation.launch.py
## Copyright (c) 2022, 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 ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node def generate_launch_description(): use_sim_time = LaunchConfiguration("use_sim_time", default="True") map_dir = LaunchConfiguration( "map", default=os.path.join( get_package_share_directory("carter_navigation"), "maps", "carter_warehouse_navigation.yaml" ), ) param_dir = LaunchConfiguration( "params_file", default=os.path.join( get_package_share_directory("carter_navigation"), "params", "carter_navigation_params.yaml" ), ) nav2_bringup_launch_dir = os.path.join(get_package_share_directory("nav2_bringup"), "launch") rviz_config_dir = os.path.join(get_package_share_directory("carter_navigation"), "rviz2", "carter_navigation.rviz") return LaunchDescription( [ DeclareLaunchArgument("map", default_value=map_dir, description="Full path to map file to load"), DeclareLaunchArgument( "params_file", default_value=param_dir, description="Full path to param file to load" ), DeclareLaunchArgument( "use_sim_time", default_value="true", description="Use simulation (Omniverse Isaac Sim) clock if true" ), IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(nav2_bringup_launch_dir, "rviz_launch.py")), launch_arguments={"namespace": "", "use_namespace": "False", "rviz_config": rviz_config_dir}.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource([nav2_bringup_launch_dir, "/bringup_launch.py"]), launch_arguments={"map": map_dir, "use_sim_time": use_sim_time, "params_file": param_dir}.items(), ), ] )
2,582
Python
42.77966
119
0.684741
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/carter_navigation/launch/carter_navigation_individual.launch.py
## Copyright (c) 2022, 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 ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument, ExecuteProcess, IncludeLaunchDescription from launch.conditions import IfCondition from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import LaunchConfiguration, PythonExpression from launch_ros.actions import Node def generate_launch_description(): # Get the launch directory nav2_launch_dir = os.path.join(get_package_share_directory("nav2_bringup"), "launch") # Create the launch configuration variables slam = LaunchConfiguration("slam") namespace = LaunchConfiguration("namespace") use_namespace = LaunchConfiguration("use_namespace") map_yaml_file = LaunchConfiguration("map") use_sim_time = LaunchConfiguration("use_sim_time") params_file = LaunchConfiguration("params_file") default_bt_xml_filename = LaunchConfiguration("default_bt_xml_filename") autostart = LaunchConfiguration("autostart") # Declare the launch arguments declare_namespace_cmd = DeclareLaunchArgument("namespace", default_value="", description="Top-level namespace") declare_use_namespace_cmd = DeclareLaunchArgument( "use_namespace", default_value="false", description="Whether to apply a namespace to the navigation stack" ) declare_slam_cmd = DeclareLaunchArgument("slam", default_value="False", description="Whether run a SLAM") declare_map_yaml_cmd = DeclareLaunchArgument( "map", default_value=os.path.join(nav2_launch_dir, "maps", "turtlebot3_world.yaml"), description="Full path to map file to load", ) declare_use_sim_time_cmd = DeclareLaunchArgument( "use_sim_time", default_value="True", description="Use simulation (Isaac Sim) clock if true" ) declare_params_file_cmd = DeclareLaunchArgument( "params_file", default_value=os.path.join(nav2_launch_dir, "params", "nav2_params.yaml"), description="Full path to the ROS2 parameters file to use for all launched nodes", ) declare_bt_xml_cmd = DeclareLaunchArgument( "default_bt_xml_filename", default_value=os.path.join( get_package_share_directory("nav2_bt_navigator"), "behavior_trees", "navigate_w_replanning_and_recovery.xml" ), description="Full path to the behavior tree xml file to use", ) declare_autostart_cmd = DeclareLaunchArgument( "autostart", default_value="true", description="Automatically startup the nav2 stack" ) bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(nav2_launch_dir, "bringup_launch.py")), launch_arguments={ "namespace": namespace, "use_namespace": use_namespace, "slam": slam, "map": map_yaml_file, "use_sim_time": use_sim_time, "params_file": params_file, "default_bt_xml_filename": default_bt_xml_filename, "autostart": autostart, }.items(), ) # Create the launch description and populate ld = LaunchDescription() # Declare the launch options ld.add_action(declare_namespace_cmd) ld.add_action(declare_use_namespace_cmd) ld.add_action(declare_slam_cmd) ld.add_action(declare_map_yaml_cmd) ld.add_action(declare_use_sim_time_cmd) ld.add_action(declare_params_file_cmd) ld.add_action(declare_bt_xml_cmd) ld.add_action(declare_autostart_cmd) ld.add_action(bringup_cmd) return ld
4,044
Python
39.049505
120
0.710435
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/carter_navigation/launch/multiple_robot_carter_navigation_hospital.launch.py
## Copyright (c) 2022, 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. """ Example for spawing multiple robots in Gazebo. This is an example on how to create a launch file for spawning multiple robots into Gazebo and launch multiple instances of the navigation stack, each controlling one robot. The robots co-exist on a shared environment and are controlled by independent nav stacks """ import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument, ExecuteProcess, GroupAction, IncludeLaunchDescription, LogInfo from launch.conditions import IfCondition from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import LaunchConfiguration, TextSubstitution def generate_launch_description(): # Get the launch and rviz directories carter_nav2_bringup_dir = get_package_share_directory("carter_navigation") nav2_bringup_dir = get_package_share_directory("nav2_bringup") nav2_bringup_launch_dir = os.path.join(nav2_bringup_dir, "launch") rviz_config_dir = os.path.join(carter_nav2_bringup_dir, "rviz2", "carter_navigation_namespaced.rviz") # Names and poses of the robots robots = [{"name": "carter1"}, {"name": "carter2"}, {"name": "carter3"}] # Common settings ENV_MAP_FILE = "carter_hospital_navigation.yaml" use_sim_time = LaunchConfiguration("use_sim_time", default="True") map_yaml_file = LaunchConfiguration("map") default_bt_xml_filename = LaunchConfiguration("default_bt_xml_filename") autostart = LaunchConfiguration("autostart") rviz_config_file = LaunchConfiguration("rviz_config") use_rviz = LaunchConfiguration("use_rviz") log_settings = LaunchConfiguration("log_settings", default="true") # Declare the launch arguments declare_map_yaml_cmd = DeclareLaunchArgument( "map", default_value=os.path.join(carter_nav2_bringup_dir, "maps", ENV_MAP_FILE), description="Full path to map file to load", ) declare_robot1_params_file_cmd = DeclareLaunchArgument( "carter1_params_file", default_value=os.path.join( carter_nav2_bringup_dir, "params", "hospital", "multi_robot_carter_navigation_params_1.yaml" ), description="Full path to the ROS2 parameters file to use for robot1 launched nodes", ) declare_robot2_params_file_cmd = DeclareLaunchArgument( "carter2_params_file", default_value=os.path.join( carter_nav2_bringup_dir, "params", "hospital", "multi_robot_carter_navigation_params_2.yaml" ), description="Full path to the ROS2 parameters file to use for robot2 launched nodes", ) declare_robot3_params_file_cmd = DeclareLaunchArgument( "carter3_params_file", default_value=os.path.join( carter_nav2_bringup_dir, "params", "hospital", "multi_robot_carter_navigation_params_3.yaml" ), description="Full path to the ROS2 parameters file to use for robot3 launched nodes", ) declare_bt_xml_cmd = DeclareLaunchArgument( "default_bt_xml_filename", default_value=os.path.join( get_package_share_directory("nav2_bt_navigator"), "behavior_trees", "navigate_w_replanning_and_recovery.xml" ), description="Full path to the behavior tree xml file to use", ) declare_autostart_cmd = DeclareLaunchArgument( "autostart", default_value="True", description="Automatically startup the stacks" ) declare_rviz_config_file_cmd = DeclareLaunchArgument( "rviz_config", default_value=rviz_config_dir, description="Full path to the RVIZ config file to use." ) declare_use_rviz_cmd = DeclareLaunchArgument("use_rviz", default_value="True", description="Whether to start RVIZ") # Define commands for launching the navigation instances nav_instances_cmds = [] for robot in robots: params_file = LaunchConfiguration(robot["name"] + "_params_file") group = GroupAction( [ IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(nav2_bringup_launch_dir, "rviz_launch.py")), condition=IfCondition(use_rviz), launch_arguments={ "namespace": TextSubstitution(text=robot["name"]), "use_namespace": "True", "rviz_config": rviz_config_file, }.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource( os.path.join(carter_nav2_bringup_dir, "launch", "carter_navigation_individual.launch.py") ), launch_arguments={ "namespace": robot["name"], "use_namespace": "True", "map": map_yaml_file, "use_sim_time": use_sim_time, "params_file": params_file, "default_bt_xml_filename": default_bt_xml_filename, "autostart": autostart, "use_rviz": "False", "use_simulator": "False", "headless": "False", }.items(), ), LogInfo(condition=IfCondition(log_settings), msg=["Launching ", robot["name"]]), LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " map yaml: ", map_yaml_file]), LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " params yaml: ", params_file]), LogInfo( condition=IfCondition(log_settings), msg=[robot["name"], " behavior tree xml: ", default_bt_xml_filename], ), LogInfo( condition=IfCondition(log_settings), msg=[robot["name"], " rviz config file: ", rviz_config_file] ), LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " autostart: ", autostart]), ] ) nav_instances_cmds.append(group) # Create the launch description and populate ld = LaunchDescription() # Declare the launch options ld.add_action(declare_map_yaml_cmd) ld.add_action(declare_robot1_params_file_cmd) ld.add_action(declare_robot2_params_file_cmd) ld.add_action(declare_robot3_params_file_cmd) ld.add_action(declare_bt_xml_cmd) ld.add_action(declare_use_rviz_cmd) ld.add_action(declare_autostart_cmd) ld.add_action(declare_rviz_config_file_cmd) for simulation_instance_cmd in nav_instances_cmds: ld.add_action(simulation_instance_cmd) return ld
7,216
Python
42.215569
120
0.640244
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/carter_navigation/launch/multiple_robot_carter_navigation_office.launch.py
## Copyright (c) 2022, 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. """ Example for spawing multiple robots in Gazebo. This is an example on how to create a launch file for spawning multiple robots into Gazebo and launch multiple instances of the navigation stack, each controlling one robot. The robots co-exist on a shared environment and are controlled by independent nav stacks """ import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument, ExecuteProcess, GroupAction, IncludeLaunchDescription, LogInfo from launch.conditions import IfCondition from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import LaunchConfiguration, TextSubstitution def generate_launch_description(): # Get the launch and rviz directories carter_nav2_bringup_dir = get_package_share_directory("carter_navigation") nav2_bringup_dir = get_package_share_directory("nav2_bringup") nav2_bringup_launch_dir = os.path.join(nav2_bringup_dir, "launch") rviz_config_dir = os.path.join(carter_nav2_bringup_dir, "rviz2", "carter_navigation_namespaced.rviz") # Names and poses of the robots robots = [{"name": "carter1"}, {"name": "carter2"}, {"name": "carter3"}] # Common settings ENV_MAP_FILE = "carter_office_navigation.yaml" use_sim_time = LaunchConfiguration("use_sim_time", default="True") map_yaml_file = LaunchConfiguration("map") default_bt_xml_filename = LaunchConfiguration("default_bt_xml_filename") autostart = LaunchConfiguration("autostart") rviz_config_file = LaunchConfiguration("rviz_config") use_rviz = LaunchConfiguration("use_rviz") log_settings = LaunchConfiguration("log_settings", default="true") # Declare the launch arguments declare_map_yaml_cmd = DeclareLaunchArgument( "map", default_value=os.path.join(carter_nav2_bringup_dir, "maps", ENV_MAP_FILE), description="Full path to map file to load", ) declare_robot1_params_file_cmd = DeclareLaunchArgument( "carter1_params_file", default_value=os.path.join( carter_nav2_bringup_dir, "params", "office", "multi_robot_carter_navigation_params_1.yaml" ), description="Full path to the ROS2 parameters file to use for robot1 launched nodes", ) declare_robot2_params_file_cmd = DeclareLaunchArgument( "carter2_params_file", default_value=os.path.join( carter_nav2_bringup_dir, "params", "office", "multi_robot_carter_navigation_params_2.yaml" ), description="Full path to the ROS2 parameters file to use for robot2 launched nodes", ) declare_robot3_params_file_cmd = DeclareLaunchArgument( "carter3_params_file", default_value=os.path.join( carter_nav2_bringup_dir, "params", "office", "multi_robot_carter_navigation_params_3.yaml" ), description="Full path to the ROS2 parameters file to use for robot3 launched nodes", ) declare_bt_xml_cmd = DeclareLaunchArgument( "default_bt_xml_filename", default_value=os.path.join( get_package_share_directory("nav2_bt_navigator"), "behavior_trees", "navigate_w_replanning_and_recovery.xml" ), description="Full path to the behavior tree xml file to use", ) declare_autostart_cmd = DeclareLaunchArgument( "autostart", default_value="True", description="Automatically startup the stacks" ) declare_rviz_config_file_cmd = DeclareLaunchArgument( "rviz_config", default_value=rviz_config_dir, description="Full path to the RVIZ config file to use." ) declare_use_rviz_cmd = DeclareLaunchArgument("use_rviz", default_value="True", description="Whether to start RVIZ") # Define commands for launching the navigation instances nav_instances_cmds = [] for robot in robots: params_file = LaunchConfiguration(robot["name"] + "_params_file") group = GroupAction( [ IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(nav2_bringup_launch_dir, "rviz_launch.py")), condition=IfCondition(use_rviz), launch_arguments={ "namespace": TextSubstitution(text=robot["name"]), "use_namespace": "True", "rviz_config": rviz_config_file, }.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource( os.path.join(carter_nav2_bringup_dir, "launch", "carter_navigation_individual.launch.py") ), launch_arguments={ "namespace": robot["name"], "use_namespace": "True", "map": map_yaml_file, "use_sim_time": use_sim_time, "params_file": params_file, "default_bt_xml_filename": default_bt_xml_filename, "autostart": autostart, "use_rviz": "False", "use_simulator": "False", "headless": "False", }.items(), ), LogInfo(condition=IfCondition(log_settings), msg=["Launching ", robot["name"]]), LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " map yaml: ", map_yaml_file]), LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " params yaml: ", params_file]), LogInfo( condition=IfCondition(log_settings), msg=[robot["name"], " behavior tree xml: ", default_bt_xml_filename], ), LogInfo( condition=IfCondition(log_settings), msg=[robot["name"], " rviz config file: ", rviz_config_file] ), LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " autostart: ", autostart]), ] ) nav_instances_cmds.append(group) # Create the launch description and populate ld = LaunchDescription() # Declare the launch options ld.add_action(declare_map_yaml_cmd) ld.add_action(declare_robot1_params_file_cmd) ld.add_action(declare_robot2_params_file_cmd) ld.add_action(declare_robot3_params_file_cmd) ld.add_action(declare_bt_xml_cmd) ld.add_action(declare_use_rviz_cmd) ld.add_action(declare_autostart_cmd) ld.add_action(declare_rviz_config_file_cmd) for simulation_instance_cmd in nav_instances_cmds: ld.add_action(simulation_instance_cmd) return ld
7,208
Python
42.167664
120
0.639845
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/carter_navigation/maps/carter_office_navigation.yaml
image: carter_office_navigation.png resolution: 0.05 origin: [-29.975, -39.975, 0.0000] negate: 0 occupied_thresh: 0.65 free_thresh: 0.196
139
YAML
18.999997
35
0.733813
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/carter_navigation/maps/carter_hospital_navigation.yaml
image: carter_hospital_navigation.png resolution: 0.05 origin: [-49.625, -4.675, 0.0000] negate: 0 occupied_thresh: 0.65 free_thresh: 0.196
140
YAML
19.142854
37
0.735714
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/carter_navigation/maps/carter_warehouse_navigation.yaml
image: carter_warehouse_navigation.png resolution: 0.05 origin: [-11.975, -17.975, 0.0000] negate: 0 occupied_thresh: 0.65 free_thresh: 0.196
142
YAML
19.428569
38
0.739437
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/setup.py
from setuptools import setup from glob import glob import os package_name = "isaac_ros_navigation_goal" setup( name=package_name, version="0.0.1", packages=[package_name, package_name + "/goal_generators"], data_files=[ ("share/ament_index/resource_index/packages", ["resource/" + package_name]), ("share/" + package_name, ["package.xml"]), (os.path.join("share", package_name, "launch"), glob("launch/*.launch.py")), ("share/" + package_name + "/assets", glob("assets/*")), ], install_requires=["setuptools"], zip_safe=True, maintainer="isaac sim", maintainer_email="[email protected]", description="Package to set goals for navigation stack.", license="NVIDIA Isaac ROS Software License", tests_require=["pytest"], entry_points={"console_scripts": ["SetNavigationGoal = isaac_ros_navigation_goal.set_goal:main"]}, )
906
Python
33.884614
102
0.651214
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/test/test_flake8.py
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_flake8.main import main_with_errors import pytest @pytest.mark.flake8 @pytest.mark.linter def test_flake8(): rc, errors = main_with_errors(argv=[]) assert rc == 0, "Found %d code style errors / warnings:\n" % len(errors) + "\n".join(errors)
864
Python
35.041665
96
0.741898
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/test/test_pep257.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_pep257.main import main import pytest @pytest.mark.linter @pytest.mark.pep257 def test_pep257(): rc = main(argv=[".", "test"]) assert rc == 0, "Found code style errors / warnings"
803
Python
32.499999
74
0.743462
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/launch/isaac_ros_navigation_goal.launch.py
# Copyright (c) 2022, 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 ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node def generate_launch_description(): map_yaml_file = LaunchConfiguration( "map_yaml_path", default=os.path.join( get_package_share_directory("isaac_ros_navigation_goal"), "assets", "carter_warehouse_navigation.yaml" ), ) goal_text_file = LaunchConfiguration( "goal_text_file_path", default=os.path.join(get_package_share_directory("isaac_ros_navigation_goal"), "assets", "goals.txt"), ) navigation_goal_node = Node( name="set_navigation_goal", package="isaac_ros_navigation_goal", executable="SetNavigationGoal", parameters=[ { "map_yaml_path": map_yaml_file, "iteration_count": 3, "goal_generator_type": "RandomGoalGenerator", "action_server_name": "navigate_to_pose", "obstacle_search_distance_in_meters": 0.2, "goal_text_file_path": goal_text_file, "initial_pose": [-6.4, -1.04, 0.0, 0.0, 0.0, 0.99, 0.02], } ], output="screen", ) return LaunchDescription([navigation_goal_node])
1,782
Python
35.387754
114
0.654882
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/obstacle_map.py
import numpy as np import yaml import os import math from PIL import Image class GridMap: def __init__(self, yaml_file_path): self.__get_meta_from_yaml(yaml_file_path) self.__get_raw_map() self.__add_max_range_to_meta() # print(self.__map_meta) def __get_meta_from_yaml(self, yaml_file_path): """ Reads map meta from the yaml file. Parameters ---------- yaml_file_path: path of the yaml file. """ with open(yaml_file_path, "r") as f: file_content = f.read() self.__map_meta = yaml.safe_load(file_content) self.__map_meta["image"] = os.path.join(os.path.dirname(yaml_file_path), self.__map_meta["image"]) def __get_raw_map(self): """ Reads the map image and generates the grid map.\n Grid map is a 2D boolean matrix where True=>occupied space & False=>Free space. """ img = Image.open(self.__map_meta.get("image")) img = np.array(img) # Anything greater than free_thresh is considered as occupied if self.__map_meta["negate"]: res = np.where((img / 255)[:, :, 0] > self.__map_meta["free_thresh"]) else: res = np.where(((255 - img) / 255)[:, :, 0] > self.__map_meta["free_thresh"]) self.__grid_map = np.zeros(shape=(img.shape[:2]), dtype=bool) for i in range(res[0].shape[0]): self.__grid_map[res[0][i], res[1][i]] = 1 def __add_max_range_to_meta(self): """ Calculates and adds the max value of pose in x & y direction to the meta. """ max_x = self.__grid_map.shape[1] * self.__map_meta["resolution"] + self.__map_meta["origin"][0] max_y = self.__grid_map.shape[0] * self.__map_meta["resolution"] + self.__map_meta["origin"][1] self.__map_meta["max_x"] = round(max_x, 2) self.__map_meta["max_y"] = round(max_y, 2) def __pad_obstacles(self, distance): pass def get_range(self): """ Returns the bounds of pose values in x & y direction.\n Returns ------- [List]:\n Where list[0][0]: min value in x direction list[0][1]: max value in x direction list[1][0]: min value in y direction list[1][1]: max value in y direction """ return [ [self.__map_meta["origin"][0], self.__map_meta["max_x"]], [self.__map_meta["origin"][1], self.__map_meta["max_y"]], ] def __transform_to_image_coordinates(self, point): """ Transforms a pose in meters to image pixel coordinates. Parameters ---------- Point: A point as list. where list[0]=>pose.x and list[1]=pose.y Returns ------- [Tuple]: tuple[0]=>pixel value in x direction. i.e column index. tuple[1]=> pixel vlaue in y direction. i.e row index. """ p_x, p_y = point i_x = math.floor((p_x - self.__map_meta["origin"][0]) / self.__map_meta["resolution"]) i_y = math.floor((p_y - self.__map_meta["origin"][1]) / self.__map_meta["resolution"]) # because origin in yaml is at bottom left of image i_y = self.__grid_map.shape[0] - i_y return i_x, i_y def __transform_distance_to_pixels(self, distance): """ Converts the distance in meters to number of pixels based on the resolution. Parameters ---------- distance: value in meters Returns ------- [Integer]: number of pixel which represent the same distance. """ return math.ceil(distance / self.__map_meta["resolution"]) def __is_obstacle_in_distance(self, img_point, distance): """ Checks if any obstacle is in vicinity of the given image point. Parameters ---------- img_point: pixel values of the point distance: distnace in pixels in which there shouldn't be any obstacle. Returns ------- [Bool]: True if any obstacle found else False. """ # need to make sure that patch xmin & ymin are >=0, # because of python's negative indexing capability row_start_idx = 0 if img_point[1] - distance < 0 else img_point[1] - distance col_start_idx = 0 if img_point[0] - distance < 0 else img_point[0] - distance # image point acts as the center of the square, where each side of square is of size # 2xdistance patch = self.__grid_map[row_start_idx : img_point[1] + distance, col_start_idx : img_point[0] + distance] obstacles = np.where(patch == True) return len(obstacles[0]) > 0 def is_valid_pose(self, point, distance=0.2): """ Checks if a given pose is "distance" away from a obstacle. Parameters ---------- point: pose in 2D space. where point[0]=pose.x and point[1]=pose.y distance: distance in meters. Returns ------- [Bool]: True if pose is valid else False """ assert len(point) == 2 img_point = self.__transform_to_image_coordinates(point) img_pixel_distance = self.__transform_distance_to_pixels(distance) # Pose is not valid if there is obstacle in the vicinity return not self.__is_obstacle_in_distance(img_point, img_pixel_distance)
5,443
Python
33.455696
113
0.553188
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/set_goal.py
import rclpy from rclpy.action import ActionClient from rclpy.node import Node from nav2_msgs.action import NavigateToPose from .obstacle_map import GridMap from .goal_generators import RandomGoalGenerator, GoalReader import sys from geometry_msgs.msg import PoseWithCovarianceStamped import time class SetNavigationGoal(Node): def __init__(self): super().__init__("set_navigation_goal") self.declare_parameters( namespace="", parameters=[ ("iteration_count", 1), ("goal_generator_type", "RandomGoalGenerator"), ("action_server_name", "navigate_to_pose"), ("obstacle_search_distance_in_meters", 0.2), ("frame_id", "map"), ("map_yaml_path", None), ("goal_text_file_path", None), ("initial_pose", None), ], ) self.__goal_generator = self.__create_goal_generator() action_server_name = self.get_parameter("action_server_name").value self._action_client = ActionClient(self, NavigateToPose, action_server_name) self.MAX_ITERATION_COUNT = self.get_parameter("iteration_count").value assert self.MAX_ITERATION_COUNT > 0 self.curr_iteration_count = 1 self.__initial_goal_publisher = self.create_publisher(PoseWithCovarianceStamped, "/initialpose", 1) self.__initial_pose = self.get_parameter("initial_pose").value self.__is_initial_pose_sent = True if self.__initial_pose is None else False def __send_initial_pose(self): """ Publishes the initial pose. This function is only called once that too before sending any goal pose to the mission server. """ goal = PoseWithCovarianceStamped() goal.header.frame_id = self.get_parameter("frame_id").value goal.header.stamp = self.get_clock().now().to_msg() goal.pose.pose.position.x = self.__initial_pose[0] goal.pose.pose.position.y = self.__initial_pose[1] goal.pose.pose.position.z = self.__initial_pose[2] goal.pose.pose.orientation.x = self.__initial_pose[3] goal.pose.pose.orientation.y = self.__initial_pose[4] goal.pose.pose.orientation.z = self.__initial_pose[5] goal.pose.pose.orientation.w = self.__initial_pose[6] self.__initial_goal_publisher.publish(goal) def send_goal(self): """ Sends the goal to the action server. """ if not self.__is_initial_pose_sent: self.get_logger().info("Sending initial pose") self.__send_initial_pose() self.__is_initial_pose_sent = True # Assumption is that initial pose is set after publishing first time in this duration. # Can be changed to more sophisticated way. e.g. /particlecloud topic has no msg until # the initial pose is set. time.sleep(10) self.get_logger().info("Sending first goal") self._action_client.wait_for_server() goal_msg = self.__get_goal() if goal_msg is None: rclpy.shutdown() sys.exit(1) self._send_goal_future = self._action_client.send_goal_async( goal_msg, feedback_callback=self.__feedback_callback ) self._send_goal_future.add_done_callback(self.__goal_response_callback) def __goal_response_callback(self, future): """ Callback function to check the response(goal accpted/rejected) from the server.\n If the Goal is rejected it stops the execution for now.(We can change to resample the pose if rejected.) """ goal_handle = future.result() if not goal_handle.accepted: self.get_logger().info("Goal rejected :(") rclpy.shutdown() return self.get_logger().info("Goal accepted :)") self._get_result_future = goal_handle.get_result_async() self._get_result_future.add_done_callback(self.__get_result_callback) def __get_goal(self): """ Get the next goal from the goal generator. Returns ------- [NavigateToPose][goal] or None if the next goal couldn't be generated. """ goal_msg = NavigateToPose.Goal() goal_msg.pose.header.frame_id = self.get_parameter("frame_id").value goal_msg.pose.header.stamp = self.get_clock().now().to_msg() pose = self.__goal_generator.generate_goal() # couldn't sample a pose which is not close to obstacles. Rare but might happen in dense maps. if pose is None: self.get_logger().error( "Could not generate next goal. Returning. Possible reasons for this error could be:" ) self.get_logger().error( "1. If you are using GoalReader then please make sure iteration count <= number of goals avaiable in file." ) self.get_logger().error( "2. If RandomGoalGenerator is being used then it was not able to sample a pose which is given distance away from the obstacles." ) return self.get_logger().info("Generated goal pose: {0}".format(pose)) goal_msg.pose.pose.position.x = pose[0] goal_msg.pose.pose.position.y = pose[1] goal_msg.pose.pose.orientation.x = pose[2] goal_msg.pose.pose.orientation.y = pose[3] goal_msg.pose.pose.orientation.z = pose[4] goal_msg.pose.pose.orientation.w = pose[5] return goal_msg def __get_result_callback(self, future): """ Callback to check result.\n It calls the send_goal() function in case current goal sent count < required goals count. """ # Nav2 is sending empty message for success as well as for failure. result = future.result().result self.get_logger().info("Result: {0}".format(result.result)) if self.curr_iteration_count < self.MAX_ITERATION_COUNT: self.curr_iteration_count += 1 self.send_goal() else: rclpy.shutdown() def __feedback_callback(self, feedback_msg): """ This is feeback callback. We can compare/compute/log while the robot is on its way to goal. """ # self.get_logger().info('FEEDBACK: {}\n'.format(feedback_msg)) pass def __create_goal_generator(self): """ Creates the GoalGenerator object based on the specified ros param value. """ goal_generator_type = self.get_parameter("goal_generator_type").value goal_generator = None if goal_generator_type == "RandomGoalGenerator": if self.get_parameter("map_yaml_path").value is None: self.get_logger().info("Yaml file path is not given. Returning..") sys.exit(1) yaml_file_path = self.get_parameter("map_yaml_path").value grid_map = GridMap(yaml_file_path) obstacle_search_distance_in_meters = self.get_parameter("obstacle_search_distance_in_meters").value assert obstacle_search_distance_in_meters > 0 goal_generator = RandomGoalGenerator(grid_map, obstacle_search_distance_in_meters) elif goal_generator_type == "GoalReader": if self.get_parameter("goal_text_file_path").value is None: self.get_logger().info("Goal text file path is not given. Returning..") sys.exit(1) file_path = self.get_parameter("goal_text_file_path").value goal_generator = GoalReader(file_path) else: self.get_logger().info("Invalid goal generator specified. Returning...") sys.exit(1) return goal_generator def main(): rclpy.init() set_goal = SetNavigationGoal() result = set_goal.send_goal() rclpy.spin(set_goal) if __name__ == "__main__": main()
7,971
Python
37.887805
144
0.605696
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/goal_reader.py
from .goal_generator import GoalGenerator class GoalReader(GoalGenerator): def __init__(self, file_path): self.__file_path = file_path self.__generator = self.__get_goal() def generate_goal(self, max_num_of_trials=1000): try: return next(self.__generator) except StopIteration: return def __get_goal(self): for row in open(self.__file_path, "r"): yield list(map(float, row.strip().split(" ")))
486
Python
26.055554
58
0.584362
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/random_goal_generator.py
import numpy as np from .goal_generator import GoalGenerator class RandomGoalGenerator(GoalGenerator): """ Random goal generator. parameters ---------- grid_map: GridMap Object distance: distance in meters to check vicinity for obstacles. """ def __init__(self, grid_map, distance): self.__grid_map = grid_map self.__distance = distance def generate_goal(self, max_num_of_trials=1000): """ Generate the goal. Parameters ---------- max_num_of_trials: maximum number of pose generations when generated pose keep is not a valid pose. Returns ------- [List][Pose]: Pose in format [pose.x,pose.y,orientaion.x,orientaion.y,orientaion.z,orientaion.w] """ range_ = self.__grid_map.get_range() trial_count = 0 while trial_count < max_num_of_trials: x = np.random.uniform(range_[0][0], range_[0][1]) y = np.random.uniform(range_[1][0], range_[1][1]) orient_x = np.random.uniform(0, 1) orient_y = np.random.uniform(0, 1) orient_z = np.random.uniform(0, 1) orient_w = np.random.uniform(0, 1) if self.__grid_map.is_valid_pose([x, y], self.__distance): goal = [x, y, orient_x, orient_y, orient_z, orient_w] return goal trial_count += 1
1,405
Python
30.954545
107
0.560854
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/__init__.py
from .random_goal_generator import RandomGoalGenerator from .goal_reader import GoalReader
91
Python
29.666657
54
0.857143
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/goal_generator.py
from abc import ABC, abstractmethod class GoalGenerator(ABC): """ Parent class for the Goal generators """ def __init__(self): pass @abstractmethod def generate_goal(self, max_num_of_trials=2000): """ Generate the goal. Parameters ---------- max_num_of_trials: maximum number of pose generations when generated pose keep is not a valid pose. Returns ------- [List][Pose]: Pose in format [pose.x,pose.y,orientaion.x,orientaion.y,orientaion.z,orientaion.w] """ pass
582
Python
21.423076
107
0.580756
swadaskar/Isaac_Sim_Folder/ros2_workspace/src/navigation/isaac_ros_navigation_goal/assets/carter_warehouse_navigation.yaml
image: carter_warehouse_navigation.png resolution: 0.05 origin: [-11.975, -17.975, 0.0000] negate: 0 occupied_thresh: 0.65 free_thresh: 0.196
142
YAML
19.428569
38
0.739437
swadaskar/Isaac_Sim_Folder/extension_examples/path_planning/__init__.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.path_planning.path_planning import PathPlanning from omni.isaac.examples.path_planning.path_planning_extension import PathPlanningExtension from omni.isaac.examples.path_planning.path_planning_task import PathPlanningTask from omni.isaac.examples.path_planning.path_planning_controller import PathPlannerController
772
Python
58.461534
92
0.838083
swadaskar/Isaac_Sim_Folder/extension_examples/path_planning/path_planning.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.base_sample import BaseSample from .path_planning_task import FrankaPathPlanningTask from .path_planning_controller import FrankaRrtController 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"]) 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): if self._franka_task.target_reached(): return 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,442
Python
38.669643
115
0.632823
swadaskar/Isaac_Sim_Folder/extension_examples/path_planning/path_planning_task.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.core.tasks import BaseTask from omni.isaac.franka import Franka from omni.isaac.core.prims import XFormPrim from omni.isaac.core.utils.prims import is_prim_path_valid from omni.isaac.core.utils.string import find_unique_string_name from omni.isaac.core.utils.rotations import euler_angles_to_quat from omni.isaac.core.scenes.scene import Scene from omni.isaac.core.objects import FixedCuboid, VisualCuboid from omni.isaac.core.utils.stage import get_stage_units from collections import OrderedDict from typing import Optional, List, Tuple import numpy as np 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 ( 6 * np.array([1.0e08, 1.0e08, 1.0e08, 1.0e08, 1.0e08, 1.0e08, 1.0e08, 1.0e07, 1.0e07]), 10 * np.array( [ 10000000.0, 10000000.0, 10000000.0, 10000000.0, 10000000.0, 10000000.0, 10000000.0, 1000000.0, 1000000.0, ] ), )
12,634
Python
36.716418
120
0.56435
swadaskar/Isaac_Sim_Folder/extension_examples/path_planning/path_planning_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.path_planning import PathPlanning import asyncio import omni.ui as ui from omni.isaac.ui.ui_utils import btn_builder, str_builder, state_btn_builder import carb 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/app_isaacsim/app_isaacsim/overview.html", 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,745
Python
39.154762
197
0.553595
swadaskar/Isaac_Sim_Folder/extension_examples/path_planning/path_planning_controller.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.core.controllers import BaseController from omni.isaac.motion_generation import PathPlannerVisualizer, PathPlanner from omni.isaac.motion_generation.lula import RRT from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.articulations import Articulation from omni.isaac.motion_generation import interface_config_loader import omni.isaac.core.objects import carb from typing import Optional import numpy as np class PathPlannerController(BaseController): def __init__( self, name: str, path_planner_visualizer: PathPlannerVisualizer, cspace_interpolation_max_dist: float = 0.5, frames_per_waypoint: int = 30, ): BaseController.__init__(self, name) self._path_planner_visualizer = path_planner_visualizer self._path_planner = path_planner_visualizer.get_path_planner() self._cspace_interpolation_max_dist = cspace_interpolation_max_dist self._frames_per_waypoint = frames_per_waypoint self._plan = None self._frame_counter = 1 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() self._plan = self._path_planner_visualizer.compute_plan_as_articulation_actions( max_cspace_dist=self._cspace_interpolation_max_dist ) if self._plan is None or self._plan == []: carb.log_warn("No plan could be generated to target pose: " + str(target_end_effector_position)) def forward( self, target_end_effector_position: np.ndarray, target_end_effector_orientation: Optional[np.ndarray] = None ) -> ArticulationAction: if self._plan 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._plan) == 0: # The plan is completed; return null action to remain in place self._frame_counter = 1 return ArticulationAction() if self._frame_counter % self._frames_per_waypoint != 0: # Stop at each waypoint in the plan for self._frames_per_waypoint frames self._frame_counter += 1 return self._plan[0] else: self._frame_counter += 1 return self._plan.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._plan = None self._frame_counter = 1 def get_path_planner_visualizer(self) -> PathPlannerVisualizer: return self._path_planner_visualizer def get_path_planner(self) -> PathPlanner: return self._path_planner class FrankaRrtController(PathPlannerController): def __init__( self, name, robot_articulation: Articulation, cspace_interpolation_max_dist: float = 0.5, frames_per_waypoint: int = 30, ): rrt_config = interface_config_loader.load_supported_path_planner_config("Franka", "RRT") rrt = RRT(**rrt_config) visualizer = PathPlannerVisualizer(robot_articulation, rrt) PathPlannerController.__init__(self, name, visualizer, cspace_interpolation_max_dist, frames_per_waypoint)
4,221
Python
38.830188
116
0.685383
swadaskar/Isaac_Sim_Folder/extension_examples/base_sample/base_sample.py
# Copyright (c) 2018-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.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 import gc from abc import abstractmethod 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,657
Python
34.287879
115
0.624222
swadaskar/Isaac_Sim_Folder/extension_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. # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription from omni.isaac.ui.menu import make_menu_item_description import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core import World 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: with ui.VStack(spacing=5, height=0): 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,714
Python
35.927966
119
0.543608
swadaskar/Isaac_Sim_Folder/extension_examples/base_sample/__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.base_sample.base_sample import BaseSample from omni.isaac.examples.base_sample.base_sample_extension import BaseSampleExtension
582
Python
47.583329
85
0.821306
swadaskar/Isaac_Sim_Folder/extension_examples/unitree_quadruped/quadruped_example.py
from omni.isaac.core.prims import GeometryPrim, XFormPrim from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction # This extension includes several generic controllers that could be used with multiple robots from omni.isaac.motion_generation import WheelBasePoseController # Robot specific controller from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController from omni.isaac.core.controllers import BaseController from omni.isaac.core.tasks import BaseTask from omni.isaac.manipulators import SingleManipulator from omni.isaac.manipulators.grippers import SurfaceGripper import numpy as np from omni.isaac.core.objects import VisualCuboid, DynamicCuboid from omni.isaac.core.utils import prims from pxr import UsdLux, Sdf, UsdGeom import omni.usd from omni.isaac.dynamic_control import _dynamic_control from omni.isaac.universal_robots import KinematicsSolver import carb from collections import deque, defaultdict import time class CustomDifferentialController(BaseController): def __init__(self): super().__init__(name="my_cool_controller") # An open loop controller that uses a unicycle model self._wheel_radius = 0.125 self._wheel_base = 1.152 return def forward(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) def turn(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0][0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0][1]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0][2]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0][3]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) class RobotsPlaying(BaseTask): def __init__(self, name): super().__init__(name=name, offset=None) # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -2.628, 0.03551]), np.array([-5.40137, -15.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.eb_goal_position = np.array([-4.39666, 7.64828, 0.035]) self.ur10_goal_position = np.array([]) # self.mp_goal_orientation = np.array([1, 0, 0, 0]) self._task_event = 0 self.task_done = [False]*120 self.motion_event = 0 self.motion_done = [False]*120 self._bool_event = 0 self.count=0 self.delay=0 return def set_up_scene(self, scene): super().set_up_scene(scene) assets_root_path = get_assets_root_path() # http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.2.1 asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/photos/real_microfactory_1_2.usd" robot_arm_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd" # adding UR10 for pick and place add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/UR10") # gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/short_gripper.usd" gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/RG2_v2/RG2_v2.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10/ee_link") gripper = SurfaceGripper(end_effector_prim_path="/World/UR10/ee_link", translate=0.1611, direction="x") self.ur10 = scene.add( SingleManipulator(prim_path="/World/UR10", name="my_ur10", end_effector_prim_name="ee_link", gripper=gripper, translation = np.array([-6.10078, -5.19303, 0.24168]), orientation=np.array([0,0,0,1]), scale=np.array([1,1,1])) ) self.ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10 for screwing in part add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/Screw_driving_UR10") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/screw_driver_link/screw_driver_link.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/Screw_driving_UR10/ee_link") screw_gripper = SurfaceGripper(end_effector_prim_path="/World/Screw_driving_UR10/ee_link", translate=0, direction="x") self.screw_ur10 = scene.add( SingleManipulator(prim_path="/World/Screw_driving_UR10", name="my_screw_ur10", end_effector_prim_name="ee_link", gripper=screw_gripper, translation = np.array([-3.78767, -5.00871, 0.24168]), orientation=np.array([0, 0, 0, 1]), scale=np.array([1,1,1])) ) self.screw_ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) large_robot_asset_path = small_robot_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/Collected_full_warehouse_microfactory/Collected_mobile_platform_improved/Collected_mobile_platform/mobile_platform.usd" # add floor add_reference_to_stage(usd_path=asset_path, prim_path="/World/Environment") # add moving platform self.moving_platform = scene.add( WheeledRobot( prim_path="/mock_robot", name="moving_platform", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=large_robot_asset_path, position=np.array([-5.26025, 1.25718, 0.03551]), orientation=np.array([0.5, 0.5, -0.5, -0.5]), ) ) self.engine_bringer = scene.add( WheeledRobot( prim_path="/engine_bringer", name="engine_bringer", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=small_robot_asset_path, position=np.array([-7.60277, -5.70312, 0.035]), orientation=np.array([0,0,0.70711, 0.70711]), ) ) return def get_observations(self): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_eb_position, current_eb_orientation = self.engine_bringer.get_world_pose() current_joint_positions_ur10 = self.ur10.get_joint_positions() observations= { "task_event": self._task_event, "task_event": self._task_event, self.moving_platform.name: { "position": current_mp_position, "orientation": current_mp_orientation, "goal_position": self.mp_goal_position }, self.engine_bringer.name: { "position": current_eb_position, "orientation": current_eb_orientation, "goal_position": self.eb_goal_position }, self.ur10.name: { "joint_positions": current_joint_positions_ur10, }, self.screw_ur10.name: { "joint_positions": current_joint_positions_ur10, }, "bool_counter": self._bool_event } return observations def get_params(self): params_representation = {} params_representation["arm_name"] = {"value": self.ur10.name, "modifiable": False} params_representation["screw_arm"] = {"value": self.screw_ur10.name, "modifiable": False} params_representation["mp_name"] = {"value": self.moving_platform.name, "modifiable": False} params_representation["eb_name"] = {"value": self.engine_bringer.name, "modifiable": False} return params_representation def check_prim_exists(self, prim): if prim: return True return False def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def pre_step(self, control_index, simulation_time): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_eb_position, current_eb_orientation = self.engine_bringer.get_world_pose() ee_pose = self.give_location("/World/UR10/ee_link") screw_ee_pose = self.give_location("/World/Screw_driving_UR10/ee_link") # iteration 1 if self._task_event == 0: if self.task_done[self._task_event]: self._task_event += 1 self.task_done[self._task_event] = True elif self._task_event == 1: if self.task_done[self._task_event] and current_mp_position[1]<-5.3: self._task_event = 51 self._bool_event+=1 self.task_done[self._task_event] = True elif self._task_event == 51: if np.mean(np.abs(ee_pose.p - np.array([-5.00127, -4.80822, 0.53949])))<0.02: self._task_event = 71 self._bool_event+=1 elif self._task_event == 71: if np.mean(np.abs(screw_ee_pose.p - np.array([-3.70349, -4.41856, 0.56125])))<0.058: self._task_event=2 elif self._task_event == 2: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 3: pass return def post_reset(self): self._task_event = 0 return class QuadrupedExample(BaseSample): def __init__(self) -> None: super().__init__() self.done = False return def setup_scene(self): world = self.get_world() # adding light l = UsdLux.SphereLight.Define(world.stage, Sdf.Path("/World/Lights")) # l.CreateExposureAttr(...) l.CreateColorTemperatureAttr(10000) l.CreateIntensityAttr(7500) l.CreateRadiusAttr(75) l.AddTranslateOp() XFormPrim("/World/Lights").set_local_pose(translation=np.array([0,0,100])) world.add_task(RobotsPlaying(name="awesome_task")) self.isDone = [False]*120 self.bool_done = [False]*120 self.motion_task_counter=0 self.delay=0 print("inside setup_scene", self.motion_task_counter) return async def setup_post_load(self): self._world = self.get_world() task_params = self._world.get_task("awesome_task").get_params() # bring in moving platforms self.moving_platform = self._world.scene.get_object(task_params["mp_name"]["value"]) self.engine_bringer = self._world.scene.get_object(task_params["eb_name"]["value"]) # static suspensions on the table self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.83704, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_01", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.69733, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_02", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.54469, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_03", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.3843, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_04", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.22546, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_05", np.array([0.001,0.001,0.001]), np.array([-6.10203, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_06", np.array([0.001,0.001,0.001]), np.array([-5.96018, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_07", np.array([0.001,0.001,0.001]), np.array([-5.7941, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_08", np.array([0.001,0.001,0.001]), np.array([-5.63427, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_09", np.array([0.001,0.001,0.001]), np.array([-5.47625, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("mock_robot/platform","engine_no_rigid", "engine", np.array([0.001,0.001,0.001]), np.array([-0.16041, -0.00551, 0.46581]), np.array([0.98404, -0.00148, -0.17792, -0.00274])) self.add_part("FFrame", "frame", np.array([0.001, 0.001, 0.001]), np.array([0.45216, -0.32084, 0.28512]), np.array([0, 0, 0.70711, 0.70711])) self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) # Initialize our controller after load and the first reset self._my_custom_controller = CustomDifferentialController() self._my_controller = WheelBasePoseController(name="cool_controller", open_loop_wheel_controller=DifferentialController(name="simple_control", wheel_radius=0.125, wheel_base=0.46), is_holonomic=False) self.ur10 = self._world.scene.get_object(task_params["arm_name"]["value"]) self.screw_ur10 = self._world.scene.get_object(task_params["screw_arm"]["value"]) self.my_controller = KinematicsSolver(self.ur10, attach_gripper=True) self.screw_my_controller = KinematicsSolver(self.screw_ur10, attach_gripper=True) self.articulation_controller = self.ur10.get_articulation_controller() self.screw_articulation_controller = self.screw_ur10.get_articulation_controller() return async def setup_post_reset(self): self._my_controller.reset() await self._world.play_async() return def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def move_ur10(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) # actions.joint_velocities = [0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] # actions.joint_velocities = [1,1,1,1,1,1] print(actions) if success: print("still homing on this location") self.articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.015: self.motion_task_counter+=1 # time.sleep(0.3) print("Completed one motion plan: ", self.motion_task_counter) def do_screw_driving(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.screw_my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) if success: print("still homing on this location") self.screw_articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/Screw_driving_UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.02: self.motion_task_counter+=1 print("Completed one motion plan: ", self.motion_task_counter) # def do_screw_driving(self, locations, task_name=""): # print(self.motion_task_counter) # target_location = locations[self.motion_task_counter] # print("Doing "+str(target_location["index"])+"th motion plan") # actions, success = self.screw_my_controller.compute_inverse_kinematics( # target_position=target_location["position"], # target_orientation=target_location["orientation"], # ) # if success: # print("still homing on this location") # controller_name = getattr(self,"screw_articulation_controller"+task_name) # controller_name.apply_action(actions) # else: # carb.log_warn("IK did not converge to a solution. No action is being taken.") # # check if reached location # curr_location = self.give_location(f"/World/Screw_driving_UR10{task_name}/ee_link") # print("Curr:",curr_location.p) # print("Goal:", target_location["goal_position"]) # print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) # if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.02: # self.motion_task_counter+=1 # print("Completed one motion plan: ", self.motion_task_counter) def transform_for_screw_ur10(self, position): position[0]-=0 position[1]+=0 position[2]+=-0 return position def send_robot_actions(self, step_size): current_observations = self._world.get_observations() task_params = self._world.get_task("awesome_task").get_params() ## Task event numbering: # 1 - 30 normal events: forward, stop and add piece, turn # 51 - 61 smaller moving platforms events: forward, stop, disappear piece # 71 - pick place tasks # Terminology # mp - moving platform # iteration 1 # go forward if current_observations["task_event"] == 1: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) if not self.isDone[current_observations["task_event"]]: self.isDone[current_observations["task_event"]]=True # small mp brings in part elif current_observations["task_event"] == 51: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0,0])) if not self.isDone[current_observations["task_event"]]: motion_plan = [{"index":0, "position": np.array([0.72034, -0.05477, 0.33852-0.16+0.2]), "orientation": np.array([0.5,-0.5,0.5,0.5]), "goal_position":np.array([-6.822, -5.13962, 0.58122+0.2]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":1, "position": np.array([0.72034, -0.05477, 0.33852-0.16]), "orientation": np.array([0.5,-0.5,0.5,0.5]), "goal_position":np.array([-6.822, -5.13962, 0.58122]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":2, "position": np.array([0.72034, -0.05477, 0.33852-0.16+0.2]), "orientation": np.array([0.5,-0.5,0.5,0.5]), "goal_position":np.array([-6.822, -5.13962, 0.58122+0.2]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":3, "position": np.array([-0.96615-0.16, -0.56853+0.12, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-5.13459, -4.62413-0.12, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":4, "position": np.array([-1.10845-0.16, -0.56853+0.12, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-4.99229, -4.62413-0.12, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":5, "position": np.array([-1.10842-0.16, -0.39583, 0.29724]), "orientation": np.array([-0.00055, 0.0008, -0.82242, -0.56888]), "goal_position":np.array([-5.00127, -4.80822, 0.53949]), "goal_orientation":np.array([0.56437, 0.82479, 0.02914, 0.01902])}] # {"index":0, "position": np.array([1.11096, -0.01839, 0.31929-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-7.2154, -5.17695, 0.56252]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, # {"index":1, "position": np.array([1.11096, -0.01839, 0.19845-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-7.2154, -5.17695, 0.44167]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, # {"index":2, "position": np.array([1.11096, -0.01839, 0.31929]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-7.2154, -5.17695, 0.56252]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, self.move_ur10(motion_plan) if self.motion_task_counter==2 and not self.bool_done[current_observations["bool_counter"]]: self.bool_done[current_observations["bool_counter"]] = True self.remove_part("World/Environment", "FSuspensionBack_01") self.add_part_custom("World/UR10/ee_link","FSuspensionBack", "qFSuspensionBack", np.array([0.001,0.001,0.001]), np.array([0.16839, 0.158, -0.44332]), np.array([0,0,0,1])) if self.motion_task_counter==6: print("Done motion plan") self.isDone[current_observations["task_event"]]=True # arm_robot picks and places part elif current_observations["task_event"] == 71: if not self.isDone[current_observations["task_event"]]: if not self.bool_done[current_observations["bool_counter"]]: self.bool_done[current_observations["bool_counter"]] = True print("Part removal done") self.remove_part("World/UR10/ee_link", "qFSuspensionBack") self.motion_task_counter=0 self.add_part_custom("mock_robot/platform","FSuspensionBack", "xFSuspensionBack", np.array([0.001,0.001,0.001]), np.array([-0.87892, 0.0239, 0.82432]), np.array([0.40364, -0.58922, 0.57252, -0.40262])) motion_plan = [{"index":0, "position": self.transform_for_screw_ur10(np.array([-0.56003, 0.05522, -0.16+0.43437+0.25])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.2273, -5.06269, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":1, "position": self.transform_for_screw_ur10(np.array([-0.56003, 0.05522, -0.16+0.43437])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.2273, -5.06269, 0.67593]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":2, "position": self.transform_for_screw_ur10(np.array([-0.56003, 0.05522, -0.16+0.43437+0.25])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.2273, -5.06269, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":3, "position": self.transform_for_screw_ur10(np.array([0.83141+0.16-0.2, -0.16343, 0.34189])), "orientation": np.array([1,0,0,0]), "goal_position":np.array([-4.61995+0.2, -4.84629, 0.58477]), "goal_orientation":np.array([0,0,0,1])}, {"index":4, "position": self.transform_for_screw_ur10(np.array([0.87215+0.16, -0.16343, 0.34189])), "orientation": np.array([1,0,0,0]), "goal_position":np.array([-4.66069, -4.84629,0.58477]), "goal_orientation":np.array([0,0,0,1])}, {"index":5, "position": self.transform_for_screw_ur10(np.array([0.83141+0.16-0.2, -0.16343, 0.34189])), "orientation": np.array([1,0,0,0]), "goal_position":np.array([-4.61995+0.2, -4.84629, 0.58477]), "goal_orientation":np.array([0,0,0,1])}, {"index":6, "position": self.transform_for_screw_ur10(np.array([-0.55625, -0.1223, -0.16+0.43437+0.2])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.23108, -4.88517, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":7, "position": self.transform_for_screw_ur10(np.array([-0.55625, -0.1223, -0.16+0.43437])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.23108, -4.88517, 0.67593]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":8, "position": self.transform_for_screw_ur10(np.array([-0.55625, -0.1223, -0.16+0.43437+0.2])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.23108, -4.88517, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":9, "position": self.transform_for_screw_ur10(np.array([0.81036+0.16-0.1, -0.26815, 0.24723])), "orientation": np.array([0,-1, 0, 0]), "goal_position":np.array([-4.59801+0.1, -4.7396, 0.49012]), "goal_orientation":np.array([0,0,1,0])}, {"index":10, "position": self.transform_for_screw_ur10(np.array([0.91167+0.16, -0.26815, 0.24723])), "orientation": np.array([0,-1, 0, 0]), "goal_position":np.array([-4.69933, -4.7396, 0.49012]), "goal_orientation":np.array([0,0,1,0])}, {"index":11, "position": self.transform_for_screw_ur10(np.array([0.81036+0.16-0.1, -0.26815, 0.24723])), "orientation": np.array([0,-1, 0, 0]), "goal_position":np.array([-4.59801+0.1, -4.7396, 0.49012]), "goal_orientation":np.array([0,0,1,0])}, {"index":12, "position": self.transform_for_screw_ur10(np.array([-0.08295-0.16, -0.58914, 0.32041-0.15])), "orientation": np.array([0,0.70711, 0, -0.70711]), "goal_position":np.array([-3.70349, -4.41856, 0.56125]), "goal_orientation":np.array([0.70711,0,0.70711,0])}] print(self.motion_task_counter) self.do_screw_driving(motion_plan) if self.motion_task_counter==13: self.isDone[current_observations["task_event"]]=True self.done = True self.motion_task_counter=0 motion_plan = [{"index":0, "position": np.array([-0.95325-0.16, -0.38757, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-5.14749, -4.80509, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":1, "position": np.array([0.07, -0.81, 0.21]), "orientation": np.array([-0.69, 0, 0, 0.72]), "goal_position":np.array([-4.18372, 7.03628, 0.44567]), "goal_orientation":np.array([0.9999, 0, 0, 0])}] self.move_ur10(motion_plan) # self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) print("done", self.motion_task_counter) # remove engine and add engine elif current_observations["task_event"] == 2: if not self.isDone[current_observations["task_event"]]: self.isDone[current_observations["task_event"]]=True self.done = True self.motion_task_counter=0 motion_plan = [{"index":0, "position": np.array([-0.95325-0.16, -0.38757, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-5.14749, -4.80509, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":1, "position": np.array([0.07, -0.81, 0.21]), "orientation": np.array([-0.69, 0, 0, 0.72]), "goal_position":np.array([-4.18372, 7.03628, 0.44567]), "goal_orientation":np.array([0.9999, 0, 0, 0])}] self.move_ur10(motion_plan) print("task 2 delay") elif current_observations["task_event"] == 3: print("task 3") self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) return def add_part(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/mock_robot/platform/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/mock_robot/platform/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) def add_part_custom(self, parent_prim_name, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/{parent_prim_name}/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/{parent_prim_name}/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def add_part_without_parent(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/World/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/World/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def remove_part(self, parent_prim_name, child_prim_name): prim_path = f"/{parent_prim_name}/{child_prim_name}" # world = self.get_world() prims.delete_prim(prim_path) def move(self, task): mp = self._world.get_observations()[self._world.get_task("awesome_task").get_params()["mp_name"]["value"]] print(mp) position, orientation, goal_position = mp['position'], mp['orientation'], mp['goal_position'][task-1] # In the function where you are sending robot commands print(goal_position) action = self._my_controller.forward(start_position=position, start_orientation=orientation, goal_position=goal_position) # Change the goal position to what you want full_action = ArticulationAction(joint_efforts=np.concatenate([action.joint_efforts, action.joint_efforts]) if action.joint_efforts else None, joint_velocities=np.concatenate([action.joint_velocities, action.joint_velocities]), joint_positions=np.concatenate([action.joint_positions, action.joint_positions]) if action.joint_positions else None) self.moving_platform.apply_action(full_action)
35,604
Python
63.268953
441
0.605578
swadaskar/Isaac_Sim_Folder/extension_examples/unitree_quadruped/__init__.py
# Copyright (c) 2018-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. # # 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
717
Python
50.285711
103
0.828452
swadaskar/Isaac_Sim_Folder/extension_examples/unitree_quadruped/quadruped_example_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.unitree_quadruped import QuadrupedExample class QuadrupedExampleExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) overview = "This Example shows how to simulate an Unitree A1 quadruped in Isaac Sim." super().start_extension( menu_name="", submenu_name="", name="cell 2 suspension", title="Unitree A1 Quadruped Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_quadruped.html", overview=overview, file_path=os.path.abspath(__file__), sample=QuadrupedExample(), ) return
1,233
Python
38.80645
113
0.704785
swadaskar/Isaac_Sim_Folder/extension_examples/franka_nut_and_bolt/nut_bolt_controller.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.core.controllers import BaseController from omni.isaac.core.utils.stage import get_stage_units from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles import numpy as np import typing from omni.isaac.manipulators.controllers.pick_place_controller import PickPlaceController from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController from .screw_controller import ScrewController from omni.isaac.franka.franka import Franka from .nut_vibra_table_controller import VibraFSM 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,948
Python
38.66
120
0.624748
swadaskar/Isaac_Sim_Folder/extension_examples/franka_nut_and_bolt/screw_controller.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.core.controllers import BaseController from omni.isaac.core.controllers.articulation_controller import ArticulationController from omni.isaac.core.utils.stage import get_stage_units from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.articulations import Articulation from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles import numpy as np import typing from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController 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.005, 0.1, 0.05, 0.005, 0.1, 0.01] 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._screw_speed = 60.0 / 180.0 * np.pi self._screw_speed_back = 120.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 = 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.002, 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._screw_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._screw_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._screw_speed = 60.0 / 180.0 * np.pi self._screw_speed_back = 120.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,114
Python
42.412017
150
0.614198
swadaskar/Isaac_Sim_Folder/extension_examples/franka_nut_and_bolt/__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.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
626
Python
51.249996
107
0.821086
swadaskar/Isaac_Sim_Folder/extension_examples/franka_nut_and_bolt/franka_nut_and_bolt.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.utils.stage import add_reference_to_stage from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.prims import GeometryPrim, XFormPrim from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.materials.physics_material import PhysicsMaterial from omni.isaac.franka.franka import Franka from pxr import Gf, Usd, UsdPhysics, PhysxSchema, UsdShade from .nut_bolt_controller import NutBoltController import numpy as np # 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.005]) 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 # 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", } self._num_bolts = 6 self._num_nuts = 6 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): 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") # gives asset ref path world.scene.add(GeometryPrim(prim_path="/World/env/table", name=f"table_ref_geom", collision=True)) # declares in the world 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.3, dynamic_friction=0.3, ) 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])) # 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() self._convexIncludeRel.AddTarget(self._franka.prim_path + "/panda_leftfinger") self._convexIncludeRel.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) self._meshCollisionGroup = UsdPhysics.CollisionGroup.Define( self._world.scene.stage, "/World/collisionGroups/meshColliders" ) collectionAPI = Usd.CollectionAPI.ApplyCollection(self._meshCollisionGroup.GetPrim(), "colliders") self._nutMeshIncludeRel = collectionAPI.CreateIncludesRel() self._convexCollisionGroup = UsdPhysics.CollisionGroup.Define( self._world.scene.stage, "/World/collisionGroups/convexColliders" ) collectionAPI = Usd.CollectionAPI.ApplyCollection(self._convexCollisionGroup.GetPrim(), "colliders") self._convexIncludeRel = collectionAPI.CreateIncludesRel() self._boltCollisionGroup = UsdPhysics.CollisionGroup.Define( self._world.scene.stage, "/World/collisionGroups/boltColliders" ) collectionAPI = Usd.CollectionAPI.ApplyCollection(self._boltCollisionGroup.GetPrim(), "colliders") self._boltMeshIncludeRel = 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 each other, the vibra table, and the grippers filteredRel = self._convexCollisionGroup.CreateFilteredGroupsRel() filteredRel.AddTarget("/World/collisionGroups/convexColliders") # # the SDF mesh bolt only collides with the SDF mesh nut colliders filteredRel = self._boltCollisionGroup.CreateFilteredGroupsRel() filteredRel.AddTarget("/World/collisionGroups/meshColliders") async def setup_pre_reset(self): return async def setup_post_reset(self): self._controller._vibraSM.reset() self._controller._vibraSM._i = 0 self._controller.reset(franka=self._franka) self._controller._i = self._controller._vibraSM._i self._franka.gripper.open() self._controller._vibraSM.stop_feed_after_delay(delay_sec=5.0) await self._world.play_async() return def world_cleanup(self): self._controller = None return
24,713
Python
49.747433
131
0.642698
swadaskar/Isaac_Sim_Folder/extension_examples/franka_nut_and_bolt/franka_nut_and_bolt_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.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="", overview="Franka robot arms picking and screwing nuts onto bolts", file_path=os.path.abspath(__file__), sample=FrankaNutAndBolt(), ) return
1,103
Python
38.42857
78
0.698096
swadaskar/Isaac_Sim_Folder/extension_examples/franka_nut_and_bolt/nut_vibra_table_controller.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import 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 = 5.0 _stop_time = 5.0 _backward_time = 1.5 _realign_time = 1.5 def __init__(self, dt=None): self.reset() self._i = 0 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,978
Python
34.047058
98
0.600403
swadaskar/Isaac_Sim_Folder/extension_examples/omnigraph_keyboard/omnigraph_keyboard_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.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/app_isaacsim/app_isaacsim/tutorial_advanced_input_devices.html", overview=overview, file_path=os.path.abspath(__file__), sample=OmnigraphKeyboard(), )
1,557
Python
44.823528
135
0.696853
swadaskar/Isaac_Sim_Folder/extension_examples/omnigraph_keyboard/omnigraph_keyboard.py
# Copyright (c) 2022, 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 omni.ext import numpy as np import omni.graph.core as og from omni.isaac.core.utils.viewports import set_camera_view from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.objects import VisualCuboid 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, 10.0]), # Using the current stage units which is cms by default. size=10.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([75, 75, 45]), 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"), ("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), ("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", "SizeAdd.inputs:a"), ("CubeRead.outputs:value", "SizeAdd.inputs:b"), ("SizeAdd.outputs:sum", "CubeWrite.inputs:value"), ], }, ) def world_cleanup(self): pass
3,957
Python
45.564705
106
0.544099
swadaskar/Isaac_Sim_Folder/extension_examples/omnigraph_keyboard/__init__.py
# Copyright (c) 2022, 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
624
Python
51.083329
106
0.833333
swadaskar/Isaac_Sim_Folder/extension_examples/isaac_demo/isaac_demo_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.hello_world import HelloWorld class IsaacDemoExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="Isaac Demo", title="Isaac Sim Demo", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="A standard Simulation software demo.", file_path=os.path.abspath(__file__), sample=HelloWorld(), ) return
1,122
Python
39.107141
114
0.69697
swadaskar/Isaac_Sim_Folder/extension_examples/isaac_demo/__init__.py
# Copyright (c) 2018-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. # # NOTE: Import here your extension examples to be propagated to ISAAC SIM Extensions startup from omni.isaac.examples.isaac_demo.isaac_demo import IsaacDemo from omni.isaac.examples.isaac_demo.isaac_demo_extension import IsaacDemoExtension
673
Python
55.166662
92
0.820208
swadaskar/Isaac_Sim_Folder/extension_examples/isaac_demo/isaac_demo.py
from omni.isaac.examples.base_sample import BaseSample import numpy as np from omni.isaac.core.objects import DynamicCuboid class IsaacDemo(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/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]), )) return async def setup_post_load(self): self._world = self.get_world() self._cube = self._world.scene.get_object("fancy_cube") 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 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)) # # 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 # # 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() # return # async def setup_post_load(self): # return # async def setup_pre_reset(self): # return # async def setup_post_reset(self): # return # def world_cleanup(self): # return
2,649
Python
15.060606
120
0.613439
swadaskar/Isaac_Sim_Folder/extension_examples/surface_gripper/__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. # # NOTE: Import here your extension examples to be propagated to ISAAC SIM Extensions startup from omni.isaac.examples.surface_gripper.surface_gripper import BatteryTask from omni.isaac.examples.surface_gripper.surface_gripper_extension import BatteryTaskExtension
693
Python
52.384611
94
0.825397
swadaskar/Isaac_Sim_Folder/extension_examples/surface_gripper/surface_gripper_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.surface_gripper.surface_gripper import BatteryTask class BatteryTaskExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) overview = "This Example shows how to simulate an Unitree A1 quadruped in Isaac Sim." super().start_extension( menu_name="", submenu_name="", name="cell 4 battery", title="Unitree A1 Quadruped Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_quadruped.html", overview=overview, file_path=os.path.abspath(__file__), sample=BatteryTask(), ) return
1,229
Python
38.677418
113
0.702197
swadaskar/Isaac_Sim_Folder/extension_examples/surface_gripper/surface_gripper.py
from omni.isaac.core.prims import GeometryPrim, XFormPrim from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction # This extension includes several generic controllers that could be used with multiple robots from omni.isaac.motion_generation import WheelBasePoseController # Robot specific controller from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController from omni.isaac.core.controllers import BaseController from omni.isaac.core.tasks import BaseTask from omni.isaac.manipulators import SingleManipulator from omni.isaac.manipulators.grippers import SurfaceGripper import numpy as np from omni.isaac.core.objects import VisualCuboid, DynamicCuboid from omni.isaac.core.utils import prims from pxr import UsdLux, Sdf, UsdGeom import omni.usd from omni.isaac.dynamic_control import _dynamic_control from omni.isaac.universal_robots import KinematicsSolver import carb from collections import deque, defaultdict import time class CustomDifferentialController(BaseController): def __init__(self): super().__init__(name="my_cool_controller") # An open loop controller that uses a unicycle model self._wheel_radius = 0.125 self._wheel_base = 1.152 return def forward(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) def turn(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0][0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0][1]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0][2]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0][3]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) class RobotsPlaying(BaseTask): def __init__(self, name): super().__init__(name=name, offset=None) # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -2.628, 0.03551]), np.array([-5.40137, -15.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.eb_goal_position = np.array([-4.39666, 7.64828, 0.035]) self.ur10_goal_position = np.array([]) # self.mp_goal_orientation = np.array([1, 0, 0, 0]) self._task_event = 0 self.task_done = [False]*120 self.motion_event = 0 self.motion_done = [False]*120 self._bool_event = 0 self.count=0 self.delay=0 return def set_up_scene(self, scene): super().set_up_scene(scene) assets_root_path = get_assets_root_path() # http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.2.1 asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/photos/real_microfactory_show_without_robots.usd" robot_arm_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd" # adding UR10 for pick and place add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/UR10") # gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/short_gripper.usd" gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/RG2_v2/RG2_v2.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10/ee_link") gripper = SurfaceGripper(end_effector_prim_path="/World/UR10/ee_link", translate=0.1611, direction="x") self.ur10 = scene.add( SingleManipulator(prim_path="/World/UR10", name="my_ur10", end_effector_prim_name="ee_link", gripper=gripper, translation = np.array([-16.5464, -16.02288, 0.24168]), orientation=np.array([0,0,0,1]), scale=np.array([1,1,1])) ) self.ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10 for screwing in part add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/Screw_driving_UR10") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/screw_driver_link/screw_driver_link.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/Screw_driving_UR10/ee_link") screw_gripper = SurfaceGripper(end_effector_prim_path="/World/Screw_driving_UR10/ee_link", translate=0, direction="x") self.screw_ur10 = scene.add( SingleManipulator(prim_path="/World/Screw_driving_UR10", name="my_screw_ur10", end_effector_prim_name="ee_link", gripper=screw_gripper, translation = np.array([-16.35161, -18.32382, 0.24168]), orientation=np.array([0, 0, 0, 1]), scale=np.array([1,1,1])) ) self.screw_ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) large_robot_asset_path = small_robot_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/Collected_full_warehouse_microfactory/Collected_mobile_platform_improved/Collected_mobile_platform/mobile_platform.usd" # add floor add_reference_to_stage(usd_path=asset_path, prim_path="/World/Environment") # add moving platform self.moving_platform = scene.add( WheeledRobot( prim_path="/mock_robot", name="moving_platform", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=large_robot_asset_path, position=np.array([-10.23701, -17.06208, 0.03551]), orientation=np.array([0, 0, -0.70711, -0.70711]), ) ) self.engine_bringer = scene.add( WheeledRobot( prim_path="/engine_bringer", name="engine_bringer", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=small_robot_asset_path, position=np.array([-7.60277, -5.70312, 0.035]), orientation=np.array([0,0,0.70711, 0.70711]), ) ) return def get_observations(self): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_eb_position, current_eb_orientation = self.engine_bringer.get_world_pose() current_joint_positions_ur10 = self.ur10.get_joint_positions() observations= { "task_event": self._task_event, "task_event": self._task_event, self.moving_platform.name: { "position": current_mp_position, "orientation": current_mp_orientation, "goal_position": self.mp_goal_position }, self.engine_bringer.name: { "position": current_eb_position, "orientation": current_eb_orientation, "goal_position": self.eb_goal_position }, self.ur10.name: { "joint_positions": current_joint_positions_ur10, }, self.screw_ur10.name: { "joint_positions": current_joint_positions_ur10, }, "bool_counter": self._bool_event } return observations def get_params(self): params_representation = {} params_representation["arm_name"] = {"value": self.ur10.name, "modifiable": False} params_representation["screw_arm"] = {"value": self.screw_ur10.name, "modifiable": False} params_representation["mp_name"] = {"value": self.moving_platform.name, "modifiable": False} params_representation["eb_name"] = {"value": self.engine_bringer.name, "modifiable": False} return params_representation def check_prim_exists(self, prim): if prim: return True return False def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def pre_step(self, control_index, simulation_time): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_eb_position, current_eb_orientation = self.engine_bringer.get_world_pose() ee_pose = self.give_location("/World/UR10/ee_link") screw_ee_pose = self.give_location("/World/Screw_driving_UR10/ee_link") # iteration 1 if self._task_event == 0: if self.task_done[self._task_event]: self._task_event += 1 self.task_done[self._task_event] = True elif self._task_event == 1: if self.task_done[self._task_event] and current_mp_position[1]<-5.3: self._task_event = 51 self._bool_event+=1 self.task_done[self._task_event] = True elif self._task_event == 51: if np.mean(np.abs(ee_pose.p - np.array([-5.00127, -4.80822, 0.53949])))<0.02: self._task_event = 71 self._bool_event+=1 elif self._task_event == 71: if np.mean(np.abs(screw_ee_pose.p - np.array([-3.70349, -4.41856, 0.56125])))<0.058: self._task_event=2 elif self._task_event == 2: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 3: pass return def post_reset(self): self._task_event = 0 return class BatteryTask(BaseSample): def __init__(self) -> None: super().__init__() self.done = False return def setup_scene(self): world = self.get_world() # adding light l = UsdLux.SphereLight.Define(world.stage, Sdf.Path("/World/Lights")) # l.CreateExposureAttr(...) l.CreateColorTemperatureAttr(10000) l.CreateIntensityAttr(7500) l.CreateRadiusAttr(75) l.AddTranslateOp() XFormPrim("/World/Lights").set_local_pose(translation=np.array([0,0,100])) world.add_task(RobotsPlaying(name="awesome_task")) self.isDone = [False]*120 self.bool_done = [False]*120 self.motion_task_counter=0 self.delay=0 print("inside setup_scene", self.motion_task_counter) return async def setup_post_load(self): self._world = self.get_world() task_params = self._world.get_task("awesome_task").get_params() # bring in moving platforms self.moving_platform = self._world.scene.get_object(task_params["mp_name"]["value"]) self.engine_bringer = self._world.scene.get_object(task_params["eb_name"]["value"]) # static suspensions on the table self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.83704, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_01", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.69733, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_02", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.54469, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_03", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.3843, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_04", np.array([0.001,0.001,0.001]), np.array([-6.66288, -4.22546, 0.41322]), np.array([0.5, 0.5, -0.5, 0.5])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_05", np.array([0.001,0.001,0.001]), np.array([-6.10203, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_06", np.array([0.001,0.001,0.001]), np.array([-5.96018, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_07", np.array([0.001,0.001,0.001]), np.array([-5.7941, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_08", np.array([0.001,0.001,0.001]), np.array([-5.63427, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("World/Environment","FSuspensionBack", "FSuspensionBack_09", np.array([0.001,0.001,0.001]), np.array([-5.47625, -4.74457, 0.41322]), np.array([0.70711, 0, -0.70711, 0])) self.add_part_custom("mock_robot/platform","engine_no_rigid", "engine", np.array([0.001,0.001,0.001]), np.array([-0.16041, -0.00551, 0.46581]), np.array([0.98404, -0.00148, -0.17792, -0.00274])) self.add_part("FFrame", "frame", np.array([0.001, 0.001, 0.001]), np.array([0.45216, -0.32084, 0.28512]), np.array([0, 0, 0.70711, 0.70711])) self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) # Initialize our controller after load and the first reset self._my_custom_controller = CustomDifferentialController() self._my_controller = WheelBasePoseController(name="cool_controller", open_loop_wheel_controller=DifferentialController(name="simple_control", wheel_radius=0.125, wheel_base=0.46), is_holonomic=False) self.ur10 = self._world.scene.get_object(task_params["arm_name"]["value"]) self.screw_ur10 = self._world.scene.get_object(task_params["screw_arm"]["value"]) self.my_controller = KinematicsSolver(self.ur10, attach_gripper=True) self.screw_my_controller = KinematicsSolver(self.screw_ur10, attach_gripper=True) self.articulation_controller = self.ur10.get_articulation_controller() self.screw_articulation_controller = self.screw_ur10.get_articulation_controller() return async def setup_post_reset(self): self._my_controller.reset() await self._world.play_async() return def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def move_ur10(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) # actions.joint_velocities = [0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] # actions.joint_velocities = [1,1,1,1,1,1] print(actions) if success: print("still homing on this location") self.articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.015: self.motion_task_counter+=1 # time.sleep(0.3) print("Completed one motion plan: ", self.motion_task_counter) def do_screw_driving(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.screw_my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) if success: print("still homing on this location") self.screw_articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/Screw_driving_UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.02: self.motion_task_counter+=1 print("Completed one motion plan: ", self.motion_task_counter) # def do_screw_driving(self, locations, task_name=""): # print(self.motion_task_counter) # target_location = locations[self.motion_task_counter] # print("Doing "+str(target_location["index"])+"th motion plan") # actions, success = self.screw_my_controller.compute_inverse_kinematics( # target_position=target_location["position"], # target_orientation=target_location["orientation"], # ) # if success: # print("still homing on this location") # controller_name = getattr(self,"screw_articulation_controller"+task_name) # controller_name.apply_action(actions) # else: # carb.log_warn("IK did not converge to a solution. No action is being taken.") # # check if reached location # curr_location = self.give_location(f"/World/Screw_driving_UR10{task_name}/ee_link") # print("Curr:",curr_location.p) # print("Goal:", target_location["goal_position"]) # print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) # if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.02: # self.motion_task_counter+=1 # print("Completed one motion plan: ", self.motion_task_counter) def transform_for_screw_ur10(self, position): position[0]-=0 position[1]+=0 position[2]+=-0 return position def send_robot_actions(self, step_size): current_observations = self._world.get_observations() task_params = self._world.get_task("awesome_task").get_params() ## Task event numbering: # 1 - 30 normal events: forward, stop and add piece, turn # 51 - 61 smaller moving platforms events: forward, stop, disappear piece # 71 - pick place tasks # Terminology # mp - moving platform # iteration 1 # go forward if current_observations["task_event"] == 1: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) if not self.isDone[current_observations["task_event"]]: self.isDone[current_observations["task_event"]]=True # small mp brings in part elif current_observations["task_event"] == 51: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0,0])) if not self.isDone[current_observations["task_event"]]: motion_plan = [{"index":0, "position": np.array([0.72034, -0.05477, 0.33852-0.16+0.2]), "orientation": np.array([0.5,-0.5,0.5,0.5]), "goal_position":np.array([-6.822, -5.13962, 0.58122+0.2]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":1, "position": np.array([0.72034, -0.05477, 0.33852-0.16]), "orientation": np.array([0.5,-0.5,0.5,0.5]), "goal_position":np.array([-6.822, -5.13962, 0.58122]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":2, "position": np.array([0.72034, -0.05477, 0.33852-0.16+0.2]), "orientation": np.array([0.5,-0.5,0.5,0.5]), "goal_position":np.array([-6.822, -5.13962, 0.58122+0.2]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":3, "position": np.array([-0.96615-0.16, -0.56853+0.12, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-5.13459, -4.62413-0.12, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":4, "position": np.array([-1.10845-0.16, -0.56853+0.12, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-4.99229, -4.62413-0.12, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":5, "position": np.array([-1.10842-0.16, -0.39583, 0.29724]), "orientation": np.array([-0.00055, 0.0008, -0.82242, -0.56888]), "goal_position":np.array([-5.00127, -4.80822, 0.53949]), "goal_orientation":np.array([0.56437, 0.82479, 0.02914, 0.01902])}] # {"index":0, "position": np.array([1.11096, -0.01839, 0.31929-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-7.2154, -5.17695, 0.56252]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, # {"index":1, "position": np.array([1.11096, -0.01839, 0.19845-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-7.2154, -5.17695, 0.44167]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, # {"index":2, "position": np.array([1.11096, -0.01839, 0.31929]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-7.2154, -5.17695, 0.56252]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, self.move_ur10(motion_plan) if self.motion_task_counter==2 and not self.bool_done[current_observations["bool_counter"]]: self.bool_done[current_observations["bool_counter"]] = True self.remove_part("World/Environment", "FSuspensionBack_01") self.add_part_custom("World/UR10/ee_link","FSuspensionBack", "qFSuspensionBack", np.array([0.001,0.001,0.001]), np.array([0.16839, 0.158, -0.44332]), np.array([0,0,0,1])) if self.motion_task_counter==6: print("Done motion plan") self.isDone[current_observations["task_event"]]=True # arm_robot picks and places part elif current_observations["task_event"] == 71: if not self.isDone[current_observations["task_event"]]: if not self.bool_done[current_observations["bool_counter"]]: self.bool_done[current_observations["bool_counter"]] = True print("Part removal done") self.remove_part("World/UR10/ee_link", "qFSuspensionBack") self.motion_task_counter=0 self.add_part_custom("mock_robot/platform","FSuspensionBack", "xFSuspensionBack", np.array([0.001,0.001,0.001]), np.array([-0.87892, 0.0239, 0.82432]), np.array([0.40364, -0.58922, 0.57252, -0.40262])) motion_plan = [{"index":0, "position": self.transform_for_screw_ur10(np.array([-0.56003, 0.05522, -0.16+0.43437+0.25])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.2273, -5.06269, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":1, "position": self.transform_for_screw_ur10(np.array([-0.56003, 0.05522, -0.16+0.43437])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.2273, -5.06269, 0.67593]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":2, "position": self.transform_for_screw_ur10(np.array([-0.56003, 0.05522, -0.16+0.43437+0.25])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.2273, -5.06269, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":3, "position": self.transform_for_screw_ur10(np.array([0.83141+0.16-0.2, -0.16343, 0.34189])), "orientation": np.array([1,0,0,0]), "goal_position":np.array([-4.61995+0.2, -4.84629, 0.58477]), "goal_orientation":np.array([0,0,0,1])}, {"index":4, "position": self.transform_for_screw_ur10(np.array([0.87215+0.16, -0.16343, 0.34189])), "orientation": np.array([1,0,0,0]), "goal_position":np.array([-4.66069, -4.84629,0.58477]), "goal_orientation":np.array([0,0,0,1])}, {"index":5, "position": self.transform_for_screw_ur10(np.array([0.83141+0.16-0.2, -0.16343, 0.34189])), "orientation": np.array([1,0,0,0]), "goal_position":np.array([-4.61995+0.2, -4.84629, 0.58477]), "goal_orientation":np.array([0,0,0,1])}, {"index":6, "position": self.transform_for_screw_ur10(np.array([-0.55625, -0.1223, -0.16+0.43437+0.2])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.23108, -4.88517, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":7, "position": self.transform_for_screw_ur10(np.array([-0.55625, -0.1223, -0.16+0.43437])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.23108, -4.88517, 0.67593]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":8, "position": self.transform_for_screw_ur10(np.array([-0.55625, -0.1223, -0.16+0.43437+0.2])), "orientation": np.array([0, -0.70711,0,0.70711]), "goal_position":np.array([-3.23108, -4.88517, 0.67593+0.25]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":9, "position": self.transform_for_screw_ur10(np.array([0.81036+0.16-0.1, -0.26815, 0.24723])), "orientation": np.array([0,-1, 0, 0]), "goal_position":np.array([-4.59801+0.1, -4.7396, 0.49012]), "goal_orientation":np.array([0,0,1,0])}, {"index":10, "position": self.transform_for_screw_ur10(np.array([0.91167+0.16, -0.26815, 0.24723])), "orientation": np.array([0,-1, 0, 0]), "goal_position":np.array([-4.69933, -4.7396, 0.49012]), "goal_orientation":np.array([0,0,1,0])}, {"index":11, "position": self.transform_for_screw_ur10(np.array([0.81036+0.16-0.1, -0.26815, 0.24723])), "orientation": np.array([0,-1, 0, 0]), "goal_position":np.array([-4.59801+0.1, -4.7396, 0.49012]), "goal_orientation":np.array([0,0,1,0])}, {"index":12, "position": self.transform_for_screw_ur10(np.array([-0.08295-0.16, -0.58914, 0.32041-0.15])), "orientation": np.array([0,0.70711, 0, -0.70711]), "goal_position":np.array([-3.70349, -4.41856, 0.56125]), "goal_orientation":np.array([0.70711,0,0.70711,0])}] print(self.motion_task_counter) self.do_screw_driving(motion_plan) if self.motion_task_counter==13: self.isDone[current_observations["task_event"]]=True self.done = True self.motion_task_counter=0 motion_plan = [{"index":0, "position": np.array([-0.95325-0.16, -0.38757, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-5.14749, -4.80509, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":1, "position": np.array([0.07, -0.81, 0.21]), "orientation": np.array([-0.69, 0, 0, 0.72]), "goal_position":np.array([-4.18372, 7.03628, 0.44567]), "goal_orientation":np.array([0.9999, 0, 0, 0])}] self.move_ur10(motion_plan) # self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) print("done", self.motion_task_counter) # remove engine and add engine elif current_observations["task_event"] == 2: if not self.isDone[current_observations["task_event"]]: self.isDone[current_observations["task_event"]]=True self.done = True self.motion_task_counter=0 motion_plan = [{"index":0, "position": np.array([-0.95325-0.16, -0.38757, 0.31143]), "orientation": np.array([-0.00257, 0.00265, -0.82633, -0.56318]), "goal_position":np.array([-5.14749, -4.80509, 0.55254]), "goal_orientation":np.array([0.56316, 0.82633, -0.00001, -0.00438])}, {"index":1, "position": np.array([0.07, -0.81, 0.21]), "orientation": np.array([-0.69, 0, 0, 0.72]), "goal_position":np.array([-4.18372, 7.03628, 0.44567]), "goal_orientation":np.array([0.9999, 0, 0, 0])}] self.move_ur10(motion_plan) print("task 2 delay") elif current_observations["task_event"] == 3: print("task 3") self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) return def add_part(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/mock_robot/platform/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/mock_robot/platform/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) def add_part_custom(self, parent_prim_name, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/{parent_prim_name}/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/{parent_prim_name}/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def add_part_without_parent(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/World/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/World/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def remove_part(self, parent_prim_name, child_prim_name): prim_path = f"/{parent_prim_name}/{child_prim_name}" # world = self.get_world() prims.delete_prim(prim_path) def move(self, task): mp = self._world.get_observations()[self._world.get_task("awesome_task").get_params()["mp_name"]["value"]] print(mp) position, orientation, goal_position = mp['position'], mp['orientation'], mp['goal_position'][task-1] # In the function where you are sending robot commands print(goal_position) action = self._my_controller.forward(start_position=position, start_orientation=orientation, goal_position=goal_position) # Change the goal position to what you want full_action = ArticulationAction(joint_efforts=np.concatenate([action.joint_efforts, action.joint_efforts]) if action.joint_efforts else None, joint_velocities=np.concatenate([action.joint_velocities, action.joint_velocities]), joint_positions=np.concatenate([action.joint_positions, action.joint_positions]) if action.joint_positions else None) self.moving_platform.apply_action(full_action)
35,625
Python
63.306859
441
0.605811
swadaskar/Isaac_Sim_Folder/extension_examples/bin_filling/__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.bin_filling.bin_filling import BinFilling from omni.isaac.examples.bin_filling.bin_filling_extension import BinFillingExtension
582
Python
47.583329
85
0.821306
swadaskar/Isaac_Sim_Folder/extension_examples/bin_filling/bin_filling_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.bin_filling import BinFilling import asyncio import omni.ui as ui 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/app_isaacsim/app_isaacsim/menu_examples.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,772
Python
39.188405
228
0.630231
swadaskar/Isaac_Sim_Folder/extension_examples/bin_filling/bin_filling.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.core.utils.rotations import euler_angles_to_quat from omni.isaac.examples.base_sample import BaseSample from omni.isaac.universal_robots.tasks import BinFilling as BinFillingTask from omni.isaac.universal_robots.controllers import PickPlaceController import numpy as np 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,149
Python
40.999999
117
0.662115
swadaskar/Isaac_Sim_Folder/extension_examples/user_examples/simple_case.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 argparse from omni.isaac.kit import SimulationApp import numpy as np import omni # This sample loads a usd stage and starts simulation CONFIG = {"width": 1280, "height": 720, "sync_loads": True, "headless": False, "renderer": "RayTracedLighting"} # Set up command line arguments parser = argparse.ArgumentParser("Usd Load sample") parser.add_argument("--headless", default=False, action="store_true", help="Run stage headless") args, unknown = parser.parse_known_args() # Start the omniverse application CONFIG["headless"] = args.headless simulation_app = SimulationApp(launch_config=CONFIG) from omni.isaac.core import World from omni.isaac.core.robots import Robot from omni.isaac.core.utils.types import ArticulationAction # open stage omni.usd.get_context().open_stage("simple_case.usd") # wait two frames so that stage starts loading simulation_app.update() simulation_app.update() print("Loading stage...") from omni.isaac.core.utils.stage import is_stage_loading while is_stage_loading(): simulation_app.update() print("Loading Complete") world = World(stage_units_in_meters=1.0) robot = world.scene.add(Robot(prim_path="/World/panda", name="robot")) world.reset() while simulation_app.is_running(): world.step(render=not args.headless) # deal with pause/stop if world.is_playing(): if world.current_time_step_index == 0: world.reset() # apply actions robot.get_articulation_controller().apply_action( ArticulationAction(joint_positions=np.random.random(9)) ) simulation_app.close()
2,016
Python
30.515625
111
0.745536
swadaskar/Isaac_Sim_Folder/extension_examples/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.disassembly import Disassembly from omni.isaac.examples.user_examples.disassembly_extension import DisassemblyExtension
588
Python
48.083329
88
0.826531
swadaskar/Isaac_Sim_Folder/extension_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(1000): 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,420
Python
40.794116
110
0.714789
swadaskar/Isaac_Sim_Folder/extension_examples/user_examples/disassembly_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.disassembly import Disassembly class DisassemblyExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="Awesome example", title="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=Disassembly(), ) return
1,221
Python
42.642856
135
0.710074
swadaskar/Isaac_Sim_Folder/extension_examples/user_examples/disassembly.py
from omni.isaac.core.prims import GeometryPrim, XFormPrim from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction # This extension includes several generic controllers that could be used with multiple robots from omni.isaac.motion_generation import WheelBasePoseController # Robot specific controller from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController from omni.isaac.core.controllers import BaseController from omni.isaac.core.tasks import BaseTask from omni.isaac.manipulators import SingleManipulator from omni.isaac.manipulators.grippers import SurfaceGripper import numpy as np from omni.isaac.core.objects import VisualCuboid, DynamicCuboid from omni.isaac.core.utils import prims from pxr import UsdLux, Sdf, UsdGeom, Gf import omni.usd from omni.isaac.dynamic_control import _dynamic_control from omni.isaac.universal_robots import KinematicsSolver import carb from collections import deque, defaultdict from omni.physx.scripts import utils import time class CustomDifferentialController(BaseController): def __init__(self): super().__init__(name="my_cool_controller") # An open loop controller that uses a unicycle model self._wheel_radius = 0.125 self._wheel_base = 1.152 return def forward(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) def turn(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0][0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0][1]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0][2]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0][3]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) class RobotsPlaying(BaseTask): def __init__(self, name): super().__init__(name=name, offset=None) self.mp_goal_position = [np.array([-28.07654, 18.06421, 0]), np.array([-25.04914, 18.06421, 0])] self._task_event = 0 self.task_done = [False]*120 self.delay = 0 return def set_up_scene(self, scene): super().set_up_scene(scene) assets_root_path = get_assets_root_path() # http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.2.1 asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/photos/real_microfactory_show_without_robots_l.usd" large_robot_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/Collected_full_warehouse_microfactory/Collected_mobile_platform_improved/Collected_mobile_platform_unfinished/mobile_platform_flattened.usd" # add floor add_reference_to_stage(usd_path=asset_path, prim_path="/World/Environment") robot_arm_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd" # adding UR10 for pick and place add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/UR10") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/Cover_Gripper/Cover_Gripper.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10/ee_link") gripper = SurfaceGripper(end_effector_prim_path="/World/UR10/ee_link", translate=0.1611, direction="x") self.ur10 = scene.add( SingleManipulator(prim_path="/World/UR10", name="my_ur10", end_effector_prim_name="ee_link", gripper=gripper, translation = np.array([-17.73638,-17.06779, 0.81965]), orientation=np.array([0.70711, 0, 0, -0.70711]), scale=np.array([1,1,1])) ) self.ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10_02 for pick and place add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/UR10_02") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/RG2_v2/RG2_v2.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10_02/ee_link") gripper = SurfaceGripper(end_effector_prim_path="/World/UR10_02/ee_link", translate=0.1611, direction="x") self.ur10_02 = scene.add( SingleManipulator(prim_path="/World/UR10_02", name="my_ur10_02", end_effector_prim_name="ee_link", gripper=gripper, translation = np.array([-14.28725, -16.26194, 0.24133]), orientation=np.array([1,0,0,0]), scale=np.array([1,1,1])) ) self.ur10_02.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10_01 for pick and place add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/UR10_01") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/RG2_v2/RG2_v2.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10_01/ee_link") gripper = SurfaceGripper(end_effector_prim_path="/World/UR10_01/ee_link", translate=0.1611, direction="x") self.ur10_01 = scene.add( SingleManipulator(prim_path="/World/UR10_01", name="my_ur10_01", end_effector_prim_name="ee_link", gripper=gripper, translation = np.array([-14.28725, -18.32192, 0.24133]), orientation=np.array([0,0,0,1]), scale=np.array([1,1,1])) ) self.ur10_01.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10 for screwing in part add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/Screw_driving_UR10") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/screw_driver_link/screw_driver_link.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/Screw_driving_UR10/ee_link") screw_gripper = SurfaceGripper(end_effector_prim_path="/World/Screw_driving_UR10/ee_link", translate=0, direction="x") self.screw_ur10 = scene.add( SingleManipulator(prim_path="/World/Screw_driving_UR10", name="my_screw_ur10", end_effector_prim_name="ee_link", gripper=screw_gripper, translation = np.array([-15.71653, -16.26185, 0.24133]), orientation=np.array([1,0,0,0]), scale=np.array([1,1,1])) ) self.screw_ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10_01 for screwing in part add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/Screw_driving_UR10_01") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/screw_driver_link/screw_driver_link.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/Screw_driving_UR10_01/ee_link") screw_gripper = SurfaceGripper(end_effector_prim_path="/World/Screw_driving_UR10_01/ee_link", translate=0, direction="x") self.screw_ur10_01 = scene.add( SingleManipulator(prim_path="/World/Screw_driving_UR10_01", name="my_screw_ur10_01", end_effector_prim_name="ee_link", gripper=screw_gripper, translation = np.array([-15.7071, -18.31962, 0.24133]), orientation=np.array([0,0,0,1]), scale=np.array([1,1,1])) ) self.screw_ur10_01.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # add moving platform self.moving_platform = scene.add( WheeledRobot( prim_path="/mobile_platform", name="moving_platform", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=large_robot_asset_path, position=np.array([-16.80027, -17.26595, 0]), orientation=np.array([0.70711, 0, 0, -0.70711]) ) ) return def get_observations(self): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_joint_positions_ur10 = self.ur10.get_joint_positions() observations= { "task_event": self._task_event, "delay": self.delay, self.moving_platform.name: { "position": current_mp_position, "orientation": current_mp_orientation, "goal_position": self.mp_goal_position }, self.ur10.name: { "joint_positions": current_joint_positions_ur10, } } return observations def get_params(self): params_representation = {} params_representation["arm_name"] = {"value": self.ur10.name, "modifiable": False} params_representation["mp_name"] = {"value": self.moving_platform.name, "modifiable": False} return params_representation def check_prim_exists(self, prim): if prim: return True return False def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def pre_step(self, control_index, simulation_time): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() ee_pose = self.give_location("/World/UR10/ee_link") # iteration 1 if self._task_event == 0: print(self._task_event) self._task_event =21 if self.task_done[self._task_event]: self._task_event =21 self.task_done[self._task_event] = True elif self._task_event == 21: if np.mean(np.abs(ee_pose.p-np.array([-18.01444, -15.97435, 1.40075])))<0.01: self._task_event = 60 elif self._task_event == 60: if self.task_done[self._task_event]: if self.delay == 320: self._task_event = 11 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 11: if self.task_done[self._task_event] and current_mp_position[1]<-24.98: self._task_event =12 self.task_done[self._task_event] = True elif self._task_event == 12: print(np.mean(np.abs(current_mp_orientation-np.array([0,0,0,-1])))) if self.task_done[self._task_event] and np.mean(np.abs(current_mp_orientation-np.array([0,0,0,-1]))) < 0.503: self._task_event = 13 self.task_done[self._task_event] = True elif self._task_event == 13: if self.task_done[self._task_event] and current_mp_position[0]<-36.3: self._task_event =14 self.task_done[self._task_event] = True elif self._task_event == 14: print(np.mean(np.abs(current_mp_orientation-np.array([0.70711,0,0,0.70711])))) if self.task_done[self._task_event] and np.mean(np.abs(current_mp_orientation-np.array([0.70711,0,0,0.70711]))) < 0.0042: self._task_event = 1 self.task_done[self._task_event] = True elif self._task_event == 1: if self.task_done[self._task_event] and current_mp_position[1]>17.3: self._task_event +=1 self.task_done[self._task_event] = True elif self._task_event == 2: print(np.mean(np.abs(current_mp_orientation-np.array([1,0,0,0])))) if self.task_done[self._task_event] and np.mean(np.abs(current_mp_orientation-np.array([1,0,0,0]))) < 0.008: self._task_event += 1 self.task_done[self._task_event] = True elif self._task_event == 3: if self.task_done[self._task_event] and current_mp_position[0]>-20.25: self._task_event +=1 self.task_done[self._task_event] = True # disassembling parts elif self._task_event == 4: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 5: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 6: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 7: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 8: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 9: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 10: if self.task_done[self._task_event]: if self.delay == 100: self._task_event +=1 self.delay=0 else: self.delay+=1 self.task_done[self._task_event] = True elif self._task_event == 11: pass # iteration 9 elif self._task_event == 22: _, current_mp_orientation = self.moving_platform.get_world_pose() if self.task_done[self._task_event] and np.mean(np.abs(current_mp_orientation-np.array([0, 0, 0.70711, 0.70711]))) < 0.035: self._task_event += 1 self.task_done[self._task_event] = True elif self._task_event == 23: current_mp_position, _ = self.moving_platform.get_world_pose() if self.task_done[self._task_event] and current_mp_position[0]<-36: self._task_event += 1 self.task_done[self._task_event] = True elif self._task_event == 24: if self.count >100: if self.task_done[self._task_event]: self._task_event += 1 self.count=0 else: self.count+=1 self.task_done[self._task_event] = True elif self._task_event == 25: if self.count >100: if self.task_done[self._task_event]: self._task_event += 1 self.count=0 else: self.count+=1 self.task_done[self._task_event] = True return def post_reset(self): self._task_event = 0 return class Disassembly(BaseSample): def __init__(self) -> None: super().__init__() self.done = False return def setup_scene(self): world = self.get_world() # adding light l = UsdLux.SphereLight.Define(world.stage, Sdf.Path("/World/Lights")) # l.CreateExposureAttr(...) l.CreateColorTemperatureAttr(10000) l.CreateIntensityAttr(7500) l.CreateRadiusAttr(75) l.AddTranslateOp() XFormPrim("/World/Lights").set_local_pose(translation=np.array([0,0,100])) world.add_task(RobotsPlaying(name="awesome_task")) self.isDone = [False]*120 self.bool_done = [False]*120 self.motion_task_counter=0 return async def setup_post_load(self): self._world = self.get_world() task_params = self._world.get_task("awesome_task").get_params() # bring in moving platforms self.moving_platform = self._world.scene.get_object(task_params["mp_name"]["value"]) # add main cover on table self.add_part_custom("World","main_cover", "ymain_cover", np.array([0.001,0.001,0.001]), np.array([-18.7095, -15.70872, 0.28822]), np.array([0.70711, 0.70711,0,0])) # add parts self.add_part_custom("mobile_platform/platform/unfinished_stuff","FFrame", "FFrame", np.array([1,1,1]), np.array([-5.82832, 0, 0]), np.array([0.5,0.5,0.5,0.5])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","engine_no_rigid", "engine", np.array([1,1,1]), np.array([311.20868, 598.91546, 181.74458]), np.array([0.7,-0.1298,-0.10842,-0.69374])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","FSuspensionFront", "FSuspensionFront", np.array([1,1,1]), np.array([721.62154, 101.55373, 215.10539]), np.array([0.5564, -0.43637, -0.43637, 0.5564])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","FSuspensionFront", "FSuspensionFront_01", np.array([1,1,1]), np.array([797.10001, 103.5, 422.80001]), np.array([0.44177, -0.55212, -0.55212, 0.44177])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","FSuspensionBack", "FSuspensionBack", np.array([1,1,1]), np.array([443.3, 1348.4, 462.9]), np.array([0.09714, -0.03325, -0.76428, 0.63666])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","battery", "battery", np.array([1,1,1]), np.array([377.63, 788.49883, 270.90454]), np.array([0, 0, -0.70711, -0.70711])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","fuel", "fuel", np.array([1,1,1]), np.array([230.13538, 289.31525, 377.64262]), np.array([0.5,0.5,0.5,0.5])) # self.add_part_custom("mobile_platform/platform/unfinished_stuff","main_cover", "main_cover", np.array([1,1,1]), np.array([596.47952, 1231.52815, -151.59531]), np.array([0.51452, 0.48504, -0.51452, -0.48504])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","lower_cover", "lower_cover", np.array([1,1,1]), np.array([435.65021, 418.57531,21.83379]), np.array([0.50942, 0.50942,0.4904, 0.4904])) self.add_part_custom("mobile_platform/platform/unfinished_stuff","lower_cover", "lower_cover_01", np.array([1,1,1]), np.array([36.473, 415.8277, 25.66846]), np.array([0.5,0.5, 0.5, 0.5])) # self.add_part_custom("mobile_platform/platform/unfinished_stuff","Seat", "Seat", np.array([1,1,1]), np.array([179.725, 448.55839, 383.33431]), np.array([0.5,0.5, 0.5, 0.5])) self.add_part_custom(f"mobile_platform/platform/unfinished_stuff","FWheel", f"wheel_03", np.array([1,1,1]), np.array([0.15255, -0.1948, 0.56377]), np.array([0.5, -0.5, 0.5, -0.5])) self.add_part_custom(f"mobile_platform/platform/unfinished_stuff","FWheel", f"wheel_01", np.array([1,1,1]), np.array([0.1522, 0.33709, 0.56377]), np.array([0.5, -0.5, 0.5, -0.5])) self.add_part_custom(f"mobile_platform/platform/unfinished_stuff","FWheel", f"wheel_04", np.array([1,1,1]), np.array([-0.80845, -0.22143, 0.43737]), np.array([0.5, -0.5, 0.5, -0.5])) self.add_part_custom(f"mobile_platform/platform/unfinished_stuff","FWheel", f"wheel_02", np.array([1,1,1]), np.array([-0.80934, 0.35041, 0.43888]), np.array([0.5, -0.5, 0.5, -0.5])) # self.moving_platform = self._world.scene.get_object("moving_platform") self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) # Initialize our controller after load and the first reset self._my_custom_controller = CustomDifferentialController() self._my_controller = WheelBasePoseController(name="cool_controller", open_loop_wheel_controller=DifferentialController(name="simple_control", wheel_radius=0.125, wheel_base=0.46), is_holonomic=False) self.ur10 = self._world.scene.get_object(task_params["arm_name"]["value"]) self.my_controller = KinematicsSolver(self.ur10, attach_gripper=True) self.articulation_controller = self.ur10.get_articulation_controller() # add ee cover on robot # self.add_part_custom("World/UR10/ee_link","main_cover", "main_cover", np.array([0.001,0.001,0.001]), np.array([0.71735, 0.26961, -0.69234]), np.array([0.5,0.5, -0.5, 0.5])) # human body movements declaration # self.set_new_transform("/World/male_human_01/Character_Source/Root/Root/Pelvis/Spine1", [0, 7.16492, -0.03027], [-0.68407, 0.6840694, 0.1790224, -0.1790201]) # self.set_new_transform("/World/male_human/Character_Source/Root/Root/Pelvis/Spine1/Spine2/Spine3/Chest/L_Clavicle/L_UpArm", [18.5044, 0.00001, 0], [0.5378302, -0.2149462, 0.791071, 0.1968338]) # self.set_new_transform("/World/male_human/Character_Source/Root/Root/Pelvis/Spine1/Spine2/Spine3/Chest/R_Clavicle/R_UpArm", [-18.50437, -0.00021, -0.00001], [0.5108233, -0.1681133, 0.8128292, 0.223844]) # for i in range(4): # if i==0: # self.set_new_transform("/World/male_human/Character_Source/Root/Root/Pelvis/Spine1", [0, 7.16492, -0.03027], [-0.68407, 0.6840694, 0.1790224, -0.1790201]) # self.set_new_transform("/World/male_human/Character_Source/Root/Root/Pelvis/Spine1/Spine2/Spine3/Chest/L_Clavicle/L_UpArm", [18.5044, 0.00001, 0], [0.5378302, -0.2149462, 0.791071, 0.1968338]) # self.set_new_transform("/World/male_human/Character_Source/Root/Root/Pelvis/Spine1/Spine2/Spine3/Chest/R_Clavicle/R_UpArm", [-18.50437, -0.00021, -0.00001], [0.5108233, -0.1681133, 0.8128292, 0.223844]) # else: # self.set_new_transform("/World/male_human"+f"_0{i}"+"/Character_Source/Root/Root/Pelvis/Spine1", [0, 7.16492, -0.03027], [-0.68407, 0.6840694, 0.1790224, -0.1790201]) # self.set_new_transform("/World/male_human"+f"_0{i}"+"/Character_Source/Root/Root/Pelvis/Spine1/Spine2/Spine3/Chest/L_Clavicle/L_UpArm", [18.5044, 0.00001, 0], [0.5378302, -0.2149462, 0.791071, 0.1968338]) # self.set_new_transform("/World/male_human"+f"_0{i}"+"/Character_Source/Root/Root/Pelvis/Spine1/Spine2/Spine3/Chest/R_Clavicle/R_UpArm", [-18.50437, -0.00021, -0.00001], [0.5108233, -0.1681133, 0.8128292, 0.223844]) return async def setup_post_reset(self): self._my_controller.reset() await self._world.play_async() return def set_new_transform(self, prim_path, translation, orientation): dc = _dynamic_control.acquire_dynamic_control_interface() # Get the prim you want to move prim = dc.get_rigid_body(prim_path) # Set the new location new_location = Gf.Vec3f(translation[0], translation[1], translation[2]) # Replace with your desired location new_rotation = Gf.Rotation(orientation[0], orientation[1], orientation[2], orientation[3]) # Replace with your desired rotation # Create a new transform new_transform = UsdGeom.TransformAPI(prim) new_transform.SetTransform(UsdGeom.XformOp.Transform(Gf.Matrix4d(new_rotation.GetMatrix(), new_location))) # Apply the new transform dc.set_rigid_body_pose(prim, new_transform.GetLocalTransformation()) def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def move_ur10(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) print(actions) if success: print("still homing on this location") self.articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.05: self.motion_task_counter+=1 print("Completed one motion plan: ", self.motion_task_counter) def send_robot_actions(self, step_size): current_observations = self._world.get_observations() task_params = self._world.get_task("awesome_task").get_params() ## Task event numbering: # 1 - 30 normal events: forward, stop and add piece, turn # 51 - 61 smaller moving platforms events: forward, stop, disappear piece # 71 - pick place tasks if current_observations["task_event"] == 0: print("task 0") print(current_observations["task_event"]) if not self.isDone[current_observations["task_event"]]: self.isDone[current_observations["task_event"]]=True if current_observations["task_event"] == 21: # self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]]: motion_plan = [{"index":0, "position": np.array([-1.09352, -0.27789, 0.58455-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-18.01444, -15.97435, 1.40075]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":1, "position": np.array([-1.09352, -0.27789, 0.19772-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-18.01444, -15.97435, 1.01392]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":2, "position": np.array([-1.09352, -0.27789, 0.58455-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-18.01444, -15.97435, 1.40075]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}, {"index":3, "position": np.array([-0.89016, 0.32513, 0.51038-0.16]), "orientation": np.array([0.60698, -0.36274, 0.60698, 0.36274]), "goal_position":np.array([-17.41105, -16.1764, 1.33072]), "goal_orientation":np.array([0.68569, 0.1727, 0.68569, -0.1727])}, {"index":4, "position": np.array([-0.74286, 0.42878, 0.51038-0.16]), "orientation": np.array([0.6511, -0.2758, 0.6511, 0.2758]), "goal_position":np.array([-17.30707, -16.32381, 1.33072]), "goal_orientation":np.array([0.65542, 0.26538, 0.65542, -0.26538])}, {"index":5, "position": np.array([-0.5015, 0.55795, 0.51038-0.16]), "orientation": np.array([0.6954, -0.12814, 0.6954, 0.12814]), "goal_position":np.array([-17.17748, -16.5655, 1.33072]), "goal_orientation":np.array([0.58233, 0.40111, 0.58233, -0.40111])}, {"index":6, "position": np.array([-0.28875, 0.74261, 0.51038-0.16]), "orientation": np.array([0.70458, -0.0597, 0.70458, 0.0597]), "goal_position":np.array([-16.99268, -16.77844, 1.33072]), "goal_orientation":np.array([0.54043, 0.456, 0.54043, -0.456])}, {"index":7, "position": np.array([0.11095, 0.94627, 0.49096-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-16.79175, -17.17995, 1.31062]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":8, "position": np.array([0.11095, 0.94627, 0.2926-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-16.79175, -17.17995, 1.11226]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":9, "position": np.array([0.11095, 0.94627, 0.19682-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-16.79175, -17.17995, 1.01648]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":10, "position": np.array([0.11095, 0.94627, 0.15697-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-16.79175, -17.17995, 0.97663]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":11, "position": np.array([0.11095, 0.94627, 0.11895-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-16.79175, -17.17995, 0.93861]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":12, "position": np.array([0.11095, 0.94627, 0.07882-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-16.79175, -17.17995, 0.89848]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":13, "position": np.array([0.11095, 0.94627, 0.49096-0.16]), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-16.79175, -17.17995, 1.31062]), "goal_orientation":np.array([0.5,0.5,0.5,-0.5])}, {"index":14, "position": np.array([-0.28875, 0.74261, 0.51038-0.16]), "orientation": np.array([0.70458, -0.0597, 0.70458, 0.0597]), "goal_position":np.array([-16.99268, -16.77844, 1.33072]), "goal_orientation":np.array([0.54043, 0.456, 0.54043, -0.456])}, {"index":15, "position": np.array([-0.5015, 0.55795, 0.51038-0.16]), "orientation": np.array([0.6954, -0.12814, 0.6954, 0.12814]), "goal_position":np.array([-17.17748, -16.5655, 1.33072]), "goal_orientation":np.array([0.58233, 0.40111, 0.58233, -0.40111])}, {"index":16, "position": np.array([-0.74286, 0.42878, 0.51038-0.16]), "orientation": np.array([0.6511, -0.2758, 0.6511, 0.2758]), "goal_position":np.array([-17.30707, -16.32381, 1.33072]), "goal_orientation":np.array([0.65542, 0.26538, 0.65542, -0.26538])}, {"index":17, "position": np.array([-0.89016, 0.32513, 0.51038-0.16]), "orientation": np.array([0.60698, -0.36274, 0.60698, 0.36274]), "goal_position":np.array([-17.41105, -16.1764, 1.33072]), "goal_orientation":np.array([0.68569, 0.1727, 0.68569, -0.1727])}, {"index":18, "position": np.array([-1.09352, -0.27789, 0.58455-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-18.01444, -15.97435, 1.40075]), "goal_orientation":np.array([0.70711, 0, 0.70711, 0])}] self.move_ur10(motion_plan) # remove world main cover and add ee main cover if self.motion_task_counter==2 and not self.bool_done[20]: self.bool_done[20] = True self.remove_part_custom("World", "ymain_cover") self.add_part_custom("World/UR10/ee_link","main_cover", "main_cover", np.array([0.001,0.001,0.001]), np.array([0.71735, 0.26961, -0.69234]), np.array([0.5,0.5, -0.5, 0.5])) # remove ee main cover and add mobile platform main cover if self.motion_task_counter==13 and not self.bool_done[21]: self.bool_done[21] = True self.remove_part_custom("World/UR10/ee_link", "main_cover") self.add_part_custom("mobile_platform/platform/unfinished_stuff","main_cover", "xmain_cover", np.array([1,1,1]), np.array([596.47952, 1231.52815, -151.59531]), np.array([0.51452, 0.48504, -0.51452, -0.48504])) if self.motion_task_counter==19: print("Done motion plan") self.isDone[current_observations["task_event"]]=True # delay elif current_observations["task_event"] == 60: # self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5, 0])) print("task 60 delay:", current_observations["delay"]) # iteration 0 # go forward elif current_observations["task_event"] == 11: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5, 0])) print("task 11") # turns elif current_observations["task_event"] == 12: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) self.moving_platform.apply_action(self._my_custom_controller.turn(command=[[0,0,0,0],np.pi/2])) print("task 12") # go forward elif current_observations["task_event"] == 13: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5, 0])) print("task 13") # turn elif current_observations["task_event"] == 14: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) self.moving_platform.apply_action(self._my_custom_controller.turn(command=[[0,0,0,0],np.pi/2])) print("task 14") # iteration 1 # go forward elif current_observations["task_event"] == 1: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5, 0])) print("task 1") # turn elif current_observations["task_event"] == 2: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) self.moving_platform.apply_action(self._my_custom_controller.turn(command=[[0,0,0,0],np.pi/2])) print("task 2") # go forward elif current_observations["task_event"] == 3: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5, 0])) print("task 3") # stop, remove and add part elif current_observations["task_event"] == 10: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]] and current_observations["delay"]==100: self.remove_part("engine") # prims.delete_prim("/mobile_platform/platform/engine") self.add_part_custom("World/Environment/disassembled_parts","engine_no_rigid", "qengine", np.array([1,1,1]), np.array([-19511.01549, 16368.42662, 451.93828]), np.array([0.99362,0,-0.11281,0])) self.isDone[current_observations["task_event"]]=True # remove and add part elif current_observations["task_event"] == 9: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]] and current_observations["delay"]==100: self.remove_part("FSuspensionFront") self.remove_part("FSuspensionFront_01") self.remove_part("FSuspensionBack") # self.add_part_custom("World/Environment/disassembled_parts","FSuspensionFront", "suspension_front", np.array([1,1,1]), np.array([-21252.07916, 16123.85255, -95.12237]), np.array([0.68988,-0.15515,0.17299,0.68562])) # self.add_part_custom("World/Environment/disassembled_parts","FSuspensionFront", "suspension_front_1", np.array([1,1,1]), np.array([-21253.69102, 15977.78923, -98.17269]), np.array([0.68988,-0.15515,0.17299,0.68562])) self.add_part_custom("World/Environment/disassembled_parts","FSuspensionBack", "suspension_back", np.array([1,1,1]), np.array([-21250.02819, 16296.28288, -79.20706]), np.array([0.69191,-0.16341,0.16465,0.6837])) self.isDone[current_observations["task_event"]]=True # remove and add part elif current_observations["task_event"] == 7: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]] and current_observations["delay"]==100: self.remove_part("fuel") self.add_part_custom("World/Environment/disassembled_parts","FFuelTank", "FFuelTank", np.array([1,1,1]), np.array([-23473.90962, 16316.56526, 266.94776]), np.array([0.5,0.5,0.5,0.5])) self.isDone[current_observations["task_event"]]=True # remove and add part elif current_observations["task_event"] == 8: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]] and current_observations["delay"]==100: self.remove_part("battery") self.add_part_custom("World/Environment/disassembled_parts","battery", "qbattery", np.array([1,1,1]), np.array([-18656.70206, 19011.82244, 283.39021]), np.array([0.5,0.5,0.5,0.5])) self.isDone[current_observations["task_event"]]=True # remove and add part elif current_observations["task_event"] == 6: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]] and current_observations["delay"]==100: self.remove_part("wheel_01") self.remove_part("wheel_02") self.remove_part("wheel_03") self.remove_part("wheel_04") self.add_part_custom("World/Environment/disassembled_parts","FWheel", "qwheel_01", np.array([1,1,1]), np.array([-18656.70206, 19011.82244, 283.39021]), np.array([0.5,0.5,0.5,0.5])) self.add_part_custom("World/Environment/disassembled_parts","FWheel", "qwheel_02", np.array([1,1,1]), np.array([-18656.70206, 19011.82244, 283.39021]), np.array([0.5,0.5,0.5,0.5])) self.add_part_custom("World/Environment/disassembled_parts","FWheel", "qwheel_03", np.array([1,1,1]), np.array([-18656.70206, 19011.82244, 283.39021]), np.array([0.5,0.5,0.5,0.5])) self.add_part_custom("World/Environment/disassembled_parts","FWheel", "qwheel_04", np.array([1,1,1]), np.array([-18656.70206, 19011.82244, 283.39021]), np.array([0.5,0.5,0.5,0.5])) self.isDone[current_observations["task_event"]]=True # remove and add part elif current_observations["task_event"] == 5: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]] and current_observations["delay"]==100: self.remove_part("lower_cover") self.remove_part("lower_cover_01") self.add_part_custom("World/Environment/disassembled_parts","lower_cover", "qlower_cover", np.array([1,1,1]), np.array([-20141.19845, 18913.49002, 272.27849]), np.array([0.5,0.5,0.5,0.5])) self.add_part_custom("World/Environment/disassembled_parts","lower_cover", "qlower_cover_1", np.array([1,1,1]), np.array([-21228.07681, 18923.38351, 272.27849]), np.array([0.5,0.5,0.5,0.5])) self.isDone[current_observations["task_event"]]=True # remove and add part elif current_observations["task_event"] == 4: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0, 0])) if not self.isDone[current_observations["task_event"]] and current_observations["delay"]==100: self.remove_part("xmain_cover") self.add_part_custom("World/Environment/disassembled_parts","main_cover", "qmain_cover", np.array([1,1,1]), np.array([-23651.85127, 19384.76572, 102.60316]), np.array([0.70428,0.70428,0.06314,-0.06314])) self.isDone[current_observations["task_event"]]=True elif current_observations["task_event"] == 11: print("delay") elif current_observations["task_event"] == 12: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5, 0])) return def add_part(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/mock_robot/platform/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/mock_robot/platform/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) def add_part_world(self, parent_prim_name, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/{parent_prim_name}/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/{parent_prim_name}/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_world_pose(position=position, orientation=orientation) return part def add_part_custom(self, parent_prim_name, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/{parent_prim_name}/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/{parent_prim_name}/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def add_part_without_parent(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/World/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/World/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def remove_part(self, prim_path): prims.delete_prim("/mobile_platform/platform/unfinished_stuff/"+prim_path) def remove_part_custom(self, parent_prim_name, child_prim_name): prim_path = f"/{parent_prim_name}/{child_prim_name}" # world = self.get_world() prims.delete_prim(prim_path) def move(self, task): mp = self._world.get_observations()[self._world.get_task("awesome_task").get_params()["mp_name"]["value"]] print(mp) position, orientation, goal_position = mp['position'], mp['orientation'], mp['goal_position'][task-1] # In the function where you are sending robot commands print(goal_position) action = self._my_controller.forward(start_position=position, start_orientation=orientation, goal_position=goal_position) # Change the goal position to what you want full_action = ArticulationAction(joint_efforts=np.concatenate([action.joint_efforts, action.joint_efforts]) if action.joint_efforts else None, joint_velocities=np.concatenate([action.joint_velocities, action.joint_velocities]), joint_positions=np.concatenate([action.joint_positions, action.joint_positions]) if action.joint_positions else None) self.moving_platform.apply_action(full_action)
46,252
Python
63.062327
353
0.611887
swadaskar/Isaac_Sim_Folder/extension_examples/replay_follow_target/replay_follow_target_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.replay_follow_target import ReplayFollowTarget import asyncio import omni.ui as ui 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/app_isaacsim/app_isaacsim/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,564
Python
41.663551
197
0.586766
swadaskar/Isaac_Sim_Folder/extension_examples/replay_follow_target/__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.replay_follow_target.replay_follow_target import ReplayFollowTarget from omni.isaac.examples.replay_follow_target.replay_follow_target_extension import ReplayFollowTargetExtension
634
Python
51.916662
111
0.829653
swadaskar/Isaac_Sim_Folder/extension_examples/replay_follow_target/replay_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.core.utils.types import ArticulationAction from omni.isaac.examples.base_sample import BaseSample from omni.isaac.franka.tasks import FollowTarget as FollowTargetTask import numpy as np 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,297
Python
42.973333
111
0.67061
swadaskar/Isaac_Sim_Folder/extension_examples/robo_factory/robo_factory.py
from omni.isaac.core.prims import GeometryPrim, XFormPrim from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction # This extension includes several generic controllers that could be used with multiple robots from omni.isaac.motion_generation import WheelBasePoseController # Robot specific controller from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController from omni.isaac.core.controllers import BaseController from omni.isaac.core.tasks import BaseTask from omni.isaac.manipulators import SingleManipulator from omni.isaac.manipulators.grippers import SurfaceGripper import numpy as np from omni.isaac.core.objects import VisualCuboid, DynamicCuboid from omni.isaac.core.utils import prims from pxr import UsdLux, Sdf, UsdGeom import omni.usd from omni.isaac.dynamic_control import _dynamic_control from omni.isaac.universal_robots import KinematicsSolver import carb from collections import deque, defaultdict import time class CustomDifferentialController(BaseController): def __init__(self): super().__init__(name="my_cool_controller") # An open loop controller that uses a unicycle model self._wheel_radius = 0.125 self._wheel_base = 1.152 return def forward(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) def turn(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0][0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0][1]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0][2]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0][3]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) class RobotsPlaying(BaseTask): def __init__(self, name): super().__init__(name=name, offset=None) # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -2.628, 0.03551]), np.array([-5.40137, -15.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.eb_goal_position = np.array([-4.39666, 7.64828, 0.035]) self.ur10_goal_position = np.array([]) # self.mp_goal_orientation = np.array([1, 0, 0, 0]) self._task_event = 0 self.task_done = [False]*120 self.motion_event = 0 self.motion_done = [False]*120 self._bool_event = 0 self.count=0 return def set_up_scene(self, scene): super().set_up_scene(scene) assets_root_path = get_assets_root_path() # http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.2.1 asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/photos/real_microfactory_1_2.usd" robot_arm_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd" # adding UR10 for pick and place add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/UR10") # gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/short_gripper.usd" gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/RG2_v2/RG2_v2.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10/ee_link") gripper = SurfaceGripper(end_effector_prim_path="/World/UR10/ee_link", translate=0.1611, direction="x") self.ur10 = scene.add( SingleManipulator(prim_path="/World/UR10", name="my_ur10", end_effector_prim_name="ee_link", gripper=gripper, translation = np.array([-6.09744, -16.5124, 0.24168]), orientation=np.array([0,0,0,1]), scale=np.array([1,1,1])) ) self.ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10 for screwing in part add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/Screw_driving_UR10") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/screw_driver_link/screw_driver_link.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/Screw_driving_UR10/ee_link") screw_gripper = SurfaceGripper(end_effector_prim_path="/World/Screw_driving_UR10/ee_link", translate=0, direction="x") self.screw_ur10 = scene.add( SingleManipulator(prim_path="/World/Screw_driving_UR10", name="my_screw_ur10", end_effector_prim_name="ee_link", gripper=screw_gripper, translation = np.array([-4.02094, -16.52902, 0.24168]), orientation=np.array([0, 0, 0, 1]), scale=np.array([1,1,1])) ) self.screw_ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) large_robot_asset_path = small_robot_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/Collected_full_warehouse_microfactory/Collected_mobile_platform_improved/Collected_mobile_platform/mobile_platform.usd" # add floor add_reference_to_stage(usd_path=asset_path, prim_path="/World/Environment") # add moving platform self.moving_platform = scene.add( WheeledRobot( prim_path="/mock_robot", name="moving_platform", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=large_robot_asset_path, position=np.array([-5.26025, -9.96157, 0.03551]), orientation=np.array([0.5, 0.5, -0.5, -0.5]), ) ) self.engine_bringer = scene.add( WheeledRobot( prim_path="/engine_bringer", name="engine_bringer", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=small_robot_asset_path, position=np.array([-7.47898, -16.15971, 0.035]), orientation=np.array([0,0,0.70711, 0.70711]), ) ) return def get_observations(self): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_eb_position, current_eb_orientation = self.engine_bringer.get_world_pose() current_joint_positions_ur10 = self.ur10.get_joint_positions() observations= { "task_event": self._task_event, "task_event": self._task_event, self.moving_platform.name: { "position": current_mp_position, "orientation": current_mp_orientation, "goal_position": self.mp_goal_position }, self.engine_bringer.name: { "position": current_eb_position, "orientation": current_eb_orientation, "goal_position": self.eb_goal_position }, self.ur10.name: { "joint_positions": current_joint_positions_ur10, }, self.screw_ur10.name: { "joint_positions": current_joint_positions_ur10, }, "bool_counter": self._bool_event } return observations def get_params(self): params_representation = {} params_representation["arm_name"] = {"value": self.ur10.name, "modifiable": False} params_representation["screw_arm"] = {"value": self.screw_ur10.name, "modifiable": False} params_representation["mp_name"] = {"value": self.moving_platform.name, "modifiable": False} params_representation["eb_name"] = {"value": self.engine_bringer.name, "modifiable": False} return params_representation def check_prim_exists(self, prim): if prim: return True return False def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def pre_step(self, control_index, simulation_time): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() ee_pose = self.give_location("/World/UR10/ee_link") screw_ee_pose = self.give_location("/World/Screw_driving_UR10/ee_link") # iteration 1 if self._task_event == 0: if self.task_done[self._task_event]: self._task_event += 1 self.task_done[self._task_event] = True elif self._task_event == 1: if self.task_done[self._task_event] and current_mp_position[1]<-16.69: self._task_event = 51 self._bool_event+=1 self.task_done[self._task_event] = True elif self._task_event == 51: if np.mean(np.abs(ee_pose.p - np.array([-5.005, -16.7606, 0.76714])))<0.02: self._task_event = 71 self._bool_event+=1 elif self._task_event == 71: if np.mean(np.abs(ee_pose.p - np.array([-4.18372, 7.03628, 0.44567])))<0.058: self._task_event=2 pass elif self._task_event == 2: pass return def post_reset(self): self._task_event = 0 return class RoboFactory(BaseSample): def __init__(self) -> None: super().__init__() self.done = False return def setup_scene(self): world = self.get_world() # adding light l = UsdLux.SphereLight.Define(world.stage, Sdf.Path("/World/Lights")) # l.CreateExposureAttr(...) l.CreateColorTemperatureAttr(10000) l.CreateIntensityAttr(7500) l.CreateRadiusAttr(75) l.AddTranslateOp() XFormPrim("/World/Lights").set_local_pose(translation=np.array([0,0,100])) world.add_task(RobotsPlaying(name="awesome_task")) self.isDone = [False]*120 self.bool_done = [False]*120 self.motion_task_counter=0 self.delay=0 print("inside setup_scene", self.motion_task_counter) return async def setup_post_load(self): self._world = self.get_world() task_params = self._world.get_task("awesome_task").get_params() # bring in moving platforms self.moving_platform = self._world.scene.get_object(task_params["mp_name"]["value"]) self.engine_bringer = self._world.scene.get_object(task_params["eb_name"]["value"]) self.add_part_custom("engine_bringer/platform","fuel", "fuel", np.array([0.001,0.001,0.001]), np.array([-0.1769, 0.13468, 0.24931]), np.array([0.5,0.5,-0.5,-0.5])) self.add_part_custom("mock_robot/platform","FSuspensionBack", "xFSuspensionBack", np.array([0.001,0.001,0.001]), np.array([-0.90761, 0.03096, 0.69056]), np.array([0.48732, -0.51946, 0.50085, -0.49176])) self.add_part_custom("mock_robot/platform","engine_no_rigid", "engine", np.array([0.001,0.001,0.001]), np.array([-0.16041, -0.00551, 0.46581]), np.array([0.98404, -0.00148, -0.17792, -0.00274])) self.add_part("FFrame", "frame", np.array([0.001, 0.001, 0.001]), np.array([0.45216, -0.32084, 0.28512]), np.array([0, 0, 0.70711, 0.70711])) self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) # Initialize our controller after load and the first reset self._my_custom_controller = CustomDifferentialController() self._my_controller = WheelBasePoseController(name="cool_controller", open_loop_wheel_controller=DifferentialController(name="simple_control", wheel_radius=0.125, wheel_base=0.46), is_holonomic=False) self.ur10 = self._world.scene.get_object(task_params["arm_name"]["value"]) self.screw_ur10 = self._world.scene.get_object(task_params["screw_arm"]["value"]) self.my_controller = KinematicsSolver(self.ur10, attach_gripper=True) self.screw_my_controller = KinematicsSolver(self.screw_ur10, attach_gripper=True) self.articulation_controller = self.ur10.get_articulation_controller() self.screw_articulation_controller = self.screw_ur10.get_articulation_controller() return async def setup_post_reset(self): self._my_controller.reset() await self._world.play_async() return def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def move_ur10(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) # actions.joint_velocities = [0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] # actions.joint_velocities = [1,1,1,1,1,1] print(actions) if success: print("still homing on this location") self.articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.015: self.motion_task_counter+=1 # time.sleep(0.3) print("Completed one motion plan: ", self.motion_task_counter) def do_screw_driving(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.screw_my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) if success: print("still homing on this location") self.screw_articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/Screw_driving_UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.015: self.motion_task_counter+=1 print("Completed one motion plan: ", self.motion_task_counter) def transform_for_screw_ur10(self, position): position[0]+=0.16171 position[1]+=0.00752 position[2]+=-0.00419 return position def send_robot_actions(self, step_size): current_observations = self._world.get_observations() task_params = self._world.get_task("awesome_task").get_params() ## Task event numbering: # 1 - 30 normal events: forward, stop and add piece, turn # 51 - 61 smaller moving platforms events: forward, stop, disappear piece # 71 - pick place tasks # Terminology # mp - moving platform # iteration 1 # go forward if current_observations["task_event"] == 1: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) if not self.isDone[current_observations["task_event"]]: self.isDone[current_observations["task_event"]]=True # small mp brings in part elif current_observations["task_event"] == 51: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0,0])) if not self.isDone[current_observations["task_event"]]: motion_plan = [{"index":0, "position": np.array([0.90691+0.16, 0.01077, 0.19514]), "orientation": np.array([0.70711,0.70711,0,0]), "goal_position":np.array([-7.00386, -16.5233, 0.43633]), "goal_orientation":np.array([0,0, 0.70711, 0.70711])}, {"index":1, "position": np.array([0.97165+0.16, 0.01077, 0.19514]), "orientation": np.array([0.70711,0.70711,0,0]), "goal_position":np.array([-7.00686, -16.5233, 0.43633]), "goal_orientation":np.array([0, 0, 0.70711, 0.70711])}, {"index":2, "position": np.array([0.97165+0.16, 0.01077, 0.31194]), "orientation": np.array([0.70711,0.70711,0,0]), "goal_position":np.array([-7.0686, -16.5233, 0.55313]), "goal_orientation":np.array([0, 0, 0.70711, 0.70711])}, {"index":3, "position": np.array([-1.09292-0.16, 0.24836, 0.52594]), "orientation": np.array([0,0,0.70711,0.70711]), "goal_position":np.array([-5.005, -16.7606, 0.76714]), "goal_orientation":np.array([0.70711, 0.70711, 0,0])}] self.move_ur10(motion_plan) ee_pose = self.give_location("/World/UR10/ee_link") print(ee_pose) if self.motion_task_counter==2 and not self.bool_done[current_observations["bool_counter"]]: self.bool_done[current_observations["bool_counter"]] = True print("position:", ee_pose.p) print("rotation:", ee_pose.r) self.remove_part("engine_bringer/platform", "fuel") self.add_part_custom("World/UR10/ee_link","fuel", "qfuel", np.array([0.001,0.001,0.001]), np.array([0.22927, -0.16445, -0.08733]), np.array([0.70711,0,-0.70711,0])) if self.motion_task_counter==4: print("Done motion plan") self.isDone[current_observations["task_event"]]=True # arm_robot picks and places part elif current_observations["task_event"] == 71: if not self.isDone[current_observations["task_event"]]: if not self.bool_done[current_observations["bool_counter"]]: self.bool_done[current_observations["bool_counter"]] = True print("Part removal done") self.remove_part("World/UR10/ee_link", "qfuel") self.motion_task_counter=0 self.add_part_custom("mock_robot/platform","fuel", "xfuel", np.array([0.001,0.001,0.001]), np.array([-0.03273, 0.09227, 0.58731]), np.array([0.70711,0.70711,0,0])) def transform(points): points[0]-=0.16 points[2]-=0.15 return points motion_plan = [{"index":0, "position": self.transform_for_screw_ur10(transform(np.array([0.74393, 0.15931, 0.61626]))), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-4.76508, -16.68786, 0.85892]), "goal_orientation":np.array([0,-0.70711,0,0.70711])}, {"index":1, "position": self.transform_for_screw_ur10(transform(np.array([0.74393, 0.15931, 0.5447]))), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-4.76508, -16.68786, 0.78736]), "goal_orientation":np.array([0,-0.70711,0,0.70711])}, {"index":2, "position": self.transform_for_screw_ur10(transform(np.array([0.74393, 0.15931, 0.61626]))), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-4.76508, -16.68786, 0.85892]), "goal_orientation":np.array([0,-0.70711,0,0.70711])}, {"index":3, "position": self.transform_for_screw_ur10(transform(np.array([0.74393, 0.4077, 0.61626]))), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-4.76508, -16.93625, 0.85892]), "goal_orientation":np.array([0,-0.70711,0,0.70711])}, {"index":4, "position": self.transform_for_screw_ur10(transform(np.array([0.74393, 0.4077, 0.5447]))), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-4.76508, -16.93625, 0.78736]), "goal_orientation":np.array([0,-0.70711,0,0.70711])}, {"index":5, "position": self.transform_for_screw_ur10(transform(np.array([0.74393, 0.4077, 0.61626]))), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-4.76508, -16.93625, 0.85892]), "goal_orientation":np.array([0,-0.70711,0,0.70711])}, {"index":6, "position": self.transform_for_screw_ur10(transform(np.array([-0.04511, 0.7374, 0.41493]))), "orientation": np.array([0.70711, 0, 0.70711, 0]), "goal_position":np.array([-3.97604, -17.26595,0.6576]), "goal_orientation":np.array([0,-0.70711,0,0.70711])}] print(self.motion_task_counter) self.do_screw_driving(motion_plan) ee_pose = self.give_location("/World/Screw_driving_UR10/ee_link") print("EE_Pose",ee_pose) if np.mean(np.abs(ee_pose.p - motion_plan[6]["goal_position"]))<0.058: self.isDone[current_observations["task_event"]]=True self.motion_task_counter=0 motion_plan = [{"index":0, "position": np.array([0.07, -0.81, 0.21]), "orientation": np.array([-0.69, 0, 0, 0.72]), "goal_position":np.array([-4.18372, 7.03628, 0.44567]), "goal_orientation":np.array([0.9999, 0, 0, 0])}] self.move_ur10(motion_plan) self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) print("done", self.motion_task_counter) # remove engine and add engine elif current_observations["task_event"] == 2: self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0.5,0])) # elif current_observations["task_event"] == 3: # self.moving_platform.apply_action(self._my_custom_controller.turn(command=[[-0.5, 0.5, -0.5, 0.5],0])) # self.motion_task_counter=0 # elif current_observations["task_event"] == 4: # self.moving_platform.apply_action(self._my_custom_controller.forward(command=[0,0])) # if not self.isDone[current_observations["task_event"]]: # motion_plan = [{"index":0, "position": self.transform_for_screw_ur10(np.array([0.7558, 0.59565, 0.17559])), "orientation": np.array([0.24137, -0.97029, -0.00397, -0.0163]), "goal_position":np.array([-5.3358, 5.42428, 0.41358]), "goal_orientation":np.array([0.18255, -0.68481, -0.68739, 0.15875])}, # {"index":1, "position": self.transform_for_screw_ur10(np.array([0.92167, 0.59565, 0.17559])), "orientation": np.array([0.24137, -0.97029, -0.00397, -0.0163]), "goal_position":np.array([-5.3358, 5.59014, 0.41358]), "goal_orientation":np.array([0.18255, -0.68481, -0.68739, 0.15875])}, # {"index":2, "position": self.transform_for_screw_ur10(np.array([0.7743, 0.13044, 0.24968])), "orientation": np.array([0.14946, 0.98863, 0.00992, 0.01353]), "goal_position":np.array([-4.8676, 5.44277, 0.48787]), "goal_orientation":np.array([0.09521, 0.6933, 0.70482, 0.1162])}, # {"index":3, "position": self.transform_for_screw_ur10(np.array([0.92789, 0.13045, 0.24968])), "orientation": np.array([0.14946, 0.98863, 0.00992, 0.01353]), "goal_position":np.array([-4.8676, 5.59636, 0.48787]), "goal_orientation":np.array([0.09521, 0.6933, 0.70482, 0.1162])}, # {"index":4, "position": np.array([-0.03152, -0.69498, 0.14425]), "orientation": np.array([0.69771, -0.07322, 0.09792, -0.70587]), "goal_position":np.array([-4.04212, 4.63272, 0.38666]), "goal_orientation":np.array([0.99219, -0.12149, 0.01374, 0.02475])}] # self.do_screw_driving(motion_plan) # ee_pose = self.give_location("/World/Screw_driving_UR10/ee_link") # print("EE_Pose",ee_pose) # if self.motion_task_counter>1 and np.mean(np.abs(ee_pose.p - motion_plan[4]["goal_position"]))<0.058: # self.isDone[current_observations["task_event"]]=True # print("done", self.motion_task_counter) return def add_part(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/mock_robot/platform/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/mock_robot/platform/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) def add_part_custom(self, parent_prim_name, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/{parent_prim_name}/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/{parent_prim_name}/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def add_part_without_parent(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/World/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/World/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def remove_part(self, parent_prim_name, child_prim_name): prim_path = f"/{parent_prim_name}/{child_prim_name}" # world = self.get_world() prims.delete_prim(prim_path) def move(self, task): mp = self._world.get_observations()[self._world.get_task("awesome_task").get_params()["mp_name"]["value"]] print(mp) position, orientation, goal_position = mp['position'], mp['orientation'], mp['goal_position'][task-1] # In the function where you are sending robot commands print(goal_position) action = self._my_controller.forward(start_position=position, start_orientation=orientation, goal_position=goal_position) # Change the goal position to what you want full_action = ArticulationAction(joint_efforts=np.concatenate([action.joint_efforts, action.joint_efforts]) if action.joint_efforts else None, joint_velocities=np.concatenate([action.joint_velocities, action.joint_velocities]), joint_positions=np.concatenate([action.joint_positions, action.joint_positions]) if action.joint_positions else None) self.moving_platform.apply_action(full_action)
30,709
Python
58.515504
441
0.610766
swadaskar/Isaac_Sim_Folder/extension_examples/robo_factory/__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.robo_factory.robo_factory import RoboFactory from omni.isaac.examples.robo_factory.robo_factory_extension import RoboFactoryExtension
588
Python
48.083329
88
0.823129
swadaskar/Isaac_Sim_Folder/extension_examples/robo_factory/robo_factory_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.robo_factory import RoboFactory import asyncio import omni.ui as ui 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="", submenu_name="", name="cell 3 fuel", title="RoboFactory", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.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,730
Python
38.57971
146
0.610989
swadaskar/Isaac_Sim_Folder/extension_examples/robo_party/robo_party_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.robo_party import RoboParty import asyncio import omni.ui as ui 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="", submenu_name="", name="suspension feeding", title="RoboParty", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.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,691
Python
38.014492
146
0.605723
swadaskar/Isaac_Sim_Folder/extension_examples/robo_party/robo_party.py
from omni.isaac.core.prims import GeometryPrim, XFormPrim from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction # This extension includes several generic controllers that could be used with multiple robots from omni.isaac.motion_generation import WheelBasePoseController # Robot specific controller from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController from omni.isaac.core.controllers import BaseController from omni.isaac.core.tasks import BaseTask from omni.isaac.manipulators import SingleManipulator from omni.isaac.manipulators.grippers import SurfaceGripper import numpy as np from omni.isaac.core.objects import VisualCuboid, DynamicCuboid from omni.isaac.core.utils import prims from pxr import UsdLux, Sdf, UsdGeom import omni.usd from omni.isaac.dynamic_control import _dynamic_control from omni.isaac.universal_robots import KinematicsSolver import carb from collections import deque, defaultdict import time class CustomDifferentialController(BaseController): def __init__(self): super().__init__(name="my_cool_controller") # An open loop controller that uses a unicycle model self._wheel_radius = 0.125 self._wheel_base = 1.152 return def forward(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) def turn(self, command): # command will have two elements, first element is the forward velocity # second element is the angular velocity (yaw only). joint_velocities = [0.0, 0.0, 0.0, 0.0] joint_velocities[0] = ((2 * command[0][0]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[1] = ((2 * command[0][1]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[2] = ((2 * command[0][2]) - (command[1] * self._wheel_base)) / (2 * self._wheel_radius) joint_velocities[3] = ((2 * command[0][3]) + (command[1] * self._wheel_base)) / (2 * self._wheel_radius) # A controller has to return an ArticulationAction return ArticulationAction(joint_velocities=joint_velocities) class RobotsPlaying(BaseTask): def __init__(self, name): super().__init__(name=name, offset=None) # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] # self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -4.88, 0.03551]), np.array([-5.40137, -17.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.mp_goal_position = [np.array([-5.40137, 5.54515, 0.03551]), np.array([-5.40137, -2.628, 0.03551]), np.array([-5.40137, -15.69, 0.03551]), np.array([-20.45, -17.69, 0.03551]), np.array([-36.03, -17.69, 0.03551]), np.array([-36.03, -4.71, 0.03551]), np.array([-20.84, -4.71, 0.03551]), np.array([-20.84, 7.36, 0.03551]), np.array([-36.06, 7.36, 0.03551]), np.array([-36.06, 19.64, 0.03551]), np.array([-5.40137, 19.64, 0.03551])] self.eb_goal_position = np.array([-4.39666, 7.64828, 0.035]) self.ur10_goal_position = np.array([]) # self.mp_goal_orientation = np.array([1, 0, 0, 0]) self._task_event = 0 self.task_done = [False]*120 self.motion_event = 0 self.motion_done = [False]*120 self._bool_event = 0 self.count=0 return def set_up_scene(self, scene): super().set_up_scene(scene) assets_root_path = get_assets_root_path() # http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.2.1 asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/photos/real_microfactory_1_2.usd" robot_arm_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd" # adding UR10 for pick and place add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/UR10") # gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/short_gripper.usd" gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/RG2_v2/RG2_v2.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10/ee_link") gripper = SurfaceGripper(end_effector_prim_path="/World/UR10/ee_link", translate=0.1611, direction="x") self.ur10 = scene.add( SingleManipulator(prim_path="/World/UR10", name="my_ur10", end_effector_prim_name="ee_link", gripper=gripper, translation = np.array([-6.10078, -5.19303, 0.24168]), orientation=np.array([0,0,0,1]), scale=np.array([1,1,1])) ) self.ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) # adding UR10 for screwing in part add_reference_to_stage(usd_path=robot_arm_path, prim_path="/World/Screw_driving_UR10") gripper_usd = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/robot_tools/screw_driver_link/screw_driver_link.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/Screw_driving_UR10/ee_link") screw_gripper = SurfaceGripper(end_effector_prim_path="/World/Screw_driving_UR10/ee_link", translate=0, direction="x") self.screw_ur10 = scene.add( SingleManipulator(prim_path="/World/Screw_driving_UR10", name="my_screw_ur10", end_effector_prim_name="ee_link", gripper=screw_gripper, translation = np.array([-3.78767, -5.00871, 0.24168]), orientation=np.array([0, 0, 0, 1]), scale=np.array([1,1,1])) ) self.screw_ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0])) large_robot_asset_path = small_robot_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/Collected_full_warehouse_microfactory/Collected_mobile_platform_improved/Collected_mobile_platform/mobile_platform.usd" # add floor add_reference_to_stage(usd_path=asset_path, prim_path="/World/Environment") # add moving platform self.moving_platform = scene.add( WheeledRobot( prim_path="/mock_robot", name="moving_platform", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=large_robot_asset_path, position=np.array([-5.26025, 1.25718, 0.03551]), orientation=np.array([0.5, 0.5, -0.5, -0.5]), ) ) self.engine_bringer = scene.add( WheeledRobot( prim_path="/engine_bringer", name="engine_bringer", wheel_dof_names=["wheel_tl_joint", "wheel_tr_joint", "wheel_bl_joint", "wheel_br_joint"], create_robot=True, usd_path=small_robot_asset_path, position=np.array([-10.39486, -5.70953, 0.035]), orientation=np.array([0,0,0.70711, 0.70711]), ) ) return def get_observations(self): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_eb_position, current_eb_orientation = self.engine_bringer.get_world_pose() current_joint_positions_ur10 = self.ur10.get_joint_positions() observations= { "task_event": self._task_event, "task_event": self._task_event, self.moving_platform.name: { "position": current_mp_position, "orientation": current_mp_orientation, "goal_position": self.mp_goal_position }, self.engine_bringer.name: { "position": current_eb_position, "orientation": current_eb_orientation, "goal_position": self.eb_goal_position }, self.ur10.name: { "joint_positions": current_joint_positions_ur10, }, self.screw_ur10.name: { "joint_positions": current_joint_positions_ur10, }, "bool_counter": self._bool_event } return observations def get_params(self): params_representation = {} params_representation["arm_name"] = {"value": self.ur10.name, "modifiable": False} params_representation["screw_arm"] = {"value": self.screw_ur10.name, "modifiable": False} params_representation["mp_name"] = {"value": self.moving_platform.name, "modifiable": False} params_representation["eb_name"] = {"value": self.engine_bringer.name, "modifiable": False} return params_representation def check_prim_exists(self, prim): if prim: return True return False def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def pre_step(self, control_index, simulation_time): current_mp_position, current_mp_orientation = self.moving_platform.get_world_pose() current_eb_position, current_eb_orientation = self.engine_bringer.get_world_pose() ee_pose = self.give_location("/World/UR10/ee_link") screw_ee_pose = self.give_location("/World/Screw_driving_UR10/ee_link") # iteration 1 if self._task_event == 0: if self.task_done[self._task_event]: self._task_event = 61 self.task_done[self._task_event] = True elif self._task_event == 61: if self.task_done[self._task_event] and current_eb_position[0]>=-6.20: self._task_event = 51 self._bool_event+=1 self.task_done[self._task_event] = True elif self._task_event == 51: if np.mean(np.abs(ee_pose.p - np.array([-5.00127, -4.80822, 0.53949])))<0.02: self._task_event = 71 self._bool_event+=1 elif self._task_event == 71: if np.mean(np.abs(ee_pose.p - np.array([-4.18372, 7.03628, 0.44567])))<0.058: self._task_event=2 elif self._task_event == 2: pass return def post_reset(self): self._task_event = 0 return class RoboParty(BaseSample): def __init__(self) -> None: super().__init__() self.done = False return def setup_scene(self): world = self.get_world() # adding light l = UsdLux.SphereLight.Define(world.stage, Sdf.Path("/World/Lights")) # l.CreateExposureAttr(...) l.CreateColorTemperatureAttr(10000) l.CreateIntensityAttr(7500) l.CreateRadiusAttr(75) l.AddTranslateOp() XFormPrim("/World/Lights").set_local_pose(translation=np.array([0,0,100])) world.add_task(RobotsPlaying(name="awesome_task")) self.isDone = [False]*120 self.bool_done = [False]*120 self.motion_task_counter=0 self.delay=0 print("inside setup_scene", self.motion_task_counter) return async def setup_post_load(self): self._world = self.get_world() task_params = self._world.get_task("awesome_task").get_params() # bring in moving platforms self.moving_platform = self._world.scene.get_object(task_params["mp_name"]["value"]) self.engine_bringer = self._world.scene.get_object(task_params["eb_name"]["value"]) self.add_part_custom("engine_bringer/platform","FSuspensionBack", "FSuspensionBack", np.array([0.001,0.001,0.001]), np.array([-0.84168, -0.14814, 0.31508]), np.array([0.70711, 0, 0.70711, 0])) self.add_part_custom("engine_bringer/platform","FSuspensionBack", "FSuspensionBack_01", np.array([0.001,0.001,0.001]), np.array([-0.69423, -0.14778, 0.31508]), np.array([0.70711, 0, 0.70711, 0])) self.add_part_custom("engine_bringer/platform","FSuspensionBack", "FSuspensionBack_02", np.array([0.001,0.001,0.001]), np.array([-0.53982, -0.14629, 0.31508]), np.array([0.70711, 0, 0.70711, 0])) self.add_part_custom("engine_bringer/platform","FSuspensionBack", "FSuspensionBack_03", np.array([0.001,0.001,0.001]), np.array([-0.37795, -0.147, 0.31508]), np.array([0.70711, 0, 0.70711, 0])) self.add_part_custom("engine_bringer/platform","FSuspensionBack", "FSuspensionBack_04", np.array([0.001,0.001,0.001]), np.array([-0.22874, -0.14663, 0.31508]), np.array([0.70711, 0, 0.70711, 0])) self.add_part_custom("engine_bringer/platform","FSuspensionBack", "FSuspensionBack_05", np.array([0.001,0.001,0.001]), np.array([-0.08344, -0.14627, 0.31508]), np.array([0.70711, 0, 0.70711, 0])) self.add_part_custom("mock_robot/platform","engine_no_rigid", "engine", np.array([0.001,0.001,0.001]), np.array([-0.16041, -0.00551, 0.46581]), np.array([0.98404, -0.00148, -0.17792, -0.00274])) self.add_part("FFrame", "frame", np.array([0.001, 0.001, 0.001]), np.array([0.45216, -0.32084, 0.28512]), np.array([0, 0, 0.70711, 0.70711])) self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) # Initialize our controller after load and the first reset self._my_custom_controller = CustomDifferentialController() self._my_controller = WheelBasePoseController(name="cool_controller", open_loop_wheel_controller=DifferentialController(name="simple_control", wheel_radius=0.125, wheel_base=0.46), is_holonomic=False) self.ur10 = self._world.scene.get_object(task_params["arm_name"]["value"]) self.screw_ur10 = self._world.scene.get_object(task_params["screw_arm"]["value"]) self.my_controller = KinematicsSolver(self.ur10, attach_gripper=True) self.screw_my_controller = KinematicsSolver(self.screw_ur10, attach_gripper=True) self.articulation_controller = self.ur10.get_articulation_controller() self.screw_articulation_controller = self.screw_ur10.get_articulation_controller() return async def setup_post_reset(self): self._my_controller.reset() await self._world.play_async() return def give_location(self, prim_path): dc=_dynamic_control.acquire_dynamic_control_interface() object=dc.get_rigid_body(prim_path) object_pose=dc.get_rigid_body_pose(object) return object_pose # position: object_pose.p, rotation: object_pose.r def move_ur10(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) if success: print("still homing on this location") self.articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.015: self.motion_task_counter+=1 print("Completed one motion plan: ", self.motion_task_counter) def do_screw_driving(self, locations): target_location = locations[self.motion_task_counter] print("Doing "+str(target_location["index"])+"th motion plan") actions, success = self.screw_my_controller.compute_inverse_kinematics( target_position=target_location["position"], target_orientation=target_location["orientation"], ) if success: print("still homing on this location") self.screw_articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # check if reached location curr_location = self.give_location("/World/Screw_driving_UR10/ee_link") print("Curr:",curr_location.p) print("Goal:", target_location["goal_position"]) print(np.mean(np.abs(curr_location.p - target_location["goal_position"]))) if np.mean(np.abs(curr_location.p - target_location["goal_position"]))<0.015: self.motion_task_counter+=1 print("Completed one motion plan: ", self.motion_task_counter) def transform_for_screw_ur10(self, position): position[0]+=0.16171 position[1]+=0.00752 position[2]+=-0.00419 return position def send_robot_actions(self, step_size): current_observations = self._world.get_observations() task_params = self._world.get_task("awesome_task").get_params() ## Task event numbering: # 1 - 30 normal events: forward, stop and add piece, turn # 51 - 61 smaller moving platforms events: forward, stop, disappear piece # 71 - pick place tasks # Terminology # mp - moving platform # iteration 1 if current_observations["task_event"] == 61: self.engine_bringer.apply_action(self._my_custom_controller.forward(command=[-0.5,0])) if not self.isDone[current_observations["task_event"]]: self.isDone[current_observations["task_event"]]=True # small mp brings in part elif current_observations["task_event"] == 51: self.engine_bringer.apply_action(self._my_custom_controller.forward(command=[0,0])) if not self.isDone[current_observations["task_event"]]: motion_plan = [{"index":0, "position": np.array([-0.318, 0.88177, 0.2+0.2012-0.16]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-5.78548, -6.07645, 0.2+0.44332]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":1, "position": np.array([-0.318, 0.88177, 0.2012-0.16]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-5.78548, -6.07645, 0.44332]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":2, "position": np.array([-0.318, 0.88177, 0.2+0.2012-0.16]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-5.78548, -6.07645, 0.2+0.44332]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":3, "position": np.array([0.7248, 0.10255, 0.3432+0.2-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -5.29498, 0.58419+0.2]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":4, "position": np.array([0.7248, 0.10255, 0.3432-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -5.29498, 0.58419]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":5, "position": np.array([0.7248, 0.10255, 0.3432+0.2-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -5.29498, 0.58419+0.2]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":6, "position": np.array([-0.17293, 0.88177, 0.2012-0.16+0.2]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-5.93055, -6.07645, 0.44332+0.2]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":7, "position": np.array([-0.17293, 0.88177, 0.2012-0.16]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-5.93055, -6.07645, 0.44332]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":8, "position": np.array([-0.17293, 0.88177, 0.2012-0.16+0.2]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-5.93055, -6.07645, 0.44332+0.2]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":9, "position": np.array([0.7248, -0.06149, 0.3432-0.16+0.2]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -5.13094, 0.58419+0.2]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":10, "position": np.array([0.7248, -0.06149, 0.3432-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -5.13094, 0.58419]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":11, "position": np.array([0.7248, -0.06149, 0.3432-0.16+0.2]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -5.13094, 0.58419+0.2]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":12, "position": np.array([-0.0188, 0.88177, 0.2012-0.16+0.2]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-6.08468, -6.07645, 0.44332+0.2]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":13, "position": np.array([-0.0188, 0.88177, 0.2012-0.16]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-6.08468, -6.07645, 0.44332]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":14, "position": np.array([-0.0188, 0.88177, 0.2012-0.16+0.2]), "orientation": np.array([0, -0.70711, 0, 0.70711]), "goal_position":np.array([-6.08468, -6.07645, 0.44332+0.2]), "goal_orientation":np.array([0.70711,0,0.70711,0])}, {"index":15, "position": np.array([0.7248, -0.22445, 0.3432-0.16+0.2]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -4.96798, 0.58419+0.2]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":16, "position": np.array([0.7248, -0.22445, 0.3432-0.16]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -4.96798, 0.58419]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}, {"index":17, "position": np.array([0.7248, -0.22445, 0.3432-0.16+0.2]), "orientation": np.array([0.5, -0.5, 0.5, 0.5]), "goal_position":np.array([-6.82643, -4.96798, 0.58419+0.2]), "goal_orientation":np.array([0.5, 0.5, 0.5, -0.5])}] self.move_ur10(motion_plan) # pick up suspension if self.motion_task_counter==2 and not self.bool_done[21]: self.bool_done[21] = True self.remove_part("engine_bringer/platform", "FSuspensionBack") self.add_part_custom("World/UR10/ee_link","FSuspensionBack", "qFSuspensionBack", np.array([0.001,0.001,0.001]), np.array([0.16839, 0.158, -0.44332]), np.array([0,0,0,1])) # drop suspension if self.motion_task_counter==5 and not self.bool_done[22]: self.bool_done[22] = True self.remove_part("World/UR10/ee_link", "qFSuspensionBack") self.add_part_custom("World/Environment","FSuspensionBack", "xFSuspensionBack", np.array([0.001,0.001,0.001]), np.array([-6.66734, -4.8518, 0.41407]), np.array([0.5,0.5,-0.5,0.5])) # pick up suspension if self.motion_task_counter==8 and not self.bool_done[23]: self.bool_done[23] = True self.remove_part("engine_bringer/platform", "FSuspensionBack_01") self.add_part_custom("World/UR10/ee_link","FSuspensionBack", "qFSuspensionBack_01", np.array([0.001,0.001,0.001]), np.array([0.16839, 0.158, -0.44332]), np.array([0,0,0,1])) # drop suspension if self.motion_task_counter==11 and not self.bool_done[24]: self.bool_done[24] = True self.remove_part("World/UR10/ee_link", "qFSuspensionBack_01") self.add_part_custom("World/Environment","FSuspensionBack", "xFSuspensionBack_01", np.array([0.001,0.001,0.001]), np.array([-6.66734, -4.68841, 0.41407]), np.array([0.5,0.5,-0.5,0.5])) # pick up suspension if self.motion_task_counter==14 and not self.bool_done[25]: self.bool_done[25] = True self.remove_part("engine_bringer/platform", "FSuspensionBack_02") self.add_part_custom("World/UR10/ee_link","FSuspensionBack", "qFSuspensionBack_02", np.array([0.001,0.001,0.001]), np.array([0.16839, 0.158, -0.44332]), np.array([0,0,0,1])) # drop suspension if self.motion_task_counter==17 and not self.bool_done[26]: self.bool_done[26] = True self.remove_part("World/UR10/ee_link", "qFSuspensionBack_02") self.add_part_custom("World/Environment","FSuspensionBack", "xFSuspensionBack_02", np.array([0.001,0.001,0.001]), np.array([-6.66734, -4.52502, 0.41407]), np.array([0.5,0.5,-0.5,0.5])) if self.motion_task_counter==18: print("Done motion plan") self.isDone[current_observations["task_event"]]=True # arm_robot picks and places part elif current_observations["task_event"] == 71: pass return def add_part(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/mock_robot/platform/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/mock_robot/platform/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) def add_part_custom(self, parent_prim_name, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/{parent_prim_name}/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/{parent_prim_name}/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def add_part_without_parent(self, part_name, prim_name, scale, position, orientation): world = self.get_world() base_asset_path = "/home/lm-2023/Isaac_Sim/isaac sim samples/real_microfactory/Materials/atvsstlfiles/" add_reference_to_stage(usd_path=base_asset_path+f"{part_name}/{part_name}.usd", prim_path=f"/World/{prim_name}") # gives asset ref path part= world.scene.add(XFormPrim(prim_path=f'/World/{prim_name}', name=f"q{prim_name}")) # declares in the world ## add part part.set_local_scale(scale) part.set_local_pose(translation=position, orientation=orientation) return part def remove_part(self, parent_prim_name, child_prim_name): prim_path = f"/{parent_prim_name}/{child_prim_name}" # world = self.get_world() prims.delete_prim(prim_path) def move(self, task): mp = self._world.get_observations()[self._world.get_task("awesome_task").get_params()["mp_name"]["value"]] print(mp) position, orientation, goal_position = mp['position'], mp['orientation'], mp['goal_position'][task-1] # In the function where you are sending robot commands print(goal_position) action = self._my_controller.forward(start_position=position, start_orientation=orientation, goal_position=goal_position) # Change the goal position to what you want full_action = ArticulationAction(joint_efforts=np.concatenate([action.joint_efforts, action.joint_efforts]) if action.joint_efforts else None, joint_velocities=np.concatenate([action.joint_velocities, action.joint_velocities]), joint_positions=np.concatenate([action.joint_positions, action.joint_positions]) if action.joint_positions else None) self.moving_platform.apply_action(full_action)
30,782
Python
60.566
441
0.608018
swadaskar/Isaac_Sim_Folder/extension_examples/robo_party/__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.robo_party.robo_party import RoboParty from omni.isaac.examples.robo_party.robo_party_extension import RoboPartyExtension
576
Python
47.083329
82
0.819444
swadaskar/Isaac_Sim_Folder/extension_examples/follow_target/__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.follow_target.follow_target import FollowTarget from omni.isaac.examples.follow_target.follow_target_extension import FollowTargetExtension
594
Python
48.583329
91
0.824916
swadaskar/Isaac_Sim_Folder/extension_examples/follow_target/follow_target.py
import carb import asyncio from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.robots import Robot import rospy import rosgraph # import actionlib # # Isaac sim cannot find these two modules for some reason... # from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal # from obstacle_map import GridMap # # Using /move_base_simple/goal for now from geometry_msgs.msg import PoseStamped import numpy as np class FollowTarget(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() # FIXME add_reference_to_stage(usd_path='/home/lm-2023/Isaac_Sim/navigation/Collected_real_microfactory_show/real_microfactory_show.usd', prim_path="/World") world.scene.add(Robot(prim_path="/World/damobile_platform", name="damobile_platform")) return async def setup_post_load(self): self._world = self.get_world() self._mp = self._world.scene.get_object("damobile_platform") if not rosgraph.is_master_online(): print("Please run roscore before executing this script") return try: rospy.init_node("set_goal_py") except rospy.exceptions.ROSException as e: print("Node has already been initialized, do nothing") # FIXME # self._initial_goal_publisher = rospy.Publisher("initialpose", PoseWithCovarianceStamped, queue_size=1) # self.__send_initial_pose() # await asyncio.sleep(1.0) # self._action_client = actionlib.SimpleActionClient("move_base", MoveBaseAction) self._goal_pub = rospy.Publisher("/move_base_simple/goal", PoseStamped, queue_size=1) return # def __send_initial_pose(self): # mp_position, mp_orientation = self._mp.get_world_pose() # current_pose = PoseWithCovarianceStamped() # current_pose.header.frame_id = "map" # current_pose.header.stamp = rospy.get_rostime() # current_pose.pose.pose.position.x = mp_position[0] # current_pose.pose.pose.position.y = mp_position[1] # current_pose.pose.pose.position.z = mp_position[2] # current_pose.pose.pose.orientation.x = mp_orientation[0] # current_pose.pose.pose.orientation.y = mp_orientation[1] # current_pose.pose.pose.orientation.z = mp_orientation[2] # current_pose.pose.pose.orientation.w = mp_orientation[3] # # rospy.sleep will stall Isaac sim simulation # # rospy.sleep(1) # self._initial_goal_publisher.publish(current_pose) # def __goal_response_callback(self, current_state, result): # if current_state not in [0, 1, 3]: # print("Goal rejected :(") # return # print("Goal accepted :)") # wait = self._action_client.wait_for_result() # self.__get_result_callback(wait) # def __get_result_callback(self, wait): # print("Result: "+str(wait)) # def send_navigation_goal(self, x, y, a): # FIXME # map_yaml_path = "/home/shihanzh/ros_ws/src/mp_2dnav/map/mp_microfactory_navigation.yaml" # grid_map = GridMap(map_yaml_path) # # generate random goal # if x is None: # print("No goal received. Generating random goal...") # range_ = grid_map.get_range() # x = np.random.uniform(range_[0][0], range_[0][1]) # y = np.random.uniform(range_[1][0], range_[1][1]) # orient_x = 0 # not needed because robot is in x,y plane # orient_y = 0 # not needed because robot is in x,y plane # orient_z = np.random.uniform(0, 1) # orient_w = np.random.uniform(0, 1) # else: # orient_x, orient_y, orient_z, orient_w = quaternion_from_euler(0, 0, a) # pose = [x, y, orient_x, orient_y, orient_z, orient_w] # if grid_map.is_valid_pose([x, y], 0.2): # self._action_client.wait_for_server() # goal_msg = MoveBaseGoal() # goal_msg.target_pose.header.frame_id = "map" # goal_msg.target_pose.header.stamp = rospy.get_rostime() # print("goal pose: "+str(pose)) # goal_msg.target_pose.pose.position.x = pose[0] # goal_msg.target_pose.pose.position.y = pose[1] # goal_msg.target_pose.pose.orientation.x = pose[2] # goal_msg.target_pose.pose.orientation.y = pose[3] # goal_msg.target_pose.pose.orientation.z = pose[4] # goal_msg.target_pose.pose.orientation.w = pose[5] # self._action_client.send_goal(goal_msg, done_cb=self.__goal_response_callback) # else: # print("Invalid goal "+str(pose)) # return async def setup_pre_reset(self): return async def setup_post_reset(self): return def world_cleanup(self): return
5,080
Python
39.325397
157
0.605906
swadaskar/Isaac_Sim_Folder/extension_examples/follow_target/follow_target_extension.py
import os from omni.isaac.examples.base_sample import BaseSampleExtension from omni.isaac.examples.follow_target import FollowTarget import omni.ext import omni.ui as ui from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder import asyncio import numpy as np import rospy from geometry_msgs.msg import PoseStamped from tf.transformations import euler_from_quaternion, quaternion_from_euler from math import pi class FollowTargetExtension(BaseSampleExtension): # same as in mp_2dnav package base_local_planner_params.yaml _xy_goal_tolerance = 0.25 _yaw_goal_tolerance = 0.05 def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="Navigation", 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=FollowTarget(), ) return 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: with ui.VStack(spacing=5, height=0): 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 dict = { "label": "Send Goal", "type": "button", "text": "Goal", "tooltip": "", "on_clicked_fn": self._send_navigation_goal, } self._buttons["Send Goal"] = btn_builder(**dict) self._buttons["Send Goal"].enabled = False return def post_load_button_event(self): self._buttons["Send Goal"].enabled = True def _check_goal_reached(self, goal_pose): # Cannot get result from ROS because /move_base/result also uses move_base_msgs module mp_position, mp_orientation = self._sample._mp.get_world_pose() _, _, mp_yaw = euler_from_quaternion(mp_orientation) _, _, goal_yaw = euler_from_quaternion(goal_pose[3:]) # FIXME: pi needed for yaw tolerance here because map rotated 180 degrees if np.allclose(mp_position[:2], goal_pose[:2], atol=self._xy_goal_tolerance) \ and abs(mp_yaw-goal_yaw) <= pi + self._yaw_goal_tolerance: print("Goal "+str(goal_pose)+" reached!") # This seems to crash Isaac sim... # self.get_world().remove_physics_callback("mp_nav_check") # Goal hardcoded for now def _send_navigation_goal(self, x=None, y=None, a=None): # x, y, a = -18, 14, 3.14 x,y,a = -1,7,3.14 orient_x, orient_y, orient_z, orient_w = quaternion_from_euler(0, 0, a) pose = [x, y, 0, orient_x, orient_y, orient_z, orient_w] goal_msg = PoseStamped() goal_msg.header.frame_id = "map" goal_msg.header.stamp = rospy.get_rostime() print("goal pose: "+str(pose)) goal_msg.pose.position.x = pose[0] goal_msg.pose.position.y = pose[1] goal_msg.pose.position.z = pose[2] goal_msg.pose.orientation.x = pose[3] goal_msg.pose.orientation.y = pose[4] goal_msg.pose.orientation.z = pose[5] goal_msg.pose.orientation.w = pose[6] self._sample._goal_pub.publish(goal_msg) # self._check_goal_reached(pose) world = self.get_world() if not world.physics_callback_exists("mp_nav_check"): world.add_physics_callback("mp_nav_check", lambda step_size: self._check_goal_reached(pose)) # Overwrite check with new goal else: world.remove_physics_callback("mp_nav_check") world.add_physics_callback("mp_nav_check", lambda step_size: self._check_goal_reached(pose))
6,559
Python
44.241379
135
0.523403
swadaskar/Isaac_Sim_Folder/extension_examples/tests/test_replay_follow_target.py
# Copyright (c) 2018-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. # # 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 import omni.kit.test import omni.kit import asyncio # 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 from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async import os 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
37.337209
119
0.668386
swadaskar/Isaac_Sim_Folder/extension_examples/tests/test_path_planning.py
# Copyright (c) 2018-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. # # 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 import omni.kit import asyncio # 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 from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async import numpy as np 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,026
Python
35.914634
119
0.66887
swadaskar/Isaac_Sim_Folder/extension_examples/tests/test_nut_bolt.py
# Copyright (c) 2018-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. # # 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 import omni.kit import asyncio # 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 from omni.isaac.core.utils.stage import create_new_stage_async, is_stage_loading, update_stage_async from math import isclose 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(4000): await update_stage_async() nut_on_bolt = False bolt = world.scene.get_object(f"bolt0_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(4000): await update_stage_async() nut_on_bolt = False bolt = world.scene.get_object(f"bolt0_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
37.526315
119
0.626401
swadaskar/Isaac_Sim_Folder/extension_examples/tests/__init__.py
# Copyright (c) 2018-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 .test_kaya_gamepad import * from .test_bin_filling import * from .test_follow_target import * from .test_omnigraph_keyboard import * from .test_robo_factory import * from .test_robo_party import * from .test_simple_stack import * from .test_hello_world import * from .test_replay_follow_target import * from .test_path_planning import * from .test_nut_bolt import *
805
Python
37.380951
76
0.785093