diff --git a/docs/source/policy_deployment/06_displayport_insertion/displayport_insertion_policy.rst b/docs/source/policy_deployment/06_displayport_insertion/displayport_insertion_policy.rst new file mode 100644 index 000000000000..75e67ca884e3 --- /dev/null +++ b/docs/source/policy_deployment/06_displayport_insertion/displayport_insertion_policy.rst @@ -0,0 +1,1310 @@ +.. _walkthrough_dp_insertion: + +Training a DisplayPort Cable Insertion Policy and ROS Deployment +================================================================ + +This tutorial walks you through how to train a DisplayPort plug insertion reinforcement learning (RL) policy that transfers from simulation to a real Flexiv robot. The workflow consists of two main stages: + +1. **Simulation Training in Isaac Lab**: Train the policy in a high-fidelity physics simulation with domain randomization +2. **LEAPP Export and Real Robot Deployment**: Export the trained policy with LEAPP, then deploy on hardware with Isaac ROS + +This walkthrough covers the key principles and best practices for sim-to-real transfer using Isaac Lab. + +**Supported Robot:** + +- **Flexiv Rizon 4s**: 7-DOF collaborative robot arm with Grav parallel gripper + +This environment has been successfully deployed and tested on a real Flexiv Rizon 4s robot without an IsaacLab dependency. + +**Task Details:** + +The DisplayPort insertion policy operates as follows: + +1. **Initial State**: The policy assumes the DisplayPort plug is already grasped by the gripper at the start of the episode +2. **Input Observations**: The policy receives the current state of the robot together with the pose of the socket insertion point (position and orientation) from a separate perception pipeline. The robot state is the arm joint angles in the joint-space variants, or the flange / end-effector pose in the task-space variants +3. **Policy Output**: The policy outputs an incremental command each step — delta joint positions (incremental changes to arm joint angles) in the joint-space variants, or a 6-DoF Cartesian end-effector pose delta in the task-space variants +4. **Task Goal**: Insert the DisplayPort plug into a fixed socket until the mate point aligns within the success threshold + +Both control spaces are supported end-to-end. **Task space is the recommended route for real-robot deployment**; +see :ref:`choosing-control-space` for the trade-offs and for the extra robot-calibration step joint space requires. + +**Scope of This Tutorial:** + +This tutorial covers **training and LEAPP export** in Isaac Lab. For the complete on-robot workflow (vision pipeline, robot interface, ROS inference), refer to the `Isaac ROS Documentation `_ after exporting your policy. + +**Prerequisites:** + +This walkthrough assumes a working Isaac Lab installation; see +:doc:`/source/setup/installation/index`. Every command below is run from the Isaac Lab +root. The container workflow (``./docker/container.py start base``) works as well; note +that under Docker ``logs/`` is the ``isaac-lab-logs`` named volume rather than a host +directory, so checkpoints, TensorBoard event files and recorded videos must be retrieved +with ``./docker/container.py copy`` or ``docker cp`` before you can open them on the host. + +The plug, socket and robot USDs ship in the repository under +``cable_insertion/display_cable_insertion_assets/`` via Git LFS; no separate asset +download is required. + +**Code Layout:** + +The task follows the same structure as the gear assembly deploy environments: + +- ``isaaclab_tasks/contrib/deploy/cable_insertion/displayport_insertion_env_cfg.py`` — shared task MDP (scene, assets, observations, rewards) +- ``isaaclab_tasks/contrib/deploy/cable_insertion/insertion_env.py`` — environment class that logs insertion success metrics during training +- ``isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/`` — Flexiv Rizon 4s + Grav robot-specific overrides and gym registrations +- ``isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/joint_pos_env_cfg.py`` — joint-space (relative joint position) environment +- ``isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/task_space_env_cfg.py`` — task-space (operational space control) environment +- ``scripts/reinforcement_learning/train.py`` — unified trainer (pass ``--rl_library rsl_rl``) +- ``scripts/reinforcement_learning/deploy/play_displayport_insertion.py`` — DisplayPort-specific inference / LEAPP validation / CSV logging +- ``scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py`` — DisplayPort LEAPP exporter (task-space I/O contract) + +Overview +-------- + +Successful sim-to-real transfer requires addressing three fundamental aspects: + +1. **Input Consistency**: Ensuring the observations your policy receives in simulation match those available on the real robot +2. **System Response Consistency**: Ensuring the robot and environment respond to actions in simulation the same way they do in reality +3. **Output Consistency**: Ensuring any post-processing applied to policy outputs in Isaac Lab is also applied during real-world inference + +When all three aspects are properly addressed, policies trained purely in simulation can achieve robust performance on real hardware without any real-world training data. + +**Debugging Tip**: When your policy fails on the real robot, set up the real robot with the same initial observations as in simulation, then compare how the controller responds. This isolates whether the problem is from observation mismatch (Input Consistency) or physics/controller mismatch (System Response Consistency). + +Asset Quality for Insertion Tasks +---------------------------------- + +For any contact-rich insertion task, **the quality of the plug and socket assets matters more than most other sim-to-real knobs**. DisplayPort insertion in particular operates at very small clearances between plug blades and the socket cavity. If the USD collision geometry, mass properties, or joint behavior are wrong, no amount of reward tuning or domain randomization will produce a policy that transfers well to hardware. + +The DisplayPort plug and socket assets used by these environments have been iterated extensively and work well for training policies that transfer sim-to-real. Expect considerable upfront effort to reach this quality for a new connector or cable type. + +**What to validate before training:** + +1. **Static insertion pose stability**: Load the plug fully inserted into the socket at the goal pose (no robot, no gripper). The plug should remain seated without drifting, jittering, or being ejected by contact forces. Persistent separation or slow creep at the mated pose usually indicates incorrect collision meshes, rest offsets, or mass/inertia. +2. **Collision fidelity at clearance scale**: Blade-to-cavity gaps are sub-millimeter. Convex hulls or coarse meshes often produce false contacts, snagging, or penetration. SDF or carefully authored triangle meshes with tuned ``contact_offset`` / ``rest_offset`` are typically required. +3. **Engagement behavior**: Push the plug through the approach path by hand (or with scripted motion) and confirm contact feels plausible — no explosive pops, no tunneling through the socket wall, no sticky high-friction jamming unless that matches the real connector. +4. **Grasped plug stability**: With the gripper closed at the training grasp width, the plug should not spin or slip unrealistically when the arm moves. Cable mass and plug COM should be representative of the real assembly. +5. **Mate-point alignment**: Verify ``SOCKET_INSERTION_OFFSET``, ``PLUG_INSERTION_OFFSET``, and ``PLUG_GOAL_ROT`` in ``displayport_insertion_env_cfg.py`` match the intended physical mate frame. Reward and success metrics are computed from these offsets; a mismatch here looks like a perception error on the real robot. + +**The robot asset matters too.** The checks above concern the plug and socket, but the arm's USD must also +represent *your* robot — particularly its kinematic parameters, which may vary unit to unit. This matters most for +joint-space training, where the policy commands joints directly. Flexiv's +`flexiv_calibration `__ +workflow exports a calibrated robot description for a specific arm; convert the result to USD and select it with the +``DP_ROBOT_USD`` environment variable. + +**Practical workflow:** + +1. Fix assets in isolation (drop-test or basic play env with fixed poses) before running full RL training. +2. Compare sim behavior to real hardware video at the same poses — look for drift, bounce, and penetration, not policy success rate. +3. Only after assets pass these checks, tune curriculum, rewards, and domain randomization. + +.. note:: + + Poor asset quality often shows up as policies that learn high training success but fail on hardware with inconsistent contact behavior, or as training that never achieves high ``Metrics/success_rate`` despite reward tuning. Fix the assets first. + +Part 1: Input Consistency +-------------------------- + +The observations your policy receives must be consistent between simulation and reality. This means: + +1. The observation space should only include information available from real sensors +2. Sensor noise and delays should be modeled appropriately + +Using Real-Robot-Available Observations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Your simulation environment should only use observations that are available on the real robot and not use "privileged" information that would not be available in deployment. The critic receives additional privileged observations (plug pose and joint velocities) to improve value estimation during training, but these are not passed to the actor at deployment time. + + +Observation Specification +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The DisplayPort insertion environment uses proprioceptive and exteroceptive (vision) observations. In every +variant the actor sees **the current state of the robot** plus **the socket insertion (mate) point** supplied by +perception. What differs between the two control spaces is how the robot state is represented: joint angles for +the joint-space environments, and the flange / end-effector pose for the task-space environments. + +.. tab-set:: + + .. tab-item:: Joint space + + .. list-table:: Joint-Space Observations (Flexiv Rizon 4s) + :widths: 25 10 25 20 + :header-rows: 1 + + * - Observation + - Dim + - Real-World Source + - Noise + * - ``joint_pos`` (arm only) + - 7 + - Robot controller + - None + * - ``joint_vel`` (arm only, optional) + - 7 + - Robot controller + - None + * - ``socket_pos`` (insertion mate point) + - 3 + - Perception pipeline + - ±10mm + * - ``socket_quat`` + - 4 + - Perception pipeline + - None + + **Recommended shipping configuration** (``NoJointVel`` variants): **14** policy dimensions + (7 joint positions + 3 socket position + 4 socket quaternion). + + **Training configuration with joint velocity** (``Grav`` variants without ``NoJointVel``): **21** policy dimensions. + + .. note:: + + **Within joint space, prefer the NoJointVel variants.** Policies trained with ``joint_vel`` in the actor + observation can achieve slightly higher success rates in simulation, but we consistently observe less + stable behavior on the real Flexiv robot (jittery motions, inconsistent contact during insertion). + + The ``NoJointVel`` configs remove ``joint_vel`` from the actor observation while keeping it in the critic + observation group. This matches deployment setups where joint velocity is not exposed to the policy + network but can still help the value function during training. + + This is a choice *among the joint-space variants*; the task-space environments are recommended over + joint space generally (see :ref:`choosing-control-space`), and they do not expose joint velocity to the + actor at all. + + .. tab-item:: Task space + + .. list-table:: Task-Space Observations (Flexiv Rizon 4s) + :widths: 25 10 25 20 + :header-rows: 1 + + * - Observation + - Dim + - Real-World Source + - Noise + * - ``eef_pos`` (TCP position) + - 3 + - Robot controller + - None + * - ``eef_rot_6d`` (TCP orientation) + - 6 + - Robot controller + - None + * - ``socket_kp_pos`` (insertion mate point) + - 3 + - Perception pipeline + - None by default + * - ``socket_kp_rot_6d`` + - 6 + - Perception pipeline + - None by default + + **Shipping configuration** (``TaskSpace`` variants): **18** policy dimensions + (3 + 6 end-effector pose + 3 + 6 socket keypoint frame). + + Orientations use a **6D rotation representation** (the first two rows of the rotation matrix) rather than a + quaternion. This is continuous over SO(3), which avoids the sign-flip discontinuity a quaternion introduces + and is easier for the network to regress against. + + The end-effector position is reported at the **tool center point (TCP)**, i.e. the ``flange`` body offset + along its local +Z by ``_TCP_OFFSET`` in ``task_space_env_cfg.py``. Note that the observation is taken at the + TCP while the action is applied at the flange; see :ref:`taskspace-action-space`. + +**Implementation (base class):** + +.. code-block:: python + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + joint_pos = ObsTerm( + func=mdp.joint_pos, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}, + ) + joint_vel = ObsTerm( + func=mdp.joint_vel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}, + ) + socket_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_socket"), "offset": SOCKET_INSERTION_OFFSET}, + noise=ResetSampledConstantNoiseModelCfg( + noise_cfg=UniformNoiseCfg(n_min=-0.01, n_max=0.01, operation="add") # ±10mm + ), + ) + socket_quat = ObsTerm( + func=mdp.rigid_object_quat_w, + params={"asset_cfg": SceneEntityCfg("dp_socket")}, + ) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + +**Rizon 4s overrides** (in ``config/displayport_rizon_4s/joint_pos_env_cfg.py``): + +.. code-block:: python + + # Arm joints only — gripper joints are excluded from observations + self.observations.policy.joint_pos.params["asset_cfg"].joint_names = [ + "joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7", + ] + +**Task-space actor group** (in ``config/displayport_rizon_4s/task_space_env_cfg.py``): + +.. code-block:: python + + @configclass + class PolicyCfg(ObsGroup): + """Actor observations: EEF pose + socket keypoint frame (18 dims).""" + + eef_pos = ObsTerm( + func=mdp.eef_pos_w, + params={"asset_cfg": SceneEntityCfg("robot"), "body_name": "flange", "offset": _TCP_OFFSET}, + ) + eef_rot_6d = ObsTerm( + func=mdp.eef_rot_6d_w, + params={"asset_cfg": SceneEntityCfg("robot"), "body_name": "flange"}, + ) + socket_kp_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_socket"), "offset": SOCKET_INSERTION_OFFSET}, + ) + socket_kp_rot_6d = ObsTerm( + func=mdp.rigid_object_rot_6d_w, + params={"asset_cfg": SceneEntityCfg("dp_socket")}, + ) + +In both control spaces the **critic** additionally receives privileged state that the actor never sees: joint +positions and velocities plus the plug keypoint frame (task space) or the plug pose (joint space). + +**Why No Noise for Proprioceptive Observations?** + +As with the gear assembly task, policies trained without noise on proprioceptive observations transfer well to the Flexiv Rizon 4s. The controller provides sufficiently accurate joint state feedback that modeling sensor noise on joint states does not improve sim-to-real transfer for this task. The same reasoning carries over to the task-space variants: the end-effector pose is derived from those same joint encoders through forward kinematics, so it inherits their accuracy and is likewise left noise-free. + +The socket pose, by contrast, comes from perception and *is* the observation worth corrupting. The joint-space +environments apply ±10 mm of reset-sampled uniform noise to ``socket_pos`` by default. The task-space environments +ship with observation noise disabled so the contract matches the deployed perception stack exactly; add it through +the observation term's ``noise`` field if your perception pipeline is less accurate. + + +Part 2: System Response Consistency +------------------------------------ + +Once your observations are consistent, ensure the simulated robot and environment respond to actions the same way the real system does. For DisplayPort insertion this involves: + +1. Physics simulation parameters (friction, contact properties, plug/socket collision meshes) +2. Actuator modeling (PD controller gains, effort limits) +3. Domain randomization and curriculum + +Physics Parameter Tuning +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Accurate physics simulation is critical for contact-rich insertion. The DisplayPort plug and socket use SDF collision meshes with high solver iteration counts on the rigid bodies: + +.. code-block:: python + + # From displayport_insertion_env_cfg.py — DisplayPortPlug / DisplayPortSocket + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=128, + solver_velocity_iteration_count=1, + max_depenetration_velocity=0.5, # plug; socket uses 5.0 + ), + collision_props=sim_utils.CollisionPropertiesCfg( + contact_offset=0.00001, # plug + rest_offset=-0.00005, + ), + +The Flexiv Rizon 4s arm uses lower solver iteration counts for performance, matching the gear assembly Flexiv configuration: + +.. code-block:: python + + # From config/displayport_rizon_4s/joint_pos_env_cfg.py + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + solver_position_iteration_count=4, + solver_velocity_iteration_count=1, + max_contact_impulse=1e32, + ), + collision_props=sim_utils.CollisionPropertiesCfg( + contact_offset=0.005, + rest_offset=0.0, + ), + +**Friction randomization** (in ``config/displayport_rizon_4s/joint_pos_env_cfg.py``): + +.. code-block:: python + + plug_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("dp_plug", body_names=".*"), + "static_friction_range": (0.001, 0.001), + "dynamic_friction_range": (0.001, 0.001), + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger.*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + }, + ) + +Low plug/socket friction reduces sticking during blade engagement. Gripper finger friction is set to match real grasp behavior. + +Actuator Modeling +~~~~~~~~~~~~~~~~~ + +The Rizon 4s uses ``ImplicitActuatorCfg`` with per-joint-group arm tuning from ``FLEXIV_RIZON4S_GRAV_GRIPPER_CFG``, plus dedicated Grav gripper actuators: + +.. code-block:: python + + # Grav gripper actuator configuration + self.scene.robot.actuators["gripper_drive"] = ImplicitActuatorCfg( + joint_names_expr=["finger_joint"], + effort_limit_sim=2.0, + velocity_limit_sim=1.0, + stiffness=2e3, + damping=1e1, + ) + self.scene.robot.actuators["gripper_passive"] = ImplicitActuatorCfg( + joint_names_expr=[".*_knuckle_joint"], + effort_limit_sim=1.0, + velocity_limit_sim=1.0, + stiffness=0.0, + damping=0.0, + ) + +.. note:: + + **Flexiv Rizon 4s**: Domain randomization for actuator gains and joint friction is not included in the Rizon 4s ``EventCfg``. The real-world Flexiv controller is stable and precise enough that the simulation policy transfers without these additional randomizations, consistent with the gear assembly Flexiv setup. + +.. _taskspace-action-space: + +Action Space Design +~~~~~~~~~~~~~~~~~~~ + +In both control spaces the policy commands only the arm; the gripper is not in the action space — the plug is held +at a fixed grasp width for the episode. The action is always an **incremental** (delta) command, never an absolute +target. What differs is the space that delta lives in. + +.. tab-set:: + + .. tab-item:: Joint space + + The policy controls the 7 arm joints using **incremental joint position control**. + + .. code-block:: python + + self.joint_action_scale = 0.025 # ±1.4 degrees per step + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["joint1", "joint2", "joint3", "joint4", + "joint5", "joint6", "joint7"], + scale=self.joint_action_scale, + use_zero_offset=True, + ) + + **Action dimension:** 7 — one delta per arm joint, in radians. + + .. tab-item:: Task space + + The policy emits a **6-DoF Cartesian pose delta** which an Operational Space Controller (OSC) converts into + joint efforts. This removes joint-level system identification from the sim-to-real path: the same policy can + drive the real robot through a task-space bridge. + + .. code-block:: python + + _ACTION_SCALE = 0.025 # 25 mm and 0.025 rad per step + _STIFFNESS = (300.0, 300.0, 300.0, 30.0, 30.0, 30.0) + + self.actions.arm_action = mdp.DeployOperationalSpaceControllerActionCfg( + asset_name="robot", + joint_names=_ARM_JOINTS, + body_name="flange", + controller_cfg=OperationalSpaceControllerCfg( + target_types=["pose_rel"], + motion_stiffness_task=_STIFFNESS, + ... + ), + position_scale=_ACTION_SCALE, + orientation_scale=_ACTION_SCALE, + ) + + **Action dimension:** 6 — ``[dx, dy, dz, dθx, dθy, dθz]``, the first three in metres and the last three in + radians. + + Two details matter for deployment: + + * The arm's joint PD gains are **zeroed** (``actuators[...].stiffness = 0.0``); all compliance comes from the + task-space stiffness above, so the controller — not the joint servo — sets the contact behavior. + * The action is applied at the **flange**, while ``eef_pos`` is observed at the **TCP**. Observation and + control therefore use different frames by design; the real-robot bridge must reproduce that split. + +**Action scale:** ``0.025`` in both cases — read as radians per joint per step in joint space, and as metres / +radians per step in task space. + +**Control frequency:** ``sim.dt = 1/240`` s with ``decimation = 8`` → 30 Hz policy rate, identical in both +control spaces. + +Domain Randomization Strategy +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Socket pose randomization** perturbs the fixed socket to cover perception and mounting variation: + +.. code-block:: python + + randomize_socket_pose = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={ + "pose_range": { + "x": [-0.01, 0.01], # ±1 cm + "y": [-0.01, 0.01], # ±1 cm + "z": [-0.02, 0.02], # ±2 cm + "roll": [-math.radians(2.0), math.radians(2.0)], + "pitch": [-math.radians(2.0), math.radians(2.0)], + "yaw": [-math.radians(2.0), math.radians(2.0)], + }, + "asset_cfg": SceneEntityCfg("dp_socket"), + }, + ) + +**Plug reset curriculum** starts episodes with the plug near the goal pose and anneals toward farther approach poses: + +.. code-block:: python + + reset_plug_curriculum = EventTerm( + func=mdp.reset_plug_at_goal_curriculum, + mode="reset", + params={ + "at_goal_prob": 0.8, + "at_goal_prob_final": 0.0, + "anneal_start_iter": 0.0, + "anneal_end_iter": 500.0, + "num_steps_per_env": 512, + "insertion_axis": [1.0, 0.0, 0.0], + "at_goal_depth_range": [0.0, 0.015], # 0–15 mm engaged + "approach_depth_range": [0.02, 0.06], # 20–60 mm approach + "normal_pose_range": { + "x": [-0.02, 0.02], + "y": [-0.02, 0.02], + "z": [0.0, 0.0], + }, + }, + ) + +At the start of training, 80% of resets place the plug near the inserted pose; this probability linearly anneals to 0% over 500 training iterations, forcing the policy to learn full approach and insertion. + +**Initial robot pose** is set via inverse kinematics to a grasp pose on the plug at each reset. +``grasp_offset`` / ``end_effector_body_name`` / ``num_arm_joints`` are applied in +``Rizon4sGravDisplayportInsertionEnvCfg.__post_init__``: + +.. code-block:: python + + set_robot_to_grasp_pose = EventTerm( + func=mdp.set_robot_to_object_grasp_pose, + mode="reset", + params={ + "target_object_name": "dp_plug", + "grasp_offset": [0.0025, 0.0, -0.1875], # plug local frame [m] + "end_effector_body_name": "flange", + "num_arm_joints": 7, + }, + ) + +Reward Shaping +~~~~~~~~~~~~~~ + +The environment uses keypoint-based rewards that measure alignment between the plug and socket insertion mate points. Reward terms are defined in ``displayport_insertion_env_cfg.py``: + +- **Keypoint tracking** (``plug_socket_keypoint_tracking``): Penalizes L2 keypoint distance between plug and socket mate frames +- **Exponential keypoint tracking** (``plug_socket_keypoint_tracking_exp``): Dense exponential reward for fine alignment +- **Action rate** (``action_rate_l2``): Penalizes large action changes for smooth motions + +The Rizon 4s config sets the linear and exponential keypoint reward weights to a **1:1 ratio**: + +.. code-block:: python + + self.rewards.plug_socket_keypoint_tracking_exp.weight = abs( + self.rewards.plug_socket_keypoint_tracking.weight + ) + +Terminations +~~~~~~~~~~~~ + +In addition to the episode timeout, the Rizon 4s config terminates early when: + +- **Plug dropped**: End-effector moves more than 15 cm away from the plug grasp point +- **Plug orientation exceeded**: Roll or pitch deviation exceeds 15° relative to the grasp frame + +Training Metrics +~~~~~~~~~~~~~~~~ + +Unlike gear assembly, this task uses a custom environment class (``DisplayportInsertionEnv``) to log insertion metrics to TensorBoard without changing the MDP: + +- ``Metrics/success_rate`` — fraction of environments within the 3 mm mate-point threshold +- ``Metrics/plug_socket_pos_error_m`` — mean mate-point distance +- ``Metrics/plug_socket_keypoint_dist_m`` — mean keypoint distance +- ``Metrics/terminal_success_rate`` — success rate at episode reset + + +Tuning Hyperparameters for Better Performance +---------------------------------------------- + +After asset quality and physics look correct, the following hyperparameters are the main levers for improving training speed, final success rate, and sim-to-real robustness. Defaults below are the shipped Flexiv Rizon 4s values; adjust one group at a time and monitor ``Metrics/terminal_success_rate`` in TensorBoard. + +Reward Weights +~~~~~~~~~~~~~~ + +Defined in ``displayport_insertion_env_cfg.py``; the Rizon 4s config overrides the exponential weight in ``joint_pos_env_cfg.py``. + +.. list-table:: Reward hyperparameters + :widths: 35 20 45 + :header-rows: 1 + + * - Parameter + - Default + - Effect + * - ``plug_socket_keypoint_tracking.weight`` + - ``-1.5`` + - Linear penalty on keypoint distance. More negative → stronger pull toward alignment. + * - ``plug_socket_keypoint_tracking_exp.weight`` + - ``1.5`` (matched to linear) + - Exponential bonus near the goal. Increase relative to linear for sharper fine-insertion behavior; decrease if policy is brittle or stalls short of full insertion. + * - ``kp_exp_coeffs`` + - ``[(50, 0.0001), (300, 0.0001), (600, 0.0001), (2000, 0.0001)]`` + - Per-keypoint exponential scales. Higher first values tighten the reward basin around the goal. + * - ``keypoint_scale`` + - ``0.15`` + - Spatial extent of keypoint offsets. Affects how rotation errors contribute relative to translation. + * - ``action_rate.weight`` + - ``-5e-6`` + - Smoothness penalty. More negative → slower, smoother motions; too strong can prevent final insertion force. + +**1:1 linear-to-exponential weighting** (current shipping default): + +.. code-block:: python + + self.rewards.plug_socket_keypoint_tracking_exp.weight = abs( + self.rewards.plug_socket_keypoint_tracking.weight + ) + +If the policy approaches but does not fully seat the plug, try increasing the exponential weight or tightening ``kp_exp_coeffs``. If it rushes and bounces off the socket, increase ``action_rate`` magnitude or reduce the exponential weight. + +Reset Curriculum +~~~~~~~~~~~~~~~~ + +Defined in ``config/displayport_rizon_4s/joint_pos_env_cfg.py`` → ``reset_plug_curriculum``. + +.. list-table:: Curriculum hyperparameters + :widths: 35 20 45 + :header-rows: 1 + + * - Parameter + - Default + - Effect + * - ``at_goal_prob`` / ``at_goal_prob_final`` + - ``0.8`` → ``0.0`` + - Fraction of resets with plug near full insertion. Higher start values make early learning easier; anneal to zero for full approach behavior. + * - ``anneal_end_iter`` + - ``500`` + - Training iterations over which at-goal probability anneals. Extend (e.g. 800–1000) if success rate drops when curriculum gets harder; shorten if training is too slow to reach approach poses. + * - ``at_goal_depth_range`` + - ``[0.0, 0.015]`` m + - How deep the plug starts when sampled "at goal" (0–15 mm engaged). Narrow for fine final-insertion practice; widen slightly if the policy never sees near-mated contacts. + * - ``approach_depth_range`` + - ``[0.02, 0.06]`` m + - Standoff distance when not at goal (20–60 mm). Increase upper bound for harder long-range approach; decrease if the policy struggles to reach the socket mouth. + * - ``normal_pose_range`` + - ±2 cm lateral + - Lateral misalignment when not at goal. Widen for more robustness to perception error; narrow if training fails to converge. + +If ``Metrics/success_rate`` is high early but collapses after iteration ~500, the curriculum may be annealing too aggressively — extend ``anneal_end_iter`` or raise ``at_goal_prob_final`` temporarily. + +Domain Randomization and Observations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: Randomization hyperparameters + :widths: 35 20 45 + :header-rows: 1 + + * - Parameter + - Default + - Effect + * - ``randomize_socket_pose`` ranges + - ±1 cm XY, ±2 cm Z, ±2° + - Socket pose DR. Widen to match real perception/mount error; narrow if the policy cannot learn a baseline insertion. + * - ``socket_pos`` observation noise + - ±10 mm + - Perception noise on mate point. Increase for more robust real-world pose error; decrease if sim policy is too conservative. + * - Plug/socket friction (startup) + - ``0.001`` + - Low friction reduces unrealistic jamming. Tune only after visual sim-vs-real comparison — wrong friction can dominate insertion feel. + * - Gripper finger friction + - ``0.75`` + - Affects grasp stability during insertion forces. + +Actions and Grasp +~~~~~~~~~~~~~~~~~~~ + +.. list-table:: Action / grasp hyperparameters + :widths: 35 20 45 + :header-rows: 1 + + * - Parameter + - Default + - Effect + * - ``joint_action_scale`` + - ``0.025`` + - Max joint delta per step (~±1.4°). Increase if real robot stiction prevents reaching targets; decrease for finer final alignment. + * - ``grasp_offset`` + - ``[0.0025, 0.0, -0.1875]`` m + - EE-to-plug transform for IK reset. Wrong values cause dropped-plug terminations or misaligned approach. + * - ``hand_hold_width`` / ``hand_close_width`` + - ``-0.05`` / ``-0.155`` rad + - Grav finger_joint grasp command. Adjust if plug slips or is over-compressed during insertion. + +Terminations and Success Metrics +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: Termination / metric hyperparameters + :widths: 35 20 45 + :header-rows: 1 + + * - Parameter + - Default + - Effect + * - ``success_pos_threshold`` + - ``3`` mm + - Mate-point distance counted as success in ``Metrics/success_rate``. Tighten to match real acceptance criteria. + * - ``plug_dropped`` distance threshold + - ``15`` cm + - Early reset if EE leaves plug. Tighten to discourage release; loosen if false positives during large motions. + * - Orientation thresholds (roll/pitch) + - ``15°`` + - Reset if plug tilts excessively relative to grasp frame. + +RL Algorithm (PPO) +~~~~~~~~~~~~~~~~~~ + +Defined in ``config/displayport_rizon_4s/agents/rsl_rl_ppo_cfg.py``. + +.. list-table:: PPO hyperparameters + :widths: 35 20 45 + :header-rows: 1 + + * - Parameter + - Default + - Effect + * - ``max_iterations`` + - ``1500`` + - Total training iterations. Extend if success rate is still climbing at the end. + * - ``num_steps_per_env`` + - ``512`` + - Rollout length per iteration. Affects curriculum annealing rate (tied to ``anneal_end_iter``). + * - ``learning_rate`` + - ``5e-4`` + - PPO learning rate. Reduce if training is unstable; increase if learning is very slow. + * - ``desired_kl`` + - ``0.008`` + - Target KL for adaptive LR schedule. + * - ``init_noise_std`` + - ``1.0`` + - Exploration noise. Lower for fine-tuning a near-working policy. + +**Suggested tuning order:** (1) confirm asset/physics quality, (2) curriculum depth and anneal schedule, (3) linear vs exponential reward balance, (4) socket pose DR and observation noise, (5) action scale, (6) PPO training length. + + +Part 3: Training the Policy in Isaac Lab +----------------------------------------- + +Registered Gym Environments +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Train on the** ``-ROS-Inference-v0`` **ids.** They are the environments used to produce the policies deployed on +hardware: in addition to the plain training configuration, they declare the observation/action metadata Isaac +Manipulator and LEAPP consume (``obs_order``, ``policy_action_space``, ``observation_space``, ``action_space``, +``action_scale``) and pin the plug, socket and seed joint pose to the real deployment station. Training on them +means the environment you trained in and the contract you export are the same thing, so a checkpoint can be +exported and deployed with Isaac ROS without swapping configurations. + +.. list-table:: Flexiv Rizon 4s DisplayPort Insertion Environments + :widths: 55 45 + :header-rows: 1 + + * - Environment ID + - Purpose + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0`` + - **Task-space training and deployment — recommended.** Carries the ROS / LEAPP export contract. + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-v0`` + - Task-space training without deployment metadata (ablations, experiments) + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-Play-v0`` + - Task-space evaluation / visualization (observation corruption disabled) + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0`` + - **Joint-space training and deployment.** Carries the ROS / LEAPP export contract (14-dim actor obs). + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-v0`` + - Joint-space training without deployment metadata + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-Play-v0`` + - Evaluation / visualization (observation corruption disabled) + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-ROS-Inference-v0`` + - Joint-space ROS inference with joint velocity in actor obs (21-dim) + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-v0`` + - Training with joint velocity in actor obs (21-dim) + * - ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-Play-v0`` + - Evaluation with joint velocity in actor obs + +The plain training ids remain useful when you are experimenting and do not intend to deploy that particular +checkpoint — for example when sweeping rewards or randomization. If you later want to ship such a checkpoint, export +it against the matching ``-ROS-Inference-v0`` id so the traced layout matches deployment. + +.. note:: + + Training and play use the **unified RL entrypoints**. You must pass ``--rl_library rsl_rl``. + The older path ``scripts/reinforcement_learning/rsl_rl/train.py`` no longer exists; use + ``./isaaclab.sh train ...`` or ``./isaaclab.sh -p scripts/reinforcement_learning/train.py --rl_library rsl_rl ...``. + DisplayPort-specific inference lives under ``scripts/reinforcement_learning/deploy/`` + (not the removed ``scripts/reinforcement_learning/rsl_rl/`` directory). + +Step 1: Visualize the Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Launch training with a small number of environments and visualization enabled to verify the setup. Pick the tab +for the control space you intend to deploy — task space is the recommended choice for real-robot transfer +(see :ref:`choosing-control-space`): + +.. tab-set:: + + .. tab-item:: Joint space + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \ + --num_envs 4 \ + --max_iterations 100 \ + --visualizer kit + + .. tab-item:: Task space + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0 \ + --num_envs 4 \ + --max_iterations 100 \ + --visualizer kit + +Equivalent form, invoking the unified trainer directly (substitute either task id): + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/train.py --rl_library rsl_rl \ + --task \ + --num_envs 4 \ + --max_iterations 100 \ + --visualizer kit + +**What to Expect:** + +In early training, the robot moves the grasped plug toward the socket but will not insert reliably yet. Verify that: + +- The plug is grasped at reset and held throughout the episode +- The socket pose randomization and plug curriculum produce varied starting configurations +- Contact between plug blades and socket looks physically plausible +- With the plug placed in the fully inserted pose (no policy), it stays seated without drift or instability + +Stop training (Ctrl+C) once the environment looks correct, then proceed to full-scale training. + +Step 2: Full-Scale Training with Video Recording +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + **``--video`` requires MoviePy**, which is not installed by default. Install it once + before running the commands below, or drop the ``--video*`` flags: + + .. code-block:: bash + + ./isaaclab.sh -p -m pip install "moviepy>=1.0.3,<2.0.0.dev0" + +Launch full training (training is headless unless you pass ``--visualizer``) with video +recording: + +.. tab-set:: + + .. tab-item:: Joint space + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 + + .. tab-item:: Task space + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0 \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 + +**Multi-GPU (distributed) training** — for example on a cluster / OSMO workflow (substitute either task id): + +.. code-block:: bash + + ./isaaclab.sh -p -m torch.distributed.run --nnodes=1 --nproc_per_node= \ + scripts/reinforcement_learning/train.py --rl_library rsl_rl \ + --task \ + --num_envs \ + --distributed \ + agent.max_iterations= \ + --video --video_length 200 --video_interval 25600 + +The commands above train on the ``-ROS-Inference-v0`` ids so the trained environment already carries the +deployment contract. Swap in the plain ``...-NoJointVel-v0`` / ``...-TaskSpace-v0`` ids only for experiments you do +not intend to deploy. + +**Command breakdown:** + +- ``--rl_library rsl_rl``: Selects the RSL-RL backend (required by the unified trainer) +- ``--num_envs 256``: Runs 256 parallel environments +- Training runs **headless by default**; pass ``--visualizer kit`` to open a viewer +- ``--video_length 200``: One episode per video (``episode_length_s / (sim.dt * decimation)`` ≈ 200 steps) +- ``--video_interval 76800``: Records a video every 76,800 environment steps (~every 150 iterations with 512 steps/env) +- ``--distributed``: Required when launching under ``torch.distributed.run`` + +Training uses a recurrent PPO agent (LSTM, 1500 max iterations, 512 steps per environment). Videos are saved under ``logs/``. + +.. note:: + + Checkpoints are written every ``save_interval`` iterations, which the shipped agent + configuration sets to ``50``. A ``model_0.pt`` appears immediately, but it holds an + untrained network, so the first checkpoint that reflects any learning is + ``model_50.pt``. Every step from Step 3 onwards needs a ``--checkpoint``, so to walk + the export and inference sections through sooner, append + ``agent.save_interval=`` with a smaller ``N`` to the training command above. A + checkpoint taken that early will not insert reliably; it is for exercising the export + and deployment plumbing, not for evaluating the policy. + +.. note:: + + **GPU Memory Considerations**: The default configuration uses 4096 environments in the base config but 256 is recommended for most GPUs. The plug and socket SDF collision meshes and high rigid-body solver counts increase GPU memory usage compared to primitive-shape tasks. Reduce ``num_envs`` or ``solver_position_iteration_count`` on the plug/socket assets if you encounter out-of-memory errors. + +**Monitoring Training Progress with TensorBoard:** + +.. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/displayport_insertion_rizon4s + +Monitor ``Metrics/success_rate`` and reward curves to confirm learning. The curriculum anneals over the first 500 iterations — expect success rate to rise as the at-goal reset probability decreases. + +.. _choosing-control-space: + +Choosing a Control Space +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Both control spaces train with the same algorithm, reward, curriculum, and 30 Hz control rate; they differ only in +what the policy outputs and what the real robot must reproduce. + +.. list-table:: + :widths: 20 40 40 + :header-rows: 1 + + * - + - Joint space + - Task space (recommended) + * - Policy output + - 7 joint-position deltas + - 6-DoF Cartesian pose delta (OSC) + * - Actor observation + - 14 dims (or 21 with ``joint_vel``) + - 18 dims (TCP pose + socket keypoint frame) + * - Real-robot requirement + - Joint servo behavior must match sim; benefits from joint-level system identification + - Task-space bridge that reproduces the OSC contract and the TCP-observe / flange-control split + * - Training ids + - ``...-Grav-NoJointVel-ROS-Inference-v0`` (deployable), ``...-Grav-NoJointVel-v0`` + - ``...-Grav-TaskSpace-ROS-Inference-v0`` (deployable), ``...-Grav-TaskSpace-v0`` + +**Task space is the recommended route.** In our sim-to-real testing on the Flexiv Rizon 4s, task-space policies +transfer better than joint-space ones: commanding a Cartesian pose delta keeps the policy independent of the arm's +joint servo behavior and of small errors in the robot's kinematic model, both of which are difficult to reproduce +exactly in simulation. Prefer it unless you specifically need joint-level control. + +Use **joint space** when you must control the arm through its joint interface. Because the policy then commands +joints directly, transfer depends on the simulated robot matching yours closely — see the note below on robot +kinematics. + +.. important:: + + **Joint-space training needs a robot USD that matches your specific arm.** Joint-space policies command joint + positions, so any mismatch between the simulated kinematic parameters and your physical robot shows up directly + as end-effector error during insertion — where the clearances are sub-millimetre. Individual arms differ from + the nominal CAD model, so the shipped asset will not describe your unit exactly. + + Before training a joint-space policy, confirm the robot USD reflects your arm's measured kinematics. Flexiv + publishes a per-robot calibration workflow for exporting an accurate robot description: + `flexiv_calibration `__. + Follow it to generate the calibrated description for your setup, convert it to USD, and point the environment at + it with the ``DP_ROBOT_USD`` environment variable. It overrides the robot USD in both control spaces, so the + same calibrated asset can be used for either. + + Task-space policies are less exposed to this: they are commanded in Cartesian space, so kinematic error affects + the observed end-effector pose rather than being injected straight into the commanded joint targets. Getting the + kinematics right is still worthwhile in both cases. + + The two control spaces do not start from the same robot asset. The joint-space configuration spawns the + calibrated ``Rizon4s-063459_with_Grav_calibrated_kinematics.usd`` shipped with the task, set in + ``config/displayport_rizon_4s/joint_pos_env_cfg.py``, while the task-space configuration spawns the stock + Rizon 4s asset. Neither default is guaranteed to describe the arm in use, so set ``DP_ROBOT_USD`` unless the + shipped asset has been confirmed to match that unit. + +In each case, train on the ``-ROS-Inference-v0`` id so the trained environment carries the deployment contract, +and use the ``-Play-v0`` id for evaluation and visualization. The task-space environment already uses the +LEAPP-exportable :class:`~isaaclab_tasks.contrib.deploy.mdp.DeployOperationalSpaceControllerActionCfg` action, so a +trained checkpoint can be exported directly (see :ref:`export-taskspace-leapp`). + +Step 3: Export and Deploy on Real Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Recommended workflow:** export the trained policy with **LEAPP**, validate the export in simulation, then deploy the LEAPP package with Isaac ROS / Isaac Manipulator on the Flexiv robot. + +Export from the ``-ROS-Inference-v0`` task id so the traced observation and action layout matches deployment. If +you followed the training steps above this is the same id you trained on, and no configuration swap is needed. In +joint space that is a **NoJointVel** variant (14-dim actor input); in task space it is +``-TaskSpace-ROS-Inference-v0`` (18-dim actor input). + +Export with LEAPP (Recommended) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +`LEAPP `__ (Lightweight Export Annotations for Policy Pipelines) is the **default and recommended** path from a trained checkpoint to real-robot inference. It packages the policy together with input/output semantics (observation ordering, action scaling, recurrent LSTM state) so Isaac ROS deployment does not need to reimplement Isaac Lab preprocessing by hand. + +**Prerequisites:** ``leapp>=0.5.2`` and a trained NoJointVel checkpoint. + +.. code-block:: bash + + ./isaaclab.sh -p -m pip install leapp + +**Export the policy:** + +.. tab-set:: + + .. tab-item:: Joint space + + Uses the generic RSL-RL exporter: + + .. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_.pt + + .. tab-item:: Task space + + Uses the DisplayPort exporter with ``--task_space_contract`` (see :ref:`export-taskspace-leapp`): + + .. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0 \ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_.pt \ + --task_space_contract + +Replace ```` and ```` with your training log path. + +By default, export artifacts are written next to the checkpoint: + +- Exported model (``.onnx`` by default, or ``.pt`` depending on backend) +- LEAPP metadata YAML describing the policy I/O graph +- Initial recurrent hidden state (``.safetensors``) — this policy uses an LSTM actor +- Pipeline graph visualization (``.png``) + +Useful export flags: + +- ``--export_method onnx-dynamo`` — default ONNX export backend +- ``--validation_steps 5`` — replay traced rollout data to verify the export (recommended; set ``0`` only for debugging) +- ``--export_save_path `` — write artifacts to a custom directory + +See :doc:`Exporting Policies with LEAPP ` for full CLI options, backend choices, and troubleshooting. + +**Validate the LEAPP export in simulation** before real-robot deployment. Prefer the +DisplayPort-specific play script so you can fix socket poses, inject perception error, +and write ``policy_io.csv`` for sim/real overlay: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \ + --task \ + --leapp_model logs/rsl_rl/displayport_insertion_rizon4s/ \ + --num_envs 1 \ + --socket_pos 0.476 0.127 0.07 \ + --max_steps 200 \ + --log_dir logs/dp_inference_runs \ + --visualizer kit + +where ```` is ``...-Grav-NoJointVel-ROS-Inference-v0`` for a joint-space export or +``...-Grav-TaskSpace-ROS-Inference-v0`` for a task-space one. + +``--leapp_model`` accepts either the LEAPP deploy YAML or the export directory that +contains it. Pose overrides and CSV logging still apply. Do not combine +``--leapp_model`` with ``--checkpoint`` or ``--replay_csv``. + +Generic LEAPP deploy (no DP pose / logging knobs): + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/deploy.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \ + --leapp_model logs/rsl_rl/displayport_insertion_rizon4s// \ + --viz kit + +**Deploy on hardware:** pass the LEAPP export directory and metadata to your Isaac ROS / Isaac Manipulator workflow. Refer to the `Isaac ROS manipulation DNN policy documentation `_ for on-robot setup. The on-robot pipeline typically includes: + +1. **Perception** — socket pose estimation +2. **Motion planning** — approach trajectory to the insertion station (if used) +3. **Policy inference** — LEAPP-exported policy at control frequency in the ROS inference node +4. **Robot control** — Flexiv commands derived from policy actions: joint-position deltas in joint space, or a + Cartesian pose delta applied through the task-space bridge in task space + +The ROS inference environments define the deployment metadata LEAPP traces during export: + +.. tab-set:: + + .. tab-item:: Joint space + + ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0`` + + - ``obs_order``: ``["arm_dof_pos", "socket_pos", "socket_quat"]`` + - ``policy_action_space``: ``"joint"`` + - ``observation_space``: 14 + - ``action_space``: 7 + - ``joint_action_scale``: 0.025 + + Fixed deployment poses are set in ``config/displayport_rizon_4s/ros_inference_env_cfg.py``. + + .. tab-item:: Task space + + ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0`` + + - ``obs_order``: ``["eef_pos", "eef_rot_6d", "socket_kp_pos", "socket_kp_rot_6d"]`` + - ``policy_action_space``: ``"task"`` (``pose_rel``) + - ``observation_space``: 18 + - ``action_space``: 6 + - ``action_scale``: 0.025 (metres for translation, radians for rotation) + + Fixed deployment poses are set in ``config/displayport_rizon_4s/task_space_ros_inference_env_cfg.py``. + +.. _export-taskspace-leapp: + +Exporting a Task-Space Policy +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A **task-space** checkpoint (trained on ``...-Grav-TaskSpace-v0``) is exported with the DisplayPort-specific +exporter :file:`scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py` and its +``--task_space_contract`` flag, because its action is a scaled 6-DoF Cartesian pose delta rather than joint +targets. That script reuses the generic RSL-RL export flow and only substitutes the export routine, so the +generic entry point stays task-agnostic: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0 \ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_.pt \ + --export_save_path \ + --task_space_contract + +The export writes a ``DisplayPortTaskSpace`` LEAPP package (``.onnx`` graph, ``.yaml`` semantics, and +``_initial_values.safetensors`` for the recurrent state). Its I/O contract is: + +- **Inputs:** ``eef_pos`` (3), ``eef_rot_6d`` (6), ``socket_kp_pos`` (3), ``socket_kp_rot_6d`` (6), plus the actor LSTM state. +- **Output:** ``arm_action`` (6) — a ``pose_rel`` Cartesian delta ``[dx, dy, dz, dθx, dθy, dθz]`` consumed by the + task-space bridge (``isaaclab_connection: action:arm_action:pose_rel``). + +Validate and deploy it exactly as for the joint-space export above (``play_displayport_insertion.py`` or +``scripts/reinforcement_learning/leapp/deploy.py`` with ``--leapp_model`` pointing at the exported directory). + +Alternative: Raw Checkpoint Deployment +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For development or legacy Isaac Manipulator setups, you can deploy the RSL-RL checkpoint directly without a LEAPP export step. This path uses the ``.pt`` checkpoint with ``agent.yaml`` and ``env.yaml`` from: + +.. code-block:: text + + logs/rsl_rl/displayport_insertion_rizon4s//model_.pt + +This is **not recommended for shipping** — you must manually ensure observation ordering, action scaling, and LSTM state handling match training. Prefer the LEAPP export path above for production deployment. + + +Troubleshooting +--------------- + +PhysX Collision Stack Overflow +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Error Message:** + +.. code-block:: text + + PhysX error: PxGpuDynamicsMemoryConfig::collisionStackSize buffer overflow detected + +**Cause:** GPU collision buffer is too small for contact-rich plug/socket interaction across many parallel environments. + +**Solution:** Increase ``gpu_collision_stack_size`` in ``displayport_insertion_env_cfg.py`` (default is ``2**30``): + +.. code-block:: python + + sim: SimulationCfg = SimulationCfg( + physics=PhysxCfg( + gpu_collision_stack_size=2**31, # Increase if overflow persists + gpu_max_rigid_contact_count=2**23, + gpu_max_rigid_patch_count=2**23, + ), + ) + +CUDA Out of Memory +~~~~~~~~~~~~~~~~~~ + +**Solutions (in order of preference):** + +1. Reduce parallel environments: + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task \ + --num_envs 128 + +2. Reduce plug/socket ``solver_position_iteration_count`` in ``displayport_insertion_env_cfg.py`` (trade-off: more penetration) + +3. Disable video recording during training + + +Deterministic Debugging (Play / Inference Script) +------------------------------------------------- + +For DisplayPort insertion, prefer the dedicated play script over the generic +``./isaaclab.sh play`` path. It keeps DP-specific pose overrides, perception-error +injection, and ``policy_io.csv`` logging out of the shared play entrypoint. + +The examples below use the joint-space ROS-inference task. To run a task-space policy, +substitute ``...-Grav-TaskSpace-ROS-Inference-v0`` for the ``--task`` id, point +``--checkpoint`` (or ``--leapp_model``) at the corresponding run, and pass that +environment's own station pose (``--socket_pos 0.475 0.125 0.06``) rather than the +joint-space one used below. The flags are otherwise identical. + +**RSL-RL checkpoint** (recommended shipping task): + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_.pt \ + --num_envs 1 \ + --socket_pos 0.476 0.127 0.07 \ + --observed_socket_pos 0.486 0.127 0.07 \ + --max_steps 200 \ + --log_dir logs/dp_inference_runs \ + --visualizer kit + +**Exact first observation from real/sim CSV** (closed-loop; injects ``obs_*`` from the +chosen row as the first policy input, then continues with live sim observations): + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_.pt \ + --init_obs_csv rollouts/sim_real_compare/real_policy_gt_sock.csv \ + --socket_pos 0.475 0.125 0.07 \ + --num_envs 1 \ + --max_steps 200 \ + --log_dir logs/dp_init_obs_runs \ + --visualizer kit + +Unset ``--robot_joint_pos`` / ``--observed_socket_*`` are seeded from that CSV row so the +scene starts aligned. Use ``--init_obs_step N`` to pick a non-zero row. Works with +``--leapp_model`` as well; not compatible with ``--replay_csv``. + +**LEAPP-exported ONNX policy** (same script; see Step 3 above for ``--leapp_model``). + +**Open-loop replay** of a logged ``policy_io.csv`` / real rollout: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \ + --replay_csv rollouts/sim_real_compare/real_policy.csv \ + --socket_pos 0.475 0.125 0.07 \ + --log_dir rollouts/sim_real_compare/replay_run \ + --visualizer kit + +Pose conventions: + +- ``--socket_pos`` / ``--observed_socket_pos`` are socket **insertion-geometry** + world positions (mate point), matching ``fixed_asset_init_pos_center``, not the + USD root. The USD root is derived via ``compute_socket_root``. +- Quaternions are ``(x, y, z, w)``. +- If ``--observed_socket_*`` is omitted, the policy observes the true simulated socket pose. +- Telemetry is written to ``policy_io.csv`` (+ ``run_config.json``) under ``--log_dir`` + or ``/inference_logs//``. + +Generic play (no DP pose / CSV knobs) still works for a quick smoke test: + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rsl_rl \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-Play-v0 \ + --num_envs 1 \ + --checkpoint + +To match a specific real-world station layout, edit the workspace constants of the +environment you are running. Each of the three configurations below carries its own +station pose, so re-measuring your station means updating the one you train and deploy +with; editing another has no effect: + +.. code-block:: python + + # Training layout, both control spaces (joint_pos_env_cfg.py) + _GEOMETRY_POS = (0.475, 0.125, 0.06) + _SOCKET_ROT = (0.5, 0.5, 0.5, -0.5) + + # Joint-space deployment layout (ros_inference_env_cfg.py) + _DEPLOY_GEOMETRY_POS = (0.476, 0.127, 0.07) + _DEPLOY_SOCKET_ROT = (0.5, 0.5, 0.5, -0.5) + + # Task-space deployment layout (task_space_ros_inference_env_cfg.py) + _HUBBLE_GEOMETRY_POS = (0.475, 0.125, 0.06) + _HUBBLE_SOCKET_ROT = (0.5, 0.5, 0.5, -0.5) + _HUBBLE_PLUG_CLEARANCE_Z = 0.068 + +The two deployment stations do not currently hold the same position. Pass the pose of the +environment you are actually running to ``--socket_pos``, and re-measure both if you +deploy both control spaces against one physical station. + +This workflow is useful for: + +- Comparing simulated and real-world policy behavior at a known socket pose +- Validating LEAPP exports before hardware deployment +- Verifying plug grasp and approach trajectories before full perception integration +- Debugging insertion failures at a fixed station configuration + + +Further Resources +----------------- + +- Gear Assembly Sim-to-Real Tutorial: :ref:`walkthrough_sim_to_real` +- Exporting Policies with LEAPP: :doc:`/source/policy_deployment/05_leapp/exporting_policies_with_leapp` +- `Isaac ROS Manipulation Documentation `_ +- RL Training Tutorial: :ref:`tutorial-run-rl-training` diff --git a/docs/source/policy_deployment/index.rst b/docs/source/policy_deployment/index.rst index cd89350c1773..d10e57910b81 100644 --- a/docs/source/policy_deployment/index.rst +++ b/docs/source/policy_deployment/index.rst @@ -10,6 +10,7 @@ Below, you'll find detailed examples of various policies for training and deploy 01_io_descriptors/io_descriptors_101 02_gear_assembly/gear_assembly_policy + 06_displayport_insertion/displayport_insertion_policy 03_compass_with_NuRec/compass_navigation_policy_with_NuRec 04_reach/reach_policy 05_leapp/exporting_policies_with_leapp diff --git a/scripts/reinforcement_learning/deploy/play_displayport_insertion.py b/scripts/reinforcement_learning/deploy/play_displayport_insertion.py new file mode 100644 index 000000000000..cf9d77677f48 --- /dev/null +++ b/scripts/reinforcement_learning/deploy/play_displayport_insertion.py @@ -0,0 +1,2101 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Production DisplayPort insertion policy inference in simulation. + +Run a trained RSL-RL checkpoint **or** a LEAPP-exported ONNX policy with +deterministic initial conditions, optional perception-error injection on the +socket observation, and per-step logging of observations, actions, end-effector +pose, and plug/socket state. + +Per-step telemetry is written to ``policy_io.csv`` (plus ``run_config.json``) under +``--log_dir`` or ``/inference_logs//``. The CSV column +layout matches ``rollouts/sim_real_compare/policy_io.csv`` so the same plotting +tools can overlay sim and real rollouts. + +This is intentionally separate from ``play.py`` so DisplayPort-specific pose and +logging knobs stay out of the generic play path. + +Example (recommended shipping task, RSL-RL checkpoint): + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \\ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \\ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_1500.pt \\ + --num_envs 1 \\ + --socket_pos 0.476 0.127 0.07 \\ + --observed_socket_pos 0.486 0.127 0.07 \\ + --max_steps 200 \\ + --log_dir logs/dp_inference_runs \\ + --visualizer kit + +LEAPP-exported policy (ONNX + deploy YAML). Pass a YAML path or the export directory: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \\ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \\ + --leapp_model logs/rsl_rl/dp_exps/displayport_default_model900 \\ + --num_envs 1 \\ + --socket_pos 0.476 0.127 0.07 \\ + --max_steps 200 \\ + --log_dir logs/dp_inference_runs \\ + --visualizer kit + +Open-loop replay of a real (or sim) ``policy_io`` CSV: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \\ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \\ + --replay_csv rollouts/sim_real_compare/real_policy.csv \\ + --socket_pos 0.475 0.125 0.07 \\ + --log_dir rollouts/sim_real_compare/replay_run \\ + --visualizer kit + +Closed-loop policy with the **exact** first observation from a real/sim CSV +(``obs_*`` from the chosen row replaces the first vector fed to the policy): + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/deploy/play_displayport_insertion.py \\ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0 \\ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_1500.pt \\ + --init_obs_csv rollouts/sim_real_compare/real_policy_gt_sock.csv \\ + --socket_pos 0.475 0.125 0.07 \\ + --num_envs 1 \\ + --max_steps 200 \\ + --log_dir logs/dp_init_obs_runs \\ + --visualizer kit + +Pose conventions +---------------- +* ``--socket_pos`` / ``--observed_socket_pos`` are socket **insertion-geometry** + world positions (mate point), matching ``fixed_asset_init_pos_center``, not the + USD root. The USD root is derived via ``compute_socket_root``. +* Quaternions are ``(x, y, z, w)``. +* If ``--observed_socket_*`` is omitted, the policy observes the true simulated + socket pose. +* If ``--robot_joint_pos`` is set, IK grasp reset is replaced with a plug snap + into the gripper so the requested joints are preserved. +* ``--replay_csv`` open-loop-replays absolute arm joint targets from a + ``policy_io.csv`` / ``real_policy.csv`` instead of running the policy. The + same ``policy_io.csv`` logging path is used. Checkpoint is optional in this + mode. When init overrides are omitted, row 0 of the CSV seeds + ``--robot_joint_pos`` and ``--observed_socket_*``. +* ``--init_obs_csv`` closed-loop only: for the **first** policy step, feed the + flat ``obs_*`` vector from the CSV (default row ``--init_obs_step 0``) instead + of the sim-computed observation. Later steps use live sim observations. + Unset ``--robot_joint_pos`` / ``--observed_socket_*`` are seeded from that + same row so the physical scene starts aligned. Compatible with ``--checkpoint`` + and ``--leapp_model``; mutually exclusive with ``--replay_csv``. +* ``--leapp_model`` runs a LEAPP-exported ONNX policy (``InferenceManager``) + instead of an RSL-RL ``.pt`` checkpoint. Accepts the deploy ``.yaml`` or the + export directory containing it. Pose overrides and ``policy_io.csv`` logging + still apply. Mutually exclusive with ``--checkpoint`` / ``--replay_csv``. +""" + +from __future__ import annotations + +import argparse +import contextlib +import csv +import importlib.metadata as metadata +import json +import os +import re +import sys +import time +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import gymnasium as gym +import numpy as np +import torch +import yaml +from packaging import version +from rsl_rl.runners import DistillationRunner, OnPolicyRunner + +import isaaclab.utils.math as math_utils +from isaaclab.app import add_launcher_args, launch_simulation +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils.assets import retrieve_file_path + +# isaaclab.assets / warp must not be imported at module scope before SimulationApp starts. +if TYPE_CHECKING: + from isaaclab.assets import Articulation, RigidObject + +# local imports +from isaaclab_rl.entrypoints.backends import cli_args_rsl_rl as cli_args +from isaaclab_rl.rsl_rl import RslRlBaseRunnerCfg, RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.contrib.deploy.cable_insertion.displayport_insertion_env_cfg import ( + compute_plug_pose, + compute_socket_root, +) +from isaaclab_tasks.utils import get_checkpoint_path, setup_preset_cli +from isaaclab_tasks.utils.hydra import hydra_task_config + +from success_utils import SuccessTracker # isort: skip + +_DEFAULT_TASK = "Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0" + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser( + description="DisplayPort insertion policy inference with controllable poses and step logging.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, +) +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=_DEFAULT_TASK, help="Registered gym task id.") +parser.add_argument("--agent", type=str, default="rsl_rl_cfg_entry_point", help="RL agent configuration entry point.") +parser.add_argument("--seed", type=int, default=None, help="Environment seed.") +parser.add_argument( + "--use_pretrained_checkpoint", action="store_true", help="Use the published Nucleus pretrained checkpoint." +) +parser.add_argument("--real-time", action="store_true", default=False, help="Throttle stepping to wall-clock dt.") + +# Initial / observed state +parser.add_argument( + "--robot_joint_pos", + type=str, + nargs="+", + default=None, + metavar="VALUE_RAD | JOINT_NAME=VALUE_RAD", + help=( + "Starting joint positions in radians. Either 7 bare values in arm-joint order" + " (e.g. --robot_joint_pos 0.44 -0.25 0.04 2.23 -0.01 0.91 2.08) or 'name=value' pairs" + " (e.g. joint1=0.44). Disables IK grasp reset." + ), +) +parser.add_argument( + "--socket_pos", + type=float, + nargs=3, + default=None, + metavar=("X", "Y", "Z"), + help="Actual simulated socket insertion-geometry world position [m].", +) +parser.add_argument( + "--socket_rot", + type=float, + nargs=4, + default=None, + metavar=("X", "Y", "Z", "W"), + help="Actual simulated socket orientation quaternion (x, y, z, w).", +) +parser.add_argument( + "--observed_socket_pos", + type=float, + nargs=3, + default=None, + metavar=("X", "Y", "Z"), + help="Socket insertion-geometry world position [m] fed to the policy (perception belief).", +) +parser.add_argument( + "--observed_socket_rot", + type=float, + nargs=4, + default=None, + metavar=("X", "Y", "Z", "W"), + help="Socket orientation quaternion (x, y, z, w) fed to the policy.", +) +parser.add_argument( + "--z_clearance", + type=float, + default=0.068, + help="Initial plug-above-socket clearance [m] when --socket_pos is set.", +) + +# Replay / open-loop debugging +parser.add_argument( + "--replay_csv", + type=str, + default=None, + metavar="PATH", + help=( + "Open-loop replay absolute arm joint targets from a policy_io / real_policy CSV " + "instead of running the policy. Accepts target_joint_pos_* (sim) or " + "safety_cmd_* + measured joints (real: absolute = joint + safety_cmd). " + "Checkpoint is optional. Ends after the CSV is exhausted unless --max_steps is smaller." + ), +) +parser.add_argument( + "--leapp_model", + type=str, + default=None, + metavar="PATH", + help=( + "Path to a LEAPP-exported deploy YAML, or a directory containing one " + "(e.g. logs/rsl_rl/dp_exps/displayport_default_model900). Runs the exported " + "ONNX policy via InferenceManager instead of an RSL-RL .pt checkpoint." + ), +) +parser.add_argument( + "--init_obs_csv", + type=str, + default=None, + metavar="PATH", + help=( + "Closed-loop: feed the exact flat obs_* vector from this policy_io CSV as the " + "first policy observation (see --init_obs_step). Also seeds unset " + "--robot_joint_pos / --observed_socket_* from that row. Not compatible with " + "--replay_csv." + ), +) +parser.add_argument( + "--init_obs_step", + type=int, + default=0, + help="Row index in --init_obs_csv used for the first policy observation (default: 0).", +) + +# Run control / logging +parser.add_argument("--max_steps", type=int, default=None, help="Stop after this many policy steps.") +parser.add_argument( + "--num_episodes", + type=int, + default=None, + help="Stop after this many completed episodes (requires env auto-reset).", +) +parser.add_argument( + "--log_dir", + type=str, + default=None, + help=("Directory for run logs. Default: /inference_logs/."), +) +parser.add_argument("--no_print", action="store_true", help="Disable per-step terminal printing.") +parser.add_argument( + "--no_log_file", + action="store_true", + help="Disable policy_io.csv / run_config.json file logging.", +) +parser.add_argument( + "--print_every", + type=int, + default=1, + help="Print every N steps (file logging still records every step unless --no_log_file).", +) + +cli_args.add_rsl_rl_args(parser) +add_launcher_args(parser) +args_cli, remaining_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + remaining_args + +installed_version = metadata.version("rsl-rl-lib") + + +# -- helpers ----------------------------------------------------------------- + + +def _to_torch(x): + """Convert a warp/torch-backed data field to a torch tensor (mappings pass through).""" + from collections.abc import Mapping + + if x is None: + return None + if isinstance(x, Mapping): + return x + if hasattr(x, "torch"): + return x.torch + try: + import warp as wp + + return wp.to_torch(x) + except Exception: + return x + + +def _fmt(t) -> str: + """Format a tensor/array/mapping as a compact rounded string.""" + from collections.abc import Mapping + + if t is None: + return "N/A" + if isinstance(t, Mapping): + return "{" + ", ".join(f"{k}: {_fmt(v)}" for k, v in t.items()) + "}" + if hasattr(t, "detach"): + arr = t.detach().cpu().numpy().reshape(-1) + return np.array2string(arr, precision=4, suppress_small=True, max_line_width=240) + try: + arr = np.asarray(t).reshape(-1) + return np.array2string(arr, precision=4, suppress_small=True, max_line_width=240) + except Exception: + return str(t) + + +def _get_attr(obj, *names): + for n in names: + if hasattr(obj, n): + return getattr(obj, n) + return None + + +def _get_asset(scene, candidate_names): + for n in candidate_names: + try: + return scene[n], n + except Exception: + continue + return None, None + + +def _as_numpy_1d(x) -> np.ndarray | None: + t = _to_torch(x) + if t is None: + return None + if hasattr(t, "detach"): + return t.detach().cpu().numpy().reshape(-1) + return np.asarray(t).reshape(-1) + + +def _extract_lstm_hidden_state(policy) -> tuple[np.ndarray | None, np.ndarray | None]: + """Return per-env-0 LSTM state as ``(h, c)`` with shape ``(num_layers, hidden_dim)``. + + Supports: + * rsl-rl >= 4 ``RNNModel.get_hidden_state()`` → ``(h, c)`` for LSTM / ``h`` for GRU + * older ``ActorCriticRecurrent`` via ``memory_a.hidden_states`` / ``.hidden_state`` + + Pack into deploy ``rnn_*`` columns with :func:`_pack_rnn_state`. + """ + if policy is None: + return None, None + + hs = None + if hasattr(policy, "get_hidden_state"): + try: + hs = policy.get_hidden_state() + except Exception: + hs = None + if hs is None: + for attr in ("memory_a", "rnn", "actor"): + mod = getattr(policy, attr, None) + if mod is None: + continue + hs = getattr(mod, "hidden_state", None) + if hs is None: + hs = getattr(mod, "hidden_states", None) + if hs is not None: + break + if hasattr(mod, "get_hidden_state"): + try: + hs = mod.get_hidden_state() + except Exception: + hs = None + if hs is not None: + break + + if hs is None: + return None, None + + def _env0_layers(t) -> np.ndarray | None: + tt = _to_torch(t) + if tt is None: + return None + if hasattr(tt, "detach"): + tt = tt.detach() + # Expected shapes: (num_layers, num_envs, hidden_dim) or already (L, H). + if tt.ndim == 3: + tt = tt[:, 0, :] + elif tt.ndim == 1: + # Already flat; treat as a single layer. + tt = tt.reshape(1, -1) + return tt.contiguous().cpu().numpy() + + if isinstance(hs, (tuple, list)): + if len(hs) == 0: + return None, None + h = _env0_layers(hs[0]) + c = _env0_layers(hs[1]) if len(hs) > 1 else None + return h, c + return _env0_layers(hs), None + + +def _pack_rnn_state(h: np.ndarray | None, c: np.ndarray | None) -> np.ndarray | None: + """Pack LSTM state into the real-robot ``rnn_in_*`` / ``rnn_out_*`` flatten order. + + Matches ``policy_io_csv_schema.md``: for each layer, concatenate hidden then + cell (ONNX ``actor_state_L_{in,out}`` with shape ``[2, 1, H]``), then stack layers. + DisplayPort (2 x 256 LSTM) → 1024 floats: ``[h0, c0, h1, c1]``. + """ + if h is None: + return None + h_arr = np.asarray(h, dtype=np.float64) + if h_arr.ndim == 1: + h_arr = h_arr.reshape(1, -1) + parts: list[np.ndarray] = [] + if c is None: + for layer in range(h_arr.shape[0]): + parts.append(h_arr[layer].reshape(-1)) + else: + c_arr = np.asarray(c, dtype=np.float64) + if c_arr.ndim == 1: + c_arr = c_arr.reshape(1, -1) + if c_arr.shape != h_arr.shape: + # Fall back to all-h then all-c so something useful is still logged. + return np.concatenate([h_arr.reshape(-1), c_arr.reshape(-1)], axis=0) + for layer in range(h_arr.shape[0]): + parts.append(h_arr[layer].reshape(-1)) + parts.append(c_arr[layer].reshape(-1)) + return np.concatenate(parts, axis=0) + + +def _parse_robot_joint_pos(entries: list[str], ordered_joint_names: list[str]) -> dict[str, float]: + """Parse ``--robot_joint_pos`` as either bare ordered values or ``name=value`` pairs. + + Args: + entries: CLI tokens, e.g. ``["0.44", "-0.25", ...]`` or ``["joint1=0.44", ...]``. + ordered_joint_names: Arm joint names in policy order, used to map bare values. + """ + named = [e for e in entries if "=" in e] + if named and len(named) != len(entries): + raise ValueError( + "--robot_joint_pos must be either all bare values (positional) or all 'name=value' pairs, not mixed." + ) + + if named: + return {e.partition("=")[0]: float(e.partition("=")[2]) for e in entries} + + values = [float(e) for e in entries] + if len(values) > len(ordered_joint_names): + raise ValueError( + f"--robot_joint_pos got {len(values)} values but only {len(ordered_joint_names)} arm joints are known" + f" ({ordered_joint_names}). Use 'name=value' pairs to set gripper joints." + ) + return dict(zip(ordered_joint_names, values)) + + +def _arm_joint_names(env_cfg) -> list[str]: + """Ordered arm joint names, taken from the policy ``joint_pos`` observation term.""" + try: + names = env_cfg.observations.policy.joint_pos.params["asset_cfg"].joint_names + if names: + return list(names) + except Exception: + pass + num_arm = int(getattr(env_cfg, "num_arm_joints", 7) or 7) + return [f"joint{i + 1}" for i in range(num_arm)] + + +def _trailing_int(name: str) -> int: + m = re.search(r"(\d+)$", name) + return int(m.group(1)) if m else 1_000_000 + + +@dataclass +class ReplayTrajectory: + """Open-loop arm joint targets loaded from a policy I/O CSV.""" + + path: Path + source: str # how absolute targets were derived + targets: np.ndarray # (T, num_arm) absolute joint positions [rad] + init_joint_pos: np.ndarray | None = None # (num_arm,) + observed_socket_pos: np.ndarray | None = None # (3,) + observed_socket_rot: np.ndarray | None = None # (4,) xyzw + csv_actions: np.ndarray | None = None # (T, num_arm) original logged actions, if present + + @property + def num_steps(self) -> int: + return int(self.targets.shape[0]) + + @property + def num_arm_joints(self) -> int: + return int(self.targets.shape[1]) + + +def load_replay_trajectory(path: str | Path, num_arm_joints: int = 7) -> ReplayTrajectory: + """Load absolute arm joint targets from a sim or real ``policy_io``-style CSV. + + Column priority (see ``policy_io_csv_schema.md``): + 1. ``blend_cmd_*`` — absolute blended/safety-limited command written to hardware (real). + In sim this is the policy-intent target (``q + scale * raw``), which is the + faithful thing to replay. + 2. ``target_joint_pos_{i}`` — sim logger extra; the applied ``joint_pos_target``, + re-anchored on the last physics substep, so replaying it overshoots slightly. + 3. measured ``joint_*_pos`` + ``safety_cmd_*`` — real pre-blend path when + ``safety_cmd`` is a scaled delta (``joint + safety_cmd``). + 4. ``action_{i}`` — policy output; for this DisplayPort deploy the values are + absolute joint targets (rejected if they do not look like joint angles). + """ + csv_path = Path(path).expanduser().resolve() + if not csv_path.is_file(): + raise FileNotFoundError(f"--replay_csv not found: {csv_path}") + + with open(csv_path, newline="", encoding="utf-8") as f: + reader = csv.DictReader(f) + if reader.fieldnames is None: + raise ValueError(f"--replay_csv has no header: {csv_path}") + header = list(reader.fieldnames) + rows = list(reader) + if not rows: + raise ValueError(f"--replay_csv is empty: {csv_path}") + + def _stack(keys: list[str]) -> np.ndarray: + return np.asarray([[float(r[k]) for k in keys] for r in rows], dtype=np.float64) + + tgt_keys = sorted( + [k for k in header if re.fullmatch(r"target_joint_pos_\d+", k)], + key=_trailing_int, + ) + blend_keys = sorted( + [k for k in header if re.search(r"blend_cmd_.*joint\d+$", k) or re.fullmatch(r"blend_cmd_\d+", k)], + key=_trailing_int, + ) + safety_keys = sorted( + [k for k in header if re.search(r"safety_cmd_.*joint\d+$", k) or re.fullmatch(r"safety_cmd_\d+", k)], + key=_trailing_int, + ) + # Prefer explicit arm joint_pos columns; fall back to obs_0..N-1. + joint_keys = [k for k in header if re.fullmatch(r"joint_joint\d+_pos", k)] + if not joint_keys: + joint_keys = [k for k in header if re.search(r"joint_.*joint\d+_pos$", k)] + joint_keys = sorted(joint_keys, key=_trailing_int) + act_keys = sorted([k for k in header if re.fullmatch(r"action_\d+", k)], key=_trailing_int) + obs_keys = sorted([k for k in header if re.fullmatch(r"obs_\d+", k)], key=_trailing_int) + + source: str + if len(blend_keys) >= num_arm_joints: + targets = _stack(blend_keys[:num_arm_joints]) + source = "blend_cmd" + elif len(tgt_keys) >= num_arm_joints: + targets = _stack(tgt_keys[:num_arm_joints]) + source = "target_joint_pos" + elif len(safety_keys) >= num_arm_joints and len(joint_keys) >= num_arm_joints: + measured = _stack(joint_keys[:num_arm_joints]) + deltas = _stack(safety_keys[:num_arm_joints]) + targets = measured + deltas + source = "joint_pos+safety_cmd" + print("[INFO] Replay CSV uses real-style safety_cmd deltas; absolute targets = measured_joint + safety_cmd.") + elif len(act_keys) >= num_arm_joints: + candidate = _stack(act_keys[:num_arm_joints]) + # Guard against older sim logs where action_* held raw normalized output. + reference = ( + _stack(joint_keys[:num_arm_joints])[0] + if len(joint_keys) >= num_arm_joints + else (_stack(obs_keys[:num_arm_joints])[0] if len(obs_keys) >= num_arm_joints else None) + ) + if reference is not None and np.max(np.abs(candidate[0] - reference)) > 0.5: + raise ValueError( + f"--replay_csv {csv_path}: action_* does not look like absolute joint angles " + f"(row 0 differs from measured joints by " + f"{np.max(np.abs(candidate[0] - reference)):.3f} rad). Prefer blend_cmd_* / " + "target_joint_pos_* or re-log with the current schema." + ) + targets = candidate + source = "action (absolute)" + else: + raise ValueError( + f"--replay_csv {csv_path} has no usable joint targets. Need " + f"blend_cmd_*, target_joint_pos_*, safety_cmd_* + joint_*_pos, or absolute action_*. " + f"Found: blend={len(blend_keys)}, target={len(tgt_keys)}, safety_cmd={len(safety_keys)}, " + f"joint={len(joint_keys)}, action={len(act_keys)}." + ) + + init_joint_pos = None + if len(joint_keys) >= num_arm_joints: + init_joint_pos = _stack(joint_keys[:num_arm_joints])[0] + elif len(obs_keys) >= num_arm_joints: + init_joint_pos = _stack(obs_keys[:num_arm_joints])[0] + + observed_socket_pos = observed_socket_rot = None + if all(k in header for k in ("goal_px", "goal_py", "goal_pz")): + observed_socket_pos = np.asarray( + [float(rows[0]["goal_px"]), float(rows[0]["goal_py"]), float(rows[0]["goal_pz"])], + dtype=np.float64, + ) + elif len(obs_keys) >= num_arm_joints + 3: + observed_socket_pos = _stack(obs_keys[num_arm_joints : num_arm_joints + 3])[0] + if all(k in header for k in ("goal_qx", "goal_qy", "goal_qz", "goal_qw")): + observed_socket_rot = np.asarray( + [ + float(rows[0]["goal_qx"]), + float(rows[0]["goal_qy"]), + float(rows[0]["goal_qz"]), + float(rows[0]["goal_qw"]), + ], + dtype=np.float64, + ) + elif len(obs_keys) >= num_arm_joints + 7: + observed_socket_rot = _stack(obs_keys[num_arm_joints + 3 : num_arm_joints + 7])[0] + + csv_actions = _stack(act_keys[:num_arm_joints]) if len(act_keys) >= num_arm_joints else None + + print( + f"[INFO] Loaded replay trajectory from {csv_path}: " + f"{targets.shape[0]} steps, {targets.shape[1]} arm joints, source={source}" + ) + return ReplayTrajectory( + path=csv_path, + source=source, + targets=targets, + init_joint_pos=init_joint_pos, + observed_socket_pos=observed_socket_pos, + observed_socket_rot=observed_socket_rot, + csv_actions=csv_actions, + ) + + +@dataclass +class InitPolicyObs: + """Flat policy observation (and optional RNN) taken from a policy_io CSV row.""" + + path: Path + step: int + obs: np.ndarray # (D,) + rnn_in: np.ndarray | None = None # (K,) packed layout, if present + joint_pos: np.ndarray | None = None # (num_arm,) from obs[0:num_arm] + observed_socket_pos: np.ndarray | None = None # (3,) + observed_socket_rot: np.ndarray | None = None # (4,) xyzw + + +def load_init_policy_obs( + path: str | Path, + step: int = 0, + num_arm_joints: int = 7, +) -> InitPolicyObs: + """Load flat ``obs_*`` (and optional ``rnn_in_*``) from one CSV row. + + Expected NoJointVel layout: ``[joint_pos(7), socket_pos(3), socket_quat(4)]``. + With joint velocity in the actor: ``[joint_pos(7), joint_vel(7), socket_pos(3), + socket_quat(4)]``. Socket slices are taken from the end of the vector. + """ + csv_path = Path(path).expanduser().resolve() + if not csv_path.is_file(): + raise FileNotFoundError(f"--init_obs_csv not found: {csv_path}") + if step < 0: + raise ValueError(f"--init_obs_step must be >= 0, got {step}") + + with open(csv_path, newline="", encoding="utf-8") as f: + reader = csv.DictReader(f) + if reader.fieldnames is None: + raise ValueError(f"--init_obs_csv has no header: {csv_path}") + header = list(reader.fieldnames) + rows = list(reader) + if not rows: + raise ValueError(f"--init_obs_csv is empty: {csv_path}") + if step >= len(rows): + raise ValueError(f"--init_obs_step={step} out of range for {csv_path} ({len(rows)} rows).") + + obs_keys = sorted([k for k in header if re.fullmatch(r"obs_\d+", k)], key=_trailing_int) + if not obs_keys: + raise ValueError(f"--init_obs_csv {csv_path} has no obs_* columns.") + row = rows[step] + obs = np.asarray([float(row[k]) for k in obs_keys], dtype=np.float64) + + rin_keys = sorted([k for k in header if re.fullmatch(r"rnn_in_\d+", k)], key=_trailing_int) + rnn_in = np.asarray([float(row[k]) for k in rin_keys], dtype=np.float64) if rin_keys else None + + joint_pos = obs[:num_arm_joints].copy() if obs.size >= num_arm_joints else None + observed_socket_pos = observed_socket_rot = None + # Prefer explicit goal_* columns when present (real logger), else obs tail. + if all(k in header for k in ("goal_px", "goal_py", "goal_pz")): + observed_socket_pos = np.asarray( + [float(row["goal_px"]), float(row["goal_py"]), float(row["goal_pz"])], + dtype=np.float64, + ) + elif obs.size >= num_arm_joints + 7: + # socket_pos/quat are always the last 7 entries of the actor obs. + observed_socket_pos = obs[-7:-4].copy() + if all(k in header for k in ("goal_qx", "goal_qy", "goal_qz", "goal_qw")): + observed_socket_rot = np.asarray( + [ + float(row["goal_qx"]), + float(row["goal_qy"]), + float(row["goal_qz"]), + float(row["goal_qw"]), + ], + dtype=np.float64, + ) + elif obs.size >= 4: + observed_socket_rot = obs[-4:].copy() + + print( + f"[INFO] Loaded init policy obs from {csv_path} row {step}: " + f"obs_dim={obs.size}" + (f", rnn_in_dim={rnn_in.size}" if rnn_in is not None else ", rnn_in=absent") + ) + return InitPolicyObs( + path=csv_path, + step=step, + obs=obs, + rnn_in=rnn_in, + joint_pos=joint_pos, + observed_socket_pos=observed_socket_pos, + observed_socket_rot=observed_socket_rot, + ) + + +def _seed_cli_from_init_obs(seed: InitPolicyObs): + """Fill unset pose CLI args from the init-obs CSV row.""" + if args_cli.robot_joint_pos is None and seed.joint_pos is not None: + args_cli.robot_joint_pos = [f"{v:.6f}" for v in seed.joint_pos.tolist()] + print(f"[INFO] --robot_joint_pos seeded from init obs: {args_cli.robot_joint_pos}") + if args_cli.observed_socket_pos is None and seed.observed_socket_pos is not None: + args_cli.observed_socket_pos = [float(v) for v in seed.observed_socket_pos.tolist()] + print(f"[INFO] --observed_socket_pos seeded from init obs: {args_cli.observed_socket_pos}") + if args_cli.observed_socket_rot is None and seed.observed_socket_rot is not None: + args_cli.observed_socket_rot = [float(v) for v in seed.observed_socket_rot.tolist()] + print(f"[INFO] --observed_socket_rot seeded from init obs: {args_cli.observed_socket_rot}") + + +def _replace_policy_obs_vector(obs, flat: np.ndarray, num_envs: int, device): + """Return a copy of ``obs`` whose policy vector is replaced by ``flat``. + + Supports TensorDict / mapping with a ``policy`` key, or a bare ``(N, D)`` tensor. + """ + flat_t = torch.as_tensor(flat, device=device, dtype=torch.float32).reshape(-1) + tiled = flat_t.unsqueeze(0).expand(num_envs, -1).contiguous() + + # TensorDict / dict-like + if isinstance(obs, dict) or hasattr(obs, "keys"): + try: + keys = list(obs.keys()) + except Exception: + keys = [] + if "policy" in keys: + pol = obs["policy"] + if torch.is_tensor(pol) and pol.shape[-1] != flat_t.numel(): + raise ValueError( + f"--init_obs_csv obs dim {flat_t.numel()} != live policy obs dim {pol.shape[-1]}. " + "Use a CSV recorded with the same task / observation layout." + ) + # TensorDict supports item assignment; fall back to clone+set. + with contextlib.suppress(Exception): + obs = obs.clone() + obs["policy"] = tiled.to(device=pol.device if torch.is_tensor(pol) else device) + return obs + + if torch.is_tensor(obs): + if obs.shape[-1] != flat_t.numel(): + raise ValueError(f"--init_obs_csv obs dim {flat_t.numel()} != live obs dim {obs.shape[-1]}.") + out = obs.clone() + out[:] = tiled.to(device=obs.device, dtype=obs.dtype) + return out + + raise TypeError(f"Unsupported observation container for --init_obs_csv: {type(obs)}") + + +def _seed_cli_from_replay(traj: ReplayTrajectory): + """Fill unset pose CLI args from the first CSV row so replay starts matched.""" + if args_cli.robot_joint_pos is None and traj.init_joint_pos is not None: + args_cli.robot_joint_pos = [f"{v:.6f}" for v in traj.init_joint_pos.tolist()] + print(f"[INFO] --robot_joint_pos seeded from CSV row 0: {args_cli.robot_joint_pos}") + if args_cli.observed_socket_pos is None and traj.observed_socket_pos is not None: + args_cli.observed_socket_pos = [float(v) for v in traj.observed_socket_pos.tolist()] + print(f"[INFO] --observed_socket_pos seeded from CSV: {args_cli.observed_socket_pos}") + if args_cli.observed_socket_rot is None and traj.observed_socket_rot is not None: + args_cli.observed_socket_rot = [float(v) for v in traj.observed_socket_rot.tolist()] + print(f"[INFO] --observed_socket_rot seeded from CSV: {args_cli.observed_socket_rot}") + + +def _action_scale(env) -> float: + """Relative joint action scale used by the env (default 0.025).""" + base = env.unwrapped + cfg_scale = getattr(base.cfg, "joint_action_scale", None) + if cfg_scale is not None: + return float(cfg_scale) + try: + term = base.action_manager.get_term("arm_action") + scale = getattr(term, "_scale", None) + if scale is not None: + s = _as_numpy_1d(scale) + if s is not None and s.size: + return float(s.reshape(-1)[0]) + except Exception: + pass + return 0.025 + + +def _absolute_targets_to_relative_actions( + env, + targets_1d: np.ndarray, + clip_actions: float | None, +) -> torch.Tensor: + """Convert absolute arm joint targets to RelativeJointPositionAction inputs. + + ``apply_actions`` does ``target = action * scale + q``, so + ``action = (target - q) / scale``. + + Note that the action term re-evaluates ``q`` at every physics substep, so the + target actually applied at the end of the step is anchored later than the ``q`` + read here. This inverse uses the policy-time ``q``, matching how the real robot + anchors its command once per control cycle. + """ + base = env.unwrapped + robot = base.scene["robot"] + num_arm = int(targets_1d.shape[0]) + q = _as_numpy_1d(_to_torch(robot.data.joint_pos)[0]) + if q is None: + raise RuntimeError("Cannot read robot joint_pos for replay action conversion.") + scale = _action_scale(env) + rel = (targets_1d - q[:num_arm]) / scale + if clip_actions is not None: + rel = np.clip(rel, -clip_actions, clip_actions) + actions = torch.zeros((base.num_envs, env.num_actions), device=base.device, dtype=torch.float32) + actions[:, :num_arm] = torch.as_tensor(rel, device=base.device, dtype=torch.float32) + return actions + + +def resolve_leapp_model_yaml(path: str | Path) -> Path: + """Resolve ``--leapp_model`` to a LEAPP deploy YAML file. + + Accepts either a ``.yaml``/``.yml`` file or a directory that contains one + (prefers ``*deploy*.yaml``, then any single YAML in the directory). + """ + model_path = Path(path).expanduser().resolve() + if model_path.is_file(): + if model_path.suffix.lower() not in {".yaml", ".yml"}: + raise ValueError(f"--leapp_model must be a YAML file or directory, got: {model_path}") + return model_path + if not model_path.is_dir(): + raise FileNotFoundError(f"--leapp_model not found: {model_path}") + + yaml_files = sorted(model_path.glob("*.yaml")) + sorted(model_path.glob("*.yml")) + if not yaml_files: + raise FileNotFoundError(f"No YAML found under --leapp_model directory: {model_path}") + deploy_candidates = [p for p in yaml_files if "deploy" in p.name.lower()] + if len(deploy_candidates) == 1: + return deploy_candidates[0] + if len(yaml_files) == 1: + return yaml_files[0] + if deploy_candidates: + names = ", ".join(p.name for p in deploy_candidates) + raise ValueError(f"Multiple deploy YAML files under {model_path}: {names}. Pass the YAML path explicitly.") + names = ", ".join(p.name for p in yaml_files) + raise ValueError(f"Multiple YAML files under {model_path}: {names}. Pass the YAML path explicitly.") + + +class LeappDisplayportPolicy: + """Run a LEAPP-exported DisplayPort policy against a ManagerBased gym env. + + LEAPP packages observation preprocessing, LSTM state, and action decoding into + an ONNX graph that emits **absolute** arm joint targets. This adapter: + + 1. Reads ``robot_joint_pos`` / ``socket_pos`` / ``socket_quat`` from the live + scene and observation terms (so ``--observed_socket_*`` overrides apply). + 2. Runs ``InferenceManager.run_policy``. + 3. Converts absolute targets back to relative action-manager inputs so the + existing ``env.step`` / logging path stays unchanged. + """ + + def __init__(self, env, leapp_yaml: Path, clip_actions: float | None = None): + try: + from leapp import InferenceManager + except ImportError as exc: + raise ImportError( + "LEAPP is required for --leapp_model. Install with: ./isaaclab.sh -p -m pip install leapp" + ) from exc + + self.env = env + self.base = env.unwrapped + self.clip_actions = clip_actions + self.yaml_path = Path(leapp_yaml) + self.inference = InferenceManager(str(self.yaml_path)) + + with open(self.yaml_path, encoding="utf-8") as f: + desc = yaml.safe_load(f) + pipeline = desc["pipeline"] + models = desc["models"] + # Prefer the single pipeline input node; fall back to the only model key. + input_nodes = list(pipeline.get("inputs", {}).keys()) + if not input_nodes: + raise ValueError(f"LEAPP YAML has no pipeline inputs: {self.yaml_path}") + self.node_name = input_nodes[0] + if self.node_name not in models: + # Some exports use a shortened model key; keep going with pipeline name. + pass + + self.input_names = list(pipeline["inputs"][self.node_name]) + self._joint_ids = self._resolve_arm_joint_ids() + self.last_outputs: dict[str, torch.Tensor] = {} + self.last_absolute_targets: np.ndarray | None = None + self.last_rnn_in: np.ndarray | None = None + self.last_rnn_out: np.ndarray | None = None + # One-shot override: when set, next __call__ uses these structured inputs + # (from a flat policy_io obs_*) instead of live scene terms. + self._forced_flat_obs: np.ndarray | None = None + + print(f"[INFO] LEAPP policy loaded from: {self.yaml_path}") + print(f"[INFO] LEAPP node='{self.node_name}', inputs={self.input_names}") + # Feedback lives in InferenceManager.value_dict (not run_policy return). + fb = self._read_feedback_packed() + if fb is not None: + print(f"[INFO] LEAPP feedback state dim={fb.size} (will log rnn_in_*/rnn_out_*).") + else: + print("[WARNING] LEAPP export has no readable actor_state_*_in feedback buffers.") + + def force_flat_obs_once(self, flat: np.ndarray): + """Use ``flat`` (policy_io ``obs_*``) as structured LEAPP inputs for the next call only.""" + self._forced_flat_obs = np.asarray(flat, dtype=np.float64).reshape(-1) + + def _resolve_arm_joint_ids(self) -> list[int] | None: + robot = self.base.scene["robot"] + try: + names = list(self.base.cfg.observations.policy.joint_pos.params["asset_cfg"].joint_names) + except Exception: + names = [f"joint{i + 1}" for i in range(int(getattr(self.base.cfg, "num_arm_joints", 7) or 7))] + if not names: + return None + # Exact names if provided; otherwise treat as regex patterns via find_joints. + if all(n in list(robot.joint_names) for n in names): + return [list(robot.joint_names).index(n) for n in names] + joint_ids, _ = robot.find_joints(names, preserve_order=True) + return list(joint_ids) + + def _read_observation_term(self, term_name: str) -> torch.Tensor: + """Evaluate a policy observation term (honors live overrides / noise flags).""" + obs_mgr = self.base.observation_manager + names = list(obs_mgr._group_obs_term_names["policy"]) + cfgs = list(obs_mgr._group_obs_term_cfgs["policy"]) + if term_name not in names: + raise KeyError(f"Policy observation term '{term_name}' not found (have {names})") + cfg = cfgs[names.index(term_name)] + out = cfg.func(self.base, **cfg.params) + if not torch.is_tensor(out): + out = torch.as_tensor(out, device=self.base.device, dtype=torch.float32) + return out + + def _gather_inputs(self) -> dict[str, torch.Tensor]: + n = self.base.num_envs + device = self.base.device + forced = self._forced_flat_obs + if forced is not None: + # Consume one-shot override. Layout matches NoJointVel ROS obs_order: + # joint_pos (7) [+ optional joint_vel (7)] + socket_pos (3) + socket_quat (4). + flat = torch.as_tensor(forced, device=device, dtype=torch.float32).reshape(-1) + self._forced_flat_obs = None + if flat.numel() < 7 + 3 + 4: + raise ValueError( + f"Forced LEAPP obs dim {flat.numel()} too small; need at least 14 " + "(joint_pos + socket_pos + socket_quat)." + ) + socket_quat = flat[-4:].unsqueeze(0).expand(n, -1).contiguous() + socket_pos = flat[-7:-4].unsqueeze(0).expand(n, -1).contiguous() + remainder = flat[:-7] + joint_pos = remainder[:7].unsqueeze(0).expand(n, -1).contiguous() + values: dict[str, torch.Tensor] = {} + for name in self.input_names: + if name in ("robot_joint_pos", "arm_dof_pos", "joint_pos"): + values[name] = joint_pos + elif name in ("socket_pos",): + values[name] = socket_pos + elif name in ("socket_quat",): + values[name] = socket_quat + elif name in ("robot_joint_vel", "arm_dof_vel", "joint_vel"): + if remainder.numel() >= 14: + values[name] = remainder[7:14].unsqueeze(0).expand(n, -1).contiguous() + else: + values[name] = torch.zeros(n, 7, device=device, dtype=torch.float32) + elif name.startswith("actor_state_"): + continue + else: + raise KeyError( + f"Unsupported LEAPP input '{name}' under forced obs. " + "Expected robot_joint_pos / socket_pos / socket_quat." + ) + return {f"{self.node_name}/{name}": tensor for name, tensor in values.items()} + + robot = self.base.scene["robot"] + joint_pos = _to_torch(robot.data.joint_pos) + if self._joint_ids is not None: + joint_pos = joint_pos[:, self._joint_ids] + + values = {} + for name in self.input_names: + if name in ("robot_joint_pos", "arm_dof_pos", "joint_pos"): + values[name] = joint_pos + elif name in ("socket_pos",): + values[name] = self._read_observation_term("socket_pos") + elif name in ("socket_quat",): + values[name] = self._read_observation_term("socket_quat") + elif name.startswith("actor_state_"): + # Feedback tensors are owned by InferenceManager; omit from external inputs. + continue + else: + raise KeyError( + f"Unsupported LEAPP input '{name}' for DisplayPort play. " + "Expected robot_joint_pos / socket_pos / socket_quat (plus LSTM feedback)." + ) + + return {f"{self.node_name}/{name}": tensor for name, tensor in values.items()} + + def _feedback_layer_names(self) -> list[str]: + """Ordered ``actor_state_{i}_in`` names present in the LEAPP value buffers.""" + buf = getattr(self.inference, "value_dict", {}).get(self.node_name, {}) + names: list[str] = [] + for i in range(16): + name = f"actor_state_{i}_in" + if name not in buf: + break + names.append(name) + return names + + def _pack_layer_states(self, layer_states: list[torch.Tensor]) -> np.ndarray | None: + """Pack per-layer ``[2, B, H]`` (h/c) tensors into the flat deploy rnn layout.""" + if not layer_states: + return None + h_layers: list[np.ndarray] = [] + c_layers: list[np.ndarray | None] = [] + has_cell = True + for state in layer_states: + t = state + if t.ndim == 3: + if t.shape[0] >= 2: + h_layers.append(_as_numpy_1d(t[0, 0])) + c_layers.append(_as_numpy_1d(t[1, 0])) + else: + h_layers.append(_as_numpy_1d(t[0, 0])) + c_layers.append(None) + has_cell = False + elif t.ndim == 2: + h_layers.append(_as_numpy_1d(t[0])) + c_layers.append(None) + has_cell = False + else: + h_layers.append(_as_numpy_1d(t)) + c_layers.append(None) + has_cell = False + if not h_layers or any(h is None for h in h_layers): + return None + h = np.stack(h_layers, axis=0) + if not has_cell or any(c is None for c in c_layers): + return _pack_rnn_state(h, None) + c = np.stack(c_layers, axis=0) + return _pack_rnn_state(h, c) + + def _read_feedback_packed(self) -> np.ndarray | None: + """Read packed LSTM feedback from ``InferenceManager.value_dict`` input slots. + + Feedback outs are written back into the ``actor_state_*_in`` buffers after each + ``run_policy`` call, so: + - before ``run_policy`` → ``rnn_in`` + - after ``run_policy`` → ``rnn_out`` (also next step's ``rnn_in``) + """ + buf = getattr(self.inference, "value_dict", {}).get(self.node_name, {}) + names = self._feedback_layer_names() + if not names: + return None + return self._pack_layer_states([buf[n] for n in names]) + + def __call__(self, obs=None) -> torch.Tensor: + """Run one LEAPP inference step; ``obs`` is ignored (inputs are re-read).""" + del obs # LEAPP graph takes structured I/O, not the flat RSL-RL vector. + inputs = self._gather_inputs() + + # Capture rnn_in from feedback buffers BEFORE inference updates them. + rnn_vals = self._read_feedback_packed() + self.last_rnn_in = None if rnn_vals is None else rnn_vals.copy() + + with torch.inference_mode(): + self.last_outputs = self.inference.run_policy(inputs) + + # After run_policy, feedback outs have been copied into the *_in slots. + rout = self._read_feedback_packed() + self.last_rnn_out = None if rout is None else rout.copy() + + abs_key = f"{self.node_name}/arm_action" + if abs_key not in self.last_outputs: + # Fall back to the first tensor that looks like an arm command. + candidates = [k for k in self.last_outputs if k.endswith("/arm_action") or "action" in k.split("/")[-1]] + if not candidates: + raise KeyError(f"LEAPP outputs missing arm_action. Keys: {list(self.last_outputs.keys())}") + abs_key = candidates[0] + + absolute = self.last_outputs[abs_key] + abs_np = _as_numpy_1d(absolute[0] if absolute.ndim > 1 else absolute) + if abs_np is None: + raise RuntimeError("Failed to read LEAPP arm_action tensor.") + self.last_absolute_targets = abs_np.copy() + + return _absolute_targets_to_relative_actions(self.env, abs_np, self.clip_actions) + + def reset(self, dones=None): + """Reset LEAPP recurrent state when any env episode ends.""" + do_reset = dones is None + if not do_reset: + dones_b = torch.as_tensor(dones).bool().view(-1) + do_reset = bool(dones_b.any()) + if do_reset: + self.inference.reset() + + def extract_lstm_state(self) -> tuple[np.ndarray | None, np.ndarray | None]: + """Return ``(h, c)`` for the current feedback buffers (post-inference if after run).""" + buf = getattr(self.inference, "value_dict", {}).get(self.node_name, {}) + names = self._feedback_layer_names() + if not names: + return None, None + packed = self._pack_layer_states([buf[n] for n in names]) + if packed is None: + return None, None + # Unpack is not needed by callers anymore; keep API for compatibility. + # Reconstruct (h, c) from flat packing: per layer [h, c] then layers. + # Prefer reading raw tensors when available. + h_layers = [] + c_layers = [] + has_cell = True + for name in names: + t = buf[name] + if t.ndim == 3 and t.shape[0] >= 2: + h_layers.append(_as_numpy_1d(t[0, 0])) + c_layers.append(_as_numpy_1d(t[1, 0])) + else: + h_layers.append(_as_numpy_1d(t[0] if t.ndim >= 2 else t)) + has_cell = False + if not h_layers or any(h is None for h in h_layers): + return None, None + h = np.stack(h_layers, axis=0) + if not has_cell: + return h, None + c = np.stack(c_layers, axis=0) + return h, c + + +def place_plug_at_grasp_pose( + env, + env_ids: torch.Tensor, + robot_asset_cfg: SceneEntityCfg, + target_object_name: str, + end_effector_body_name: str, + grasp_offset: list, + grasp_rot_offset: list, + gripper_joint_setter_func, + hand_hold_width: float, + hand_close_width: float, + num_arm_joints: int, +): + """Snap the plug into the gripper from the robot's already-reset end-effector pose.""" + import warp as wp + + robot: Articulation = env.scene[robot_asset_cfg.name] + held_object: RigidObject = env.scene[target_object_name] + + eef_indices, _ = robot.find_bodies([end_effector_body_name]) + eef_idx = eef_indices[0] + + num_reset_envs = len(env_ids) + grasp_offset_tensor = ( + torch.tensor(grasp_offset, device=env.device, dtype=torch.float32).unsqueeze(0).repeat(num_reset_envs, 1) + ) + grasp_rot_offset_tensor = ( + torch.tensor(grasp_rot_offset, device=env.device, dtype=torch.float32).unsqueeze(0).repeat(num_reset_envs, 1) + ) + + achieved_hand_pos = wp.to_torch(robot.data.body_pos_w)[env_ids, eef_idx].clone() + achieved_hand_quat = wp.to_torch(robot.data.body_quat_w)[env_ids, eef_idx].clone() + + inv_grasp_rot_offset = math_utils.quat_conjugate(grasp_rot_offset_tensor) + target_obj_quat = math_utils.quat_mul(achieved_hand_quat, inv_grasp_rot_offset) + grasp_offset_in_world = math_utils.quat_apply(achieved_hand_quat, grasp_offset_tensor) + target_obj_pos = achieved_hand_pos - grasp_offset_in_world + + new_root_pose = torch.cat([target_obj_pos, target_obj_quat], dim=-1) + zero_velocity = torch.zeros((num_reset_envs, 6), device=env.device, dtype=torch.float32) + held_object.write_root_pose_to_sim_index(root_pose=new_root_pose, env_ids=env_ids) + held_object.write_root_velocity_to_sim_index(root_velocity=zero_velocity, env_ids=env_ids) + + all_joints, _ = robot.find_joints([".*"]) + finger_joints = all_joints[num_arm_joints:] + joint_pos = wp.to_torch(robot.data.joint_pos)[env_ids].clone() + joint_vel = torch.zeros_like(joint_pos) + + gripper_joint_setter_func(joint_pos, list(range(num_reset_envs)), finger_joints, hand_hold_width) + robot.write_joint_position_to_sim_index(position=joint_pos, env_ids=env_ids) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel, env_ids=env_ids) + + gripper_joint_setter_func(joint_pos, list(range(num_reset_envs)), finger_joints, hand_close_width) + robot.set_joint_position_target_index(target=joint_pos, joint_ids=all_joints, env_ids=env_ids) + + +class _FixedObservedSocketPos: + """Override ``socket_pos`` observation with a fixed insertion-geometry world position.""" + + def __init__(self, env, geometry_pos_w): + self.pos_w = torch.tensor(geometry_pos_w, device=env.device, dtype=torch.float32) + + def __call__(self, env, **kwargs): + pos = self.pos_w.unsqueeze(0).repeat(env.num_envs, 1) + return pos - env.scene.env_origins + + def reset(self, env_ids=None): + pass + + +class _FixedObservedSocketQuat: + """Override ``socket_quat`` observation with a fixed world orientation.""" + + def __init__(self, env, rot_w): + self.rot_w = torch.tensor(rot_w, device=env.device, dtype=torch.float32) + + def __call__(self, env, **kwargs): + quat = self.rot_w.unsqueeze(0).repeat(env.num_envs, 1) + w_negative = quat[:, 3] < 0 + positive_quat = quat.clone() + positive_quat[w_negative] = -quat[w_negative] + return positive_quat + + def reset(self, env_ids=None): + pass + + +def _flatten_policy_obs(obs) -> np.ndarray | None: + """Return a flat 1D numpy observation for env 0 (policy vector if dict/TensorDict).""" + # Prefer the policy group when present (RSL-RL / Isaac Lab convention). + if isinstance(obs, dict) or hasattr(obs, "items"): + try: + items = dict(obs.items()) + if "policy" in items: + arr = _as_numpy_1d(items["policy"][0] if hasattr(items["policy"], "__getitem__") else items["policy"]) + if arr is not None: + return arr + parts = [] + for _, v in items.items(): + arr = _as_numpy_1d(v[0] if hasattr(v, "__getitem__") else v) + if arr is not None: + parts.append(arr) + if parts: + return np.concatenate(parts, axis=0) + except Exception: + pass + return _as_numpy_1d(obs[0] if hasattr(obs, "__getitem__") else obs) + + +class InferenceLogger: + """Print and/or save per-step inference telemetry for env 0. + + CSV layout mirrors ``policy_io_csv_schema.md`` / real-robot ``policy_io.csv``: + + ``wall_time, ros_time, step, controller_step, policy_ros_time, + joint__pos, obs_*, action_*, rnn_in_*, rnn_out_*, + goal_p*/q*, eef_p*/q*, blend_cmd_`` (+ sim-only extras). + + Column convention (aligned with the real synced-bundle logger): + + * ``action_{i}`` — absolute arm joint target [rad] the policy asked for, + decoded as ``q_at_policy_time + scale * action_raw``. Matches real + ``action_*``, which for this LEAPP export already lives in joint-angle + space and is likewise anchored once on the measured joint position. + * ``action_raw_{i}`` — sim-only: normalized network output before the action + term scales/decodes it. + * ``rnn_in_{i}`` — LSTM state fed into this inference step (zeros after reset). + * ``rnn_out_{i}`` — LSTM state produced by this inference step. Next step's + ``rnn_in_*`` equals this step's ``rnn_out_*``. + * ``controller_step`` / ``policy_ros_time`` — sim aliases of ``step`` / + ``ros_time`` so columns align with the real bundle logger. + * ``blend_cmd_`` — absolute command applied this cycle. In sim there is + no safety blend, so this equals ``action_*``. + * ``target_joint_pos_{i}`` — sim-only: ``joint_pos_target`` as it stands after + ``env.step()``. :class:`RelativeJointPositionAction` re-anchors on the live + joint position at every one of the ``decimation`` physics substeps, so this + is anchored on the *last* substep and is larger than ``action_*``. Use it to + see what the articulation was actually commanded; use ``action_*`` to + compare against real. + + Extra sim-only columns (plug/socket GT, success metrics, episode) are appended. + """ + + def __init__(self, env, log_dir: Path | None, print_enabled: bool, print_every: int): + self.env = env + self.base = env.unwrapped + self.log_dir = log_dir + self.print_enabled = print_enabled + self.print_every = max(1, print_every) + self.rows: list[dict[str, Any]] = [] + # Match real-robot logger filename for drop-in use with plot_sim_real_compare.py. + self.csv_path = (log_dir / "policy_io.csv") if log_dir is not None else None + self._fieldnames: list[str] | None = None + self._t0 = time.time() + self._action_scale = _action_scale(env) + # Arm joint positions sampled when the policy ran, carried from + # begin_step() to end_step() to decode action_* the way real does. + self._arm_q_at_policy: np.ndarray | None = None + if self.log_dir is not None: + self.log_dir.mkdir(parents=True, exist_ok=True) + + def _collect_row( + self, + obs, + actions, + step: int, + episode: int, + rnn_in: np.ndarray | None = None, + rnn_out: np.ndarray | None = None, + ) -> dict[str, Any]: + """Snapshot the state the policy acted on, before the action is applied.""" + scene = self.base.scene + # Timing: Unix epoch wall clock (matches real logger); ros_time := sim time. + sim_dt = float(getattr(self.base, "step_dt", 0.0) or 0.0) + # Real synced logger is 1-indexed for step/controller_step; keep sim 0-indexed + # ``step`` for existing plots, and mirror it into controller_step. + ros_time = step * sim_dt + row: dict[str, Any] = { + "wall_time": time.time(), + "ros_time": ros_time, + "step": step, + "controller_step": step, + "policy_ros_time": ros_time, + "episode": episode, + } + + # Flat policy observation vector (obs_0..N). + obs_arr = _flatten_policy_obs(obs) + if obs_arr is not None: + for i, val in enumerate(obs_arr.tolist()): + row[f"obs_{i}"] = float(val) + + # Raw normalized policy output (sim-only). Absolute action_* / blend_cmd_* + # are filled in end_step() from joint_pos_target. + act = _as_numpy_1d(actions[0] if hasattr(actions, "__getitem__") else actions) + if act is not None: + for i, val in enumerate(act.tolist()): + row[f"action_raw_{i}"] = float(val) + + # Recurrent in/out (matches real ``rnn_in_*`` / ``rnn_out_*``). + if rnn_in is not None: + for i, val in enumerate(np.asarray(rnn_in, dtype=np.float64).reshape(-1).tolist()): + row[f"rnn_in_{i}"] = float(val) + if rnn_out is not None: + for i, val in enumerate(np.asarray(rnn_out, dtype=np.float64).reshape(-1).tolist()): + row[f"rnn_out_{i}"] = float(val) + + robot = scene["robot"] + joint_names = list(_get_attr(robot.data, "joint_names") or _get_attr(robot, "joint_names") or []) + + joint_pos = _as_numpy_1d(_to_torch(robot.data.joint_pos)[0]) + self._arm_q_at_policy = None if joint_pos is None else joint_pos.copy() + if joint_pos is not None: + names = joint_names if joint_names else [str(i) for i in range(len(joint_pos))] + for name, val in zip(names, joint_pos.tolist()): + # Reference real logs use ``joint__pos``. + row[f"joint_{name}_pos"] = float(val) + + # Goal pose = policy-visible socket (observed override if set, else true socket). + goal_pos, goal_quat = self._resolve_goal_pose() + if goal_pos is not None and len(goal_pos) >= 3: + row["goal_px"], row["goal_py"], row["goal_pz"] = map(float, goal_pos[:3]) + if goal_quat is not None and len(goal_quat) >= 4: + row["goal_qx"], row["goal_qy"], row["goal_qz"], row["goal_qw"] = map(float, goal_quat[:4]) + + eef_name = getattr(self.base.cfg, "end_effector_body_name", "flange") + body_names = _get_attr(robot.data, "body_names") or _get_attr(robot, "body_names") + if body_names is not None and eef_name in list(body_names): + idx = list(body_names).index(eef_name) + eef_pos = _as_numpy_1d(_to_torch(robot.data.body_pos_w)[0, idx]) + eef_quat = _as_numpy_1d(_to_torch(robot.data.body_quat_w)[0, idx]) + if eef_pos is not None: + # Reference naming: eef_p{x,y,z} / eef_q{x,y,z,w} + row["eef_px"], row["eef_py"], row["eef_pz"] = map(float, eef_pos.tolist()) + if eef_quat is not None: + row["eef_qx"], row["eef_qy"], row["eef_qz"], row["eef_qw"] = map(float, eef_quat.tolist()) + + # Extra sim-only ground truth (not in real policy_io.csv, but useful for debugging). + for asset_key, candidates in (("plug", ["dp_plug"]), ("socket", ["dp_socket"])): + asset, _ = _get_asset(scene, candidates) + if asset is None: + continue + pos = _as_numpy_1d(_to_torch(asset.data.root_pos_w)[0]) + quat = _as_numpy_1d(_to_torch(asset.data.root_quat_w)[0]) + if pos is not None: + row[f"{asset_key}_pos_x"], row[f"{asset_key}_pos_y"], row[f"{asset_key}_pos_z"] = map( + float, pos.tolist() + ) + if quat is not None: + ( + row[f"{asset_key}_quat_x"], + row[f"{asset_key}_quat_y"], + row[f"{asset_key}_quat_z"], + row[f"{asset_key}_quat_w"], + ) = map(float, quat.tolist()) + + return row + + def _resolve_goal_pose(self) -> tuple[np.ndarray | None, np.ndarray | None]: + """Return (pos_w, quat_xyzw) for the policy goal / socket. + + Uses the live ``socket_pos`` / ``socket_quat`` observation callables when present + (so ``--observed_socket_*`` overrides are reflected), otherwise the true socket root. + """ + scene = self.base.scene + goal_pos = goal_quat = None + socket, _ = _get_asset(scene, ["dp_socket"]) + if socket is not None: + goal_pos = _as_numpy_1d(_to_torch(socket.data.root_pos_w)[0]) + goal_quat = _as_numpy_1d(_to_torch(socket.data.root_quat_w)[0]) + + try: + obs_mgr = self.base.observation_manager + names = list(obs_mgr._group_obs_term_names["policy"]) + cfgs = list(obs_mgr._group_obs_term_cfgs["policy"]) + origins = _as_numpy_1d(_to_torch(scene.env_origins)[0]) + for name, cfg in zip(names, cfgs): + if name not in ("socket_pos", "socket_quat"): + continue + out = cfg.func(self.base, **cfg.params) + arr = _as_numpy_1d(out[0] if hasattr(out, "__getitem__") else out) + if arr is None: + continue + if name == "socket_pos" and arr.shape[0] >= 3: + # Observation terms are in env frame; convert to world. + goal_pos = arr[:3].copy() + if origins is not None: + goal_pos = goal_pos + origins[:3] + elif name == "socket_quat" and arr.shape[0] >= 4: + goal_quat = arr[:4].copy() + except Exception: + pass + return goal_pos, goal_quat + + def print_step( + self, + obs, + actions, + step: int, + success_info: dict | None, + lstm_h: np.ndarray | None = None, + lstm_c: np.ndarray | None = None, + rnn_in: np.ndarray | None = None, + rnn_out: np.ndarray | None = None, + ): + if not self.print_enabled or (step % self.print_every) != 0: + return + + scene = self.base.scene + print(f"\n================= STEP {step} =================") + obs_arr = _flatten_policy_obs(obs) + if obs_arr is not None: + print(f"[obs] {_fmt(torch.as_tensor(obs_arr))}") + else: + print(f"[obs] {_fmt(_to_torch(obs))}") + + print(f"[actions] {_fmt(_to_torch(actions)[0] if hasattr(actions, '__getitem__') else actions)}") + + robot = scene["robot"] + joint_pos = _to_torch(robot.data.joint_pos)[0] + joint_names = _get_attr(robot.data, "joint_names") or _get_attr(robot, "joint_names") + if joint_names is not None: + pairs = {n: round(float(v), 4) for n, v in zip(list(joint_names), joint_pos.tolist())} + print(f"[joint_pos] {pairs}") + else: + print(f"[joint_pos] {_fmt(joint_pos)}") + + try: + target = _to_torch(robot.data.joint_pos_target)[0] + num_arm = int(getattr(self.base.cfg, "num_arm_joints", 7) or 7) + print(f"[target_joint_pos] {_fmt(target[:num_arm])}") + except Exception: + pass + + if rnn_in is None and lstm_h is not None: + # Legacy path: only post-forward state was provided. + rnn_out = _pack_rnn_state(lstm_h, lstm_c) if rnn_out is None else rnn_out + if rnn_in is not None: + rnn_vals = np.asarray(rnn_in, dtype=np.float64).reshape(-1) + print(f"[rnn_in] dim={rnn_vals.size} ||rnn_in||={np.linalg.norm(rnn_vals):.4f}") + if rnn_out is not None: + rout = np.asarray(rnn_out, dtype=np.float64).reshape(-1) + print(f"[rnn_out] dim={rout.size} ||rnn_out||={np.linalg.norm(rout):.4f}") + + eef_name = getattr(self.base.cfg, "end_effector_body_name", "flange") + body_names = _get_attr(robot.data, "body_names") or _get_attr(robot, "body_names") + if body_names is not None and eef_name in list(body_names): + idx = list(body_names).index(eef_name) + print( + f"[eef '{eef_name}'] pos={_fmt(_to_torch(robot.data.body_pos_w)[0, idx])} " + f"quat(xyzw)={_fmt(_to_torch(robot.data.body_quat_w)[0, idx])}" + ) + + for candidates in (["dp_plug"], ["dp_socket"]): + asset, name = _get_asset(scene, candidates) + if asset is None: + continue + print( + f"[{name}] pos={_fmt(_to_torch(asset.data.root_pos_w)[0])} " + f"quat(xyzw)={_fmt(_to_torch(asset.data.root_quat_w)[0])}" + ) + + if success_info is not None: + print(SuccessTracker.format(success_info)) + + def print_success(self, step: int, success_info: dict | None): + if not self.print_enabled or success_info is None or (step % self.print_every) != 0: + return + print(SuccessTracker.format(success_info)) + + def begin_step( + self, + obs, + actions, + step: int, + episode: int, + rnn_in: np.ndarray | None = None, + rnn_out: np.ndarray | None = None, + ) -> dict[str, Any] | None: + """Snapshot pre-step state. Call after ``policy(obs)`` but before ``env.step``. + + Keeps ``obs_*`` and the action columns on the same row time-aligned (the action is + the one the policy produced from that observation), matching the real-robot logger. + ``rnn_in`` / ``rnn_out`` are packed deploy recurrent-state layouts. + """ + if self.csv_path is None: + return None + return self._collect_row(obs, actions, step, episode, rnn_in=rnn_in, rnn_out=rnn_out) + + def end_step(self, row: dict[str, Any] | None, success_info: dict | None): + """Attach post-step command / metrics to a row from :meth:`begin_step`.""" + if row is None: + return + robot = self.base.scene["robot"] + num_arm = int(getattr(self.base.cfg, "num_arm_joints", 7) or 7) + joint_names = list(_get_attr(robot.data, "joint_names") or _get_attr(robot, "joint_names") or []) + try: + # Absolute joint command produced by applying the logged action. + target = _as_numpy_1d(_to_torch(robot.data.joint_pos_target)[0]) + except Exception: + target = None + if target is not None: + arm_n = min(num_arm, len(target)) + for i in range(arm_n): + # joint_pos_target as left by the action term. RelativeJointPositionAction + # re-anchors on live joint_pos every physics substep, so this reflects the + # last substep's joint position, not the one the policy saw. + row[f"target_joint_pos_{i}"] = float(target[i]) + + # action_* / blend_cmd_* = the absolute target the policy asked for, anchored + # once on the joint position it observed: q + scale * raw. This is the real + # robot's convention (single command per control cycle), so the columns stay + # comparable across sim and hardware. + q0 = self._arm_q_at_policy + arm_n = min(num_arm, 0 if q0 is None else len(q0)) + raw = [row.get(f"action_raw_{i}") for i in range(arm_n)] + if arm_n and all(v is not None for v in raw): + policy_target = q0[:arm_n] + self._action_scale * np.asarray(raw, dtype=np.float64) + names = joint_names[:arm_n] if joint_names else [f"joint{i + 1}" for i in range(arm_n)] + for i, val in enumerate(policy_target.tolist()): + row[f"action_{i}"] = float(val) + for name, val in zip(names, policy_target.tolist()): + row[f"blend_cmd_{name}"] = float(val) + elif target is not None: + # Replay mode has no action_raw_*; fall back to the applied target. + arm_n = min(num_arm, len(target)) + names = joint_names[:arm_n] if joint_names else [f"joint{i + 1}" for i in range(arm_n)] + for i in range(arm_n): + row[f"action_{i}"] = float(target[i]) + for name, val in zip(names, target[:arm_n].tolist()): + row[f"blend_cmd_{name}"] = float(val) + + if success_info is not None: + row["instant_success_rate"] = success_info["instant_success_rate"] + row["pos_error_m"] = success_info["pos_error_m"] + row["keypoint_dist_m"] = success_info["keypoint_dist_m"] + row["episode_success_rate"] = success_info["episode_success_rate"] + row["num_episodes"] = success_info["num_episodes"] + + self.rows.append(row) + + def flush(self): + if self.csv_path is None or not self.rows: + return + # Prefer reference column order from policy_io_csv_schema.md, then extras. + preferred = [ + "wall_time", + "ros_time", + "step", + "controller_step", + "policy_ros_time", + "episode", + ] + keys: list[str] = [] + seen = set() + for preferred_key in preferred: + if any(preferred_key in row for row in self.rows): + keys.append(preferred_key) + seen.add(preferred_key) + # Group remaining keys to mirror the reference column order. ``action_`` must be + # matched exactly so it does not also swallow ``action_raw_``. + groups = ( + lambda k: k.startswith("joint_"), + lambda k: re.fullmatch(r"obs_\d+", k) is not None, + lambda k: re.fullmatch(r"action_\d+", k) is not None, + lambda k: re.fullmatch(r"rnn_in_\d+", k) is not None, + lambda k: re.fullmatch(r"rnn_out_\d+", k) is not None, + # Legacy flat rnn_* (kept last among rnn groups for old CSVs if mixed). + lambda k: re.fullmatch(r"rnn_\d+", k) is not None, + lambda k: k.startswith("goal_"), + lambda k: k.startswith("eef_"), + lambda k: k.startswith("blend_cmd_"), + # Sim-only extras (after the real schema groups). + lambda k: k.startswith("action_raw_"), + lambda k: k.startswith("target_joint_pos_"), + lambda k: k.startswith("safety_cmd_"), + ) + for matches in groups: + for row in self.rows: + for k in row: + if k not in seen and matches(k): + keys.append(k) + seen.add(k) + for row in self.rows: + for k in row: + if k not in seen: + keys.append(k) + seen.add(k) + self._fieldnames = keys + with open(self.csv_path, "w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=keys, extrasaction="ignore") + writer.writeheader() + writer.writerows(self.rows) + print(f"[INFO] Wrote {len(self.rows)} steps to {self.csv_path}") + + +def _disable_randomization(env_cfg): + """Make resets deterministic for debugging / replay.""" + zero_range = { + "x": [0.0, 0.0], + "y": [0.0, 0.0], + "z": [0.0, 0.0], + "roll": [0.0, 0.0], + "pitch": [0.0, 0.0], + "yaw": [0.0, 0.0], + } + if hasattr(env_cfg.events, "randomize_socket_pose"): + env_cfg.events.randomize_socket_pose.params["pose_range"] = zero_range + if hasattr(env_cfg.events, "randomize_plug_pose"): + env_cfg.events.randomize_plug_pose.params["pose_range"] = zero_range + if hasattr(env_cfg.events, "reset_plug_curriculum"): + env_cfg.events.reset_plug_curriculum.params["at_goal_prob"] = 0.0 + env_cfg.events.reset_plug_curriculum.params["normal_pose_range"] = { + "x": [0.0, 0.0], + "y": [0.0, 0.0], + "z": [0.0, 0.0], + } + # Disable observation corruption for deterministic inference. + if hasattr(env_cfg.observations, "policy") and hasattr(env_cfg.observations.policy, "enable_corruption"): + env_cfg.observations.policy.enable_corruption = False + + +def _apply_robot_joint_override(env_cfg): + if args_cli.robot_joint_pos is None: + return + + overrides = _parse_robot_joint_pos(args_cli.robot_joint_pos, _arm_joint_names(env_cfg)) + robot_cfg = env_cfg.scene.robot + joint_pos = dict(robot_cfg.init_state.joint_pos) + joint_pos.update(overrides) + robot_cfg.init_state.joint_pos = joint_pos + print(f"[INFO] Manual robot joint override applied: {overrides}") + + grasp_event = getattr(env_cfg.events, "set_robot_to_grasp_pose", None) + if grasp_event is None: + print( + "[WARNING] No 'set_robot_to_grasp_pose' event found; plug will spawn at its configured pose, " + "not necessarily in the gripper." + ) + return + + params = grasp_event.params + env_cfg.events.set_robot_to_grasp_pose = None + env_cfg.events.place_plug_in_grasp = EventTerm( + func=place_plug_at_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": params.get("robot_asset_cfg", SceneEntityCfg("robot")), + "target_object_name": params["target_object_name"], + "end_effector_body_name": params["end_effector_body_name"], + "grasp_offset": params.get("grasp_offset", [0.0, 0.0, 0.0]), + "grasp_rot_offset": params["grasp_rot_offset"], + "gripper_joint_setter_func": params["gripper_joint_setter_func"], + "hand_hold_width": env_cfg.hand_hold_width, + "hand_close_width": env_cfg.hand_close_width, + "num_arm_joints": params["num_arm_joints"], + }, + ) + print("[INFO] Replaced IK grasp reset with place_plug_in_grasp (keeps manual joint pose).") + + +def _apply_socket_override(env_cfg) -> dict[str, Any]: + """Apply actual socket/plug init poses. Returns resolved pose metadata for logging.""" + socket_cfg = env_cfg.scene.dp_socket + plug_cfg = env_cfg.scene.dp_plug + socket_rot = tuple(args_cli.socket_rot) if args_cli.socket_rot is not None else tuple(socket_cfg.init_state.rot) + meta: dict[str, Any] = {"socket_rot_xyzw": list(socket_rot)} + + if args_cli.socket_pos is not None: + geometry_pos = tuple(args_cli.socket_pos) + socket_root = compute_socket_root(geometry_pos, socket_rot) + plug_root, plug_rot = compute_plug_pose(geometry_pos, socket_rot, z_clearance=args_cli.z_clearance) + socket_cfg.init_state.pos = socket_root + socket_cfg.init_state.rot = socket_rot + plug_cfg.init_state.pos = plug_root + plug_cfg.init_state.rot = plug_rot + if hasattr(env_cfg, "fixed_asset_init_pos_center"): + env_cfg.fixed_asset_init_pos_center = list(geometry_pos) + meta.update( + { + "socket_geometry_pos": list(geometry_pos), + "socket_root_pos": list(socket_root), + "plug_root_pos": list(plug_root), + "plug_rot_xyzw": list(plug_rot), + "z_clearance": args_cli.z_clearance, + } + ) + print("[INFO] Actual socket override applied:") + print(f" socket geometry pos = {tuple(round(v, 4) for v in geometry_pos)}") + print(f" socket root pos = {tuple(round(v, 4) for v in socket_root)}") + print(f" socket rot (xyzw) = {tuple(round(v, 4) for v in socket_rot)}") + print(f" plug root pos = {tuple(round(v, 4) for v in plug_root)}") + else: + meta["socket_geometry_pos"] = "env_default" + print("[INFO] No --socket_pos given; using env-configured socket pose (randomization disabled).") + + _disable_randomization(env_cfg) + return meta + + +def _apply_observed_socket_override(env) -> dict[str, Any]: + meta: dict[str, Any] = {} + if args_cli.observed_socket_pos is None and args_cli.observed_socket_rot is None: + return meta + + base = env.unwrapped + obs_mgr = base.observation_manager + term_names = obs_mgr.active_terms["policy"] + term_cfgs = obs_mgr._group_obs_term_cfgs["policy"] + + for name, term_cfg in zip(term_names, term_cfgs): + if name == "socket_pos" and args_cli.observed_socket_pos is not None: + term_cfg.func = _FixedObservedSocketPos(base, args_cli.observed_socket_pos) + term_cfg.noise = None + meta["observed_socket_pos"] = list(args_cli.observed_socket_pos) + elif name == "socket_quat" and args_cli.observed_socket_rot is not None: + term_cfg.func = _FixedObservedSocketQuat(base, args_cli.observed_socket_rot) + meta["observed_socket_rot"] = list(args_cli.observed_socket_rot) + + print("[INFO] Observed (policy-visible) socket pose override applied:") + if args_cli.observed_socket_pos is not None: + print(f" observed socket geometry pos = {tuple(round(v, 4) for v in args_cli.observed_socket_pos)}") + if args_cli.observed_socket_rot is not None: + print(f" observed socket rot (xyzw) = {tuple(round(v, 4) for v in args_cli.observed_socket_rot)}") + return meta + + +def _resolve_log_dir(resume_path: str | None) -> Path | None: + if args_cli.no_log_file: + return None + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + if args_cli.log_dir is not None: + return Path(args_cli.log_dir).expanduser().resolve() / stamp + if resume_path is not None: + return Path(os.path.dirname(resume_path)) / "inference_logs" / stamp + return Path("logs") / "dp_replay" / stamp + + +def _write_run_metadata( + log_dir: Path, + resume_path: str | None, + pose_meta: dict[str, Any], + replay: ReplayTrajectory | None = None, + leapp_model: str | None = None, + init_obs: InitPolicyObs | None = None, +): + payload = { + "task": args_cli.task, + "checkpoint": resume_path, + "leapp_model": leapp_model, + "replay_csv": str(replay.path) if replay is not None else None, + "replay_source": replay.source if replay is not None else None, + "replay_num_steps": replay.num_steps if replay is not None else None, + "init_obs_csv": str(init_obs.path) if init_obs is not None else None, + "init_obs_step": init_obs.step if init_obs is not None else None, + "init_obs_dim": int(init_obs.obs.size) if init_obs is not None else None, + "num_envs": args_cli.num_envs, + "max_steps": args_cli.max_steps, + "num_episodes": args_cli.num_episodes, + "seed": args_cli.seed, + "robot_joint_pos": args_cli.robot_joint_pos, + "socket_pos": args_cli.socket_pos, + "socket_rot": args_cli.socket_rot, + "observed_socket_pos": args_cli.observed_socket_pos, + "observed_socket_rot": args_cli.observed_socket_rot, + "z_clearance": args_cli.z_clearance, + "resolved_poses": pose_meta, + "timestamp": datetime.now().isoformat(timespec="seconds"), + } + path = log_dir / "run_config.json" + with open(path, "w", encoding="utf-8") as f: + json.dump(payload, f, indent=2) + print(f"[INFO] Wrote run config to {path}") + + +@hydra_task_config(args_cli.task, args_cli.agent) +def main( # noqa: C901 + env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agent_cfg: RslRlBaseRunnerCfg +): + """Run DisplayPort insertion inference with controllable poses and logging.""" + with launch_simulation(env_cfg, args_cli): + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "").replace("-ROS-Inference", "") + replay_mode = args_cli.replay_csv is not None + leapp_mode = args_cli.leapp_model is not None + init_obs_mode = args_cli.init_obs_csv is not None + + if leapp_mode and replay_mode: + raise ValueError("Use only one of --leapp_model and --replay_csv.") + if init_obs_mode and replay_mode: + raise ValueError("Use only one of --init_obs_csv and --replay_csv.") + if leapp_mode and (args_cli.checkpoint or args_cli.use_pretrained_checkpoint): + print("[WARNING] --leapp_model set; ignoring --checkpoint / --use_pretrained_checkpoint.") + if replay_mode and (args_cli.checkpoint or args_cli.use_pretrained_checkpoint): + print("[WARNING] --replay_csv set; checkpoint will not be used for actions.") + if init_obs_mode and not leapp_mode and not (args_cli.checkpoint or args_cli.use_pretrained_checkpoint): + # Still allow hydra default checkpoint resolution below; just note the feature. + print("[INFO] --init_obs_csv set: first policy step will use CSV obs_* verbatim.") + + agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, installed_version) + env_cfg.seed = agent_cfg.seed + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + replay_traj: ReplayTrajectory | None = None + init_obs_seed: InitPolicyObs | None = None + num_arm = int(getattr(env_cfg, "num_arm_joints", 7) or 7) + if replay_mode: + replay_traj = load_replay_trajectory(args_cli.replay_csv, num_arm_joints=num_arm) + _seed_cli_from_replay(replay_traj) + # Avoid mid-replay resets wiping the open-loop track. + if hasattr(env_cfg, "episode_length_s"): + env_cfg.episode_length_s = max(float(env_cfg.episode_length_s), replay_traj.num_steps * 10.0) + if init_obs_mode: + init_obs_seed = load_init_policy_obs( + args_cli.init_obs_csv, + step=int(args_cli.init_obs_step), + num_arm_joints=num_arm, + ) + _seed_cli_from_init_obs(init_obs_seed) + + _apply_robot_joint_override(env_cfg) + pose_meta = _apply_socket_override(env_cfg) + + log_root_path = os.path.abspath(os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)) + resume_path: str | None = None + leapp_yaml: Path | None = None + if leapp_mode: + leapp_yaml = resolve_leapp_model_yaml(args_cli.leapp_model) + resume_path = str(leapp_yaml) + print(f"[INFO] Using LEAPP model: {leapp_yaml}") + elif args_cli.use_pretrained_checkpoint: + print(f"[INFO] Loading experiment from directory: {log_root_path}") + resume_path = get_published_pretrained_checkpoint("rsl_rl", train_task_name) + if not resume_path: + print("[INFO] No pre-trained checkpoint is currently available for this task.") + return + elif args_cli.checkpoint: + print(f"[INFO] Loading experiment from directory: {log_root_path}") + resume_path = retrieve_file_path(args_cli.checkpoint) + elif not replay_mode: + print(f"[INFO] Loading experiment from directory: {log_root_path}") + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + else: + print("[INFO] Replay mode: no checkpoint required (policy will not be loaded).") + + if resume_path is not None: + env_cfg.log_dir = os.path.dirname(resume_path) + log_dir = _resolve_log_dir(resume_path) + + env = gym.make(args_cli.task, cfg=env_cfg) + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + observed_meta = _apply_observed_socket_override(env) + pose_meta.update(observed_meta) + if log_dir is not None: + log_dir.mkdir(parents=True, exist_ok=True) + _write_run_metadata( + log_dir, + resume_path if not leapp_mode else None, + pose_meta, + replay=replay_traj, + leapp_model=str(leapp_yaml) if leapp_yaml is not None else None, + init_obs=init_obs_seed, + ) + + env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + + policy = None + policy_nn = None + leapp_policy: LeappDisplayportPolicy | None = None + if leapp_mode: + assert leapp_yaml is not None + leapp_policy = LeappDisplayportPolicy(env, leapp_yaml, clip_actions=agent_cfg.clip_actions) + policy = leapp_policy + elif not replay_mode: + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + runner.load(resume_path) + policy = runner.get_inference_policy(device=env.unwrapped.device) + if version.parse(installed_version) < version.parse("4.0.0"): + if version.parse(installed_version) >= version.parse("2.3.0"): + policy_nn = runner.alg.policy + else: + policy_nn = runner.alg.actor_critic + else: + assert replay_traj is not None + print( + f"[INFO] Open-loop replay of {replay_traj.num_steps} absolute joint targets " + f"(source={replay_traj.source}, action_scale={_action_scale(env):.4f})." + ) + + dt = env.unwrapped.step_dt + logger = InferenceLogger( + env, + log_dir=log_dir, + print_enabled=not args_cli.no_print, + print_every=args_cli.print_every, + ) + success_tracker = SuccessTracker(env) + + obs = env.get_observations() + pending_init_obs = init_obs_seed + if pending_init_obs is not None: + sim_obs = _flatten_policy_obs(obs) + if sim_obs is not None: + if sim_obs.size != pending_init_obs.obs.size: + raise ValueError( + f"--init_obs_csv obs dim {pending_init_obs.obs.size} != live sim obs dim " + f"{sim_obs.size}. Record the CSV with the same task observation layout." + ) + delta = float(np.max(np.abs(sim_obs - pending_init_obs.obs))) + print( + f"[INFO] Injecting CSV init obs for first policy step " + f"(max |csv - sim_obs| before inject = {delta:.6g})." + ) + else: + print("[INFO] Injecting CSV init obs for first policy step.") + obs = _replace_policy_obs_vector( + obs, + pending_init_obs.obs, + num_envs=env.unwrapped.num_envs, + device=env.unwrapped.device, + ) + if leapp_policy is not None: + leapp_policy.force_flat_obs_once(pending_init_obs.obs) + step_count = 0 + episode_count = 0 + lstm_logged_once = False + try: + while True: + start_time = time.time() + with torch.inference_mode(): + rnn_in = rnn_out = None + if replay_mode: + assert replay_traj is not None + if step_count >= replay_traj.num_steps: + print(f"[INFO] Reached end of replay CSV ({replay_traj.num_steps} steps).") + break + actions = _absolute_targets_to_relative_actions( + env, + replay_traj.targets[step_count], + clip_actions=agent_cfg.clip_actions, + ) + elif leapp_policy is not None: + actions = leapp_policy(obs) + rnn_in = leapp_policy.last_rnn_in + rnn_out = leapp_policy.last_rnn_out + pending_init_obs = None + else: + # Capture LSTM state fed into this step, then post-forward out. + h_in, c_in = _extract_lstm_hidden_state(policy) + if h_in is None and policy_nn is not None: + h_in, c_in = _extract_lstm_hidden_state(policy_nn) + actions = policy(obs) + pending_init_obs = None + h_out, c_out = _extract_lstm_hidden_state(policy) + if h_out is None and policy_nn is not None: + h_out, c_out = _extract_lstm_hidden_state(policy_nn) + rnn_out = _pack_rnn_state(h_out, c_out) + rnn_in = _pack_rnn_state(h_in, c_in) + if rnn_out is not None and rnn_in is None: + # First step / inaccessible pre-state: zeros match real reset. + rnn_in = np.zeros_like(rnn_out) + + if not replay_mode and not lstm_logged_once: + if rnn_out is not None: + print( + f"[INFO] Logging recurrent state as rnn_in_*/rnn_out_* " + f"(dim={int(np.asarray(rnn_out).size)})." + ) + else: + print( + "[WARNING] Policy has no accessible LSTM hidden state; " + "rnn_in_*/rnn_out_* will not be written." + ) + lstm_logged_once = True + + # Snapshot the state the policy/replay actually saw, before the action lands. + pending_row = logger.begin_step( + obs, actions, step_count, episode_count, rnn_in=rnn_in, rnn_out=rnn_out + ) + logger.print_step(obs, actions, step_count, None, rnn_in=rnn_in, rnn_out=rnn_out) + + obs, _, dones, _ = env.step(actions) + success_info = success_tracker.update(dones) + dones_b = torch.as_tensor(dones).bool().view(-1) + if bool(dones_b.any()): + episode_count += int(dones_b.sum().item()) + + logger.end_step(pending_row, success_info) + logger.print_success(step_count, success_info) + step_count += 1 + + if leapp_policy is not None: + leapp_policy.reset(dones) + elif not replay_mode: + if version.parse(installed_version) >= version.parse("4.0.0"): + policy.reset(dones) + else: + policy_nn.reset(dones) + elif bool(dones_b.any()): + print( + "[WARNING] Env reset during open-loop replay; subsequent CSV targets " + "no longer match the robot state. Stopping." + ) + break + + if args_cli.max_steps is not None and step_count >= args_cli.max_steps: + print(f"[INFO] Reached --max_steps={args_cli.max_steps}.") + break + if args_cli.num_episodes is not None and episode_count >= args_cli.num_episodes: + print(f"[INFO] Reached --num_episodes={args_cli.num_episodes}.") + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + except KeyboardInterrupt: + print("\n[INFO] Interrupted by user.") + finally: + logger.flush() + if success_tracker.enabled and success_tracker.num_episodes > 0: + print( + f"[INFO] Final episode success rate: " + f"{success_tracker.num_success_episodes / success_tracker.num_episodes:.3f} " + f"({success_tracker.num_success_episodes}/{success_tracker.num_episodes})" + ) + env.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/reinforcement_learning/deploy/success_utils.py b/scripts/reinforcement_learning/deploy/success_utils.py new file mode 100644 index 000000000000..6bf9aff75225 --- /dev/null +++ b/scripts/reinforcement_learning/deploy/success_utils.py @@ -0,0 +1,87 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Helper for printing task-success statistics during RSL-RL inference/play. + +Works with any environment that exposes a ``_compute_success()`` method returning +``(is_success, pos_error, keypoint_dist)`` per environment (see +``deploy.cable_insertion.insertion_env.DisplayportInsertionEnv``). For other +environments the tracker disables itself gracefully. +""" + +from __future__ import annotations + +import torch + + +class SuccessTracker: + """Accumulate and format success statistics across play steps/episodes. + + Two rates are tracked: + + - **instantaneous success rate**: fraction of envs currently in the success + state (plug mate point within threshold of the socket mate point). + - **episode success rate**: fraction of completed episodes in which the env + reached the success state at least once. This is robust to the fact that + manager-based envs auto-reset inside ``step()`` (the terminal state is not + visible post-step), because success is accumulated from prior in-episode + steps. + """ + + def __init__(self, env): + self.base = env.unwrapped + self.enabled = hasattr(self.base, "_compute_success") + if not self.enabled: + return + n = self.base.num_envs + self.device = self.base.device + self._ever_success = torch.zeros(n, dtype=torch.bool, device=self.device) + self.num_episodes = 0 + self.num_success_episodes = 0 + + def update(self, dones) -> dict | None: + """Update stats after an ``env.step``. ``dones`` is the per-env done tensor. + + Returns a dict of scalars, or ``None`` if the env does not support success. + """ + if not self.enabled: + return None + + is_success, pos_error, keypoint_dist = self.base._compute_success() + dones_b = torch.as_tensor(dones, device=self.device).bool().view(-1) + + # An episode ends this step for done envs: record whether it reached success + # at any point (accumulated in prior steps), then reseed with the fresh state. + if dones_b.any(): + reached = self._ever_success[dones_b] + self.num_episodes += int(dones_b.sum().item()) + self.num_success_episodes += int(reached.sum().item()) + self._ever_success[dones_b] = is_success[dones_b] + # Accumulate success for ongoing episodes. + ongoing = ~dones_b + self._ever_success[ongoing] |= is_success[ongoing] + + episode_rate = (self.num_success_episodes / self.num_episodes) if self.num_episodes > 0 else float("nan") + return { + "instant_success_rate": is_success.float().mean().item(), + "pos_error_m": pos_error.mean().item(), + "keypoint_dist_m": keypoint_dist.mean().item(), + "episode_success_rate": episode_rate, + "num_episodes": self.num_episodes, + } + + @staticmethod + def format(info: dict | None) -> str: + """Format the stats dict as a compact one-line string (empty if unsupported).""" + if info is None: + return "" + ep = info["episode_success_rate"] + ep_str = f"{ep:.3f}" if ep == ep else "n/a" # NaN check + return ( + f"[success] instant={info['instant_success_rate']:.3f} | " + f"episode={ep_str} (n={info['num_episodes']}) | " + f"pos_err={info['pos_error_m'] * 1000:.2f}mm | " + f"kp_dist={info['keypoint_dist_m'] * 1000:.2f}mm" + ) diff --git a/scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py b/scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py new file mode 100644 index 000000000000..2d35958ef94f --- /dev/null +++ b/scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py @@ -0,0 +1,356 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Export a DisplayPort cable-insertion task-space policy for Isaac ROS Deploy. + +The generic exporter (``export.py``) publishes the actor observation as a single opaque +vector and the raw ``[-1, 1]`` policy output as the action. The Isaac ROS Deploy bridge +instead expects the task-space contract: four named pose tensors in, and the clipped, +scaled Cartesian pose delta out. + +Rather than adding task-specific branches to the generic entry point, this script reuses +it wholesale and substitutes only the export routine. ``run_export_with_hydra`` resolves +``export_rsl_rl_agent`` as a module global, so rebinding that name is enough to inject +the DisplayPort contract while argument parsing, checkpoint resolution, Hydra handling, +runner construction, and graph compilation all stay shared with upstream. + +Usage: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py \ + --task Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0 \ + --checkpoint logs/rsl_rl/displayport_insertion_rizon4s//model_.pt \ + --task_space_contract +""" + +from __future__ import annotations + +import argparse +import contextlib +import os +import sys +import time +from collections.abc import Mapping + +_THIS_DIR = os.path.dirname(os.path.abspath(__file__)) +if _THIS_DIR not in sys.path: + sys.path.insert(0, _THIS_DIR) + +import export as _export # noqa: E402 (generic RSL-RL exporter, reused as-is) + +# Name of the exported LEAPP graph. The Deploy bridge looks the model up by this name, so +# it is deliberately independent of the (much longer) gym task id. +TASK_SPACE_EXPORT_MODEL_NAME = "DisplayPortTaskSpace" + +_ROT6D_ELEMENTS = ["r00", "r01", "r02", "r10", "r11", "r12"] + +# (tensor name, slice of the 18D actor observation, element names, source tag, LEAPP kind) +_TASK_SPACE_INPUT_SPEC = ( + ("eef_pos", slice(0, 3), ["x", "y", "z"], "eef_pose_pos", "state/body/position"), + ("eef_rot_6d", slice(3, 9), _ROT6D_ELEMENTS, "eef_pose_rot6d", "state/body/rotation_6d"), + ("socket_kp_pos", slice(9, 12), ["x", "y", "z"], "socket_kp_pose_pos", "state/body/position"), + ("socket_kp_rot_6d", slice(12, 18), _ROT6D_ELEMENTS, "socket_kp_pose_rot6d", "state/body/rotation_6d"), +) + +_ACTION_ELEMENT_NAMES = [ + "delta_x", + "delta_y", + "delta_z", + "delta_axis_angle_x", + "delta_axis_angle_y", + "delta_axis_angle_z", +] + + +def parse_export_args(argv: list[str] | None = None) -> tuple[argparse.Namespace, list[str]]: + """Parse export arguments, adding the DisplayPort task-space contract flag.""" + _leapp_scripts_dir = os.path.dirname(_THIS_DIR) + if _leapp_scripts_dir not in sys.path: + sys.path.insert(0, _leapp_scripts_dir) + from export_utils import add_common_export_args, finalize_export_args + + parser = argparse.ArgumentParser(description="Export a DisplayPort cable-insertion policy with RSL-RL.") + add_common_export_args(parser, agent_default="rsl_rl_cfg_entry_point") + parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment.") + parser.add_argument( + "--experiment_name", type=str, default=None, help="Name of the experiment folder used to locate checkpoints." + ) + parser.add_argument( + "--task_space_contract", + action="store_true", + help=( + "Export the task-space I/O contract used by Isaac ROS Deploy: split the 18D actor" + " observation into named pose tensors (eef_pos, eef_rot_6d, socket_kp_pos," + " socket_kp_rot_6d) and emit the clipped, scaled Cartesian delta as 'arm_action'." + " Requires an operational-space action term exposing position/orientation scales." + ), + ) + return finalize_export_args(parser, argv) + + +def task_space_policy_obs(obs): + """Return the 18D actor observation tensor from an RSL-RL TensorDict.""" + if "policy" not in obs.keys(): + raise KeyError(f"Expected a 'policy' observation group, got keys: {list(obs.keys())}") + policy_obs = obs["policy"] + if policy_obs.shape[-1] != 18: + raise ValueError(f"Expected 18D task-space actor observation, got shape {tuple(policy_obs.shape)}") + return policy_obs + + +def split_and_annotate_task_space_obs(graph_name: str, policy_obs): + """Expose the exact 18D trained observation as four Deploy-facing input tensors.""" + from leapp.utils.tensor_description import TensorSemantics + + parts = [] + for name, index, element_names, source, kind in _TASK_SPACE_INPUT_SPEC: + parts.append( + _export.annotate.input_tensors( + graph_name, + TensorSemantics( + name=name, + ref=policy_obs[:, index], + kind=kind, + element_names=[element_names], + extra={"source": source}, + ), + ) + ) + # Re-concatenate so the policy still sees the byte-identical vector it was trained on. + return _export.torch.cat(parts, dim=-1) + + +def export_task_space_action(graph_name: str, tensor, export_method: str) -> None: + """Annotate the deploy-facing processed (clipped and scaled) task-space action.""" + from leapp.utils.tensor_description import TensorSemantics + + _export.annotate.output_tensors( + graph_name, + TensorSemantics( + name="arm_action", + ref=tensor, + kind="target/body/pose_relative", + element_names=[_ACTION_ELEMENT_NAMES], + extra={ + "isaaclab_connection": "action:arm_action:pose_rel", + "target_types": ["pose_rel"], + }, + ), + export_with=export_method, + ) + + +def task_space_action_scale(env_cfg, device, dtype): + """Return ``[pos_scale] * 3 + [rot_scale] * 3`` from the task configuration.""" + action_cfg = env_cfg.actions.arm_action + for attr in ("position_scale", "orientation_scale"): + if not hasattr(action_cfg, attr): + raise AttributeError( + f"--task_space_contract requires an operational-space action term exposing '{attr}'; " + f"got {type(action_cfg).__name__}." + ) + scale_values = [float(action_cfg.position_scale)] * 3 + [float(action_cfg.orientation_scale)] * 3 + return _export.torch.tensor(scale_values, device=device, dtype=dtype).unsqueeze(0) + + +def export_displayport_agent( + args_cli: argparse.Namespace, + env_cfg, + agent_cfg, + simulation_app=None, +) -> bool: + """Export a DisplayPort RSL-RL agent, optionally with the task-space I/O contract. + + Mirrors :func:`export.export_rsl_rl_agent`; the DisplayPort-specific behaviour is + confined to the blocks guarded by ``args_cli.task_space_contract``. + """ + _export._load_runtime_dependencies() + + task_name = args_cli.task.split(":")[-1] + checkpoint_task_name = task_name.replace("-Play", "") + + agent_cfg = _export._update_agent_cfg_from_export_args(agent_cfg, args_cli) + env_cfg.scene.num_envs = 1 + + agent_cfg = _export.handle_deprecated_rsl_rl_cfg(agent_cfg, _export.installed_version) + + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Loading checkpoint search path from directory: {log_root_path}") + if args_cli.checkpoint == "pretrained": + backend_names = _export.get_pretrained_checkpoint_backend_names(env_cfg) + resume_path = _export.get_published_pretrained_checkpoint("rsl_rl", checkpoint_task_name, *backend_names) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return False + elif args_cli.checkpoint and os.path.isdir(args_cli.checkpoint): + resume_path = _export.get_checkpoint_path( + os.path.dirname(args_cli.checkpoint), os.path.basename(args_cli.checkpoint), agent_cfg.load_checkpoint + ) + elif args_cli.checkpoint: + resume_path = _export.retrieve_file_path(args_cli.checkpoint) + else: + resume_path = _export.get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + if not resume_path: + print(f"[INFO] No checkpoint found for task: {checkpoint_task_name} in directory: {log_root_path}") + return False + + log_dir = os.path.dirname(resume_path) + env_cfg.log_dir = log_dir + + env = None + leapp_started = False + + try: + env = _export.gym.make(args_cli.task, cfg=env_cfg, render_mode=None) + policy_node_name = _export.ensure_env_spec_id(env) + + graph_name = args_cli.export_task_name if args_cli.export_task_name is not None else task_name + if args_cli.task_space_contract and args_cli.export_task_name is None: + graph_name = TASK_SPACE_EXPORT_MODEL_NAME + if args_cli.task_space_contract: + # The contract publishes inputs/outputs under ``graph_name``; the recurrent-state + # annotations must target that same node or LEAPP cannot find it. + policy_node_name = graph_name + + # Resolve the export backend once, so every downstream annotation uses the same + # default. ``--export_method`` defaults to ``None`` in argparse; forwarding that + # ``None`` to LEAPP silently skips model compilation, producing a package with no + # ``.onnx`` graph whose validation is skipped but still reported as passing. + export_method = "onnx-dynamo" if args_cli.export_method is None else args_cli.export_method + + if isinstance(env.unwrapped, _export.ManagerBasedRLEnv): + # Patch only the observation groups consumed by the actor policy. + # This filters out the critic and teacher observation groups. + obs_groups_cfg = getattr(agent_cfg, "obs_groups", None) + if isinstance(obs_groups_cfg, Mapping): + required_obs_groups = set(obs_groups_cfg.get("actor", ["policy"])) + else: + required_obs_groups = {"policy"} + # The task-space contract annotates its own inputs/outputs under a dedicated graph + # node, so the automatic patcher must stay out of the way: it would annotate the + # same observation tensors under a node named after the task id, and LEAPP refuses + # to mix two active tracing contexts for one tensor. + if not args_cli.task_space_contract: + _export.patch_env_for_export( + env, + export_method=export_method, + required_obs_groups=required_obs_groups, + ) + elif args_cli.export_method is not None: + raise ValueError( + "--export_method is only supported for manager-based environments. For direct environments, " + "set export_with directly in the annotate.output_tensors() call instead." + ) + + env = _export.RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + if agent_cfg.class_name == "OnPolicyRunner": + runner = _export.OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = _export.DistillationRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + runner.load(resume_path) + + policy = runner.get_inference_policy(device=env.unwrapped.device) + + task_space_scale = None + if args_cli.task_space_contract: + task_space_scale = task_space_action_scale( + env.unwrapped.cfg, env.unwrapped.device, next(policy.parameters()).dtype + ) + print(f"[INFO] Exporting processed task-space action with scale: {task_space_scale.flatten().tolist()}") + + if args_cli.export_save_path is not None: + save_path = args_cli.export_save_path + elif args_cli.checkpoint == "pretrained": + # Use a predictable path independent of the Nucleus mirror directory structure. + save_path = os.path.join(".pretrained_checkpoints", "rsl_rl", checkpoint_task_name) + else: + save_path = log_dir + _export.leapp.start(graph_name, save_path=save_path, max_cached_io=max(args_cli.validation_steps, 2)) + leapp_started = True + obs = env.reset()[0] + if simulation_app is not None: + while not simulation_app.is_running(): + time.sleep(0.5) + + for _ in range(max(args_cli.validation_steps, 2)): + with _export.torch.inference_mode(): + # Inputs must be annotated before ``state_tensors``: the first ``input_tensors`` + # call is what creates the graph node the recurrent state attaches to. + if args_cli.task_space_contract: + policy_obs = task_space_policy_obs(obs).to(dtype=next(policy.parameters()).dtype) + obs_for_policy = obs.clone() + obs_for_policy["policy"] = split_and_annotate_task_space_obs(graph_name, policy_obs) + else: + obs_for_policy = obs + + if _export.is_actor_recurrent_policy(policy): + actor_hidden = _export.ensure_actor_hidden_state_initialized( + policy, + batch_size=env.num_envs, + device=env.unwrapped.device, + dtype=next(policy.parameters()).dtype, + ) + registered_state = _export.annotate.state_tensors( + policy_node_name, + _export.state_dict_from_actor_hidden(actor_hidden), + ) + _export.set_actor_hidden_state( + policy, _export.actor_hidden_from_registered(registered_state, actor_hidden) + ) + + actions = policy(obs_for_policy) + + if _export.is_actor_recurrent_policy(policy): + actor_hidden_after = _export.get_actor_hidden_state(policy) + _export.annotate.update_state( + policy_node_name, + _export.state_dict_from_actor_hidden(actor_hidden_after), + ) + + if args_cli.task_space_contract: + processed_action = _export.torch.clamp(actions, -1.0, 1.0) * task_space_scale + export_task_space_action(graph_name, processed_action, export_method) + # Refresh inputs without invoking the action manager, which would apply the + # raw (unscaled) action and desynchronise the traced graph. + obs = env.get_observations() + else: + obs, _, _, _ = env.step(actions) + + _export.leapp.stop() + leapp_started = False + validate = args_cli.validation_steps > 0 + _export.leapp.compile_graph(visualize=not args_cli.disable_graph_visualization, validate=validate) + finally: + if leapp_started: + with contextlib.suppress(Exception): + _export.leapp.stop() + if env is not None: + env.close() + + return True + + +def main_cli(argv: list[str] | None = None) -> bool: + """Run the DisplayPort export flow, reusing the generic Hydra/simulation wrapper.""" + args_cli, hydra_args = parse_export_args(argv) + # ``run_export_with_hydra`` resolves ``export_rsl_rl_agent`` as a module global, so + # rebinding it here injects the DisplayPort contract without editing the generic script. + _export.export_rsl_rl_agent = export_displayport_agent + return _export.run_export_with_hydra(args_cli, hydra_args) + + +if __name__ == "__main__": + main_cli() diff --git a/source/isaaclab/changelog.d/j3soon-fix-dp-cable-ship.skip b/source/isaaclab/changelog.d/j3soon-fix-dp-cable-ship.skip new file mode 100644 index 000000000000..928059249162 --- /dev/null +++ b/source/isaaclab/changelog.d/j3soon-fix-dp-cable-ship.skip @@ -0,0 +1,2 @@ +Internal: normalised the joint indices resolved by ``JointAction`` to ``int64`` so the term is ONNX-exportable. +The warp-backed ``int32`` form it replaces exists only on ``develop``, so no released behaviour changes. diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py index 435a04574a06..1625c1075e43 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py @@ -66,7 +66,11 @@ def __init__(self, cfg: actions_cfg.JointActionCfg, env: ManagerBasedEnv) -> Non self.cfg.joint_names, preserve_order=self.cfg.preserve_order, as_proxy=True ) self._num_joints = len(joint_ids) - self._joint_ids = joint_ids.torch + # ``find_joints`` returns warp-backed indices, which surface as ``int32``. Torch + # accepts int32 for advanced indexing, but ONNX ``GatherND`` requires int64, so an + # int32 index tensor produces a structurally invalid graph when this action term is + # traced for export. Normalise to int64 at resolution time. + self._joint_ids = joint_ids.torch.long() # log the resolved joint names for debugging logger.info( f"Resolved joint names for the action term {self.__class__.__name__}:" diff --git a/source/isaaclab_tasks/changelog.d/dp-taskspace-osc-leapp.minor.rst b/source/isaaclab_tasks/changelog.d/dp-taskspace-osc-leapp.minor.rst new file mode 100644 index 000000000000..16f1eddbe6b8 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/dp-taskspace-osc-leapp.minor.rst @@ -0,0 +1,17 @@ +Added +^^^^^ + +* Added a task-space (Operational Space Control) variant of the DisplayPort cable-insertion environment for the + Flexiv Rizon 4S, registered as ``Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-v0`` along with its + ``-TaskSpace-Play-v0`` and ``-TaskSpace-ROS-Inference-v0`` variants. +* Added LEAPP-exportable deploy action wrappers + :class:`~isaaclab_tasks.contrib.deploy.mdp.DeployOperationalSpaceControllerActionCfg`, + :class:`~isaaclab_tasks.contrib.deploy.mdp.DeployRelativeJointPositionActionCfg`, and + :class:`~isaaclab_tasks.contrib.deploy.mdp.DeployDifferentialInverseKinematicsActionCfg`, which export the scaled + pose/joint deltas needed to run task-space policies through LEAPP. +* Added :file:`scripts/reinforcement_learning/leapp/rsl_rl/export_displayport_insertion.py`, a DisplayPort-specific + LEAPP exporter that reuses the generic RSL-RL export flow and adds the ``--task_space_contract`` option, which + publishes the Isaac ROS Deploy task-space I/O contract (four named pose inputs and a scaled Cartesian pose delta). +* Added support for the ``DP_ROBOT_USD`` environment variable, which selects the robot USD spawned by the + DisplayPort cable-insertion environments in both control spaces. The value is passed to the spawner untouched, + so a calibrated robot description may be a local path, a Nucleus URL or an HTTP(S) URL. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/__init__.py index 3de316ff3300..5004a831f4a0 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/__init__.py @@ -11,5 +11,7 @@ The deploy module includes: - Reach environments for end-effector pose tracking +- Gear assembly environments for multi-gear insertion tasks +- Cable insertion environments for DisplayPort plug insertion tasks """ diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/__init__.py new file mode 100644 index 000000000000..b1d487e2b679 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""DisplayPort cable insertion environments.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/__init__.py new file mode 100644 index 000000000000..1332dd34866f --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configurations for arm-based cable insertion environments.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/__init__.py new file mode 100644 index 000000000000..2f18884e7421 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/__init__.py @@ -0,0 +1,120 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +from . import agents + +_INSERTION_ENV_ENTRY = ( + "isaaclab_tasks.contrib.deploy.cable_insertion.insertion_env:DisplayportInsertionEnv" +) + +## +# Register Gym environments. +## + +# Flexiv Rizon 4s - Joint space +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:Rizon4sGravDisplayportInsertionEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Joint space Play +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-Play-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:Rizon4sGravDisplayportInsertionEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Joint space without joint velocity +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:Rizon4sGravDisplayportInsertionNoJointVelEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Joint space without joint velocity Play +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-Play-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:Rizon4sGravDisplayportInsertionNoJointVelEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Joint space ROS Inference without joint velocity +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-NoJointVel-ROS-Inference-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": ( + f"{__name__}.ros_inference_env_cfg:Rizon4sGravDisplayportInsertionNoJointVelROSInferenceEnvCfg" + ), + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Joint space ROS Inference +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-ROS-Inference-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.ros_inference_env_cfg:Rizon4sGravDisplayportInsertionROSInferenceEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Task space (Operational Space Control) +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.task_space_env_cfg:Rizon4sTaskSpaceDisplayportInsertionEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Task space Play +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-Play-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.task_space_env_cfg:Rizon4sTaskSpaceDisplayportInsertionEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Task space ROS Inference +gym.register( + id="Isaac-Deploy-DisplayportInsertion-Rizon4s-Grav-TaskSpace-ROS-Inference-v0", + entry_point=_INSERTION_ENV_ENTRY, + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": ( + f"{__name__}.task_space_ros_inference_env_cfg:" + "Rizon4sTaskSpaceDisplayportInsertionROSInferenceEnvCfg" + ), + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGravDisplayportInsertionRNNPPORunnerCfg", + }, +) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/agents/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/agents/__init__.py new file mode 100644 index 000000000000..6fc9a6577ee8 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/agents/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Package containing agent configurations for RL with Rizon 4s for DisplayPort insertion.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/agents/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/agents/rsl_rl_ppo_cfg.py new file mode 100644 index 000000000000..7dcb69667ecc --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/agents/rsl_rl_ppo_cfg.py @@ -0,0 +1,49 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils.configclass import configclass + +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlPpoActorCriticRecurrentCfg, RslRlPpoAlgorithmCfg + + +@configclass +class Rizon4sGravDisplayportInsertionRNNPPORunnerCfg(RslRlOnPolicyRunnerCfg): + num_steps_per_env = 512 + max_iterations = 1500 + save_interval = 50 + experiment_name = "displayport_insertion_rizon4s" + clip_actions = 1.0 + resume = False + obs_groups = { + "policy": ["policy"], + "critic": ["critic"], + } + policy = RslRlPpoActorCriticRecurrentCfg( + state_dependent_std=True, + init_noise_std=1.0, + actor_obs_normalization=True, + critic_obs_normalization=True, + actor_hidden_dims=[256, 128, 64], + critic_hidden_dims=[256, 128, 64], + noise_std_type="log", + activation="elu", + rnn_type="lstm", + rnn_hidden_dim=256, + rnn_num_layers=2, + ) + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.0, + num_learning_epochs=8, + num_mini_batches=16, + learning_rate=5.0e-4, + schedule="adaptive", + gamma=0.99, + lam=0.95, + desired_kl=0.008, + max_grad_norm=1.0, + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/joint_pos_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/joint_pos_env_cfg.py new file mode 100644 index 000000000000..8a28ab278ad8 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/joint_pos_env_cfg.py @@ -0,0 +1,438 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Joint-space DisplayPort insertion environment for Flexiv Rizon 4S + Grav gripper.""" + +import math +import os + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import ArticulationCfg, RigidObjectCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.utils.configclass import configclass + +import isaaclab_tasks.contrib.deploy.mdp as mdp +import isaaclab_tasks.contrib.deploy.mdp.terminations as cable_terminations +from isaaclab_tasks.contrib.deploy.cable_insertion.displayport_insertion_env_cfg import ( + DISPLAY_ASSETS_DIR, + PLUG_GOAL_ROT, + PLUG_INSERTION_OFFSET, + SOCKET_INSERTION_OFFSET, + DisplayportInsertionEnvCfg, + compute_plug_pose, + compute_socket_root, + resolve_robot_usd, +) + +# DisplayPort insertion station layout in the Flexiv workspace. +# _GEOMETRY_POS is the desired insertion (mate) point; _SOCKET_ROT orients the socket opening up. +_GEOMETRY_POS = (0.475, 0.125, 0.06) +_SOCKET_ROT = (0.5, 0.5, 0.5, -0.5) # opening faces +Z (top-down insertion) +_PLUG_CLEARANCE_Z = 0.068 # vertical clearance between plug and socket at reset + +_SOCKET_ROOT = compute_socket_root(_GEOMETRY_POS, _SOCKET_ROT) +_PLUG_ROOT, _PLUG_ROT = compute_plug_pose( + _GEOMETRY_POS, + _SOCKET_ROT, + z_clearance=_PLUG_CLEARANCE_Z, +) + +# Blade engagement along the insertion axis used by the at-goal curriculum [m]. +_INSERTION_LENGTH = 0.011 + +# Calibrated Rizon4s USD (measured kinematics) used in place of the stock Nucleus robot USD. +_RIZON4S_CALIBRATED_USD_PATH = os.path.join( + DISPLAY_ASSETS_DIR, + "Rizon4s-063459_with_Grav_calibrated_kinematics.usd", +) + +## +# Pre-defined configs +## +from isaaclab_assets import FLEXIV_RIZON4S_GRAV_GRIPPER_CFG # isort: skip + + +## +# Gripper-specific helper functions +## + + +def set_finger_joint_pos_grav( + joint_pos: torch.Tensor, + reset_ind_joint_pos: list[int], + finger_joints: list[int], + finger_joint_position: float, +): + """Set finger joint positions for Grav gripper. + + Args: + joint_pos: Joint positions tensor + reset_ind_joint_pos: Row indices into the sliced joint_pos tensor + finger_joints: List of all gripper joint indices (6 joints total) + finger_joint_position: Target position for main finger joint (in radians) + + Note: + Grav gripper joint structure (indices from finger_joints list): + [0] finger_joint - main controllable joint + [1] left_inner_knuckle_joint - mimic with -1 gearing + [2] right_inner_knuckle_joint - mimic with -1 gearing + [3] right_outer_knuckle_joint - mimic with -1 gearing + [4] left_outer_finger_joint - mimic with +1 gearing + [5] right_outer_finger_joint - mimic with +1 gearing + """ + for idx in reset_ind_joint_pos: + if len(finger_joints) < 6: + raise ValueError(f"Grav gripper requires at least 6 finger joints, got {len(finger_joints)}") + + # Main controllable joint + joint_pos[idx, finger_joints[0]] = finger_joint_position + + # Mimic joints with -1 gearing + joint_pos[idx, finger_joints[1]] = finger_joint_position # left_inner_knuckle_joint + joint_pos[idx, finger_joints[2]] = finger_joint_position # right_inner_knuckle_joint + joint_pos[idx, finger_joints[3]] = finger_joint_position # right_outer_knuckle_joint + + # Mimic joints with +1 gearing + joint_pos[idx, finger_joints[4]] = -finger_joint_position # left_outer_finger_joint + joint_pos[idx, finger_joints[5]] = -finger_joint_position # right_outer_finger_joint + + +## +# Environment configuration +## + + +@configclass +class EventCfg: + """Configuration for events.""" + + plug_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("dp_plug", body_names=".*"), + "static_friction_range": (0.001, 0.001), + "dynamic_friction_range": (0.001, 0.001), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + socket_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("dp_socket", body_names=".*"), + "static_friction_range": (0.001, 0.001), + "dynamic_friction_range": (0.001, 0.001), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger.*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + + randomize_socket_pose = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={ + "pose_range": { + "x": [-0.01, 0.01], + "y": [-0.01, 0.01], + "z": [-0.02, 0.02], + "roll": [-math.radians(2.0), math.radians(2.0)], # 2 degree + "pitch": [-math.radians(2.0), math.radians(2.0)], # 2 degree + "yaw": [-math.radians(2.0), math.radians(2.0)], # 2 degree + }, + "velocity_range": {}, + "asset_cfg": SceneEntityCfg("dp_socket"), + }, + ) + + reset_plug_curriculum = EventTerm( + func=mdp.reset_plug_at_goal_curriculum, + mode="reset", + params={ + "plug_cfg": SceneEntityCfg("dp_plug"), + "socket_cfg": SceneEntityCfg("dp_socket"), + "at_goal_prob": 0.8, + "at_goal_prob_final": 0.0, + "anneal_start_iter": 0.0, + "anneal_end_iter": 500.0, + "num_steps_per_env": 512, + "insertion_axis": [1.0, 0.0, 0.0], + "insertion_length": _INSERTION_LENGTH, + "at_goal_depth_range": [0.0, 0.015], + "approach_depth_range": [0.02, 0.06], + "socket_insertion_offset": SOCKET_INSERTION_OFFSET, + "plug_insertion_offset": PLUG_INSERTION_OFFSET, + "goal_rot": list(PLUG_GOAL_ROT), + "normal_pose_range": { + "x": [-0.02, 0.02], + "y": [-0.02, 0.02], + "z": [0.0, 0.0], + }, + }, + ) + + set_robot_to_grasp_pose = EventTerm( + func=mdp.set_robot_to_object_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "pos_randomization_range": {"x": [-0.0, 0.0], "y": [-0.0, 0.0], "z": [-0.0, 0.0]}, + "target_object_name": "dp_plug", + "grasp_offset": [0.0, 0.0, 0.0], + }, + ) + + +@configclass +class TerminationsCfg: + """Configuration for termination terms.""" + + time_out = DoneTerm(func=mdp.time_out, time_out=True) + + plug_dropped = DoneTerm( + func=cable_terminations.reset_when_plug_dropped, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "plug_asset_cfg": SceneEntityCfg("dp_plug"), + "distance_threshold": 0.15, + "end_effector_body_name": "link7", + "grasp_offset": [0.0, 0.0, 0.0], + "grasp_rot_offset": [0.0, 0.0, 0.0, 1.0], + }, + ) + + plug_orientation_exceeded = DoneTerm( + func=cable_terminations.reset_when_plug_orientation_exceeded, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "plug_asset_cfg": SceneEntityCfg("dp_plug"), + "roll_threshold_deg": 15.0, + "pitch_threshold_deg": 15.0, + "yaw_threshold_deg": 180.0, + "end_effector_body_name": "link7", + "grasp_rot_offset": [0.0, 0.0, 0.0, 1.0], + }, + ) + + +@configclass +class Rizon4sGravDisplayportInsertionEnvCfg(DisplayportInsertionEnvCfg): + """Configuration for Flexiv Rizon 4s with Grav Gripper DisplayPort insertion. + + The Flexiv Rizon 4s is a 7-DOF collaborative robot arm equipped with the + Flexiv Grav parallel gripper for DisplayPort plug insertion tasks. + """ + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # Match exponential keypoint reward weight to the linear term (1:1 weighting) + self.rewards.plug_socket_keypoint_tracking_exp.weight = abs(self.rewards.plug_socket_keypoint_tracking.weight) + + # Robot-specific parameters for Flexiv Rizon 4s with Grav gripper + self.end_effector_body_name = "flange" # End effector body name for IK + self.num_arm_joints = 7 # Number of arm joints (Rizon 4s has 7 DOF) + # Grasp offset in the DisplayPort plug's local frame [m] + self.grasp_offset = [0.0025, 0.0, -0.1875] + # Rotation offset for grasp pose (quaternion [x, y, z, w]) + self.grasp_rot_offset = [0.0, 0.0, 0.0, 1.0] + self.gripper_joint_setter_func = set_finger_joint_pos_grav # Grav gripper joint setter function + + # Plug orientation termination thresholds (in degrees) + self.plug_orientation_roll_threshold_deg = 15.0 # Maximum allowed roll deviation + self.plug_orientation_pitch_threshold_deg = 15.0 # Maximum allowed pitch deviation + self.plug_orientation_yaw_threshold_deg = 180.0 # Maximum allowed yaw deviation + + # Common observation configuration for Rizon 4s joints (arm only, not gripper) + self.observations.policy.joint_pos.params["asset_cfg"].joint_names = [ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ] + self.observations.policy.joint_vel.params["asset_cfg"].joint_names = [ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ] + + # override events + self.events = EventCfg() + + self.terminations = TerminationsCfg() + + # Update termination thresholds from config + self.terminations.plug_orientation_exceeded.params["roll_threshold_deg"] = ( + self.plug_orientation_roll_threshold_deg + ) + self.terminations.plug_orientation_exceeded.params["pitch_threshold_deg"] = ( + self.plug_orientation_pitch_threshold_deg + ) + self.terminations.plug_orientation_exceeded.params["yaw_threshold_deg"] = ( + self.plug_orientation_yaw_threshold_deg + ) + + # Action configuration for Rizon 4s arm + self.joint_action_scale = 0.025 + _arm_joint_names = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"] + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=_arm_joint_names, + scale=self.joint_action_scale, + use_zero_offset=True, + ) + + # Switch robot to Flexiv Rizon 4s with Grav gripper + self.scene.robot = FLEXIV_RIZON4S_GRAV_GRIPPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=FLEXIV_RIZON4S_GRAV_GRIPPER_CFG.spawn.replace( + usd_path=resolve_robot_usd(_RIZON4S_CALIBRATED_USD_PATH), + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=3666.0, + enable_gyroscopic_forces=True, + solver_position_iteration_count=4, + solver_velocity_iteration_count=1, + max_contact_impulse=1e32, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=4, + solver_velocity_iteration_count=1, + ), + collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.005, rest_offset=0.0), + ), + # Joint positions for the DisplayPort insertion station home pose + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": math.radians(32.44), + "joint2": math.radians(-16.71), + "joint3": math.radians(-5.69), + "joint4": math.radians(128.38), + "joint5": math.radians(6.74), + "joint6": math.radians(55.95), + "joint7": math.radians(111.54), + }, + pos=(0.0, 0.0, 0.0), + rot=(0.0, 0.0, 0.0, 1.0), + ), + ) + + # Grav gripper actuator configuration + self.scene.robot.actuators["gripper_drive"] = ImplicitActuatorCfg( + joint_names_expr=["finger_joint"], + effort_limit_sim=2.0, + velocity_limit_sim=1.0, + stiffness=2e3, + damping=1e1, + ) + + # Passive/mimic joints in the gripper - set to zero stiffness/damping + self.scene.robot.actuators["gripper_passive"] = ImplicitActuatorCfg( + joint_names_expr=[".*_knuckle_joint"], + effort_limit_sim=1.0, + velocity_limit_sim=1.0, + stiffness=0.0, + damping=0.0, + ) + + # Override socket/plug initial states for the DisplayPort insertion station + self.scene.dp_socket.init_state = RigidObjectCfg.InitialStateCfg( + pos=_SOCKET_ROOT, + rot=_SOCKET_ROT, + ) + self.scene.dp_plug.init_state = RigidObjectCfg.InitialStateCfg( + pos=_PLUG_ROOT, + rot=_PLUG_ROT, + ) + + # Grasp widths for Grav gripper (raw radian values for finger_joint) + self.hand_grasp_width = 0.3 + self.hand_hold_width = -0.05 + self.hand_close_width = -0.155 + + # Populate event term parameters + self.events.set_robot_to_grasp_pose.params["end_effector_body_name"] = self.end_effector_body_name + self.events.set_robot_to_grasp_pose.params["num_arm_joints"] = self.num_arm_joints + self.events.set_robot_to_grasp_pose.params["grasp_rot_offset"] = self.grasp_rot_offset + self.events.set_robot_to_grasp_pose.params["grasp_offset"] = self.grasp_offset + self.events.set_robot_to_grasp_pose.params["gripper_joint_setter_func"] = self.gripper_joint_setter_func + self.events.set_robot_to_grasp_pose.params["max_iterations"] = 150 + + # Populate termination term parameters + self.terminations.plug_dropped.params["end_effector_body_name"] = self.end_effector_body_name + self.terminations.plug_dropped.params["grasp_offset"] = self.grasp_offset + self.terminations.plug_dropped.params["grasp_rot_offset"] = self.grasp_rot_offset + + self.terminations.plug_orientation_exceeded.params["end_effector_body_name"] = self.end_effector_body_name + self.terminations.plug_orientation_exceeded.params["grasp_rot_offset"] = self.grasp_rot_offset + + +@configclass +class Rizon4sGravDisplayportInsertionEnvCfg_PLAY(Rizon4sGravDisplayportInsertionEnvCfg): + """Play configuration for Flexiv Rizon 4s DisplayPort insertion.""" + + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False + + +@configclass +class Rizon4sGravDisplayportInsertionNoJointVelEnvCfg(Rizon4sGravDisplayportInsertionEnvCfg): + """DisplayPort insertion without joint velocity in the policy observation. + + The critic retains joint velocity as privileged information for the value function. + """ + + def __post_init__(self): + super().__post_init__() + # Remove joint velocity from the actor observation group + self.observations.policy.joint_vel = None + + +@configclass +class Rizon4sGravDisplayportInsertionNoJointVelEnvCfg_PLAY(Rizon4sGravDisplayportInsertionNoJointVelEnvCfg): + """Play configuration for the no-joint-velocity joint-space variant.""" + + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/ros_inference_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/ros_inference_env_cfg.py new file mode 100644 index 000000000000..8ed1d7ca5efc --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/ros_inference_env_cfg.py @@ -0,0 +1,133 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +from isaaclab.assets import RigidObjectCfg +from isaaclab.utils.configclass import configclass + +from isaaclab_tasks.contrib.deploy.cable_insertion.displayport_insertion_env_cfg import ( + compute_plug_pose, + compute_socket_root, +) + +from .joint_pos_env_cfg import Rizon4sGravDisplayportInsertionEnvCfg + +# Deployment socket/plug poses for the physical DisplayPort insertion station. +_DEPLOY_GEOMETRY_POS = (0.476, 0.127, 0.07) +_DEPLOY_SOCKET_ROT = (0.5, 0.5, 0.5, -0.5) +_DEPLOY_PLUG_CLEARANCE_Z = 0.068 + +_DEPLOY_SOCKET_ROOT = compute_socket_root(_DEPLOY_GEOMETRY_POS, _DEPLOY_SOCKET_ROT) +_DEPLOY_PLUG_ROOT, _DEPLOY_PLUG_ROT = compute_plug_pose( + _DEPLOY_GEOMETRY_POS, + _DEPLOY_SOCKET_ROT, + z_clearance=_DEPLOY_PLUG_CLEARANCE_Z, +) + + +@configclass +class Rizon4sGravDisplayportInsertionROSInferenceEnvCfg(Rizon4sGravDisplayportInsertionEnvCfg): + """Configuration for ROS inference with Flexiv Rizon 4s and Grav gripper. + + This configuration: + - Exposes variables needed for ROS inference + - Overrides robot and plug/socket initial poses for fixed/deterministic setup + """ + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # Variables used by Isaac Manipulator for on robot inference + # These parameters allow the ROS inference node to validate environment configuration, + # perform checks during inference, and correctly interpret observations and actions. + self.obs_order = ["arm_dof_pos", "arm_dof_vel", "socket_pos", "socket_quat"] + self.policy_action_space = "joint" + # Use inherited joint names from parent's observation configuration + self.arm_joint_names = self.observations.policy.joint_pos.params["asset_cfg"].joint_names + # Use inherited num_arm_joints from parent + self.action_space = self.num_arm_joints + # State: 7 joint pos + 7 joint vel + 3 socket pos + 4 socket quat + 3 plug pos + 4 plug quat = 28 + self.state_space = 28 + # Observation: 7 joint pos + 7 joint vel + 3 socket pos + 4 socket quat = 21 + self.observation_space = 21 + + # Set joint_action_scale from the existing arm_action.scale + self.joint_action_scale = self.actions.arm_action.scale + + # Dynamically generate action_scale_joint_space based on action_space + self.action_scale_joint_space = [self.joint_action_scale] * self.action_space + + # Override robot initial pose for ROS inference (fixed pose, no randomization) + self.scene.robot.init_state.pos = (0.0, 0.0, 0.0) + self.scene.robot.init_state.rot = (0.0, 0.0, 0.0, 1.0) # Identity quaternion (x, y, z, w) + self.scene.robot.init_state.joint_pos = { + "joint1": math.radians(32.44), + "joint2": math.radians(-16.71), + "joint3": math.radians(-5.69), + "joint4": math.radians(128.38), + "joint5": math.radians(6.74), + "joint6": math.radians(55.95), + "joint7": math.radians(111.54), + } + + # Override socket/plug initial poses (fixed poses for ROS inference) + self.scene.dp_socket.init_state = RigidObjectCfg.InitialStateCfg( + pos=_DEPLOY_SOCKET_ROOT, + rot=_DEPLOY_SOCKET_ROT, + ) + + self.scene.dp_plug.init_state = RigidObjectCfg.InitialStateCfg( + pos=_DEPLOY_PLUG_ROOT, + rot=_DEPLOY_PLUG_ROT, + ) + + self.events.set_robot_to_grasp_pose.params["max_iterations"] = 150 + + # Fixed asset parameters for ROS inference - derived from configuration + # These parameters are used by the ROS inference node to validate the environment setup + # and apply appropriate noise models for robust real-world deployment. + self.fixed_asset_init_pos_center = list(_DEPLOY_GEOMETRY_POS) + + pose_range = self.events.randomize_socket_pose.params["pose_range"] + self.fixed_asset_init_pos_range = [ + pose_range["x"][1], # max value + pose_range["y"][1], # max value + pose_range["z"][1], # max value + ] + # Orientation in degrees for the vertical table-top Flexiv mount + self.fixed_asset_init_orn_deg = [0.0, 0.0, 0.0] + # Derive orientation range from parent's pose_range (radians to degrees) + self.fixed_asset_init_orn_deg_range = [ + math.degrees(pose_range["roll"][1]), # convert radians to degrees + math.degrees(pose_range["pitch"][1]), + math.degrees(pose_range["yaw"][1]), + ] + # Derive observation noise level from parent's socket_pos noise configuration + socket_pos_noise = self.observations.policy.socket_pos.noise.noise_cfg.n_max + self.fixed_asset_pos_obs_noise_level = [ + socket_pos_noise, + socket_pos_noise, + socket_pos_noise, + ] + + +@configclass +class Rizon4sGravDisplayportInsertionNoJointVelROSInferenceEnvCfg(Rizon4sGravDisplayportInsertionROSInferenceEnvCfg): + """ROS inference configuration without joint velocity in the policy observation.""" + + def __post_init__(self): + super().__post_init__() + + # Remove joint velocity from the actor observation group + self.observations.policy.joint_vel = None + + # Update Isaac Manipulator metadata for the velocity-free actor + self.obs_order = ["arm_dof_pos", "socket_pos", "socket_quat"] + # Observation: 7 joint pos + 3 socket pos + 4 socket quat = 14 + self.observation_space = 14 + # State (critic) is unchanged: 7 jpos + 7 jvel + 3 socket pos + 4 socket quat + 3 plug pos + 4 plug quat = 28 + self.state_space = 28 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/task_space_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/task_space_env_cfg.py new file mode 100644 index 000000000000..1f0ab5a0662d --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/task_space_env_cfg.py @@ -0,0 +1,447 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Task-space DisplayPort insertion environment for the Flexiv Rizon 4S + Grav gripper. + +Uses Operational Space Control (OSC) with 6D-rotation observations and an at-goal +reset curriculum. The end-effector pose is commanded as a relative Cartesian delta. +""" + +import math + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import ArticulationCfg, RigidObjectCfg +from isaaclab.controllers.operational_space_cfg import OperationalSpaceControllerCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.utils.configclass import configclass + +import isaaclab_tasks.contrib.deploy.mdp as mdp +import isaaclab_tasks.contrib.deploy.mdp.terminations as cable_terminations +from isaaclab_tasks.contrib.deploy.cable_insertion.displayport_insertion_env_cfg import ( + PLUG_GOAL_ROT, + PLUG_INSERTION_OFFSET, + SOCKET_INSERTION_OFFSET, + DisplayportInsertionEnvCfg, + resolve_robot_usd, +) + +from .joint_pos_env_cfg import ( + _PLUG_ROOT, + _PLUG_ROT, + _SOCKET_ROOT, + _SOCKET_ROT, + set_finger_joint_pos_grav, +) + +from isaaclab_assets import FLEXIV_RIZON4S_GRAV_GRIPPER_CFG # isort: skip + +# Rizon 4S arm joint names. +_ARM_JOINTS = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"] + +# OSC task-space gains. d_gain = 2 * sqrt(p_gain) * damping_ratio. +_STIFFNESS = (300.0, 300.0, 300.0, 30.0, 30.0, 30.0) +_DAMPING_RATIO_TRANS = 35.0 / (2.0 * math.sqrt(300.0)) +_DAMPING_RATIO_ROT = 1.1 / (2.0 * math.sqrt(30.0)) +_DAMPING_RATIO = ( + _DAMPING_RATIO_TRANS, + _DAMPING_RATIO_TRANS, + _DAMPING_RATIO_TRANS, + _DAMPING_RATIO_ROT, + _DAMPING_RATIO_ROT, + _DAMPING_RATIO_ROT, +) + +# Per-step Cartesian action scale applied to both position [m] and rotation [rad]. +_ACTION_SCALE = 0.025 + +# DisplayPort blade engagement along the insertion axis at the seated pose [m]. +_INSERTION_LENGTH = 0.011 + +# Gripper tool-center-point (TCP) offset from the flange body, in the flange's local +# frame [m]. The policy observes the TCP pose (where the plug is held), not the raw +# flange; the TCP shares the flange orientation, so only the position is offset. +_TCP_OFFSET = [0.0, 0.0, 0.2 - 0.0075] + + +## +# Observation configuration +## + + +@configclass +class TaskSpaceObservationsCfg: + """Task-space observations with 6D rotation representation.""" + + @configclass + class PolicyCfg(ObsGroup): + """Actor observations: EEF pose + socket keypoint frame (18 dims).""" + + eef_pos = ObsTerm( + func=mdp.eef_pos_w, + params={"asset_cfg": SceneEntityCfg("robot"), "body_name": "flange", "offset": _TCP_OFFSET}, + ) + eef_rot_6d = ObsTerm( + func=mdp.eef_rot_6d_w, + params={"asset_cfg": SceneEntityCfg("robot"), "body_name": "flange"}, + ) + socket_kp_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_socket"), "offset": SOCKET_INSERTION_OFFSET}, + ) + socket_kp_rot_6d = ObsTerm( + func=mdp.rigid_object_rot_6d_w, + params={"asset_cfg": SceneEntityCfg("dp_socket")}, + ) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + @configclass + class CriticCfg(ObsGroup): + """Critic observations: joint state + both keypoint frames (32 dims).""" + + joint_pos = ObsTerm( + func=mdp.joint_pos, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=_ARM_JOINTS)}, + ) + joint_vel = ObsTerm( + func=mdp.joint_vel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=_ARM_JOINTS)}, + ) + socket_kp_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_socket"), "offset": SOCKET_INSERTION_OFFSET}, + ) + socket_kp_rot_6d = ObsTerm( + func=mdp.rigid_object_rot_6d_w, + params={"asset_cfg": SceneEntityCfg("dp_socket")}, + ) + plug_kp_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_plug"), "offset": PLUG_INSERTION_OFFSET}, + ) + plug_kp_rot_6d = ObsTerm( + func=mdp.rigid_object_rot_6d_w, + params={"asset_cfg": SceneEntityCfg("dp_plug")}, + ) + + policy: PolicyCfg = PolicyCfg() + critic: CriticCfg = CriticCfg() + + +## +# Event configuration +## + + +@configclass +class TaskSpaceEventCfg: + """Events for the task-space DisplayPort insertion environment.""" + + plug_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("dp_plug", body_names=".*"), + "static_friction_range": (0.001, 0.001), + "dynamic_friction_range": (0.001, 0.001), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + socket_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("dp_socket", body_names=".*"), + "static_friction_range": (0.001, 0.001), + "dynamic_friction_range": (0.001, 0.001), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger.*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + + randomize_socket_pose = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={ + "pose_range": { + "x": [-0.01, 0.01], + "y": [-0.01, 0.01], + "z": [-0.02, 0.02], + "roll": [-math.radians(2.0), math.radians(2.0)], + "pitch": [-math.radians(2.0), math.radians(2.0)], + "yaw": [-math.radians(2.0), math.radians(2.0)], + }, + "velocity_range": {}, + "asset_cfg": SceneEntityCfg("dp_socket"), + }, + ) + + # At-goal reset curriculum: a fraction ``at_goal_prob`` of envs spawn the plug + # already inserted at a random depth with goal orientation; the rest start from a + # uniformly randomized approach pose. ``at_goal_prob`` anneals linearly from 0.8 to + # 0.0 over the first 500 iterations so the policy learns the full approach. + reset_plug_curriculum = EventTerm( + func=mdp.reset_plug_at_goal_curriculum, + mode="reset", + params={ + "plug_cfg": SceneEntityCfg("dp_plug"), + "socket_cfg": SceneEntityCfg("dp_socket"), + "at_goal_prob": 0.8, + "at_goal_prob_final": 0.0, + "anneal_start_iter": 0.0, + "anneal_end_iter": 500.0, + "num_steps_per_env": 512, + "insertion_axis": [1.0, 0.0, 0.0], + "insertion_length": _INSERTION_LENGTH, + "at_goal_depth_range": [0.0, 0.015], + "approach_depth_range": [0.02, 0.06], + "socket_insertion_offset": SOCKET_INSERTION_OFFSET, + "plug_insertion_offset": PLUG_INSERTION_OFFSET, + "goal_rot": list(PLUG_GOAL_ROT), + "normal_pose_range": { + "x": [-0.02, 0.02], + "y": [-0.02, 0.02], + "z": [0.0, 0.0], + }, + }, + ) + + set_robot_to_grasp_pose = EventTerm( + func=mdp.set_robot_to_object_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "pos_randomization_range": {"x": [-0.0, 0.0], "y": [-0.0, 0.0], "z": [-0.0, 0.0]}, + "target_object_name": "dp_plug", + "grasp_offset": [0.0, 0.0, 0.0], + }, + ) + + +## +# Terminations +## + + +@configclass +class TaskSpaceTerminationsCfg: + """Termination terms for the task-space DisplayPort insertion.""" + + time_out = DoneTerm(func=mdp.time_out, time_out=True) + + plug_dropped = DoneTerm( + func=cable_terminations.reset_when_plug_dropped, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "plug_asset_cfg": SceneEntityCfg("dp_plug"), + "distance_threshold": 0.15, + "end_effector_body_name": "link7", + "grasp_offset": [0.0, 0.0, 0.0], + "grasp_rot_offset": [0.0, 0.0, 0.0, 1.0], + }, + ) + + plug_orientation_exceeded = DoneTerm( + func=cable_terminations.reset_when_plug_orientation_exceeded, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "plug_asset_cfg": SceneEntityCfg("dp_plug"), + "roll_threshold_deg": 15.0, + "pitch_threshold_deg": 15.0, + "yaw_threshold_deg": 180.0, + "end_effector_body_name": "link7", + "grasp_rot_offset": [0.0, 0.0, 0.0, 1.0], + }, + ) + + +## +# Main environment configuration +## + + +@configclass +class Rizon4sTaskSpaceDisplayportInsertionEnvCfg(DisplayportInsertionEnvCfg): + """Task-space DisplayPort insertion with OSC control, 6D observations, and curriculum.""" + + def __post_init__(self): + super().__post_init__() + + # EEF / grasp settings (shared with the joint-space variant). + self.end_effector_body_name = "flange" + self.num_arm_joints = 7 + self.grasp_offset = [0.0025, 0.0, -0.1875] + self.grasp_rot_offset = [0.0, 0.0, 0.0, 1.0] + self.gripper_joint_setter_func = set_finger_joint_pos_grav + + self.plug_orientation_roll_threshold_deg = 15.0 + self.plug_orientation_pitch_threshold_deg = 15.0 + self.plug_orientation_yaw_threshold_deg = 180.0 + + # ----- Observations: task-space with 6D rotation ----- + self.observations = TaskSpaceObservationsCfg() + + # ----- Actions: Operational Space Controller ----- + # The Deploy OSC action wrapper behaves identically to the stock OSC action at + # train time and additionally exposes the scaled pose-delta contract used by the + # LEAPP export (see scripts/debug/export_taskspace_policy_leapp.py). + self.actions.arm_action = mdp.DeployOperationalSpaceControllerActionCfg( + asset_name="robot", + joint_names=_ARM_JOINTS, + body_name="flange", + controller_cfg=OperationalSpaceControllerCfg( + target_types=["pose_rel"], + impedance_mode="fixed", + inertial_dynamics_decoupling=False, + motion_stiffness_task=_STIFFNESS, + motion_damping_ratio_task=_DAMPING_RATIO, + nullspace_control="none", + ), + position_scale=_ACTION_SCALE, + orientation_scale=_ACTION_SCALE, + ) + + # ----- Events ----- + self.events = TaskSpaceEventCfg() + + # ----- Terminations ----- + self.terminations = TaskSpaceTerminationsCfg() + + self.terminations.plug_orientation_exceeded.params["roll_threshold_deg"] = ( + self.plug_orientation_roll_threshold_deg + ) + self.terminations.plug_orientation_exceeded.params["pitch_threshold_deg"] = ( + self.plug_orientation_pitch_threshold_deg + ) + self.terminations.plug_orientation_exceeded.params["yaw_threshold_deg"] = ( + self.plug_orientation_yaw_threshold_deg + ) + + # ----- Scene: robot ----- + # ``None`` keeps the robot's own default USD; ``DP_ROBOT_USD`` overrides it. + _robot_usd = resolve_robot_usd(None) + self.scene.robot = FLEXIV_RIZON4S_GRAV_GRIPPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=FLEXIV_RIZON4S_GRAV_GRIPPER_CFG.spawn.replace( + **({"usd_path": _robot_usd} if _robot_usd else {}), + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=3666.0, + enable_gyroscopic_forces=True, + solver_position_iteration_count=4, + solver_velocity_iteration_count=1, + max_contact_impulse=1e32, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=4, + solver_velocity_iteration_count=1, + ), + collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.005, rest_offset=0.0), + ), + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": math.radians(32.44), + "joint2": math.radians(-16.71), + "joint3": math.radians(-5.69), + "joint4": math.radians(128.38), + "joint5": math.radians(6.74), + "joint6": math.radians(55.95), + "joint7": math.radians(111.54), + }, + pos=(0.0, 0.0, 0.0), + rot=(0.0, 0.0, 0.0, 1.0), + ), + ) + + # OSC requires the arm joints to be pure torque-controlled. The stock Flexiv cfg + # gives the arm a stiff implicit position PD that would hold each joint at its + # reset target and override the OSC-computed efforts, so zero the arm PD gains + # (damping is provided by the OSC via ``motion_damping_ratio_task``). + for _arm_actuator in ("shoulder", "elbow", "wrist"): + self.scene.robot.actuators[_arm_actuator].stiffness = 0.0 + self.scene.robot.actuators[_arm_actuator].damping = 0.0 + + # Grav gripper actuators. + self.scene.robot.actuators["gripper_drive"] = ImplicitActuatorCfg( + joint_names_expr=["finger_joint"], + effort_limit_sim=2.0, + velocity_limit_sim=1.0, + stiffness=2e3, + damping=1e1, + ) + self.scene.robot.actuators["gripper_passive"] = ImplicitActuatorCfg( + joint_names_expr=[".*_knuckle_joint", ".*_outer_finger_joint"], + effort_limit_sim=1.0, + velocity_limit_sim=1.0, + stiffness=0.0, + damping=0.0, + ) + + # ----- Workspace poses ----- + self.scene.dp_socket.init_state = RigidObjectCfg.InitialStateCfg(pos=_SOCKET_ROOT, rot=_SOCKET_ROT) + self.scene.dp_plug.init_state = RigidObjectCfg.InitialStateCfg(pos=_PLUG_ROOT, rot=_PLUG_ROT) + + # Gripper widths for the DisplayPort plug. + self.hand_grasp_width = 0.3 + self.hand_hold_width = -0.05 + self.hand_close_width = -0.155 + + # Wire grasp-event params. + self.events.set_robot_to_grasp_pose.params["end_effector_body_name"] = self.end_effector_body_name + self.events.set_robot_to_grasp_pose.params["num_arm_joints"] = self.num_arm_joints + self.events.set_robot_to_grasp_pose.params["grasp_rot_offset"] = self.grasp_rot_offset + self.events.set_robot_to_grasp_pose.params["grasp_offset"] = self.grasp_offset + self.events.set_robot_to_grasp_pose.params["gripper_joint_setter_func"] = self.gripper_joint_setter_func + self.events.set_robot_to_grasp_pose.params["max_iterations"] = 150 + + # Wire termination params. + self.terminations.plug_dropped.params["end_effector_body_name"] = self.end_effector_body_name + self.terminations.plug_dropped.params["grasp_offset"] = self.grasp_offset + self.terminations.plug_dropped.params["grasp_rot_offset"] = self.grasp_rot_offset + + self.terminations.plug_orientation_exceeded.params["end_effector_body_name"] = self.end_effector_body_name + self.terminations.plug_orientation_exceeded.params["grasp_rot_offset"] = self.grasp_rot_offset + + # Use 1:1 linear:exponential keypoint-tracking reward weighting. + self.rewards.plug_socket_keypoint_tracking_exp.weight = abs(self.rewards.plug_socket_keypoint_tracking.weight) + + +@configclass +class Rizon4sTaskSpaceDisplayportInsertionEnvCfg_PLAY(Rizon4sTaskSpaceDisplayportInsertionEnvCfg): + """Play configuration for task-space DisplayPort insertion.""" + + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/task_space_ros_inference_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/task_space_ros_inference_env_cfg.py new file mode 100644 index 000000000000..9295d836027b --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/config/displayport_rizon_4s/task_space_ros_inference_env_cfg.py @@ -0,0 +1,113 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Task-space ROS inference configuration for DisplayPort insertion with the Flexiv Rizon 4S. + +Inherits from the task-space training config and adds the Isaac Manipulator metadata +fields plus a fixed, deterministic socket/plug setup for on-robot inference. +""" + +import math + +from isaaclab.assets import RigidObjectCfg +from isaaclab.utils.configclass import configclass + +from isaaclab_tasks.contrib.deploy.cable_insertion.displayport_insertion_env_cfg import ( + compute_plug_pose, + compute_socket_root, +) + +from .task_space_env_cfg import _ACTION_SCALE, Rizon4sTaskSpaceDisplayportInsertionEnvCfg + +# Deployment socket/plug station pose. CALIBRATE: re-measure for the real DisplayPort +# station (see ros_inference_env_cfg.py for the joint-space equivalent). +_HUBBLE_GEOMETRY_POS = (0.475, 0.125, 0.06) +_HUBBLE_SOCKET_ROT = (0.5, 0.5, 0.5, -0.5) +_HUBBLE_PLUG_CLEARANCE_Z = 0.068 + +_HUBBLE_SOCKET_ROOT = compute_socket_root(_HUBBLE_GEOMETRY_POS, _HUBBLE_SOCKET_ROT) +_HUBBLE_PLUG_ROOT, _HUBBLE_PLUG_ROT = compute_plug_pose( + _HUBBLE_GEOMETRY_POS, + _HUBBLE_SOCKET_ROT, + z_clearance=_HUBBLE_PLUG_CLEARANCE_Z, +) + + +@configclass +class Rizon4sTaskSpaceDisplayportInsertionROSInferenceEnvCfg(Rizon4sTaskSpaceDisplayportInsertionEnvCfg): + """Task-space ROS / Isaac Manipulator inference config. + + Exposes the observation/action metadata Isaac Manipulator needs for on-robot + inference with task-space (OSC) control and 6D-rotation observations, and pins the + plug and socket to a fixed deployment pose. + """ + + def __post_init__(self): + super().__post_init__() + + # Metadata consumed by Isaac Manipulator for on-robot inference. + self.obs_order = ["eef_pos", "eef_rot_6d", "socket_kp_pos", "socket_kp_rot_6d"] + self.policy_action_space = "task" + self.arm_joint_names = [ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ] + # 6-DOF task-space action (3 position + 3 axis-angle rotation). + self.action_space = 6 + # Critic: 7 jpos + 7 jvel + 3 socket_pos + 6 socket_rot6d + 3 plug_pos + 6 plug_rot6d = 32. + self.state_space = 32 + # Actor: 3 eef_pos + 6 eef_rot6d + 3 socket_pos + 6 socket_rot6d = 18. + self.observation_space = 18 + + self.action_scale = [_ACTION_SCALE] * self.action_space + + # Flexiv Rizon 4S vertical (table-top) mount. Home joint pose seeds the grasp IK. + self.scene.robot.init_state.pos = (0.0, 0.0, 0.0) + self.scene.robot.init_state.rot = (0.0, 0.0, 0.0, 1.0) + self.scene.robot.init_state.joint_pos = { + "joint1": math.radians(32.44), + "joint2": math.radians(-16.71), + "joint3": math.radians(-5.69), + "joint4": math.radians(128.38), + "joint5": math.radians(6.74), + "joint6": math.radians(55.95), + "joint7": math.radians(111.54), + } + + self.scene.dp_socket.init_state = RigidObjectCfg.InitialStateCfg( + pos=_HUBBLE_SOCKET_ROOT, + rot=_HUBBLE_SOCKET_ROT, + ) + self.scene.dp_plug.init_state = RigidObjectCfg.InitialStateCfg( + pos=_HUBBLE_PLUG_ROOT, + rot=_HUBBLE_PLUG_ROT, + ) + + self.events.set_robot_to_grasp_pose.params["max_iterations"] = 150 + + # Fixed asset parameters for ROS inference (geometry center, not USD root). + self.fixed_asset_init_pos_center = list(_HUBBLE_GEOMETRY_POS) + + pose_range = self.events.randomize_socket_pose.params["pose_range"] + self.fixed_asset_init_pos_range = [ + pose_range["x"][1], + pose_range["y"][1], + pose_range["z"][1], + ] + # CALIBRATE: euler orientation of the DP socket at the station. + self.fixed_asset_init_orn_deg = [0.0, 0.0, 0.0] + self.fixed_asset_init_orn_deg_range = [ + math.degrees(pose_range["roll"][1]), + math.degrees(pose_range["pitch"][1]), + math.degrees(pose_range["yaw"][1]), + ] + + # No socket-position observation noise in the production configuration. + self.fixed_asset_pos_obs_noise_level = [0.0, 0.0, 0.0] diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/Rizon4s-063459_with_Grav_calibrated_kinematics.usd b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/Rizon4s-063459_with_Grav_calibrated_kinematics.usd new file mode 100644 index 000000000000..c826d4ef0bac --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/Rizon4s-063459_with_Grav_calibrated_kinematics.usd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:739ffb1a48af6f2aa6a95c0062fd1a36c03cb6afefddd3c3a6fb0308d556ec1d +size 4177867 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/display_port_plug_fixed_sdf.usd b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/display_port_plug_fixed_sdf.usd new file mode 100644 index 000000000000..e3e65d95be93 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/display_port_plug_fixed_sdf.usd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9f1b7fc6f1ea314f9a43a5967836dcb3f35b27b163885b179efc45c7a1cd52d +size 1885641 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/display_port_socket_fixed_sdf_noprotrusions.usd b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/display_port_socket_fixed_sdf_noprotrusions.usd new file mode 100644 index 000000000000..da586695e9df --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/display_cable_insertion_assets/display_port_socket_fixed_sdf_noprotrusions.usd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06f2c4d67bda068d9d5f61e0c2e2c35e7812d4cc574521c1ce34d9b280fdca9a +size 1460990 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/displayport_insertion_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/displayport_insertion_env_cfg.py new file mode 100644 index 000000000000..1f40d95a13b2 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/displayport_insertion_env_cfg.py @@ -0,0 +1,395 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Base RL environment for inserting a DisplayPort plug into a socket. + +Targets the right-angle DisplayPort plug/socket assets in +``display_cable_insertion_assets``. Assets load with plain +:class:`~isaaclab.sim.UsdFileCfg` at ``scale=(1,1,1)``. +""" + +import os +from dataclasses import MISSING + +from isaaclab_physx.physics import PhysxCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import ActionTermCfg as ActionTerm +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sim.simulation_cfg import SimulationCfg +from isaaclab.utils.configclass import configclass +from isaaclab.utils.noise import UniformNoiseCfg + +import isaaclab_tasks.contrib.deploy.mdp as mdp +from isaaclab_tasks.contrib.deploy.mdp.noise_models import ResetSampledConstantNoiseModelCfg + +CABLE_INSERTION_DIR = os.path.dirname(os.path.abspath(__file__)) +DISPLAY_ASSETS_DIR = os.path.join(CABLE_INSERTION_DIR, "display_cable_insertion_assets") + + +#: Environment variable used to point the DisplayPort environments at a different robot USD. +DP_ROBOT_USD_ENV_VAR = "DP_ROBOT_USD" + + +def resolve_robot_usd(default_usd_path: str | None) -> str | None: + """Return the robot USD to spawn, honouring the ``DP_ROBOT_USD`` override. + + Individual Flexiv arms differ from the nominal CAD model, and joint-space policies + command joints directly, so a kinematic mismatch shows up as end-effector error at + sub-millimetre insertion clearances. Flexiv's ``flexiv_calibration`` workflow exports + a per-arm description; converting it to USD and exporting ``DP_ROBOT_USD`` selects it + without editing the task configuration. + + The value is passed through to the spawner untouched, so it accepts anything a + ``UsdFileCfg`` accepts: a local path, an ``omniverse://`` URL, or an HTTP(S) asset + URL. The spawner resolves and, for remote paths, downloads it, and raises + ``FileNotFoundError`` naming the path if it cannot be reached, so a typo surfaces + there rather than being validated (and wrongly rejected for remote URLs) here. + + Args: + default_usd_path: USD used when the override is unset. ``None`` keeps whatever the + robot's own spawn configuration already specifies. + + Returns: + The overriding path when ``DP_ROBOT_USD`` is set to a non-empty value, else + ``default_usd_path``. + """ + override = os.environ.get(DP_ROBOT_USD_ENV_VAR, "").strip() + return override or default_usd_path + + +def _quat_rotate_vec(q_xyzw, v): + """Apply quaternion rotation to a 3D vector.""" + qx, qy, qz, qw = q_xyzw + vx, vy, vz = v + tx = 2.0 * (qy * vz - qz * vy) + ty = 2.0 * (qz * vx - qx * vz) + tz = 2.0 * (qx * vy - qy * vx) + return ( + vx + qw * tx + qy * tz - qz * ty, + vy + qw * ty + qz * tx - qx * tz, + vz + qw * tz + qx * ty - qy * tx, + ) + + +def _quat_mul(q1_xyzw, q2_xyzw): + """Multiply two quaternions in (x, y, z, w) format.""" + x1, y1, z1, w1 = q1_xyzw + x2, y2, z2, w2 = q2_xyzw + return ( + w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, + w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, + w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, + ) + + +# Asset geometry offsets expressed in each body's local frame. +SOCKET_INSERTION_OFFSET = [0.0375, 0.0, 0.0] +PLUG_INSERTION_OFFSET = [0.0, 0.0, 0.0221] +# Plug orientation relative to socket at the mated pose (x, y, z, w). +PLUG_GOAL_ROT = [0.0, -0.70711, 0.0, 0.70711] +PLUG_GOAL_ROT_INV = [0.0, 0.70711, 0.0, 0.70711] + + +def compute_socket_root(geometry_pos, socket_rot): + """Compute socket USD root position from a desired insertion-geometry world position. + + Inverts :data:`SOCKET_INSERTION_OFFSET` (expressed in the socket's local + frame) for a given world-frame socket rotation. + """ + rotated = _quat_rotate_vec(socket_rot, SOCKET_INSERTION_OFFSET) + return ( + geometry_pos[0] - rotated[0], + geometry_pos[1] - rotated[1], + geometry_pos[2] - rotated[2], + ) + + +def compute_plug_pose(geometry_pos, socket_rot, z_clearance=0.0): + """Compute plug USD root position and world-frame rotation. + + Returns ``(plug_root_pos, plug_rot)`` such that the plug insertion point + lands at ``geometry_pos`` (plus optional vertical clearance) with the + correct goal orientation relative to the socket. + """ + plug_rot = _quat_mul(socket_rot, tuple(PLUG_GOAL_ROT)) + plug_offset_world = _quat_rotate_vec(plug_rot, PLUG_INSERTION_OFFSET) + plug_root = ( + geometry_pos[0] - plug_offset_world[0], + geometry_pos[1] - plug_offset_world[1], + geometry_pos[2] - plug_offset_world[2] + z_clearance, + ) + return plug_root, plug_rot + + +_INSERTION_POINT = [0.0, 0.0, 0.1875] +_DEFAULT_SOCKET_ROT = (0.5, 0.5, 0.5, -0.5) # opening faces +Z + +_SOCKET_ROOT_POS = compute_socket_root(_INSERTION_POINT, _DEFAULT_SOCKET_ROT) +_PLUG_ROOT_POS, _DEFAULT_PLUG_ROT = compute_plug_pose( + _INSERTION_POINT, + _DEFAULT_SOCKET_ROT, + z_clearance=0.033, +) + +## +# Asset Configurations +## + + +@configclass +class DisplayPortPlug(RigidObjectCfg): + """DisplayPort right-angle plug (held asset) — dynamic.""" + + prim_path = "{ENV_REGEX_NS}/DisplayPortPlug" + spawn = sim_utils.UsdFileCfg( + usd_path=os.path.join(DISPLAY_ASSETS_DIR, "display_port_plug_fixed_sdf.usd"), + scale=(1.0, 1.0, 1.0), + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + kinematic_enabled=False, + max_depenetration_velocity=0.5, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=3666.0, + enable_gyroscopic_forces=True, + solver_position_iteration_count=128, + solver_velocity_iteration_count=1, + max_contact_impulse=None, + ), + mass_props=sim_utils.MassPropertiesCfg(mass=0.03), + collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.00001, rest_offset=-0.00005), + ) + init_state = RigidObjectCfg.InitialStateCfg(pos=_PLUG_ROOT_POS, rot=_DEFAULT_PLUG_ROT) + + +@configclass +class DisplayPortSocket(RigidObjectCfg): + """DisplayPort socket (fixed asset) — kinematic.""" + + prim_path = "{ENV_REGEX_NS}/DisplayPortSocket" + spawn = sim_utils.UsdFileCfg( + usd_path=os.path.join(DISPLAY_ASSETS_DIR, "display_port_socket_fixed_sdf_noprotrusions.usd"), + scale=(1.0, 1.0, 1.0), + activate_contact_sensors=False, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + kinematic_enabled=True, + max_depenetration_velocity=5.0, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=3666.0, + enable_gyroscopic_forces=True, + solver_position_iteration_count=128, + solver_velocity_iteration_count=1, + max_contact_impulse=1e32, + ), + mass_props=sim_utils.MassPropertiesCfg(mass=None), + collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.0001, rest_offset=-0.0001), + ) + init_state = RigidObjectCfg.InitialStateCfg(pos=_SOCKET_ROOT_POS, rot=_DEFAULT_SOCKET_ROT) + + +## +# Environment configuration +## + + +@configclass +class DisplayportInsertionSceneCfg(InteractiveSceneCfg): + """Configuration for the DisplayPort insertion scene.""" + + replicate_physics = True + + ground = AssetBaseCfg( + prim_path="/World/ground", + spawn=sim_utils.GroundPlaneCfg(), + init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, -1.05)), + ) + + dp_plug = DisplayPortPlug() + dp_socket = DisplayPortSocket() + + robot: ArticulationCfg = MISSING + + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=2500.0), + ) + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + arm_action: ActionTerm = MISSING + gripper_action: ActionTerm | None = None + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + joint_pos = ObsTerm(func=mdp.joint_pos, params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}) + joint_vel = ObsTerm(func=mdp.joint_vel, params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}) + socket_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_socket"), "offset": SOCKET_INSERTION_OFFSET}, + noise=ResetSampledConstantNoiseModelCfg( + noise_cfg=UniformNoiseCfg(n_min=-0.01, n_max=0.01, operation="add") + ), + ) + socket_quat = ObsTerm( + func=mdp.rigid_object_quat_w, + params={"asset_cfg": SceneEntityCfg("dp_socket")}, + ) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class CriticCfg(ObsGroup): + """Observations for critic group.""" + + joint_pos = ObsTerm(func=mdp.joint_pos, params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}) + joint_vel = ObsTerm(func=mdp.joint_vel, params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}) + socket_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_socket"), "offset": SOCKET_INSERTION_OFFSET}, + ) + socket_quat = ObsTerm( + func=mdp.rigid_object_quat_w, + params={"asset_cfg": SceneEntityCfg("dp_socket")}, + ) + plug_pos = ObsTerm( + func=mdp.rigid_object_pos_w, + params={"asset_cfg": SceneEntityCfg("dp_plug"), "offset": PLUG_INSERTION_OFFSET}, + ) + plug_quat = ObsTerm( + func=mdp.rigid_object_quat_w, + params={"asset_cfg": SceneEntityCfg("dp_plug")}, + ) + + policy: PolicyCfg = PolicyCfg() + critic: CriticCfg = CriticCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + + plug_socket_keypoint_tracking = RewTerm( + func=mdp.keypoint_two_body_error, + weight=-1.5, + params={ + "asset_cfg_1": SceneEntityCfg("dp_socket"), + "asset_cfg_2": SceneEntityCfg("dp_plug"), + "offset_1": SOCKET_INSERTION_OFFSET, + "offset_2": PLUG_INSERTION_OFFSET, + "rot_offset_2": PLUG_GOAL_ROT_INV, + "keypoint_scale": 0.15, + }, + ) + + plug_socket_keypoint_tracking_exp = RewTerm( + func=mdp.keypoint_two_body_error_exp, + weight=3.0, + params={ + "asset_cfg_1": SceneEntityCfg("dp_socket"), + "asset_cfg_2": SceneEntityCfg("dp_plug"), + "offset_1": SOCKET_INSERTION_OFFSET, + "offset_2": PLUG_INSERTION_OFFSET, + "rot_offset_2": PLUG_GOAL_ROT_INV, + "kp_exp_coeffs": [(50, 0.0001), (300, 0.0001), (600, 0.0001), (2000, 0.0001)], + "kp_use_sum_of_exps": False, + "keypoint_scale": 0.15, + }, + ) + + action_rate = RewTerm(func=mdp.action_rate_l2, weight=-5.0e-06) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + time_out = DoneTerm(func=mdp.time_out, time_out=True) + + +@configclass +class DisplayportInsertionEnvCfg(ManagerBasedRLEnvCfg): + """Base configuration for DisplayPort plug/socket insertion.""" + + scene: DisplayportInsertionSceneCfg = DisplayportInsertionSceneCfg(num_envs=4096, env_spacing=2.5) + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventCfg = EventCfg() + + # Task-success logging (consumed by DisplayportInsertionEnv) + log_success_metrics: bool = True + success_socket_asset: str = "dp_socket" + success_plug_asset: str = "dp_plug" + success_pos_threshold: float = 0.003 + success_keypoint_scale: float = 0.15 + success_socket_offset: list = MISSING + success_plug_offset: list = MISSING + success_plug_goal_rot_inv: list = MISSING + sim: SimulationCfg = SimulationCfg( + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + restitution=0.0, + ), + physics=PhysxCfg( + bounce_threshold_velocity=0.2, + friction_offset_threshold=0.01, + friction_correlation_distance=0.00625, + gpu_collision_stack_size=2**30, + gpu_max_rigid_contact_count=2**23, + gpu_max_rigid_patch_count=2**23, + ), + ) + + def __post_init__(self): + """Post initialization.""" + self.episode_length_s = 6.66 + self.viewer.eye = (0.5, -1.8, 1.2) + self.viewer.lookat = (0.5, 0.0, 0.5) + self.decimation = 8 + self.sim.render_interval = self.decimation + self.sim.dt = 1.0 / 240.0 + + # Success mate-point geometry mirrors the keypoint-tracking reward + self.success_socket_offset = list(SOCKET_INSERTION_OFFSET) + self.success_plug_offset = list(PLUG_INSERTION_OFFSET) + self.success_plug_goal_rot_inv = list(PLUG_GOAL_ROT_INV) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/insertion_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/insertion_env.py new file mode 100644 index 000000000000..b1fc55cc5c60 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/cable_insertion/insertion_env.py @@ -0,0 +1,124 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Manager-based insertion env with task-success detection and logging. + +Adds success metrics to ``extras["log"]`` for RSL-RL without changing the MDP +observation, action, reward, or termination logic. +""" + +from __future__ import annotations + +import torch +import warp as wp + +from isaaclab.envs import ManagerBasedRLEnv +from isaaclab.utils.math import combine_frame_transforms + + +def _keypoint_offsets_6d(device: torch.device) -> torch.Tensor: + """Return the 7 unit keypoint offsets used by the keypoint reward.""" + corners = torch.tensor([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], device=device, dtype=torch.float32) + return torch.cat((corners, -corners[-3:]), dim=0) + + +class DisplayportInsertionEnv(ManagerBasedRLEnv): + """Manager-based RL env that logs insertion success metrics during training. + + The following scalars are added to ``extras["log"]``: + + - ``Metrics/success_rate``: fraction of envs within the success threshold + - ``Metrics/plug_socket_pos_error_m``: mean mate-point distance (m) + - ``Metrics/plug_socket_keypoint_dist_m``: mean keypoint distance (m) + - ``Metrics/terminal_success_rate``: success fraction at episode reset + """ + + def __init__(self, cfg, render_mode: str | None = None, **kwargs): + super().__init__(cfg, render_mode=render_mode, **kwargs) + + self._log_success_metrics: bool = bool(getattr(cfg, "log_success_metrics", True)) + self._success_socket_asset: str = getattr(cfg, "success_socket_asset", "dp_socket") + self._success_plug_asset: str = getattr(cfg, "success_plug_asset", "dp_plug") + self._success_pos_threshold: float = float(getattr(cfg, "success_pos_threshold", 0.003)) + self._success_keypoint_scale: float = float(getattr(cfg, "success_keypoint_scale", 0.15)) + + device = self.device + self._success_socket_offset = torch.tensor( + getattr(cfg, "success_socket_offset", [0.0, 0.0, 0.0]), device=device, dtype=torch.float32 + ) + self._success_plug_offset = torch.tensor( + getattr(cfg, "success_plug_offset", [0.0, 0.0, 0.0]), device=device, dtype=torch.float32 + ) + self._success_plug_goal_rot_inv = torch.tensor( + getattr(cfg, "success_plug_goal_rot_inv", [0.0, 0.0, 0.0, 1.0]), device=device, dtype=torch.float32 + ) + + self._success_identity_quat = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device, dtype=torch.float32).repeat( + self.num_envs, 1 + ) + self._success_kp_offsets = _keypoint_offsets_6d(device) * self._success_keypoint_scale + + def _compute_success(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Compute per-env success mask, mate-point distance, and keypoint distance.""" + socket = self.scene[self._success_socket_asset] + plug = self.scene[self._success_plug_asset] + + socket_pos = wp.to_torch(socket.data.root_pos_w) + socket_quat = wp.to_torch(socket.data.root_quat_w) + plug_pos = wp.to_torch(plug.data.root_pos_w) + plug_quat = wp.to_torch(plug.data.root_quat_w) + + n = self.num_envs + socket_off = self._success_socket_offset.unsqueeze(0).expand(n, -1) + plug_off = self._success_plug_offset.unsqueeze(0).expand(n, -1) + plug_goal_rot_inv = self._success_plug_goal_rot_inv.unsqueeze(0).expand(n, -1) + + # Mate reference frames (same construction as keypoint_two_body_error) + kp_pos_s, kp_quat_s = combine_frame_transforms(socket_pos, socket_quat, socket_off, self._success_identity_quat) + kp_pos_p, kp_quat_p = combine_frame_transforms(plug_pos, plug_quat, plug_off, plug_goal_rot_inv) + + pos_error = torch.linalg.norm(kp_pos_p - kp_pos_s, dim=-1) + + k = self._success_kp_offsets.shape[0] + offs_flat = self._success_kp_offsets.unsqueeze(0).expand(n, -1, -1).reshape(-1, 3) + ident_flat = self._success_identity_quat.unsqueeze(1).expand(-1, k, -1).reshape(-1, 4) + + kp_s = combine_frame_transforms( + kp_pos_s.unsqueeze(1).expand(-1, k, -1).reshape(-1, 3), + kp_quat_s.unsqueeze(1).expand(-1, k, -1).reshape(-1, 4), + offs_flat, + ident_flat, + )[0].reshape(n, k, 3) + kp_p = combine_frame_transforms( + kp_pos_p.unsqueeze(1).expand(-1, k, -1).reshape(-1, 3), + kp_quat_p.unsqueeze(1).expand(-1, k, -1).reshape(-1, 4), + offs_flat, + ident_flat, + )[0].reshape(n, k, 3) + keypoint_dist = torch.linalg.norm(kp_p - kp_s, dim=-1).mean(dim=-1) + + is_success = pos_error < self._success_pos_threshold + return is_success, pos_error, keypoint_dist + + def step(self, action: torch.Tensor): + obs_buf, reward_buf, terminated, time_outs, extras = super().step(action) + if getattr(self, "_log_success_metrics", False): + is_success, pos_error, keypoint_dist = self._compute_success() + log = self.extras.setdefault("log", {}) + log["Metrics/success_rate"] = is_success.float().mean() + log["Metrics/plug_socket_pos_error_m"] = pos_error.mean() + log["Metrics/plug_socket_keypoint_dist_m"] = keypoint_dist.mean() + return obs_buf, reward_buf, terminated, time_outs, self.extras + + def _reset_idx(self, env_ids): + terminal_success = None + if getattr(self, "_log_success_metrics", False): + is_success, _, _ = self._compute_success() + terminal_success = is_success[env_ids].float().mean() + + super()._reset_idx(env_ids) + + if terminal_success is not None: + self.extras["log"]["Metrics/terminal_success_rate"] = terminal_success diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/__init__.pyi index 2a200c888bc0..ce5340016c34 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/__init__.pyi @@ -4,28 +4,65 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "DeployRelativeJointPositionAction", + "DeployRelativeJointPositionActionCfg", + "DeployOperationalSpaceControllerAction", + "DeployOperationalSpaceControllerActionCfg", + "DeployDifferentialInverseKinematicsAction", + "DeployDifferentialInverseKinematicsActionCfg", "randomize_gear_type", "randomize_gears_and_base_pose", "set_robot_to_grasp_pose", + "set_robot_to_object_grasp_pose", + "reset_plug_at_goal_curriculum", "ResetSampledConstantNoiseModel", "ResetSampledConstantNoiseModelCfg", "gear_pos_w", "gear_quat_w", "gear_shaft_pos_w", "gear_shaft_quat_w", + "joint_pos", + "joint_vel", + "rigid_object_pos_w", + "rigid_object_quat_w", + "rigid_object_rot_6d_w", + "eef_pos_w", + "eef_rot_6d_w", "keypoint_command_error", "keypoint_command_error_exp", "keypoint_entity_error", "keypoint_entity_error_exp", "keypoint_ee_grasp_error", "keypoint_ee_grasp_error_exp", + "keypoint_two_body_error", + "keypoint_two_body_error_exp", "reset_when_gear_dropped", "reset_when_gear_orientation_exceeds_threshold", + "reset_when_plug_dropped", + "reset_when_plug_orientation_exceeded", ] -from .events import randomize_gear_type, randomize_gears_and_base_pose, set_robot_to_grasp_pose +from .events import ( + randomize_gear_type, + randomize_gears_and_base_pose, + set_robot_to_grasp_pose, + set_robot_to_object_grasp_pose, + reset_plug_at_goal_curriculum, +) from .noise_models import ResetSampledConstantNoiseModel, ResetSampledConstantNoiseModelCfg -from .observations import gear_pos_w, gear_quat_w, gear_shaft_pos_w, gear_shaft_quat_w +from .observations import ( + gear_pos_w, + gear_quat_w, + gear_shaft_pos_w, + gear_shaft_quat_w, + joint_pos, + joint_vel, + rigid_object_pos_w, + rigid_object_quat_w, + rigid_object_rot_6d_w, + eef_pos_w, + eef_rot_6d_w, +) from .rewards import ( keypoint_command_error, keypoint_command_error_exp, @@ -33,6 +70,23 @@ from .rewards import ( keypoint_entity_error_exp, keypoint_ee_grasp_error, keypoint_ee_grasp_error_exp, + keypoint_two_body_error, + keypoint_two_body_error_exp, +) +from .terminations import ( + reset_when_gear_dropped, + reset_when_gear_orientation_exceeds_threshold, + reset_when_plug_dropped, + reset_when_plug_orientation_exceeded, +) +from .actions import ( + DeployDifferentialInverseKinematicsAction, + DeployOperationalSpaceControllerAction, + DeployRelativeJointPositionAction, +) +from .actions_cfg import ( + DeployDifferentialInverseKinematicsActionCfg, + DeployOperationalSpaceControllerActionCfg, + DeployRelativeJointPositionActionCfg, ) -from .terminations import reset_when_gear_dropped, reset_when_gear_orientation_exceeds_threshold from isaaclab.envs.mdp import * diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/actions.py new file mode 100644 index 000000000000..c6a0c85d9c0f --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/actions.py @@ -0,0 +1,213 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Deploy-specific action terms for LEAPP export workflows.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp + +from isaaclab.envs.mdp.actions.joint_actions import RelativeJointPositionAction +from isaaclab.envs.mdp.actions.task_space_actions import ( + DifferentialInverseKinematicsAction, + OperationalSpaceControllerAction, +) +from isaaclab.utils.leapp.leapp_semantics import POSE6_ELEMENT_NAMES + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + from .actions_cfg import ( + DeployDifferentialInverseKinematicsActionCfg, + DeployOperationalSpaceControllerActionCfg, + DeployRelativeJointPositionActionCfg, + ) + + +_LEAPP_TRACED_OBSERVATION_INPUTS = "_leapp_traced_observation_inputs" +_LEAPP_CONSUMED_OBSERVATION_INPUTS = "_leapp_consumed_observation_inputs" + + +def _leapp_real_env(env): + real_env = object.__getattribute__(env, "_real_env") if type(env).__name__ == "_EnvProxy" else env + return real_env + + +def _tensor_data_to_torch(data): + """Return a torch tensor view for Isaac Lab data stored as torch or Warp-backed data.""" + return data.torch if hasattr(data, "torch") else wp.to_torch(data) + + +def _get_observation_term_from_buffer(env, group_name: str, term_name: str): + """Return a term slice from the cached observation buffer.""" + obs_buffer = getattr(env, "obs_buf", None) + if obs_buffer is None: + obs_buffer = getattr(getattr(env, "observation_manager", None), "_obs_buffer", None) + if not obs_buffer or group_name not in obs_buffer: + return None + + group_obs = obs_buffer[group_name] + if isinstance(group_obs, dict): + return group_obs.get(term_name) + + obs_manager = getattr(env, "observation_manager", None) + if obs_manager is None: + return None + + term_names = obs_manager.active_terms.get(group_name, []) + if term_name not in term_names: + return None + + term_index = term_names.index(term_name) + term_dims = obs_manager.group_obs_term_dim[group_name] + concat_dim = obs_manager._group_obs_concatenate_dim[group_name] + if concat_dim > 0: + concat_dim -= 1 + + start = sum(dim[concat_dim] for dim in term_dims[:term_index]) + length = term_dims[term_index][concat_dim] + return group_obs.narrow(dim=concat_dim, start=start, length=length) + + +def _pop_leapp_traced_observation_input(env, name: str, *, group_name: str, term_name: str): + """Consume one traced observation tensor for the current LEAPP action trace.""" + real_env = _leapp_real_env(env) + consumed_inputs = getattr(real_env, _LEAPP_CONSUMED_OBSERVATION_INPUTS, None) + if consumed_inputs is None: + consumed_inputs = set() + setattr(real_env, _LEAPP_CONSUMED_OBSERVATION_INPUTS, consumed_inputs) + + if name in consumed_inputs: + return None + + traced_inputs = getattr(real_env, _LEAPP_TRACED_OBSERVATION_INPUTS, {}) + traced_tensor = traced_inputs.pop(name, None) + if traced_tensor is None: + traced_tensor = _get_observation_term_from_buffer(real_env, group_name, term_name) + + if traced_tensor is not None: + consumed_inputs.add(name) + return traced_tensor + + +def _is_leapp_observation_input_consumed(env, name: str) -> bool: + real_env = _leapp_real_env(env) + return name in getattr(real_env, _LEAPP_CONSUMED_OBSERVATION_INPUTS, set()) + + +def _pose_rel_action_extra(*, position_scale: float, orientation_scale: float, target_types: Sequence[str]): + return { + "isaaclab_connection": "action:arm_action:pose_rel", + "target_types": list(target_types), + "position_scale": float(position_scale), + "orientation_scale": float(orientation_scale), + } + + +def _diffik_pose_rel_action_extra(scale): + scale_tensor = torch.as_tensor(scale, dtype=torch.float32).flatten() + if scale_tensor.numel() == 1: + scale_values = [float(scale_tensor.item())] * 6 + else: + scale_values = [float(value) for value in scale_tensor.tolist()] + + extra = { + "isaaclab_connection": "action:arm_action:pose_rel", + "target_types": ["pose_rel"], + "scale": scale_values, + } + if len(scale_values) >= 6: + if len({round(value, 12) for value in scale_values[:3]}) == 1: + extra["position_scale"] = scale_values[0] + if len({round(value, 12) for value in scale_values[3:6]}) == 1: + extra["orientation_scale"] = scale_values[3] + return extra + + +class DeployRelativeJointPositionAction(RelativeJointPositionAction): + """Relative joint action that reuses traced current joint observations during LEAPP export.""" + + def __init__(self, cfg: DeployRelativeJointPositionActionCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + + def apply_actions(self): + asset = self._asset + if type(asset).__name__ == "_ArticulationWriteProxy": + observation_input_name = f"{self.cfg.asset_name}_joint_pos" + current_joint_pos = _pop_leapp_traced_observation_input( + self._env, + observation_input_name, + group_name="policy", + term_name="joint_pos", + ) + if current_joint_pos is None: + if not _is_leapp_observation_input_consumed(self._env, observation_input_name): + raise RuntimeError( + "DeployRelativeJointPositionAction requires the traced " + f"'{self.cfg.asset_name}_joint_pos' observation during LEAPP export." + ) + real_asset = object.__getattribute__(asset, "_real_asset") + current_joint_pos = _tensor_data_to_torch(real_asset.data.joint_pos)[:, self._joint_ids] + else: + current_joint_pos = _tensor_data_to_torch(asset.data.joint_pos)[:, self._joint_ids] + + current_actions = self.processed_actions + current_joint_pos + self._asset.set_joint_position_target_index(target=current_actions, joint_ids=self._joint_ids) + + +class DeployOperationalSpaceControllerAction(OperationalSpaceControllerAction): + """OSC action that exports scaled pose_rel deltas during LEAPP export.""" + + def __init__(self, cfg: DeployOperationalSpaceControllerActionCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._leapp_export_processed_actions = True + self._leapp_processed_action_element_names = list(POSE6_ELEMENT_NAMES) + self._leapp_processed_action_kind = None + self._leapp_processed_action_extra = _pose_rel_action_extra( + position_scale=cfg.position_scale, + orientation_scale=cfg.orientation_scale, + target_types=cfg.controller_cfg.target_types, + ) + + def apply_actions(self): + asset = self._asset + if type(asset).__name__ != "_ArticulationWriteProxy": + super().apply_actions() + return + + real_asset = object.__getattribute__(asset, "_real_asset") + self._asset = real_asset + try: + super().apply_actions() + finally: + self._asset = asset + + +class DeployDifferentialInverseKinematicsAction(DifferentialInverseKinematicsAction): + """DiffIK action that exports scaled relative TCP pose deltas during LEAPP export.""" + + def __init__(self, cfg: DeployDifferentialInverseKinematicsActionCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._leapp_export_processed_actions = True + self._leapp_processed_action_element_names = list(POSE6_ELEMENT_NAMES) + self._leapp_processed_action_kind = None + self._leapp_processed_action_extra = _diffik_pose_rel_action_extra(cfg.scale) + + def apply_actions(self): + asset = self._asset + if type(asset).__name__ != "_ArticulationWriteProxy": + super().apply_actions() + return + + real_asset = object.__getattribute__(asset, "_real_asset") + self._asset = real_asset + try: + super().apply_actions() + finally: + self._asset = asset diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/actions_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/actions_cfg.py new file mode 100644 index 000000000000..24381d5c7497 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/actions_cfg.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Deploy-specific action configuration classes.""" + +from __future__ import annotations + +from isaaclab.envs.mdp.actions.actions_cfg import ( + DifferentialInverseKinematicsActionCfg, + OperationalSpaceControllerActionCfg, + RelativeJointPositionActionCfg, +) +from isaaclab.utils.configclass import configclass + + +@configclass +class DeployRelativeJointPositionActionCfg(RelativeJointPositionActionCfg): + """Configuration for deploy relative joint actions with explicit LEAPP current-joint input.""" + + class_type: type | str = "isaaclab_tasks.contrib.deploy.mdp.actions:DeployRelativeJointPositionAction" + + +@configclass +class DeployOperationalSpaceControllerActionCfg(OperationalSpaceControllerActionCfg): + """OSC action that exports scaled pose deltas for LEAPP instead of joint efforts.""" + + class_type: type | str = "isaaclab_tasks.contrib.deploy.mdp.actions:DeployOperationalSpaceControllerAction" + + +@configclass +class DeployDifferentialInverseKinematicsActionCfg(DifferentialInverseKinematicsActionCfg): + """DiffIK action that exports scaled pose deltas for LEAPP instead of joint targets.""" + + class_type: type | str = "isaaclab_tasks.contrib.deploy.mdp.actions:DeployDifferentialInverseKinematicsAction" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/events.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/events.py index 8dde6b5c5105..6e6f72618b4b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/events.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Class-based event terms specific to the gear assembly manipulation environments.""" +"""Class-based event terms for manipulation deployment environments.""" from __future__ import annotations @@ -11,6 +11,7 @@ from typing import TYPE_CHECKING import torch +import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import EventTermCfg, ManagerTermBase, SceneEntityCfg @@ -503,3 +504,450 @@ def __call__( velocities = velocities_by_asset[asset_name] asset.write_root_pose_to_sim_index(root_pose=torch.cat([positions, orientations], dim=-1), env_ids=env_ids) asset.write_root_velocity_to_sim_index(root_velocity=velocities, env_ids=env_ids) + + +class set_robot_to_object_grasp_pose(ManagerTermBase): + """Set robot to a grasp pose over a single named target object using IK. + + Generic single-object counterpart of :class:`set_robot_to_grasp_pose` (which + is keyed on the gear-type manager). This term targets a single named + :class:`~isaaclab.assets.RigidObject` with a fixed grasp offset, suitable + for cable insertion and other single-object manipulation tasks. + + Args: + target_object_name: Name of the rigid object in the scene to grasp. + end_effector_body_name: Name of the end-effector body on the robot. + num_arm_joints: Number of arm joints (the remaining joints are + assumed to be gripper/finger joints). + grasp_offset: Position offset ``[x, y, z]`` [m] applied in the + (rotated) object frame to define the IK target. Defaults to zero. + grasp_rot_offset: Quaternion offset ``(x, y, z, w)`` applied to the + object orientation to define the IK target. + gripper_joint_setter_func: Callable used to set finger joint positions + for the configured grasp/close widths. + robot_asset_cfg: Robot asset configuration. Defaults to + ``SceneEntityCfg("robot")``. + pos_threshold: IK position-error tolerance [m]. + rot_threshold: IK rotation-error tolerance [rad]. + max_iterations: Maximum IK iterations per env reset. + pos_randomization_range: Optional dict with keys ``"x"``, ``"y"``, + ``"z"`` mapping to ``(low, high)`` tuples [m] for per-reset + randomization of the grasp offset. + """ + + def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + + self.robot_asset_cfg: SceneEntityCfg = cfg.params.get("robot_asset_cfg", SceneEntityCfg("robot")) + self.robot_asset: Articulation = env.scene[self.robot_asset_cfg.name] + + for required in ( + "end_effector_body_name", + "num_arm_joints", + "grasp_rot_offset", + "gripper_joint_setter_func", + "target_object_name", + ): + if required not in cfg.params: + raise ValueError(f"'{required}' is required in set_robot_to_object_grasp_pose configuration.") + + self.end_effector_body_name: str = cfg.params["end_effector_body_name"] + self.num_arm_joints: int = cfg.params["num_arm_joints"] + self.gripper_joint_setter_func = cfg.params["gripper_joint_setter_func"] + self.target_object_name: str = cfg.params["target_object_name"] + + grasp_offset = cfg.params.get("grasp_offset", [0.0, 0.0, 0.0]) + self.grasp_offset_tensor = torch.tensor(grasp_offset, device=env.device, dtype=torch.float32) + + grasp_rot_offset = cfg.params["grasp_rot_offset"] + self.grasp_rot_offset_tensor = ( + torch.tensor(grasp_rot_offset, device=env.device, dtype=torch.float32).unsqueeze(0).repeat(env.num_envs, 1) + ) + + self.grasp_offsets_buffer = torch.zeros(env.num_envs, 3, device=env.device, dtype=torch.float32) + + self.hand_grasp_width = env.cfg.hand_grasp_width + self.hand_close_width = env.cfg.hand_close_width + # hand_hold_width: joint angle where fingers just touch the held object + # surface. Written as the physical STATE so there is no mesh overlap. + # Falls back to hand_close_width when not set (original behaviour). + self.hand_hold_width = getattr(env.cfg, "hand_hold_width", self.hand_close_width) + + eef_indices, _ = self.robot_asset.find_bodies([self.end_effector_body_name]) + if len(eef_indices) == 0: + raise ValueError(f"End effector body '{self.end_effector_body_name}' not found in robot") + self.eef_idx = eef_indices[0] + self.jacobi_body_idx = self.eef_idx - 1 + + all_joints, _ = self.robot_asset.find_joints([".*"]) + self.all_joints = all_joints + self.finger_joints = all_joints[self.num_arm_joints :] + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor, + robot_asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + pos_threshold: float = 1e-6, + rot_threshold: float = 1e-6, + max_iterations: int = 50, + pos_randomization_range: dict | None = None, + target_object_name: str | None = None, + grasp_offset: list | None = None, + end_effector_body_name: str | None = None, + num_arm_joints: int | None = None, + grasp_rot_offset: list | None = None, + gripper_joint_setter_func: callable | None = None, + ): + num_reset_envs = len(env_ids) + grasp_offsets = self.grasp_offsets_buffer[:num_reset_envs] + grasp_rot_offset_tensor = self.grasp_rot_offset_tensor[env_ids] + + # One-shot debug log to confirm the event fires and report IK convergence. + # Remove or guard once the grasp wiring is verified. + debug_first_call = not getattr(self, "_debug_printed", False) + if debug_first_call: + self._debug_printed = True + target_object_dbg: RigidObject = env.scene[self.target_object_name] + init_obj_pos = wp.to_torch(target_object_dbg.data.root_link_pos_w)[env_ids][0].tolist() + init_obj_quat = wp.to_torch(target_object_dbg.data.root_link_quat_w)[env_ids][0].tolist() + init_eef_pos = wp.to_torch(self.robot_asset.data.body_pos_w)[env_ids, self.eef_idx][0].tolist() + init_eef_quat = wp.to_torch(self.robot_asset.data.body_quat_w)[env_ids, self.eef_idx][0].tolist() + print( + f"[GRASP-DBG] set_robot_to_object_grasp_pose fired:" + f" target={self.target_object_name!r} num_reset_envs={num_reset_envs}" + f" eef_idx={self.eef_idx} num_arm_joints={self.num_arm_joints}\n" + f" grasp_offset={self.grasp_offset_tensor.tolist()}" + f" grasp_rot_offset(xyzw)={self.grasp_rot_offset_tensor[0].tolist()}" + f" hand_close_width={self.hand_close_width}\n" + f" init_obj_pos_w={init_obj_pos}" + f" init_obj_quat(xyzw)={init_obj_quat}\n" + f" init_eef_pos_w={init_eef_pos}" + f" init_eef_quat(xyzw)={init_eef_quat}" + ) + + last_pos_err = None + last_rot_err = None + converged_at = -1 + last_target_pos = None + last_target_quat = None + + for _iter in range(max_iterations): + joint_pos = wp.to_torch(self.robot_asset.data.joint_pos)[env_ids].clone() + joint_vel = wp.to_torch(self.robot_asset.data.joint_vel)[env_ids].clone() + + target_object: RigidObject = env.scene[self.target_object_name] + grasp_object_pos_world = wp.to_torch(target_object.data.root_link_pos_w)[env_ids] + grasp_object_quat = wp.to_torch(target_object.data.root_link_quat_w)[env_ids] + + grasp_object_quat = math_utils.quat_mul(grasp_object_quat, grasp_rot_offset_tensor) + + grasp_offsets[:] = self.grasp_offset_tensor + + if pos_randomization_range is not None: + pos_keys = ["x", "y", "z"] + range_list_pos = [pos_randomization_range.get(key, (0.0, 0.0)) for key in pos_keys] + ranges_pos = torch.tensor(range_list_pos, device=env.device) + rand_pos_offsets = math_utils.sample_uniform( + ranges_pos[:, 0], ranges_pos[:, 1], (len(env_ids), 3), device=env.device + ) + grasp_offsets = grasp_offsets + rand_pos_offsets + + grasp_object_pos_world = grasp_object_pos_world + math_utils.quat_apply(grasp_object_quat, grasp_offsets) + + eef_pos = wp.to_torch(self.robot_asset.data.body_pos_w)[env_ids, self.eef_idx] + eef_quat = wp.to_torch(self.robot_asset.data.body_quat_w)[env_ids, self.eef_idx] + + last_target_pos = grasp_object_pos_world.clone() + last_target_quat = grasp_object_quat.clone() + + pos_error, axis_angle_error = fc.get_pose_error( + fingertip_midpoint_pos=eef_pos, + fingertip_midpoint_quat=eef_quat, + ctrl_target_fingertip_midpoint_pos=grasp_object_pos_world, + ctrl_target_fingertip_midpoint_quat=grasp_object_quat, + jacobian_type="geometric", + rot_error_type="axis_angle", + ) + delta_hand_pose = torch.cat((pos_error, axis_angle_error), dim=-1) + + pos_error_norm = torch.linalg.norm(pos_error, dim=-1) + rot_error_norm = torch.linalg.norm(axis_angle_error, dim=-1) + last_pos_err = pos_error_norm + last_rot_err = rot_error_norm + + if torch.all(pos_error_norm < pos_threshold) and torch.all(rot_error_norm < rot_threshold): + converged_at = _iter + break + + jacobians = wp.to_torch(self.robot_asset.root_view.get_jacobians()).clone() + jacobian = jacobians[env_ids, self.jacobi_body_idx, :, :] + + delta_dof_pos = fc._get_delta_dof_pos( + delta_pose=delta_hand_pose, + ik_method="dls", + jacobian=jacobian, + device=env.device, + ) + + joint_pos = joint_pos + delta_dof_pos + + joint_pos_limits = wp.to_torch(self.robot_asset.data.joint_pos_limits)[env_ids, : self.num_arm_joints, :] + joint_min = joint_pos_limits[:, :, 0] + joint_max = joint_pos_limits[:, :, 1] + joint_range = joint_max - joint_min + + arm_joint_pos = joint_pos[:, : self.num_arm_joints] + arm_joint_pos = torch.where( + joint_range > 0, + joint_min + torch.remainder(arm_joint_pos - joint_min, joint_range), + arm_joint_pos, + ) + joint_pos[:, : self.num_arm_joints] = arm_joint_pos + + joint_vel = torch.zeros_like(joint_pos) + + self.robot_asset.set_joint_position_target_index(target=joint_pos, env_ids=env_ids) + self.robot_asset.set_joint_velocity_target_index(target=joint_vel, env_ids=env_ids) + self.robot_asset.write_joint_position_to_sim_index(position=joint_pos, env_ids=env_ids) + self.robot_asset.write_joint_velocity_to_sim_index(velocity=joint_vel, env_ids=env_ids) + + # Snap the held object to the achieved gripper pose so the gripper actually + # holds it after closing. Without this, any IK residual error or USD + # geometry offset leaves the object outside the finger gap and gravity drops + # Snap the held object to the achieved gripper pose so the gripper + # actually holds it after closing. + held_object = env.scene[self.target_object_name] + achieved_hand_pos = wp.to_torch(self.robot_asset.data.body_pos_w)[env_ids, self.eef_idx].clone() + achieved_hand_quat = wp.to_torch(self.robot_asset.data.body_quat_w)[env_ids, self.eef_idx].clone() + + # Object orientation: inverse of grasp_rot_offset applied to the achieved hand quat, + # because IK target was ``hand = obj * grasp_rot_offset`` => ``obj = hand * grasp_rot_offset^{-1}``. + inv_grasp_rot_offset = math_utils.quat_conjugate(grasp_rot_offset_tensor) + target_obj_quat = math_utils.quat_mul(achieved_hand_quat, inv_grasp_rot_offset) + + # Object position: IK target was + # ``hand_pos = obj_pos + R(obj * grasp_rot_offset) * grasp_offset`` + # = ``obj_pos + R(hand_quat) * grasp_offset`` + # so ``obj_pos = hand_pos - R(hand_quat) * grasp_offset``. + grasp_offset_in_world = math_utils.quat_apply(achieved_hand_quat, grasp_offsets) + target_obj_pos = achieved_hand_pos - grasp_offset_in_world + + new_root_pose = torch.cat([target_obj_pos, target_obj_quat], dim=-1) + zero_velocity = torch.zeros((len(env_ids), 6), device=env.device, dtype=torch.float32) + held_object.write_root_pose_to_sim(new_root_pose, env_ids=env_ids) + held_object.write_root_velocity_to_sim(zero_velocity, env_ids=env_ids) + + if debug_first_call: + pos_err_max = float(last_pos_err.max().item()) if last_pos_err is not None else float("nan") + rot_err_max = float(last_rot_err.max().item()) if last_rot_err is not None else float("nan") + tgt_pos0 = target_obj_pos[0].tolist() + tgt_quat0 = target_obj_quat[0].tolist() + eef_pos0 = achieved_hand_pos[0].tolist() + eef_quat0 = achieved_hand_quat[0].tolist() + ik_target_pos0 = last_target_pos[0].tolist() if last_target_pos is not None else None + ik_target_quat0 = last_target_quat[0].tolist() if last_target_quat is not None else None + print( + f"[GRASP-DBG] IK done: converged_at_iter={converged_at}\n" + f" max_pos_err={pos_err_max:.6f} m, max_rot_err={rot_err_max:.6f} rad\n" + f" IK_target_pos_w[0]={ik_target_pos0}\n" + f" IK_target_quat(xyzw)[0]={ik_target_quat0}\n" + f" achieved_eef_pos_w[0]={eef_pos0}\n" + f" achieved_eef_quat(xyzw)[0]={eef_quat0}\n" + f" snapped_obj_pos_w[0]={tgt_pos0}\n" + f" snapped_obj_quat(xyzw)[0]={tgt_quat0}" + ) + + joint_vel = torch.zeros_like(wp.to_torch(self.robot_asset.data.joint_vel)[env_ids]) + joint_pos = wp.to_torch(self.robot_asset.data.joint_pos)[env_ids].clone() + + # Write gripper STATE at ``hand_hold_width`` (fingers just touching the + # plug, no mesh overlap) and set the TARGET to ``hand_close_width`` + # (fully closed) so the actuator drive squeezes around the plug. + self.gripper_joint_setter_func(joint_pos, list(range(num_reset_envs)), self.finger_joints, self.hand_hold_width) + self.robot_asset.write_joint_position_to_sim_index(position=joint_pos, env_ids=env_ids) + self.robot_asset.write_joint_velocity_to_sim_index(velocity=joint_vel, env_ids=env_ids) + + self.gripper_joint_setter_func( + joint_pos, list(range(num_reset_envs)), self.finger_joints, self.hand_close_width + ) + self.robot_asset.set_joint_position_target_index(target=joint_pos, joint_ids=self.all_joints, env_ids=env_ids) + + +class reset_plug_at_goal_curriculum(ManagerTermBase): + """Reset a fraction of plugs at the goal position (at-goal curriculum). + + For each reset batch, a fraction ``at_goal_prob`` of environments have the + plug placed along the insertion axis at a random depth (from socket opening + to full insertion) with goal orientation. The remaining environments get + normal pose randomization. + + This replaces the simple ``reset_root_state_uniform`` for the plug when + curriculum-based training is desired. + """ + + def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + + self.plug: RigidObject = env.scene[cfg.params["plug_cfg"].name] + self.socket: RigidObject = env.scene[cfg.params["socket_cfg"].name] + + self.at_goal_prob: float = cfg.params.get("at_goal_prob", 0.8) + + # Optional linear annealing of at_goal_prob over training iterations. + # `at_goal_prob` is the starting value; it decays linearly to + # `at_goal_prob_final` between `anneal_start_iter` and `anneal_end_iter`. + # Annealing is active only when both `at_goal_prob_final` and + # `anneal_end_iter` are provided (otherwise the probability is constant). + # Iterations are derived from the env step counter via `num_steps_per_env` + # (one RL iteration == `num_steps_per_env` env steps). + self.at_goal_prob_final = cfg.params.get("at_goal_prob_final", None) + self.anneal_start_iter: float = cfg.params.get("anneal_start_iter", 0.0) + self.anneal_end_iter = cfg.params.get("anneal_end_iter", None) + self.num_steps_per_env = cfg.params.get("num_steps_per_env", None) + + insertion_axis = cfg.params.get("insertion_axis", [0.0, 0.0, 1.0]) + self.insertion_axis = torch.tensor(insertion_axis, device=env.device, dtype=torch.float32) + self.insertion_axis = self.insertion_axis / self.insertion_axis.norm() + + self.insertion_length: float = cfg.params.get("insertion_length", 0.02) + + # Optional depth ranges along the insertion axis, measured from the socket keypoint origin. + self.at_goal_depth_range = cfg.params.get("at_goal_depth_range", None) + self.approach_depth_range = cfg.params.get("approach_depth_range", None) + + socket_offset = cfg.params.get("socket_insertion_offset", [0.0, 0.0, 0.0]) + self.socket_insertion_offset = torch.tensor(socket_offset, device=env.device, dtype=torch.float32) + + plug_offset = cfg.params.get("plug_insertion_offset", [0.0, 0.0, 0.0]) + self.plug_insertion_offset = torch.tensor(plug_offset, device=env.device, dtype=torch.float32) + + goal_rot = cfg.params.get("goal_rot", [0.0, 0.0, 0.0, 1.0]) + self.goal_rot = torch.tensor(goal_rot, device=env.device, dtype=torch.float32) + + self.normal_pose_range: dict = cfg.params.get("normal_pose_range", {}) + + self.identity_quat = torch.tensor([0.0, 0.0, 0.0, 1.0], device=env.device, dtype=torch.float32) + + def _current_at_goal_prob(self, env: ManagerBasedEnv) -> float: + """Return the at-goal probability for the current training progress. + + Linearly interpolates from ``at_goal_prob`` to ``at_goal_prob_final`` + between ``anneal_start_iter`` and ``anneal_end_iter``. Returns the + constant ``at_goal_prob`` when annealing is not fully configured. + """ + if self.at_goal_prob_final is None or self.anneal_end_iter is None or not self.num_steps_per_env: + return self.at_goal_prob + + current_iter = env.common_step_counter / float(self.num_steps_per_env) + span = max(float(self.anneal_end_iter) - float(self.anneal_start_iter), 1e-9) + frac = (current_iter - float(self.anneal_start_iter)) / span + frac = min(max(frac, 0.0), 1.0) + return self.at_goal_prob + frac * (float(self.at_goal_prob_final) - self.at_goal_prob) + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor, + plug_cfg: SceneEntityCfg | None = None, + socket_cfg: SceneEntityCfg | None = None, + at_goal_prob: float = 0.8, + insertion_axis: list | None = None, + insertion_length: float = 0.02, + socket_insertion_offset: list | None = None, + plug_insertion_offset: list | None = None, + goal_rot: list | None = None, + normal_pose_range: dict | None = None, + at_goal_prob_final: float | None = None, + anneal_start_iter: float = 0.0, + anneal_end_iter: float | None = None, + num_steps_per_env: int | None = None, + at_goal_depth_range: list | None = None, + approach_depth_range: list | None = None, + ): + num_envs = len(env_ids) + + socket_pos = wp.to_torch(self.socket.data.root_pos_w)[env_ids] + socket_quat = wp.to_torch(self.socket.data.root_quat_w)[env_ids] + + # Compute socket keypoint origin in world frame + socket_offset_batch = self.socket_insertion_offset.unsqueeze(0).expand(num_envs, -1) + id_quat_batch = self.identity_quat.unsqueeze(0).expand(num_envs, -1) + kp_origin_w, _ = math_utils.combine_frame_transforms( + socket_pos, + socket_quat, + socket_offset_batch, + id_quat_batch, + ) + + # Insertion axis in world frame (rotated by socket orientation) + insertion_axis_w = math_utils.quat_apply(socket_quat, self.insertion_axis.unsqueeze(0).expand(num_envs, -1)) + + # Goal plug orientation in world frame + goal_quat_w = math_utils.quat_mul(socket_quat, self.goal_rot.unsqueeze(0).expand(num_envs, -1)) + + # Plug keypoint offset rotated into world frame (for converting kp pos -> root pos) + plug_offset_batch = self.plug_insertion_offset.unsqueeze(0).expand(num_envs, -1) + plug_kp_in_world = math_utils.quat_apply(goal_quat_w, plug_offset_batch) + + # At-goal probability for the current training progress (may be annealed). + current_at_goal_prob = self._current_at_goal_prob(env) + + if self.approach_depth_range is None: + pose_range = self.normal_pose_range + rand_pos = torch.zeros(num_envs, 3, device=env.device) + for i, key in enumerate(["x", "y", "z"]): + rng = pose_range.get(key, [0.0, 0.0]) + rand_pos[:, i] = torch.empty(num_envs, device=env.device).uniform_(rng[0], rng[1]) + + default_plug_pos = ( + wp.to_torch(self.plug.data.default_root_state)[env_ids, :3] + env.scene.env_origins[env_ids] + ) + normal_plug_pos = default_plug_pos + rand_pos + normal_plug_quat = wp.to_torch(self.plug.data.default_root_state)[env_ids, 3:7] + + plug_pos = normal_plug_pos.clone() + plug_quat = normal_plug_quat.clone() + + if current_at_goal_prob > 0.0 and num_envs > 0: + at_goal_mask = torch.rand(num_envs, device=env.device) < current_at_goal_prob + at_goal_local = at_goal_mask.nonzero(as_tuple=False).squeeze(-1) + num_at_goal = int(at_goal_local.numel()) + if num_at_goal > 0: + depth_rand = torch.rand(num_at_goal, 1, device=env.device) + goal_kp_pos = ( + kp_origin_w[at_goal_local] + + depth_rand * insertion_axis_w[at_goal_local] * self.insertion_length + ) + + plug_pos[at_goal_local] = goal_kp_pos - plug_kp_in_world[at_goal_local] + plug_quat[at_goal_local] = goal_quat_w[at_goal_local] + else: + at_goal_mask = torch.rand(num_envs, device=env.device) < current_at_goal_prob + + at_goal_range = ( + self.at_goal_depth_range if self.at_goal_depth_range is not None else [0.0, self.insertion_length] + ) + depth_at_goal = torch.empty(num_envs, device=env.device).uniform_( + float(at_goal_range[0]), float(at_goal_range[1]) + ) + depth_approach = torch.empty(num_envs, device=env.device).uniform_( + float(self.approach_depth_range[0]), float(self.approach_depth_range[1]) + ) + depth = torch.where(at_goal_mask, depth_at_goal, depth_approach) + + pose_range = self.normal_pose_range + rand_pos = torch.zeros(num_envs, 3, device=env.device) + for i, key in enumerate(["x", "y", "z"]): + rng = pose_range.get(key, [0.0, 0.0]) + rand_pos[:, i] = torch.empty(num_envs, device=env.device).uniform_(rng[0], rng[1]) + rand_pos[at_goal_mask] = 0.0 + + goal_kp_pos = kp_origin_w + depth.unsqueeze(-1) * insertion_axis_w + plug_pos = goal_kp_pos - plug_kp_in_world + rand_pos + plug_quat = goal_quat_w.clone() + + new_root_pose = torch.cat([plug_pos, plug_quat], dim=-1) + zero_vel = torch.zeros(num_envs, 6, device=env.device, dtype=torch.float32) + self.plug.write_root_pose_to_sim(new_root_pose, env_ids=env_ids) + self.plug.write_root_velocity_to_sim(zero_vel, env_ids=env_ids) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/observations.py index ac12d8b22f7f..1100c2365e5d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/observations.py @@ -3,19 +3,20 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Class-based observation terms for the gear assembly manipulation environment.""" +"""Class-based observation terms for manipulation deployment environments.""" from __future__ import annotations from typing import TYPE_CHECKING import torch +import warp as wp from isaaclab.managers import ManagerTermBase, ObservationTermCfg, SceneEntityCfg -from isaaclab.utils.math import combine_frame_transforms +from isaaclab.utils.math import combine_frame_transforms, matrix_from_quat, quat_unique if TYPE_CHECKING: - from isaaclab.assets import RigidObject + from isaaclab.assets import Articulation, RigidObject from isaaclab.envs import ManagerBasedRLEnv from .events import randomize_gear_type @@ -338,3 +339,230 @@ def __call__(self, env: ManagerBasedRLEnv) -> torch.Tensor: gear_positive_quat[w_negative] = -gear_quat[w_negative] return gear_positive_quat + + +class rigid_object_pos_w(ManagerTermBase): + """Rigid object position in the environment frame, with optional local-frame offset. + + Generic observation term that returns the position of any + :class:`~isaaclab.assets.RigidObject` in the environment frame. An optional + 3D offset can be applied in the object's local frame before subtracting the + environment origin. + + Args: + asset_cfg: The asset configuration. Required. + offset: A 3D offset ``[x, y, z]`` [m] applied in the object's local frame. + Defaults to ``[0, 0, 0]``. + + Returns: + Object position tensor in the environment frame, shape ``[num_envs, 3]`` [m]. + """ + + def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + + if "asset_cfg" not in cfg.params: + raise ValueError("'asset_cfg' parameter is required in rigid_object_pos_w configuration.") + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.asset: RigidObject = env.scene[self.asset_cfg.name] + + offset = cfg.params.get("offset", [0.0, 0.0, 0.0]) + self.offset_tensor = torch.tensor(offset, device=env.device, dtype=torch.float32) + + self.identity_quat = ( + torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=env.device, dtype=torch.float32) + .repeat(env.num_envs, 1) + .contiguous() + ) + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg | None = None, + offset: list | None = None, + ) -> torch.Tensor: + obj_pos = wp.to_torch(self.asset.data.root_pos_w) + obj_quat = wp.to_torch(self.asset.data.root_quat_w) + + if torch.any(self.offset_tensor != 0): + offset_repeated = self.offset_tensor.unsqueeze(0).repeat(env.num_envs, 1) + obj_pos, _ = combine_frame_transforms(obj_pos, obj_quat, offset_repeated, self.identity_quat) + + return obj_pos - env.scene.env_origins + + +class rigid_object_quat_w(ManagerTermBase): + """Rigid object orientation in the world frame. + + Generic observation term that returns the orientation of any + :class:`~isaaclab.assets.RigidObject`. The quaternion is canonicalized so + that the ``w`` component is positive, reducing observation variation seen + by the policy. + + Args: + asset_cfg: The asset configuration. Required. + + Returns: + Object orientation as a quaternion ``(x, y, z, w)``, shape ``[num_envs, 4]``. + """ + + def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + + if "asset_cfg" not in cfg.params: + raise ValueError("'asset_cfg' parameter is required in rigid_object_quat_w configuration.") + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.asset: RigidObject = env.scene[self.asset_cfg.name] + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg | None = None, + ) -> torch.Tensor: + obj_quat = wp.to_torch(self.asset.data.root_quat_w) + + # This term is traced into the joint-space LEAPP export, so the + # canonicalisation has to stay ONNX-convertible. ``quat_unique`` is a + # branchless ``torch.where`` and exports as a plain elementwise select. + # Masked assignment is the obvious alternative but lowers to + # ``aten.masked_select``, whose output shape is data-dependent; the ONNX + # exporter has no conversion for it. + return quat_unique(obj_quat) + + +def _quat_to_rot_6d(quat: torch.Tensor) -> torch.Tensor: + """Convert quaternion (x, y, z, w) to 6D rotation (Zhou et al.). + + Takes the first two rows of the 3x3 rotation matrix and flattens + them into a 6-element vector per sample. + + Args: + quat: Quaternion tensor of shape ``(..., 4)`` in ``(x, y, z, w)`` format. + + Returns: + 6D rotation tensor of shape ``(..., 6)``. + """ + rot_mat = matrix_from_quat(quat) + batch_shape = rot_mat.shape[:-2] + return rot_mat[..., :2, :].clone().reshape(batch_shape + (6,)) + + +class rigid_object_rot_6d_w(ManagerTermBase): + """Rigid object 6D rotation in the world frame (Zhou et al.). + + Returns the first two rows of the 3x3 rotation matrix derived from + the object's root quaternion, giving a continuous 6D rotation + representation that avoids quaternion discontinuities. + + Args: + asset_cfg: The asset configuration. Required. + + Returns: + 6D rotation tensor, shape ``[num_envs, 6]``. + """ + + def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + if "asset_cfg" not in cfg.params: + raise ValueError("'asset_cfg' parameter is required in rigid_object_rot_6d_w configuration.") + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.asset: RigidObject = env.scene[self.asset_cfg.name] + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg | None = None, + ) -> torch.Tensor: + obj_quat = wp.to_torch(self.asset.data.root_quat_w) + return _quat_to_rot_6d(obj_quat) + + +class eef_pos_w(ManagerTermBase): + """End-effector position in the environment frame. + + Gets the position of a specified body on a robot articulation and + returns it relative to the environment origin. An optional 3D offset can be + applied in the body's local frame, e.g. to report the gripper tool-center + point (TCP) rather than the raw flange. + + Args: + asset_cfg: The robot articulation configuration. Required. + body_name: Name of the end-effector body link. Required. + offset: A 3D offset ``[x, y, z]`` [m] applied in the body's local frame. + Defaults to ``[0, 0, 0]``. + + Returns: + EEF position tensor, shape ``[num_envs, 3]`` [m]. + """ + + def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + if "asset_cfg" not in cfg.params: + raise ValueError("'asset_cfg' parameter is required in eef_pos_w configuration.") + if "body_name" not in cfg.params: + raise ValueError("'body_name' parameter is required in eef_pos_w configuration.") + + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.robot: Articulation = env.scene[self.asset_cfg.name] + self.body_name: str = cfg.params["body_name"] + self.body_idx = self.robot.find_bodies(self.body_name)[0][0] + + offset = cfg.params.get("offset", [0.0, 0.0, 0.0]) + self.offset_tensor = torch.tensor(offset, device=env.device, dtype=torch.float32) + self.identity_quat = ( + torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=env.device, dtype=torch.float32) + .repeat(env.num_envs, 1) + .contiguous() + ) + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg | None = None, + body_name: str | None = None, + offset: list | None = None, + ) -> torch.Tensor: + body_pos = wp.to_torch(self.robot.data.body_pos_w)[:, self.body_idx, :] + + if torch.any(self.offset_tensor != 0): + body_quat = wp.to_torch(self.robot.data.body_quat_w)[:, self.body_idx, :] + offset_repeated = self.offset_tensor.unsqueeze(0).repeat(env.num_envs, 1) + body_pos, _ = combine_frame_transforms(body_pos, body_quat, offset_repeated, self.identity_quat) + + return body_pos - env.scene.env_origins + + +class eef_rot_6d_w(ManagerTermBase): + """End-effector 6D rotation in the world frame (Zhou et al.). + + Gets the quaternion of a specified body on a robot articulation and + converts it to a continuous 6D rotation representation. + + Args: + asset_cfg: The robot articulation configuration. Required. + body_name: Name of the end-effector body link. Required. + + Returns: + 6D rotation tensor, shape ``[num_envs, 6]``. + """ + + def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + if "asset_cfg" not in cfg.params: + raise ValueError("'asset_cfg' parameter is required in eef_rot_6d_w configuration.") + if "body_name" not in cfg.params: + raise ValueError("'body_name' parameter is required in eef_rot_6d_w configuration.") + + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.robot: Articulation = env.scene[self.asset_cfg.name] + self.body_name: str = cfg.params["body_name"] + self.body_idx = self.robot.find_bodies(self.body_name)[0][0] + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg | None = None, + body_name: str | None = None, + ) -> torch.Tensor: + body_quat = wp.to_torch(self.robot.data.body_quat_w)[:, self.body_idx, :] + return _quat_to_rot_6d(body_quat) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/rewards.py index c776168e5b48..1c1d763a894a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/rewards.py @@ -568,6 +568,139 @@ def __call__( return scaled_reward +class keypoint_two_body_error(ManagerTermBase): + """Keypoint distance between two rigid objects with body-frame offsets. + + Computes keypoint frames for each object by applying a local-frame offset + (translation and optional rotation) to each object's root pose, then + measures the mean keypoint distance between the two frames. + + This handles USD assets whose root frame doesn't coincide with the + functionally relevant geometry (e.g., the GB300 socket whose root frame + is far from the actual insertion slot). + + Args: + asset_cfg_1: Scene entity config for the first rigid object (e.g., socket). + asset_cfg_2: Scene entity config for the second rigid object (e.g., plug). + offset_1: 3D offset ``[x, y, z]`` in asset 1's local frame to its keypoint + origin. Defaults to ``[0, 0, 0]``. + offset_2: 3D offset ``[x, y, z]`` in asset 2's local frame to its keypoint + origin. Defaults to ``[0, 0, 0]``. + rot_offset_2: Quaternion ``(x, y, z, w)`` rotation applied to asset 2's + keypoint frame orientation. Typically the inverse of the goal rotation + so that keypoint frames align at the insertion goal. Defaults to identity. + keypoint_scale: Scale factor for keypoint offsets. Defaults to 0.15. + """ + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + + self.asset_1 = env.scene[cfg.params["asset_cfg_1"].name] + self.asset_2 = env.scene[cfg.params["asset_cfg_2"].name] + + offset_1 = cfg.params.get("offset_1", [0.0, 0.0, 0.0]) + self.offset_1 = torch.tensor(offset_1, device=env.device, dtype=torch.float32) + + offset_2 = cfg.params.get("offset_2", [0.0, 0.0, 0.0]) + self.offset_2 = torch.tensor(offset_2, device=env.device, dtype=torch.float32) + + rot_offset_2 = cfg.params.get("rot_offset_2", [0.0, 0.0, 0.0, 1.0]) + self.rot_offset_2 = ( + torch.tensor(rot_offset_2, device=env.device, dtype=torch.float32).unsqueeze(0).repeat(env.num_envs, 1) + ) + + self.identity_quat = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=env.device, dtype=torch.float32).repeat( + env.num_envs, 1 + ) + + self.keypoint_computer = _compute_keypoint_distance(cfg, env) + + def _get_kp_frames(self, env: ManagerBasedRLEnv) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Compute keypoint frames for both assets with offsets applied.""" + import warp as wp + + pos_1 = wp.to_torch(self.asset_1.data.root_pos_w) + quat_1 = wp.to_torch(self.asset_1.data.root_quat_w) + pos_2 = wp.to_torch(self.asset_2.data.root_pos_w) + quat_2 = wp.to_torch(self.asset_2.data.root_quat_w) + + offset_1_batch = self.offset_1.unsqueeze(0).expand(env.num_envs, -1) + kp_pos_1, kp_quat_1 = combine_frame_transforms(pos_1, quat_1, offset_1_batch, self.identity_quat) + + offset_2_batch = self.offset_2.unsqueeze(0).expand(env.num_envs, -1) + kp_pos_2, kp_quat_2 = combine_frame_transforms(pos_2, quat_2, offset_2_batch, self.rot_offset_2) + + return kp_pos_1, kp_quat_1, kp_pos_2, kp_quat_2 + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg_1: SceneEntityCfg = SceneEntityCfg("factory_gear_base"), + asset_cfg_2: SceneEntityCfg = SceneEntityCfg("factory_gear_small"), + keypoint_scale: float = 0.15, + offset_1: list | None = None, + offset_2: list | None = None, + rot_offset_2: list | None = None, + ) -> torch.Tensor: + kp_pos_1, kp_quat_1, kp_pos_2, kp_quat_2 = self._get_kp_frames(env) + + keypoint_dist_sep = self.keypoint_computer.compute( + current_pos=kp_pos_1, + current_quat=kp_quat_1, + target_pos=kp_pos_2, + target_quat=kp_quat_2, + keypoint_scale=keypoint_scale, + ) + + return keypoint_dist_sep.mean(-1) + + +class keypoint_two_body_error_exp(keypoint_two_body_error): + """Exponential keypoint reward between two rigid objects with body-frame offsets. + + Same offset logic as :class:`keypoint_two_body_error`, but applies an + exponential reward transformation for sharper shaping near the goal. + """ + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg_1: SceneEntityCfg = SceneEntityCfg("factory_gear_base"), + asset_cfg_2: SceneEntityCfg = SceneEntityCfg("factory_gear_small"), + kp_exp_coeffs: list[tuple[float, float]] = [(1.0, 0.1)], + kp_use_sum_of_exps: bool = True, + keypoint_scale: float = 0.15, + offset_1: list | None = None, + offset_2: list | None = None, + rot_offset_2: list | None = None, + ) -> torch.Tensor: + kp_pos_1, kp_quat_1, kp_pos_2, kp_quat_2 = self._get_kp_frames(env) + + keypoint_dist_sep = self.keypoint_computer.compute( + current_pos=kp_pos_1, + current_quat=kp_quat_1, + target_pos=kp_pos_2, + target_quat=kp_quat_2, + keypoint_scale=keypoint_scale, + ) + + keypoint_reward_exp = torch.zeros_like(keypoint_dist_sep[:, 0]) + + if kp_use_sum_of_exps: + for coeff in kp_exp_coeffs: + a, b = coeff + keypoint_reward_exp += ( + 1.0 / (torch.exp(a * keypoint_dist_sep) + b + torch.exp(-a * keypoint_dist_sep)) + ).mean(-1) + else: + keypoint_dist = keypoint_dist_sep.mean(-1) + for coeff in kp_exp_coeffs: + a, b = coeff + keypoint_reward_exp += 1.0 / (torch.exp(a * keypoint_dist) + b + torch.exp(-a * keypoint_dist)) + + return keypoint_reward_exp + + ## # Helper functions and classes ## diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/terminations.py index 9f217c316372..983541859f24 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/deploy/mdp/terminations.py @@ -11,6 +11,7 @@ from typing import TYPE_CHECKING import torch +import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import ManagerTermBase, SceneEntityCfg, TerminationTermCfg @@ -18,7 +19,7 @@ logger = logging.getLogger(__name__) if TYPE_CHECKING: - from isaaclab.assets import Articulation + from isaaclab.assets import Articulation, RigidObject from isaaclab.envs import ManagerBasedEnv from .events import randomize_gear_type @@ -330,3 +331,184 @@ def __call__( ) return self.reset_flags + + +class reset_when_plug_dropped(ManagerTermBase): + """Check if a held plug/connector has fallen out of the gripper. + + Generic single-object counterpart of :class:`reset_when_gear_dropped`. + Computes the distance between the end effector and the plug's expected + grasp position (derived from the plug's pose and the grasp offset). + If the distance exceeds ``distance_threshold``, the environment is reset. + + Args: + robot_asset_cfg: Robot asset configuration. Defaults to + ``SceneEntityCfg("robot")``. + plug_asset_cfg: Plug rigid-object asset configuration. + distance_threshold: Distance [m] above which the plug is considered + dropped. + end_effector_body_name: End-effector body name on the robot. + grasp_offset: Position offset ``[x, y, z]`` [m] from the plug origin + to the expected grasp point in the (rotated) plug frame. + grasp_rot_offset: Quaternion offset ``(x, y, z, w)`` applied to the + plug orientation to define the grasp frame. + """ + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + + self.robot_asset_cfg: SceneEntityCfg = cfg.params.get("robot_asset_cfg", SceneEntityCfg("robot")) + self.robot_asset: Articulation = env.scene[self.robot_asset_cfg.name] + + if "plug_asset_cfg" not in cfg.params: + raise ValueError("'plug_asset_cfg' is required in reset_when_plug_dropped configuration.") + self.plug_asset_cfg: SceneEntityCfg = cfg.params["plug_asset_cfg"] + self.plug_asset: RigidObject = env.scene[self.plug_asset_cfg.name] + + for required in ("end_effector_body_name", "grasp_rot_offset", "grasp_offset"): + if required not in cfg.params: + raise ValueError(f"'{required}' is required in reset_when_plug_dropped configuration.") + + self.end_effector_body_name: str = cfg.params["end_effector_body_name"] + + grasp_offset = cfg.params["grasp_offset"] + self.grasp_offset_tensor = torch.tensor(grasp_offset, device=env.device, dtype=torch.float32) + + grasp_rot_offset = cfg.params["grasp_rot_offset"] + self.grasp_rot_offset_tensor = ( + torch.tensor(grasp_rot_offset, device=env.device, dtype=torch.float32).unsqueeze(0).repeat(env.num_envs, 1) + ) + + self.reset_flags = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + + eef_indices, _ = self.robot_asset.find_bodies([self.end_effector_body_name]) + if len(eef_indices) == 0: + logger.warning( + f"{self.end_effector_body_name} not found in robot body names. Cannot check plug drop condition." + ) + self.eef_idx = None + else: + self.eef_idx = eef_indices[0] + + def __call__( + self, + env: ManagerBasedEnv, + distance_threshold: float = 0.1, + robot_asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + plug_asset_cfg: SceneEntityCfg | None = None, + grasp_offset: list | None = None, + end_effector_body_name: str | None = None, + grasp_rot_offset: list | None = None, + ) -> torch.Tensor: + self.reset_flags.fill_(False) + + if self.eef_idx is None: + return self.reset_flags + + eef_pos_world = wp.to_torch(self.robot_asset.data.body_link_pos_w)[:, self.eef_idx] + + plug_pos_world = wp.to_torch(self.plug_asset.data.root_link_pos_w) + plug_quat_world = wp.to_torch(self.plug_asset.data.root_link_quat_w) + + plug_quat_world = math_utils.quat_mul(plug_quat_world, self.grasp_rot_offset_tensor) + + grasp_offset_batch = self.grasp_offset_tensor.unsqueeze(0).expand(plug_pos_world.shape[0], -1) + plug_grasp_pos_world = plug_pos_world + math_utils.quat_apply(plug_quat_world, grasp_offset_batch) + + distances = torch.linalg.norm(plug_grasp_pos_world - eef_pos_world, dim=-1) + self.reset_flags[:] = distances > distance_threshold + + return self.reset_flags + + +class reset_when_plug_orientation_exceeded(ManagerTermBase): + """Check if a held plug/connector has rotated too much relative to the end effector. + + Generic single-object counterpart of + :class:`reset_when_gear_orientation_exceeds_threshold`. Computes the + relative orientation between the plug (with grasp rotation offset + applied) and the end effector. If the roll, pitch, or yaw angles exceed + the configured thresholds, the environment is reset. + + Args: + robot_asset_cfg: Robot asset configuration. Defaults to + ``SceneEntityCfg("robot")``. + plug_asset_cfg: Plug rigid-object asset configuration. + roll_threshold_deg: Roll threshold [deg]. + pitch_threshold_deg: Pitch threshold [deg]. + yaw_threshold_deg: Yaw threshold [deg]. + end_effector_body_name: End-effector body name on the robot. + grasp_rot_offset: Quaternion offset ``(x, y, z, w)`` applied to the + plug orientation to define the grasp frame. + """ + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + + self.robot_asset_cfg: SceneEntityCfg = cfg.params.get("robot_asset_cfg", SceneEntityCfg("robot")) + self.robot_asset: Articulation = env.scene[self.robot_asset_cfg.name] + + if "plug_asset_cfg" not in cfg.params: + raise ValueError("'plug_asset_cfg' is required in reset_when_plug_orientation_exceeded configuration.") + self.plug_asset_cfg: SceneEntityCfg = cfg.params["plug_asset_cfg"] + self.plug_asset: RigidObject = env.scene[self.plug_asset_cfg.name] + + for required in ("end_effector_body_name", "grasp_rot_offset"): + if required not in cfg.params: + raise ValueError(f"'{required}' is required in reset_when_plug_orientation_exceeded configuration.") + + self.end_effector_body_name: str = cfg.params["end_effector_body_name"] + + grasp_rot_offset = cfg.params["grasp_rot_offset"] + self.grasp_rot_offset_tensor = ( + torch.tensor(grasp_rot_offset, device=env.device, dtype=torch.float32).unsqueeze(0).repeat(env.num_envs, 1) + ) + + self.reset_flags = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + + eef_indices, _ = self.robot_asset.find_bodies([self.end_effector_body_name]) + if len(eef_indices) == 0: + logger.warning( + f"{self.end_effector_body_name} not found in robot. Cannot check plug orientation condition." + ) + self.eef_idx = None + else: + self.eef_idx = eef_indices[0] + + def __call__( + self, + env: ManagerBasedEnv, + roll_threshold_deg: float = 30.0, + pitch_threshold_deg: float = 30.0, + yaw_threshold_deg: float = 180.0, + robot_asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + plug_asset_cfg: SceneEntityCfg | None = None, + end_effector_body_name: str | None = None, + grasp_rot_offset: list | None = None, + ) -> torch.Tensor: + self.reset_flags.fill_(False) + + if self.eef_idx is None: + return self.reset_flags + + roll_threshold_rad = torch.deg2rad(torch.tensor(roll_threshold_deg, device=env.device)) + pitch_threshold_rad = torch.deg2rad(torch.tensor(pitch_threshold_deg, device=env.device)) + yaw_threshold_rad = torch.deg2rad(torch.tensor(yaw_threshold_deg, device=env.device)) + + eef_quat_world = wp.to_torch(self.robot_asset.data.body_link_quat_w)[:, self.eef_idx] + + plug_quat_world = wp.to_torch(self.plug_asset.data.root_link_quat_w) + plug_quat_world = math_utils.quat_mul(plug_quat_world, self.grasp_rot_offset_tensor) + + eef_quat_inv = math_utils.quat_conjugate(eef_quat_world) + relative_quat = math_utils.quat_mul(plug_quat_world, eef_quat_inv) + + roll, pitch, yaw = math_utils.euler_xyz_from_quat(relative_quat) + + self.reset_flags[:] = ( + (torch.abs(roll) > roll_threshold_rad) + | (torch.abs(pitch) > pitch_threshold_rad) + | (torch.abs(yaw) > yaw_threshold_rad) + ) + + return self.reset_flags diff --git a/source/isaaclab_tasks/test/contrib/test_displayport_insertion_env_cfg.py b/source/isaaclab_tasks/test/contrib/test_displayport_insertion_env_cfg.py new file mode 100644 index 000000000000..a08f56293eb5 --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/test_displayport_insertion_env_cfg.py @@ -0,0 +1,69 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for DisplayPort cable-insertion environment configuration.""" + +import pytest + +from isaaclab_tasks.contrib.deploy.cable_insertion.config.displayport_rizon_4s.joint_pos_env_cfg import ( + Rizon4sGravDisplayportInsertionEnvCfg, + Rizon4sGravDisplayportInsertionNoJointVelEnvCfg, +) +from isaaclab_tasks.contrib.deploy.cable_insertion.config.displayport_rizon_4s.task_space_env_cfg import ( + Rizon4sTaskSpaceDisplayportInsertionEnvCfg, +) +from isaaclab_tasks.contrib.deploy.cable_insertion.displayport_insertion_env_cfg import DP_ROBOT_USD_ENV_VAR + +_CALIBRATED_USD_NAME = "Rizon4s-063459_with_Grav_calibrated_kinematics.usd" + +_JOINT_SPACE_CFGS = ( + Rizon4sGravDisplayportInsertionEnvCfg, + Rizon4sGravDisplayportInsertionNoJointVelEnvCfg, +) +_ALL_CFGS = _JOINT_SPACE_CFGS + (Rizon4sTaskSpaceDisplayportInsertionEnvCfg,) + + +@pytest.fixture(autouse=True) +def _clear_override(monkeypatch): + """Keep the ambient environment from deciding which robot the assertions see.""" + monkeypatch.delenv(DP_ROBOT_USD_ENV_VAR, raising=False) + + +@pytest.mark.parametrize("env_cfg_cls", _JOINT_SPACE_CFGS) +def test_joint_space_spawns_the_calibrated_robot_by_default(env_cfg_cls): + """Joint-space policies command joints directly, so they default to the calibrated arm.""" + assert env_cfg_cls().scene.robot.spawn.usd_path.endswith(_CALIBRATED_USD_NAME) + + +def test_task_space_keeps_the_stock_robot_by_default(): + """Task space never set a ``usd_path`` of its own, and the override must not change that.""" + usd_path = Rizon4sTaskSpaceDisplayportInsertionEnvCfg().scene.robot.spawn.usd_path + assert not usd_path.endswith(_CALIBRATED_USD_NAME) + + +@pytest.mark.parametrize("env_cfg_cls", _ALL_CFGS) +@pytest.mark.parametrize( + "override", + ( + "/tmp/calibrated_rizon4s.usd", + "omniverse://localhost/Library/calibrated_rizon4s.usd", + "https://example.invalid/assets/calibrated_rizon4s.usd", + ), + ids=("local", "omniverse", "http"), +) +def test_dp_robot_usd_selects_the_robot_in_both_control_spaces(monkeypatch, env_cfg_cls, override): + """A calibrated description may live on disk, on Nucleus, or behind a URL.""" + monkeypatch.setenv(DP_ROBOT_USD_ENV_VAR, override) + assert env_cfg_cls().scene.robot.spawn.usd_path == override + + +@pytest.mark.parametrize("env_cfg_cls", _ALL_CFGS) +@pytest.mark.parametrize("blank", ("", " "), ids=("empty", "whitespace")) +def test_blank_dp_robot_usd_falls_back_to_the_default(monkeypatch, env_cfg_cls, blank): + """An exported-but-empty variable must not blank out the robot.""" + monkeypatch.delenv(DP_ROBOT_USD_ENV_VAR, raising=False) + expected = env_cfg_cls().scene.robot.spawn.usd_path + monkeypatch.setenv(DP_ROBOT_USD_ENV_VAR, blank) + assert env_cfg_cls().scene.robot.spawn.usd_path == expected