Initial commit: Vision-Guided Robotic Pick-and-Place Simulation

This commit is contained in:
DnyaneshwariP13
2026-11-25 11:09:32 +05:30
commit 5295f0dcdc
966 changed files with 84693 additions and 0 deletions
+656
View File
@@ -0,0 +1,656 @@
# API Reference Manual
**Vision-Guided Robotic Pick-and-Place Simulation**
**NVIDIA Omniverse™ / Isaac Sim™ Ecosystem**
---
## 1. Package: `src.core`
### 1.1 `ConfigManager`
```python
class src.core.config.ConfigManager(config_dir: str | None = None)
```
Centralized YAML configuration loader ensuring zero hardcoded variables.
#### Properties
- **`simulation -> Dict[str, Any]`**: Returns physics, stepping, device, and lighting configurations.
- **`warehouse -> Dict[str, Any]`**: Returns source and destination rack dimensions and shelf parameters.
- **`objects -> Dict[str, Any]`**: Returns shape definitions, dimensional ranges, masses, and semantic labels.
- **`robot -> Dict[str, Any]`**: Returns Franka articulation paths, joint limits, gripper specs, and home poses.
- **`camera -> Dict[str, Any]`**: Returns RTX camera pose, intrinsics, resolution, and annotator keys.
- **`perception -> Dict[str, Any]`**: Returns depth filtering thresholds, coordinate conventions, and PCA flags.
- **`motion -> Dict[str, Any]`**: Returns cuMotion RMPflow parameters, obstacle clearances, and FSM frame budgets.
#### Methods
- **`reload_all() -> None`**: Reloads all configuration YAML files from disk. Raises `FileNotFoundError` if a file is missing.
---
### 1.2 `CoreSimulationManager`
```python
class src.core.simulation_manager.CoreSimulationManager(config: ConfigManager)
```
Lifecycle controller encapsulating Isaac Sim 6.2 `SimulationManager` and `app_utils`.
#### Methods
- **`setup_stage() -> None`**: Configures the PhysX physics pipeline (`SimulationManager.setup_simulation`), spawns the default `/World/GroundPlane`, and configures `/World/DomeLight`.
- **`play() -> None`**: Transitions the physics simulation timeline to playing state (`app_utils.play()`). Raises `RuntimeError` if called before `setup_stage()`.
- **`step(num_steps: int = 1) -> None`**: Advances the simulation and rendering loop by the specified number of frames via `omni.kit.app.get_app().update()`.
- **`warmup(num_frames: int | None = None) -> None`**: Advances the simulation for a designated number of frames (default: 60) for physics settlement and shader warm-up.
- **`stop() -> None`**: Halts the physics timeline (`app_utils.stop()`).
#### Properties
- **`is_running -> bool`**: Returns `True` if the physics timeline is currently active.
---
## 2. Package: `src.environment`
### 2.1 `StorageRackGenerator`
```python
class src.environment.rack_generator.StorageRackGenerator(stage: Usd.Stage)
```
Procedural builder synthesizing warehouse storage racks with collision-enabled shelves.
#### Methods
- **`create_rack(...) -> StorageRack`**: Builds corner pillars and horizontal shelves at configured heights, applies static PhysX collision APIs, and returns a `StorageRack` instance containing world surface bounds.
---
### 2.2 `ObjectGenerator`
```python
class src.environment.object_generator.ObjectGenerator(stage: Usd.Stage, seed: int | None = 42)
```
Procedural object spawner and domain randomizer.
#### Methods
- **`spawn_cube(...) -> ManipulatedObject`**: Spawns an equilateral cube with rigid body physics, mass, and `Semantics.SemanticsAPI`.
- **`spawn_cuboid(...) -> ManipulatedObject`**: Spawns an asymmetric box with custom dimensions, mass, and semantic annotations.
- **`spawn_cylinder(...) -> ManipulatedObject`**: Spawns an upright cylinder with mass and semantic annotations.
- **`spawn_randomized_objects_on_shelf(...) -> List[ManipulatedObject]`**: Performs 2D rejection sampling with boundary margins and inter-object clearance, randomizes yaw orientation via unit quaternions, and instantiates manipulation target objects.
- **`spawn_inventory_boxes_on_shelf(shelf_surface: Dict[str, Any], inventory_cfg: Dict[str, Any], num_boxes: int = 2, parent_prim_path: str = "/World/Inventory") -> List[ManipulatedObject]`**: Populates non-active storage shelves with diverse inventory boxes across small/medium/large cartons, flat parcels, blue totes, and canisters with physical mass and collision.
---
### 2.3 `WarehouseSceneBuilder`
```python
class src.environment.scene_builder.WarehouseSceneBuilder(stage: Usd.Stage, config_manager: ConfigManager)
```
High-level orchestrator for full warehouse scene composition and serialization.
#### Properties
- **`source_rack -> Optional[StorageRack]`**: Primary active picking storage rack.
- **`destination_rack -> Optional[StorageRack]`**: Primary active placement storage rack.
- **`racks -> Dict[str, StorageRack]`**: Dictionary containing all 6 instantiated warehouse racks across aisles and bays.
- **`spawned_objects -> List[ManipulatedObject]`**: List of active target manipulation objects on picking shelves.
- **`inventory_objects -> List[ManipulatedObject]`**: List of all procedural inventory boxes populated across warehouse storage shelves.
#### Methods
- **`build_warehouse_environment() -> Dict[str, Any]`**: Generates all multi-bay storage racks across aisles, spawns target manipulation objects on active picking shelf, and populates non-active shelves with assorted inventory boxes.
- **`save_scene(output_path: str) -> str`**: Serializes and exports the active USD stage to a standalone `.usda` or `.usd` file.
- **`get_ground_truth_object_poses() -> Dict[str, Dict[str, Any]]`**: Extracts real-time world coordinates and orientations from PhysX Fabric for all spawned objects.
---
---
## 3. Package: `src.robot`
### 3.1 `FrankaRobot`
```python
class src.robot.articulation.FrankaRobot(config_manager: ConfigManager, stage: Usd.Stage | None = None)
```
Encapsulates Franka Emika Panda manipulator (7 arm revolute DOFs + 2 parallel gripper prismatic DOFs). Handles USD referencing, PhysX Articulation binding, and joint target commands.
#### Methods
- **`spawn() -> str`**: Creates the robot prim on the USD stage and references the Franka Panda USD asset from the S3 Cloud CDN (`/Isaac/Robots_Multiphysics/FrankaRobotics/FrankaPanda/franka/franka.usda`). Returns the prim path (`/World/Franka`).
- **`initialize() -> None`**: Binds the Isaac Sim `Articulation` wrapper and end-effector link `RigidPrim` instances. Resolves joint index mappings.
- **`set_home_pose() -> None`**: Sets arm joints to configured home angles (`[0.0, -0.569, 0.0, -2.810, 0.0, 3.037, 0.741]` rad) and gripper fingers to open ($0.04\text{ m}$ each), synchronizing both instantaneous positions and PD position control targets.
- **`get_arm_joint_positions() -> np.ndarray`**: Returns the current 7 arm joint positions in radians (shape: `(7,)`).
- **`get_finger_positions() -> np.ndarray`**: Returns the current 2 finger joint positions in meters (shape: `(2,)`).
- **`get_all_dof_positions() -> np.ndarray`**: Returns all 9 degree-of-freedom positions (shape: `(9,)`).
- **`get_arm_joint_velocities() -> np.ndarray`**: Returns the 7 arm joint velocities in rad/s (shape: `(7,)`).
- **`get_all_dof_velocities() -> np.ndarray`**: Returns all 9 DOF velocities (shape: `(9,)`).
- **`get_dof_limits() -> Tuple[np.ndarray, np.ndarray]`**: Returns `(lower_limits, upper_limits)` for all 9 DOFs as float32 numpy arrays.
- **`get_arm_joint_limits() -> Tuple[np.ndarray, np.ndarray]`**: Returns `(lower_limits, upper_limits)` specifically for the 7 arm joints.
- **`set_arm_joint_positions(positions: np.ndarray) -> None`**: Directly sets instantaneous arm joint positions (kinematic reset / teleport), preserving finger positions.
- **`set_arm_joint_position_targets(targets: np.ndarray) -> None`**: Sets arm joint position targets for PD physics control, preserving finger position targets.
- **`set_finger_position_targets(left_target: float, right_target: float) -> None`**: Sets individual target positions for the left and right gripper fingers.
- **`set_dof_position_targets(targets: np.ndarray) -> None`**: Commands all 9 DOF position targets simultaneously.
- **`get_end_effector_pose() -> Tuple[np.ndarray, np.ndarray]`**: Queries the PhysX Fabric world pose of `panda_hand`. Returns `(position [x, y, z], quaternion [w, x, y, z])`.
- **`get_fingertip_poses() -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]`**: Returns world poses for `panda_leftfinger` and `panda_rightfinger`.
#### Properties
- **`prim_path -> str`**: USD stage path of the robot (default: `"/World/Franka"`).
- **`articulation -> Articulation`**: Direct handle to the underlying Isaac Sim `Articulation` object.
- **`arm_joint_names -> List[str]`**: List of 7 arm joint identifiers (`["panda_joint1", ..., "panda_joint7"]`).
- **`finger_joint_names -> List[str]`**: List of 2 finger joint identifiers (`["panda_finger_joint1", "panda_finger_joint2"]`).
- **`home_arm_positions -> np.ndarray`**: Array of 7 reference home angles in radians.
- **`is_initialized -> bool`**: Returns `True` if articulation and link bindings have been initialized.
---
### 3.2 `ParallelJawGripper`
```python
class src.robot.gripper.ParallelJawGripper(robot: FrankaRobot, config_manager: ConfigManager | None = None)
```
High-level controller and grasp state observer for Franka Hand parallel-jaw gripper.
#### Methods
- **`open(aperture: float | None = None) -> None`**: Commands gripper fingers to open to specified total aperture in meters (default: $0.08\text{ m}$).
- **`close(force: float | None = None) -> None`**: Commands fingers to close completely (target $0.0\text{ m}$). Object contact halts inward travel while sustaining grasp clamping effort.
- **`set_aperture(aperture: float) -> None`**: Commands symmetric finger displacement corresponding to specified aperture, clamped to $[0.0, 0.08]\text{ m}$.
- **`get_aperture() -> float`**: Returns current total distance between finger pads in meters.
- **`get_finger_positions() -> Tuple[float, float]`**: Returns individual prismatic joint positions `(left_finger_pos, right_finger_pos)`.
- **`is_grasped(min_aperture: float = 0.005, max_aperture: float = 0.075) -> bool`**: Returns `True` if aperture lies within valid object thickness interval, confirming object capture.
- **`is_open(tolerance: float = 0.005) -> bool`**: Returns `True` if aperture is within tolerance of maximum aperture ($0.08\text{ m}$).
- **`is_closed(tolerance: float = 0.005) -> bool`**: Returns `True` if aperture is within tolerance of fully closed ($0.00\text{ m}$).
---
### 3.3 `FrankaKinematics`
```python
class src.robot.kinematics.FrankaKinematics(robot_description_path: str | None = None, urdf_path: str | None = None)
```
High-performance kinematics solver wrapping NVIDIA's `LulaKinematicsSolver` for the 7-DOF Franka Panda.
#### Methods
- **`compute_forward_kinematics(joint_positions: np.ndarray, frame_name: str = "panda_hand") -> Tuple[np.ndarray, np.ndarray, np.ndarray]`**: Computes forward kinematics for the designated link. Returns `(position [x, y, z], rotation_matrix_3x3, quaternion [w, x, y, z])`.
- **`compute_inverse_kinematics(target_position: np.ndarray, target_orientation_quat: np.ndarray | None = None, warm_start: np.ndarray | None = None, position_tolerance: float = 0.001, orientation_tolerance: float = 0.01, frame_name: str = "panda_hand") -> Tuple[np.ndarray, bool]`**: Solves numerical inverse kinematics with position and orientation constraints. Returns `(joint_solution, success_flag)`.
- **`is_pose_reachable(target_position: np.ndarray, target_orientation_quat: np.ndarray | None = None, warm_start: np.ndarray | None = None) -> bool`**: Returns `True` if IK converges within allowable tolerances.
- **`get_joint_limits() -> Tuple[np.ndarray, np.ndarray]`**: Returns lower and upper joint angle limits for the 7 arm joints.
- **`get_cspace_joint_names() -> List[str]`**: Returns names of controlled configuration-space joints.
- **`get_all_frame_names() -> List[str]`**: Returns list of all defined coordinate frames on the Franka robot.
---
---
## 4. Package: `src.vision`
### 4.1 `CameraManager`
```python
class src.vision.camera_manager.CameraManager(config_manager: ConfigManager, stage: Usd.Stage | None = None)
```
Manages virtual RTX synthetic camera prims, Replicator render products, sensor annotator graphs (`rgb`, `distance_to_image_plane`, `semantic_segmentation`), and coordinate transformation matrices.
#### Methods
- **`capture_frame() -> Dict[str, Any]`**: Advances the Replicator graph by 1 step and collects fresh synchronized frames. Returns dictionary with `'rgb'`, `'depth'`, `'semantic_data'`, and `'id_to_labels'`.
- **`get_rgb() -> np.ndarray`**: Returns the latest 24-bit RGB frame as uint8 array of shape `(H, W, 3)`.
- **`get_depth() -> np.ndarray`**: Returns the latest metric depth map as float32 array of shape `(H, W)` in meters.
- **`get_semantic_segmentation() -> Tuple[np.ndarray, Dict[str, Dict[str, str]]]`**: Returns integer semantic label mask `(H, W)` and dictionary mapping integer ID strings to semantic class metadata.
- **`get_intrinsics_matrix() -> np.ndarray`**: Computes the analytical $3 \times 3$ pinhole camera matrix $K$ from focal length, aperture dimensions, and resolution.
- **`get_camera_world_pose() -> Tuple[np.ndarray, np.ndarray]`**: Returns world position `[x, y, z]` and orientation quaternion `[w, x, y, z]` of the camera prim.
- **`get_extrinsics_matrix(convention: str = "ROS") -> np.ndarray`**: Computes the $4 \times 4$ transformation matrix $T_{\text{world} \leftarrow \text{cam}}$. Supports `"ROS"` optical coordinates ($+X$ right, $+Y$ down, $+Z$ forward) and `"USD"` coordinates ($+X$ right, $+Y$ up, $-Z$ forward).
- **`pixel_to_optical_ray(u: float, v: float) -> np.ndarray`**: Unprojects 2D pixel coordinates $(u, v)$ to a normalized 3D optical ray unit direction vector.
- **`pixel_depth_to_world_point(u: float, v: float, depth_m: float) -> np.ndarray`**: Back-projects 2D pixel coordinates and metric depth into 3D world frame coordinates $[X, Y, Z]$.
---
### 4.2 `SyntheticObjectDetector`
```python
class src.vision.detector.SyntheticObjectDetector(camera_manager: CameraManager, min_pixel_threshold: int = 50)
```
Performs synthetic object detection and 2D/3D localization by querying semantic segmentation annotators and unprojecting metric depth buffers.
#### Methods
- **`detect(frame: Dict[str, Any] | None = None) -> List[DetectedObject2D]`**: Parses semantic segmentation and depth buffers, extracting 2D bounding boxes, centroids, segmented pixel areas, and back-projected 3D camera/world coordinates for all target objects (`object_cube`, `object_cuboid`, `object_cylinder`).
- **`get_detection_by_class(class_name: str) -> DetectedObject2D | None`**: Retrieves the highest-confidence detection matching the specified semantic class name or shape type.
- **`generate_semantic_overlay(rgb_image: np.ndarray, semantic_mask: np.ndarray, id_to_labels: Dict[str, Dict[str, str]], alpha: float = 0.45) -> np.ndarray`**: Alpha-blends class-specific color overlays onto the RGB frame for visualization.
---
### 4.3 `DetectedObject2D`
```python
@dataclass
class src.vision.detector.DetectedObject2D
```
Structured dataclass containing visual and geometric properties of a detected object:
- `name: str`: Unique detection identifier.
- `shape_type: str`: Object geometry (`'cube'`, `'cuboid'`, `'cylinder'`).
- `semantic_label: str`: Replicator semantic class name.
- `semantic_id: int`: Integer label ID in segmentation buffer.
- `pixel_count: int`: Number of segmented pixels.
- `bbox_2d: Tuple[int, int, int, int]`: 2D bounding box `(u_min, v_min, u_max, v_max)` in pixel coordinates.
- `centroid_2d: Tuple[float, float]`: Centroid coordinates `(u_center, v_center)` in pixel coordinates.
- `median_depth_m: float`: Median perpendicular metric depth across object mask in meters.
- `position_world: np.ndarray`: Unprojected 3D position `[X, Y, Z]` in world meter coordinates.
- `position_camera_opt: np.ndarray`: 3D position `[X, Y, Z]` in camera optical frame.
- `confidence: float`: Detection confidence score in $[0.0, 1.0]$.
---
### 4.4 `PoseEstimator6D`
```python
class src.vision.pose_estimator.PoseEstimator6D(camera_manager: CameraManager, shelf_height: float = 0.56)
```
High-precision 6D pose estimator for warehouse manipulation targets. Performs dense depth unprojection, statistical outlier rejection, camera-geometry viewing offset compensation, planar PCA covariance decomposition, Oriented Bounding Box (OBB) optimization, and rotational symmetry wrapping.
#### Methods
- **`extract_object_point_cloud(detection: DetectedObject2D, frame: Dict[str, Any], filter_outliers: bool = True) -> np.ndarray`**: Extracts dense 3D point cloud for a detected object in world coordinates. When `filter_outliers=True`, applies spatial rack boundary enforcement ($Z \ge \text{shelf\_height} - 0.02$) and $3.0\sigma$ Gaussian statistical outlier filtering. Returns array of shape `(N, 3)` in meters.
- **`estimate_object_pose(detection: DetectedObject2D, frame: Dict[str, Any]) -> EstimatedPose6D`**: Computes complete 6D pose for a single detected object:
- Surface centroid calculation.
- Camera viewing-ray horizontal offset compensation correcting front-surface visibility bias.
- Shelf contact plane constraint setting vertical centroid height.
- Planar PCA covariance decomposition on $C_{XY}$.
- Oriented Bounding Box (OBB) angular search over $[0, 90^\circ)$ with 98th-percentile span evaluation.
- Rotational symmetry wrapping (continuous for cylinders, $\pi$ for cuboids, $\pi/2$ for cubes).
- Quaternion construction $q = [\cos(\theta/2), 0, 0, \sin(\theta/2)]$.
- **`estimate_all_poses(detections: List[DetectedObject2D], frame: Dict[str, Any]) -> List[EstimatedPose6D]`**: Estimates 6D poses for all detected objects in the camera frame.
- **`compute_pose_errors(estimated: EstimatedPose6D, gt_position: np.ndarray, gt_yaw_deg: float) -> Dict[str, float]`**: Evaluates Euclidean 3D position error (mm), axis-wise errors $dX, dY, dZ$ (mm), and symmetry-aware yaw error (deg) against PhysX ground truth.
- **`project_world_to_image(pt_world: np.ndarray) -> Tuple[int, int] | None`**: Projects a 3D world coordinate point $[X, Y, Z]$ onto the 2D camera image plane $(u, v)$ using pinhole camera model and optical extrinsics.
- **`project_3d_axes_to_image(rgb_image: np.ndarray, poses: List[EstimatedPose6D], axis_length: float = 0.045, draw_boxes: bool = True) -> np.ndarray`**: Draws 3D coordinate frames ($X$-red, $Y$-green, $Z$-blue) and 3D oriented bounding box wireframes projected directly onto the RGB image.
---
### 4.5 `EstimatedPose6D`
```python
@dataclass
class src.vision.pose_estimator.EstimatedPose6D
```
Structured dataclass representing an estimated 6-DoF object pose:
- `name: str`: Unique object detection identifier.
- `shape_type: str`: Object geometric shape (`'cube'`, `'cuboid'`, `'cylinder'`).
- `semantic_label: str`: Semantic segmentation label.
- `semantic_id: int`: Integer class index.
- `position_world: np.ndarray`: Estimated 3D geometric center $[X, Y, Z]$ in meters (shape: `(3,)`).
- `orientation_quat: np.ndarray`: Normalized Hamilton quaternion $[w, x, y, z]$ (shape: `(4,)`).
- `yaw_deg: float`: Planar yaw orientation angle in degrees.
- `point_count: int`: Number of valid inlier 3D points.
- `dimensions: Dict[str, float]`: Estimated bounding box dimensions `{"length": l, "width": w, "height": h}` in meters.
- `confidence: float`: Estimation confidence score in $[0.0, 1.0]$.
- `covariance_2d: np.ndarray`: $2 \times 2$ horizontal planar covariance matrix $C_{XY}$.
- `eigenvalues: np.ndarray`: Planar eigenvalues $[\lambda_1, \lambda_2]$ in descending order.
- `surface_centroid: np.ndarray`: Raw unprojected surface point cloud centroid $[X, Y, Z]$ in meters.
---
## 5. Package: `src.motion`
### 5.1 `GraspPlanner`
```python
class src.motion.grasp_planner.GraspPlanner(
kinematics: FrankaKinematics,
max_gripper_aperture: float = 0.080,
standoff_distance: float = 0.100,
lift_distance: float = 0.120,
robot_base_pos: np.ndarray | None = None
)
```
Analytical parallel-jaw grasp planner tailored for warehouse rack manipulation. Synthesizes shape-specific grasp candidates based on estimated 6D object poses, validates parallel-jaw gripper aperture limits, solves numerical inverse kinematics via Lula, and computes multi-criteria quality rankings.
#### Constants
- `HAND_TO_FINGERTIP_OFFSET: float = 0.0584`: Distance from `panda_hand` frame origin to finger pad contact center along hand local $+Z$ (m).
- `DEFAULT_MAX_APERTURE: float = 0.080`: Maximum allowable finger opening stroke for Franka Hand (m).
- `FINGER_CLEARANCE_MARGIN: float = 0.010`: Clearance added to object grasping dimension for pre-grasp approach (m).
- `DEFAULT_STANDOFF_DIST: float = 0.100`: Pre-grasp standoff distance backed off along approach vector (m).
- `DEFAULT_LIFT_DIST: float = 0.120`: Post-grasp vertical lift height (m).
- `UPPER_SHELF_Z: float = 0.850`: Elevation of rack shelf plank above middle shelf (m).
#### Methods
- **`construct_hand_orientation(approach_vector: np.ndarray, finger_axis: np.ndarray) -> np.ndarray`**:
Synthesizes a valid $SO(3)$ rotation matrix and quaternion for `panda_hand`:
- $+Z$: points along approach vector (towards fingertips).
- $+Y$: points along finger sliding axis (connecting finger pads).
- $+X$: orthogonal lateral vector ($+Y \times +Z$).
Returns 4D quaternion $[w, x, y, z]$.
- **`generate_candidates_for_object(pose: EstimatedPose6D) -> List[GraspCandidate]`**:
Synthesizes shape-specific grasp candidates:
- **Cube:** 10 candidates (2 top-down grasps along principal $X$ and $Y$ body axes, plus 8 angled front entries at $20^\circ, 30^\circ, 40^\circ, 45^\circ$).
- **Cuboid:** 5 candidates (1 top-down narrow grasp prioritizing narrow width $w_{\text{narrow}} + 0.010\text{ m} \le 0.080\text{ m}$, plus 4 angled front entries at $20^\circ, 30^\circ, 40^\circ, 45^\circ$).
- **Cylinder:** 8 candidates (4 radial top-down candidates at $0^\circ, 45^\circ, 90^\circ, 135^\circ$ exploiting continuous symmetry, plus 4 angled front entries at $20^\circ, 30^\circ, 40^\circ, 45^\circ$).
- **`validate_reachability(candidate: GraspCandidate, position_tolerance: float = 0.008, orientation_tolerance: float = 0.08) -> bool`**:
Solves numerical inverse kinematics via Lula for both grasp pose and pre-grasp standoff pose in the robot base frame. Verifies that joint solutions are continuous and strictly within physical joint limits. Sets `is_ik_reachable`, `joint_positions`, and `pre_grasp_joint_positions`.
- **`compute_quality_score(candidate: GraspCandidate, pose: EstimatedPose6D) -> float`**:
Computes composite ranking score in $[0.0, 100.0]$:
- Feasibility & Reachability: $0.0$ if aperture infeasible or IK unreachable.
- Joint Limit Margin: normalized distance from joint physical limits $\prod (4 (q-q_{\min})(q_{\max}-q)/(q_{\max}-q_{\min})^2)^{1/7}$.
- Shelf Headroom / Collision Safety: $+20\%$ bonus for angled front entries entering through the shelf opening; penalty for top-down grasps close to upper shelf.
- Aperture Stroke Reserve: rewards larger finger stroke margins.
- **`plan_grasps_for_object(pose: EstimatedPose6D) -> List[GraspCandidate]`**:
Executes full planning pipeline for a single target: generation $\to$ reachability validation $\to$ quality ranking (sorted descending).
- **`plan_grasps_for_all_objects(poses: List[EstimatedPose6D]) -> Dict[str, List[GraspCandidate]]`**:
Plans and ranks grasp candidates for all detected objects.
- **`get_best_grasp(candidates: List[GraspCandidate]) -> GraspCandidate | None`**:
Returns highest-scoring feasible and reachable candidate, or `None` if no reachable candidates exist.
- **`project_grasps_to_image(rgb_image: np.ndarray, candidates: List[GraspCandidate], cam_mgr: CameraManager, max_grasps_per_object: int = 2) -> np.ndarray`**:
Projects planned grasp poses, approach vectors, and fingertip contact crosshairs onto the 2D RGB camera frame.
---
### 5.2 `GraspCandidate`
```python
@dataclass
class src.motion.grasp_planner.GraspCandidate
```
Descriptor representing a synthesized parallel-jaw grasp candidate:
- `candidate_id: str`: Unique identifier (e.g., `'cuboid_det_2_grasp_05'`).
- `target_object_name: str`: Target object detection identifier.
- `shape_type: str`: Object geometric shape (`'cube'`, `'cuboid'`, `'cylinder'`).
- `grasp_type: str`: Approach classification (`'TopDown_X'`, `'AngledFront_30deg'`, etc.).
- `grasp_position: np.ndarray`: 3D Cartesian position $[X, Y, Z]$ of `panda_hand` origin in world coordinates (m).
- `grasp_orientation_quat: np.ndarray`: 4D quaternion $[w, x, y, z]$ of `panda_hand` orientation.
- `fingertip_center: np.ndarray`: 3D position $[X, Y, Z]$ between finger contact pads in world coordinates (m).
- `approach_vector: np.ndarray`: Unit 3D vector along approach direction (hand local $+Z$ axis).
- `pre_grasp_position: np.ndarray`: Standoff position $[X, Y, Z]$ backed off along approach vector (m).
- `pre_grasp_orientation_quat: np.ndarray`: Standoff orientation quaternion $[w, x, y, z]$.
- `lift_position: np.ndarray`: Post-grasp vertical lift position $[X, Y, Z]$ (m).
- `required_aperture: float`: Required gripper opening width including clearance margin (m).
- `is_aperture_feasible: bool`: `True` if `required_aperture <= 0.080 m`.
- `is_ik_reachable: bool`: `True` if Lula IK converges within tolerances and joint limits for both grasp and pre-grasp poses.
- `joint_positions: np.ndarray | None`: 7-DOF arm joint angles for grasp pose (rad).
- `pre_grasp_joint_positions: np.ndarray | None`: 7-DOF arm joint angles for pre-grasp standoff pose (rad).
- `quality_score: float`: Composite ranking score in $[0.0, 100.0]$.
- `headroom_clearance_m: float`: Vertical clearance to upper shelf plank in meters.
---
### 5.3 `CuMotionPlanner`
```python
class src.motion.cumotion_planner.CuMotionPlanner(config: ConfigManager | None = None, robot: FrankaRobot | None = None, kinematics: FrankaKinematics | None = None)
```
NVIDIA cuMotion GPU-accelerated trajectory planning and Riemannian Motion Policy (RMPflow) engine.
#### Properties
- **`kinematics -> FrankaKinematics`**: Bound Lula analytical and numerical kinematics solver.
- **`rmpflow -> RmpFlow`**: Active Riemannian Motion Policy solver instance.
- **`trajectory_generator -> cumotion.TrajectoryGenerator`**: Low-level cuMotion trajectory generator bound to Franka robot descriptor.
#### Methods
- **`register_rack_obstacles(racks_cfg: Dict[str, Any]) -> None`**: Registers warehouse storage rack bounds, shelf heights, and corner pillar envelopes as analytical obstacles.
- **`check_collision_free(position: np.ndarray, margin: float = 0.025) -> Tuple[bool, Optional[str]]`**: Analytically queries whether a 3D Cartesian point infringes upon any shelf plank slab ($Z \in [s_z - \text{thick}/2 - m, s_z + \text{thick}/2]$), corner pillar ($r=0.015\text{ m} + m$), or ground boundary ($Z < 0.05\text{ m}$).
- **`plan_cspace_trajectory(waypoints: List[np.ndarray], segment_name: str = "cspace_segment", dt: float = 1.0 / 60.0) -> PlannedTrajectory`**: Generates a smooth, time-optimal joint trajectory passing through the specified joint angle waypoints using cuMotion. Includes automatic pairwise subsegment concatenation fallback if multi-waypoint spline overshoot occurs.
- **`plan_task_space_trajectory(start_q: np.ndarray, target_pos: np.ndarray, target_quat: np.ndarray, segment_name: str = "task_segment", intermediate_via_points: Optional[List[np.ndarray]] = None, dt: float = 1.0 / 60.0) -> PlannedTrajectory`**: Solves Lula numerical IK for target and via poses and generates a collision-aware cuMotion c-space trajectory.
- **`plan_pick_and_place_pipeline(home_q: np.ndarray, grasp_candidate: GraspCandidate, destination_shelf_pos: np.ndarray, destination_shelf_quat: np.ndarray, dt: float = 1.0 / 60.0) -> Dict[str, PlannedTrajectory]`**: Generates the complete 6-segment pick-and-place manipulation transfer pipeline across the warehouse movement corridor.
- **`concatenate_trajectories(trajectories: List[PlannedTrajectory], segment_name: str) -> PlannedTrajectory`**: Stitches consecutive trajectory segments into a single unified `PlannedTrajectory` preserving time continuity, point offsets, and peak kinematic metrics.
- **`step_rmpflow_policy(current_positions: np.ndarray, current_velocities: np.ndarray, target_cspace: Optional[np.ndarray] = None, target_cartesian_pos: Optional[np.ndarray] = None, target_cartesian_quat: Optional[np.ndarray] = None, dt: float = 1.0 / 60.0) -> Tuple[np.ndarray, np.ndarray]`**: Advances the reactive RMPflow policy by one physics step, outputting position and velocity targets.
- **`evaluate_trajectory_smoothness(trajectory: PlannedTrajectory) -> Dict[str, float]`**: Computes kinematic diagnostics including peak velocity, peak acceleration, RMS jerk, and Cartesian end-effector path length.
---
### 5.4 `PlannedTrajectory`
```python
@dataclass
class src.motion.cumotion_planner.PlannedTrajectory
```
Container holding dense sampled points and telemetry for a planned trajectory segment:
- `segment_name: str`: Human-readable identifier (e.g., `'SEG_4_CROSS_CORRIDOR_TRANSFER'`).
- `duration_s: float`: Total execution duration in seconds.
- `waypoints: List[np.ndarray]`: Keyframe configuration-space waypoints (shape (7,)).
- `points: List[TrajectoryPoint]`: Dense discrete sampled states at configured sampling rate (e.g. 60 Hz).
- `max_joint_velocity: float`: Peak joint velocity across all DOFs (rad/s).
- `max_joint_acceleration: float`: Peak joint acceleration across all DOFs (rad/s²).
- `max_joint_jerk: float`: Peak joint jerk across all DOFs (rad/s³).
- `is_valid: bool`: `True` if joint limits, acceleration thresholds ($< 15.0\text{ rad/s}^2$), and obstacle clearances are satisfied.
- `error_message: Optional[str]`: Failure reason if invalid.
- `sampling_rate_hz: float`: State sampling frequency (default: 60.0 Hz).
---
### 5.5 `TrajectoryPoint`
```python
@dataclass
class src.motion.cumotion_planner.TrajectoryPoint
```
Discrete kinematic state sample along a trajectory:
- `time_s: float`: Elapsed timestamp from start of segment (s).
- `positions: np.ndarray`: 7-DOF arm joint angles (rad).
- `velocities: np.ndarray`: 7-DOF arm joint velocities (rad/s).
- `accelerations: np.ndarray`: 7-DOF arm joint accelerations (rad/s²).
- `ee_position: np.ndarray`: $[X, Y, Z]$ world coordinates of tool center frame (`panda_hand`) in meters.
- `ee_orientation_quat: np.ndarray`: $[w, x, y, z]$ quaternion orientation of tool center frame.
---
## 6. Package: `omni.isaac.pick_place`
### 5.1 `PickPlaceExtension`
```python
class omni.isaac.pick_place.extension.PickPlaceExtension(omni.ext.IExt)
```
Omniverse Kit extension interface implementation.
#### Methods
- **`on_startup(ext_id: str) -> None`**: Triggered when the extension is activated by Kit. Initializes the UI window in GUI mode.
- **`on_shutdown() -> None`**: Triggered upon extension deactivation or application exit. Destroys windows and unbinds event listeners.
---
### 5.2 `PickPlaceWindow`
```python
class omni.isaac.pick_place.ui.window.PickPlaceWindow(omni.ui.Window)
```
In-viewport telemetry and control dashboard.
#### Interactive Components
- **System Status Panel**: Displays active Isaac Sim version, GPU hardware, and motion planner state.
- **Simulation Lifecycle Panel**: Interactive buttons for `Setup Scene`, `Randomize Objects`, `Start Task`, and `Stop / Reset`.
- **Vision Readout**: Displays detected object count and estimated target 6D pose.
- **KPI Metrics**: Displays live grasp success rate, placement success rate, and average cycle time.
---
## 7. Package: `src.execution`
### 7.1 `ManipulationFSM`
```python
class src.execution.manipulation_fsm.ManipulationFSM
```
Deterministic 8-phase Finite State Machine coordinating the complete autonomous vision-guided robotic pick-and-place manipulation cycle.
#### Constructor
```python
def __init__(
self,
robot: FrankaRobot,
gripper: ParallelJawGripper,
cam_mgr: CameraManager,
detector: SyntheticObjectDetector,
pose_estimator: PoseEstimator6D,
grasp_planner: GraspPlanner,
cumotion_planner: CuMotionPlanner,
config_manager: Optional[ConfigManager] = None,
)
```
#### Properties
- **`state -> ManipulationState`**: Active FSM operational state.
- **`target_object_name -> str`**: USD name of the currently targeted inventory object.
- **`selected_candidate -> Optional[GraspCandidate]`**: Optimal evaluated grasp candidate.
- **`pipeline -> Dict[str, PlannedTrajectory]`**: 6-segment cuMotion trajectory pipeline.
#### Methods
- **`step() -> ManipulationState`**: Advances the state machine by one simulation step (60 Hz). Returns the new active state.
- **`reset() -> None`**: Resets the state machine to `IDLE`, clears trajectories, opens gripper, and detaches held objects.
- **`transition_to(new_state: ManipulationState) -> None`**: Performs deterministic state transition and logs transition metrics.
- **`_resolve_target_prim_path(target_pose: EstimatedPose6D) -> Optional[str]`**: Matches estimated 3D world coordinates with physical candidate USD prims on stage.
---
### 7.2 `ManipulationState`
```python
class src.execution.manipulation_fsm.ManipulationState(Enum)
```
Enum defining all operational states in the manipulation lifecycle:
- **`IDLE`**: Initial arm configuration and gripper calibration.
- **`PERCEPTION_AND_PLANNING`**: RTX camera frame acquisition, 2D detection, 6D pose estimation, grasp ranking, and 6-segment cuMotion pipeline generation.
- **`APPROACH_STANDOFF`**: Dispatches `SEG_1_HOME_TO_STANDOFF` trajectory.
- **`APPROACH_GRASP`**: Opens gripper fingers and executes `SEG_2_STANDOFF_TO_GRASP`.
- **`GRASP_CLOSE`**: Commands 50N finger closure, verifies contact aperture, and binds `GraspAttachment`.
- **`POST_GRASP_LIFT`**: Dispatches `SEG_3_POST_GRASP_LIFT` upward vertical motion.
- **`CROSS_CORRIDOR_TRANSFER`**: Dispatches `SEG_4_CROSS_CORRIDOR_TRANSFER` across corridor to destination shelf.
- **`PLACE_DEPOSIT`**: Dispatches `SEG_5_PLACEMENT_DEPOSIT` down onto destination shelf surface.
- **`RELEASE_AND_RETRACT`**: Opens gripper, detaches object stably on shelf, and executes `SEG_6_RETRACT_TO_HOME`.
- **`COMPLETE`**: Manipulation cycle succeeded; object settled in static physical equilibrium.
- **`FAULT`**: Execution aborted due to perception, grasp, or trajectory error.
---
### 7.3 `GraspAttachment`
```python
class src.execution.attachment.GraspAttachment
```
Manages kinematic relative transform locking, zero-velocity stabilization, and surface placement decoupling for rigid bodies in Isaac Sim 6.2.
#### Methods
- **`attach(object_prim_path: str, hand_pos: np.ndarray, hand_quat: np.ndarray) -> bool`**: Locks the specified rigid body object to the tool frame (`panda_hand`) by computing the relative spatial offset $R_{\text{hand}}^T (p_{\text{obj}} - p_{\text{hand}})$ and relative orientation $q_{\text{hand}}^{-1} q_{\text{obj}}$.
- **`update(hand_pos: np.ndarray, hand_quat: np.ndarray) -> None`**: Updates the attached object's world pose to track moving tool frame while zeroing linear and angular velocities.
- **`detach(target_pos: Optional[np.ndarray] = None, target_quat: Optional[np.ndarray] = None) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]`**: Releases the held object, optionally depositing it at specified resting coordinates, zeroes physics velocities, and unbinds attachment.
---
### 7.4 Spatial Transform Math Utilities
```python
def src.execution.attachment.quat_multiply(q1: np.ndarray, q2: np.ndarray) -> np.ndarray
def src.execution.attachment.quat_conjugate(q: np.ndarray) -> np.ndarray
def src.execution.attachment.rotate_vector_by_quat(v: np.ndarray, q: np.ndarray) -> np.ndarray
```
Pure NumPy spatial algebra implementations operating on $[w, x, y, z]$ Hamilton quaternions for zero-latency 60 Hz relative transform tracking.
---
## 8. Testing & Edge Cases Module (`src.testing`)
### 8.1 `EdgeCaseRunner`
```python
class src.testing.edge_case_runner.EdgeCaseRunner(
config_manager: ConfigManager,
sim_manager: CoreSimulationManager,
robot: FrankaRobot,
gripper: ParallelJawGripper,
cam_mgr: CameraManager,
detector: SyntheticObjectDetector,
pose_estimator: PoseEstimator6D,
grasp_planner: GraspPlanner,
cumotion_planner: CuMotionPlanner,
fsm: ManipulationFSM,
)
```
Automated testing orchestrator for Monte Carlo evaluation, out-of-reach target rejection, mid-transit grasp slip / drop recovery, perception occlusion handling, and physical corridor clearance verification.
#### Methods
- **`restore_shelf_objects(jitter: bool = False) -> None`**: Teleports inventory objects on the source shelf back to resting height, restoring initial conditions for multi-trial benchmark batteries. When `jitter=True`, injects randomized spatial displacements ($\pm 5\text{ mm}$ in $X, Y$) and yaw perturbations ($\pm 5^\circ$).
- **`run_monte_carlo_battery(num_trials: int = 10, max_frames_per_trial: int = 1200) -> List[TrialResult]`**: Executes consecutive randomized pick-and-place manipulation trials, collecting pick success, transit stability, destination placement coordinates, placement error (mm), simulation cycle duration, wall-clock duration, and corridor rack clearance.
- **`test_unreachable_target_rejection() -> Dict[str, Any]`**: Validates rejection of infeasible targets:
- Deep out-of-reach shelf locations ($Y = -0.85\text{ m}$) beyond Franka kinematic reach (`is_ik_reachable = False`).
- Oversized objects ($120\text{ mm} > 80\text{ mm}$ stroke) exceeding parallel-jaw aperture limit (`is_aperture_feasible = False`).
- **`test_drop_detection_and_recovery() -> Dict[str, Any]`**: Validates active mid-transit grasp slip monitoring. Injects simulated grasp detachment during cross-corridor transit and verifies immediate transition to `ManipulationState.FAULT`, aborting destination deposit without secondary collisions.
- **`test_perception_occlusion_and_low_confidence() -> Dict[str, Any]`**: Tests graceful failure handling when perception returns zero detections (simulating extreme visual occlusion or camera blackout), verifying safe transition to `FAULT` with diagnostic error logging.
- **`test_corridor_clearance_margins() -> Dict[str, Any]`**: Verifies minimum physical clearance across the expanded $0.76\text{ m}$ transit corridor, ensuring distance between moving robot links and rack structures meets or exceeds safety thresholds ($\ge 30.0\text{ mm}$).
---
### 8.2 `TrialResult`
```python
@dataclass
class src.testing.edge_case_runner.TrialResult
```
Structured dataclass recording the execution metrics of an individual Monte Carlo trial:
- `trial_id: int`: Sequential trial index.
- `object_name: str`: Identifier of the manipulated inventory object.
- `shape_type: str`: Shape classification (`'cube'`, `'cuboid'`, `'cylinder'`).
- `spawn_pos: List[float]`: 3D coordinates where the target object spawned.
- `final_state: str`: Terminal FSM state (`COMPLETE`, `FAULT`).
- `success: bool`: Overall trial success boolean (pick + transit + place within tolerance).
- `pick_success: bool`: Whether grasp closure and lift succeeded.
- `transit_success: bool`: Whether cross-corridor transfer reached deposit phase without dropping.
- `place_success: bool`: Whether deposit was completed within horizontal error tolerance ($< 35.0\text{ mm}$).
- `placement_error_mm: float`: Horizontal ($XY$) Euclidean distance between target deposit and final settled position.
- `sim_duration_s: float`: Simulation duration in seconds (based on 60 Hz frame counter).
- `wall_clock_s: float`: Elapsed wall-clock time in seconds.
- `min_rack_clearance_mm: float`: Minimum measured clearance to adjacent rack structures during transit.
- `notes: str`: Diagnostic logs or error descriptions.
- **`to_dict() -> Dict[str, Any]`**: Serializes trial metrics to dictionary.
---
### 8.3 `EdgeCaseBenchmarkReport`
```python
@dataclass
class src.testing.edge_case_runner.EdgeCaseBenchmarkReport
```
Summary dataclass aggregating performance statistics across all trials:
- `total_trials: int`: Total number of evaluated trials.
- `successful_trials: int`: Count of trials meeting all success criteria.
- `pick_success_rate_pct: float`: Percentage of successful picks.
- `placement_success_rate_pct: float`: Percentage of successful placements.
- `overall_success_rate_pct: float`: Percentage of full-cycle successes.
- `mean_placement_error_mm: float`: Mean horizontal placement error in millimeters.
- `std_placement_error_mm: float`: Standard deviation of placement error in millimeters.
- `mean_sim_duration_s: float`: Mean simulation time per cycle in seconds.
- `min_corridor_clearance_mm: float`: Minimum recorded clearance across all trials.
- `unreachable_rejection_passed: bool`: Outcome of reachability rejection test.
- `drop_recovery_passed: bool`: Outcome of drop detection test.
- `occlusion_handling_passed: bool`: Outcome of visual occlusion test.
- **`to_dict() -> Dict[str, Any]`**: Serializes aggregate report to dictionary.
---
## 9. Metrics & UI Dashboard Module (`src.metrics` & `exts.omni.isaac.pick_place`)
### 9.1 `TelemetryCollector`
```python
class src.metrics.telemetry_collector.TelemetryCollector(output_dir: Optional[Path] = None)
```
Standardized performance telemetry engine implementing mathematical tracking of all 10 KPIs defined in `docs/KPI_DEFINITIONS.md`.
#### Methods
- **`start_trial(target_name: str, shape_type: str = "cuboid", gt_position: Optional[np.ndarray] = None, gt_yaw_deg: float = 0.0) -> TrialTelemetry`**: Initializes tracking session for a new manipulation trial.
- **`record_detection(detected: bool, est_position: Optional[np.ndarray] = None, est_yaw_deg: float = 0.0) -> None`**: Records perception accuracy ($KPI_1$), 3D Euclidean centroid error ($KPI_2$), and symmetry-aware planar orientation error ($KPI_3$).
- **`record_tcp_waypoint(tcp_position: np.ndarray) -> None`**: Integrates 3D tool center path distance ($KPI_8$).
- **`record_grasp(attempted: bool = True, success: bool = False) -> None`**: Records grasp attempt and contact verification ($KPI_4$).
- **`record_pick(success: bool = False) -> None`**: Records vertical lift and transit stability ($KPI_5$).
- **`record_placement(attempted: bool = True, success: bool = False, final_pos: Optional[np.ndarray] = None, target_dest_pos: Optional[np.ndarray] = None) -> None`**: Records destination deposit outcome and computes horizontal error ($KPI_6$).
- **`record_collision() -> None`**: Increments unplanned contact counter ($KPI_9$).
- **`record_replan() -> None`**: Increments replanning / recovery counter ($KPI_{10}$).
- **`end_trial(final_state: str, overall_success: bool, sim_frames: int = 0, notes: str = "") -> TrialTelemetry`**: Finalizes trial session, computes simulation ($KPI_7$) and wall-clock durations, and archives record.
- **`get_summary() -> KPISummary`**: Evaluates aggregate averages and pass percentages across all recorded trials.
- **`export_trial_json(trial: TrialTelemetry, filename: Optional[str] = None) -> Path`**: Serializes individual trial telemetry to `metrics/experiments/trial_<id>_<timestamp>.json`.
- **`export_summary_csv(filename: Optional[str] = None) -> Path`**: Exports aggregate summary and all trial rows to `metrics/kpi_summary.csv`.
---
### 9.2 `TrialTelemetry`
```python
@dataclass
class src.metrics.telemetry_collector.TrialTelemetry
```
Data container storing ground truth, camera estimates, grasp states, placement coordinates, trajectory length, and execution timings for a single trial.
---
### 9.3 `KPISummary`
```python
@dataclass
class src.metrics.telemetry_collector.KPISummary
```
Statistical summary aggregating all 10 KPIs across multi-trial manipulation benchmarks.
---
### 9.4 `PickPlaceWindow`
```python
class exts.omni.isaac.pick_place.omni.isaac.pick_place.ui.window.PickPlaceWindow(
title: str = "Vision Pick & Place Controller",
fsm=None,
telemetry_collector=None,
sim_manager=None,
robot=None,
scene_builder=None,
**kwargs
)
```
In-viewport control dashboard implemented via native `omni.ui`.
#### Methods
- **`bind_controllers(fsm, telemetry_collector, sim_manager, robot, scene_builder)`**: Connects runtime manipulation and simulation engines to UI controls.
- **`update()`**: High-frequency refresh routine updating FSM state, target item, estimated 3D coordinates, planar yaw, gripper aperture, and live KPI counters.
- **`_on_start_cycle()`**: Pushbutton handler triggering autonomous pick-and-place manipulation cycle.
- **`_on_reset_home()`**: Pushbutton handler resetting Franka arm to configured home configuration.
- **`_on_randomize_objects()`**: Re-rolls picking shelf inventory items.
- **`_on_emergency_halt()`**: Safe abort handler stopping simulation timeline and entering `FAULT` state.
- **`_on_export_metrics()`**: Triggers export of structured JSON and CSV telemetry records.