Using a task-space controller#
Use controllers.DifferentialIKController to command an end-effector pose
and compute joint position targets. This is useful for reaching and teleoperation,
where specifying a hand pose is often easier than choosing each joint angle.
This tutorial uses OvPhysX and the Newton RTX visualizer. Install the ov extra; Isaac Sim is not required.
For controller selection and the control-loop walkthrough, see
Controllers.
The Code#
The tutorial corresponds to the run_diff_ik.py script in the
scripts/tutorials/05_controllers directory.
Code for run_diff_ik.py
1# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
2# All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5
6"""
7This script demonstrates how to use the differential inverse kinematics controller with the simulator.
8
9The differential IK controller can be configured in different modes. It uses the Jacobians computed by
10PhysX. This helps perform parallelized computation of the inverse kinematics.
11
12The Franka high-PD preset uses the same USD and effort limits as the base preset, with stiffer gains
13for tracking IK targets. Other tasks can retain their calibrated actuator gains.
14
15.. code-block:: bash
16
17 # Usage
18 uv run --extra ov python scripts/tutorials/05_controllers/run_diff_ik.py
19
20"""
21
22"""Parse the command-line arguments first."""
23
24import argparse
25from types import SimpleNamespace
26from typing import TYPE_CHECKING
27
28from isaaclab_ov.physics import OvPhysxCfg
29
30from isaaclab.app import add_launcher_args, launch_simulation
31
32# add argparse arguments
33parser = argparse.ArgumentParser(description="Tutorial on using the differential IK controller.")
34parser.add_argument("--robot", type=str, default="franka_panda", help="Name of the robot.")
35parser.add_argument("--num_envs", type=int, default=128, help="Number of environments to spawn.")
36# append simulation launcher cli args
37add_launcher_args(parser)
38parser.set_defaults(visualizer=["newton_rtx"])
39# parse the arguments
40args_cli = parser.parse_args()
41
42"""Rest everything follows."""
43
44import torch
45
46from pxr import Usd, UsdGeom
47
48import isaaclab.sim as sim_utils
49from isaaclab.assets import AssetBaseCfg
50from isaaclab.controllers import DifferentialIKController, DifferentialIKControllerCfg
51from isaaclab.managers import SceneEntityCfg
52from isaaclab.markers import VisualizationMarkers
53from isaaclab.markers.config import FRAME_MARKER_CFG
54from isaaclab.scene import InteractiveSceneCfg
55from isaaclab.utils import clone, configclass, instantiate, replace
56from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR
57from isaaclab.utils.math import subtract_frame_transforms
58
59if TYPE_CHECKING:
60 from isaaclab.scene import InteractiveScene
61
62##
63# Pre-defined configs
64##
65from isaaclab_assets import FRANKA_PANDA_HIGH_PD_CFG, UR10_CFG # isort:skip
66
67
68def spawn_table(prim_path, cfg, translation=None, orientation=None, **kwargs) -> Usd.Prim:
69 """Correct the stand asset's face-varying normals for the Newton viewer importer."""
70 prim = sim_utils.spawn_from_usd(prim_path, cfg, translation, orientation, **kwargs)
71 mesh = UsdGeom.Mesh(prim.GetStage().GetPrimAtPath(prim.GetPath().AppendPath("Visuals/Base")))
72 normals = mesh.GetNormalsAttr().Get()
73 if len(normals) == len(mesh.GetFaceVertexIndicesAttr().Get()) and len(normals) != len(mesh.GetPointsAttr().Get()):
74 mesh.SetNormalsInterpolation(UsdGeom.Tokens.faceVarying)
75 return prim
76
77
78@configclass
79class TableTopSceneCfg(InteractiveSceneCfg):
80 """Configuration for a cart-pole scene."""
81
82 # ground plane
83 ground = AssetBaseCfg(
84 prim_path="/World/defaultGroundPlane",
85 spawn=sim_utils.GroundPlaneCfg(),
86 init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, -1.05)),
87 )
88
89 # lights
90 dome_light = AssetBaseCfg(
91 prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75))
92 )
93
94 # mount
95 table = AssetBaseCfg(
96 prim_path="{ENV_REGEX_NS}/Table",
97 spawn=sim_utils.UsdFileCfg(
98 func=spawn_table,
99 usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/Stand/stand_instanceable.usd",
100 scale=(2.0, 2.0, 2.0),
101 make_uninstanceable=True,
102 ),
103 )
104
105 # articulation
106 if args_cli.robot == "franka_panda":
107 robot = replace(FRANKA_PANDA_HIGH_PD_CFG, prim_path="{ENV_REGEX_NS}/Robot")
108 robot.spawn.variants["Physics"] = "physx"
109 elif args_cli.robot == "ur10":
110 robot = replace(UR10_CFG, prim_path="{ENV_REGEX_NS}/Robot")
111 else:
112 raise ValueError(f"Robot {args_cli.robot} is not supported. Valid: franka_panda, ur10")
113
114
115def run_simulator(sim: sim_utils.SimulationContext, scene: "InteractiveScene"):
116 """Runs the simulation loop."""
117 # Extract scene entities
118 # note: we only do this here for readability.
119 robot = scene["robot"]
120
121 # Create controller
122 diff_ik_cfg = DifferentialIKControllerCfg(command_type="pose", use_relative_mode=False, ik_method="dls")
123 diff_ik_controller = DifferentialIKController(diff_ik_cfg, num_envs=scene.num_envs, device=sim.device)
124
125 # Markers
126 frame_marker_cfg = clone(FRAME_MARKER_CFG)
127 frame_marker_cfg.markers["frame"].scale = (0.1, 0.1, 0.1)
128 ee_marker = VisualizationMarkers(replace(frame_marker_cfg, prim_path="/Visuals/ee_current"))
129 goal_marker = VisualizationMarkers(replace(frame_marker_cfg, prim_path="/Visuals/ee_goal"))
130
131 # Define goals for the arm (x,y,z,qx,qy,qz,qw)
132 ee_goals = [
133 [0.5, 0.5, 0.7, 0, 0.707, 0, 0.707],
134 [0.5, -0.4, 0.6, 0.707, 0, 0, 0.707],
135 [0.5, 0, 0.5, 1.0, 0.0, 0.0, 0.0],
136 ]
137 ee_goals = torch.tensor(ee_goals, device=sim.device)
138 # Track the given command
139 current_goal_idx = 0
140 # Create buffers to store actions
141 ik_commands = torch.zeros(scene.num_envs, diff_ik_controller.action_dim, device=robot.device)
142 ik_commands[:] = ee_goals[current_goal_idx]
143
144 # Specify robot-specific parameters
145 if args_cli.robot == "franka_panda":
146 robot_entity_cfg = SceneEntityCfg("robot", joint_names=["panda_joint.*"], body_names=["panda_hand"])
147 elif args_cli.robot == "ur10":
148 robot_entity_cfg = SceneEntityCfg("robot", joint_names=[".*"], body_names=["ee_link"])
149 else:
150 raise ValueError(f"Robot {args_cli.robot} is not supported. Valid: franka_panda, ur10")
151 # Resolving the scene entities
152 robot_entity_cfg.resolve(scene)
153 # Obtain the frame index of the end-effector
154 # For a fixed base robot, the frame index is one less than the body index. This is because
155 # the root body is not included in the returned Jacobians.
156 if robot.is_fixed_base:
157 ee_jacobi_idx = robot_entity_cfg.body_ids[0] - 1
158 else:
159 ee_jacobi_idx = robot_entity_cfg.body_ids[0]
160
161 # Define simulation stepping
162 sim_dt = sim.get_physics_dt()
163 count = 0
164 # Simulation loop
165 while sim.is_running():
166 # reset
167 if count % 150 == 0:
168 # reset time
169 count = 0
170 # reset joint state
171 joint_pos = robot.data.default_joint_pos.torch.clone()
172 joint_vel = robot.data.default_joint_vel.torch.clone()
173 robot.write_joint_position_to_sim_index(position=joint_pos)
174 robot.write_joint_velocity_to_sim_index(velocity=joint_vel)
175 robot.reset()
176 # reset actions
177 ik_commands[:] = ee_goals[current_goal_idx]
178 joint_pos_des = joint_pos[:, robot_entity_cfg.joint_ids].clone()
179 # reset controller
180 diff_ik_controller.reset()
181 diff_ik_controller.set_command(ik_commands)
182 # change goal
183 current_goal_idx = (current_goal_idx + 1) % len(ee_goals)
184 else:
185 # obtain quantities from simulation. The Jacobian DoF axis prepends
186 # ``num_base_dofs`` floating-base columns (0 for fixed-base, 6 for
187 # floating-base); shift the actuated-joint ids accordingly.
188 jacobi_joint_ids = [j + robot.num_base_dofs for j in robot_entity_cfg.joint_ids]
189 jacobian = robot.data.body_link_jacobian_w.torch[:, ee_jacobi_idx, :, jacobi_joint_ids]
190 ee_pose_w = robot.data.body_pose_w.torch[:, robot_entity_cfg.body_ids[0]]
191 root_pose_w = robot.data.root_pose_w.torch
192 joint_pos = robot.data.joint_pos.torch[:, robot_entity_cfg.joint_ids]
193 # compute frame in root frame
194 ee_pos_b, ee_quat_b = subtract_frame_transforms(
195 root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7]
196 )
197 # compute the joint commands
198 joint_pos_des = diff_ik_controller.compute(ee_pos_b, ee_quat_b, jacobian, joint_pos)
199
200 # apply actions
201 robot.set_joint_position_target_index(target=joint_pos_des, joint_ids=robot_entity_cfg.joint_ids)
202 scene.write_data_to_sim()
203 # perform step
204 sim.step()
205 # update sim-time
206 count += 1
207 # update buffers
208 scene.update(sim_dt)
209
210 # obtain quantities from simulation
211 ee_pose_w = robot.data.body_state_w.torch[:, robot_entity_cfg.body_ids[0], 0:7]
212 # update marker positions
213 ee_marker.visualize(ee_pose_w[:, 0:3], ee_pose_w[:, 3:7])
214 goal_marker.visualize(ik_commands[:, 0:3] + scene.env_origins, ik_commands[:, 3:7])
215
216
217def main():
218 """Main function."""
219 # Configure the simulation
220 sim_cfg = sim_utils.SimulationCfg(
221 physics=OvPhysxCfg(),
222 dt=0.01,
223 device=args_cli.device,
224 )
225 # Launch the simulator runtime that the configuration needs
226 scene_cfg = TableTopSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0)
227 with launch_simulation(SimpleNamespace(sim=sim_cfg, scene=scene_cfg), args_cli):
228 # Initialize the simulation context
229 sim = sim_utils.SimulationContext(sim_cfg)
230 # Set main camera
231 sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0])
232 # Design scene
233 scene = instantiate(scene_cfg)
234 # Play the simulator
235 sim.reset()
236 # Now we are ready!
237 print("[INFO]: Setup complete...")
238 # Run the simulator
239 run_simulator(sim, scene)
240
241
242if __name__ == "__main__":
243 # run the main function
244 main()
The Code Explained#
While using any task-space controller, it is important to ensure that the provided
quantities are in the correct frames. When parallelizing environment instances, they are
all existing in the same unique simulation world frame. However, typically, we want each
environment itself to have its own local frame. This is accessible through the
scene.InteractiveScene.env_origins attribute.
In our APIs, we use the following notation for frames:
The simulation world frame (denoted as
w), which is the frame of the entire simulation.The local environment frame (denoted as
e), which is the frame of the local environment.The robot’s base frame (denoted as
b), which is the frame of the robot’s base link.
Since the asset instances are not “aware” of the local environment frame, they return their states in the simulation world frame. Thus, we need to convert the obtained quantities to the local environment frame. This is done by subtracting the local environment origin from the obtained quantities.
Creating an IK controller#
The DifferentialIKController class computes the desired joint
positions for a robot to reach a desired end-effector pose. The included implementation
performs the computation in a batched format and uses PyTorch operations. It supports
different types of inverse kinematics solvers, including the damped least-squares method
and the pseudo-inverse method. These solvers can be specified using the
ik_method argument.
Additionally, the controller can handle commands as both relative and absolute poses.
In this tutorial, we will use the damped least-squares method to compute the desired joint positions. Additionally, since we want to track desired end-effector poses, we will use the absolute pose command mode.
# Create controller
diff_ik_cfg = DifferentialIKControllerCfg(command_type="pose", use_relative_mode=False, ik_method="dls")
diff_ik_controller = DifferentialIKController(diff_ik_cfg, num_envs=scene.num_envs, device=sim.device)
Obtaining the robot’s joint and body indices#
The IK controller implementation is a computation-only class. Thus, it expects the user to provide the necessary information about the robot. This includes the robot’s joint positions, current end-effector pose, and the Jacobian matrix.
While the attribute assets.ArticulationData.joint_pos provides the joint positions,
we only want the joint positions of the robot’s arm, and not the gripper. Similarly, while
the attribute assets.ArticulationData.body_state_w provides the state of all the
robot’s bodies, we only want the state of the robot’s end-effector. Thus, we need to
index into these arrays to obtain the desired quantities.
For this, the articulation class provides the methods find_joints()
and find_bodies(). These methods take in the names of the joints
and bodies and return their corresponding indices.
While you may directly use these methods to obtain the indices, we recommend using the
SceneEntityCfg class to resolve the indices. This class is used in various
places in the APIs to extract certain information from a scene entity. Internally, it
calls the above methods to obtain the indices. However, it also performs some additional
checks to ensure that the provided names are valid. Thus, it is a safer option to use
this class.
# Specify robot-specific parameters
if args_cli.robot == "franka_panda":
robot_entity_cfg = SceneEntityCfg("robot", joint_names=["panda_joint.*"], body_names=["panda_hand"])
elif args_cli.robot == "ur10":
robot_entity_cfg = SceneEntityCfg("robot", joint_names=[".*"], body_names=["ee_link"])
else:
raise ValueError(f"Robot {args_cli.robot} is not supported. Valid: franka_panda, ur10")
# Resolving the scene entities
robot_entity_cfg.resolve(scene)
# Obtain the frame index of the end-effector
# For a fixed base robot, the frame index is one less than the body index. This is because
# the root body is not included in the returned Jacobians.
if robot.is_fixed_base:
ee_jacobi_idx = robot_entity_cfg.body_ids[0] - 1
else:
ee_jacobi_idx = robot_entity_cfg.body_ids[0]
Computing robot command#
The IK controller separates the operation of setting the desired command and computing the desired joint positions. This is done to allow for the user to run the IK controller at a different frequency than the robot’s control frequency.
The set_command() method takes in
the desired end-effector pose as a single batched array. The pose is specified in
the robot’s base frame.
# reset controller
diff_ik_controller.reset()
diff_ik_controller.set_command(ik_commands)
We can then compute the desired joint positions using the
compute() method.
The method takes in the current end-effector pose (in base frame), Jacobian, and
current joint positions. We read the Jacobian matrix from the robot’s data, which uses
its value computed from the physics engine.
# obtain quantities from simulation. The Jacobian DoF axis prepends
# ``num_base_dofs`` floating-base columns (0 for fixed-base, 6 for
# floating-base); shift the actuated-joint ids accordingly.
jacobi_joint_ids = [j + robot.num_base_dofs for j in robot_entity_cfg.joint_ids]
jacobian = robot.data.body_link_jacobian_w.torch[:, ee_jacobi_idx, :, jacobi_joint_ids]
ee_pose_w = robot.data.body_pose_w.torch[:, robot_entity_cfg.body_ids[0]]
root_pose_w = robot.data.root_pose_w.torch
joint_pos = robot.data.joint_pos.torch[:, robot_entity_cfg.joint_ids]
# compute frame in root frame
ee_pos_b, ee_quat_b = subtract_frame_transforms(
root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7]
)
# compute the joint commands
joint_pos_des = diff_ik_controller.compute(ee_pos_b, ee_quat_b, jacobian, joint_pos)
The computed joint position targets can then be applied on the robot, as done in the previous tutorials.
# apply actions
robot.set_joint_position_target_index(target=joint_pos_des, joint_ids=robot_entity_cfg.joint_ids)
scene.write_data_to_sim()
The Code Execution#
Now that we have gone through the code, let’s run the script and see the result:
uv run --extra ov isaaclab -p scripts/tutorials/05_controllers/run_diff_ik.py --robot franka_panda --num_envs 128 --viz newton_rtx
The script will start a simulation with 128 robots. The robots will be controlled using the IK controller. The current and desired end-effector poses should be displayed using frame markers. The script resets and changes goals every 150 simulation steps, cycling through the poses specified in the script.
Press Ctrl+C in the terminal to stop the simulation.