Files
Pick-And-Place-Simulation-P…/scripts/run_application.py
T

491 lines
22 KiB
Python

#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Main Application Launcher — Vision-Guided Robotic Pick-and-Place Simulation.
Simulation modes (controlled via CLI flags):
--auto-start Single pick-and-place cycle (first HIGH-priority task from CSV)
--multi-moveme depth_min_threshold_m: 0.10
depth_max_threshold_m: 2.50nt Full task-sequence from simulation_tasks.csv (cross-rack + same-rack)
--task-id T001 Run a specific task by its CSV task_id
--headless No GUI (terminal-only output)
Task CSV: data/tasks/simulation_tasks.csv
Defines every movement: source rack/shelf, destination rack/shelf, placement pose,
transfer mode (cross_rack | same_rack), priority, and frame budget.
"""
import sys
import argparse
import time
import csv
import json
from pathlib import Path
project_root = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(project_root))
parser = argparse.ArgumentParser(description="Autonomous Pick & Place Simulation")
parser.add_argument("--headless", action="store_true", help="Headless mode — no GUI window")
parser.add_argument("--auto-start", action="store_true", help="Run first HIGH-priority task immediately on launch")
parser.add_argument("--multi-movement", action="store_true", help="Run full task sequence from simulation_tasks.csv")
parser.add_argument("--task-id", type=str, default=None, help="Run a single task by its CSV task_id (e.g. T001)")
parser.add_argument("--limit", type=int, default=None, help="Limit execution to first N tasks (e.g. --limit 3)")
parser.add_argument("--num-tasks", type=int, default=None, help="Alias for --limit (e.g. --num-tasks 3)")
args, _ = parser.parse_known_args()
print("\n" + "=" * 80)
print(" VISION-GUIDED ROBOTIC PICK-AND-PLACE SIMULATION")
print("=" * 80)
print(f" Mode : {'Headless' if args.headless else 'Interactive 3D GUI'}")
max_tasks_arg = args.limit or args.num_tasks
if args.task_id:
print(f" Task : {args.task_id}")
elif max_tasks_arg:
print(f" Tasks: First {max_tasks_arg} task(s) from simulation_tasks.csv")
elif args.multi_movement:
print(f" Tasks: Full sequence from simulation_tasks.csv")
elif args.auto_start:
print(f" Tasks: First HIGH-priority task from simulation_tasks.csv")
print("=" * 80)
# ── Isaac Sim must be launched FIRST before any other omni imports ─────────────
from isaacsim import SimulationApp
simulation_app = SimulationApp({"headless": args.headless, "width": 1920, "height": 1080})
import numpy as np
import omni.usd
import omni.kit.app
import carb
from isaacsim.core.utils.viewports import set_camera_view
from src.core.config import ConfigManager
from src.core.simulation_manager import CoreSimulationManager
from src.core.task_loader import TaskLoader, SimulationTask
from src.environment.scene_builder import WarehouseSceneBuilder
from src.robot.articulation import FrankaRobot
from src.robot.gripper import ParallelJawGripper
from src.robot.kinematics import FrankaKinematics
from src.vision.camera_manager import CameraManager
from src.vision.detector import SyntheticObjectDetector
from src.vision.pose_estimator import PoseEstimator6D
from src.motion.grasp_planner import GraspPlanner
from src.motion.cumotion_planner import CuMotionPlanner
from src.execution.manipulation_fsm import ManipulationFSM, ManipulationState
from src.metrics.telemetry_collector import TelemetryCollector
# Load omni.ui dashboard extension (optional — fails gracefully in headless)
PickPlaceWindow = None
try:
import importlib.util
_win_path = (
project_root / "exts" / "omni.isaac.pick_place"
/ "omni" / "isaac" / "pick_place" / "ui" / "window.py"
)
_spec = importlib.util.spec_from_file_location("omni.isaac.pick_place.ui.window", str(_win_path))
_win_mod = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_win_mod)
PickPlaceWindow = _win_mod.PickPlaceWindow
except Exception as _e:
carb.log_warn(f"[App] omni.ui window module not loaded: {_e}")
# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────
def _rack_dest_from_config(cfg: ConfigManager, rack_name: str, shelf_idx: int) -> np.ndarray:
"""
Computes a safe, centered destination [x, y, z] on the given rack's shelf
directly from YAML config — used when a task doesn't override dest_pos.
"""
rack_cfg = cfg.warehouse.get("racks", {}).get(rack_name, {})
pos = rack_cfg.get("position", [0.46, 0.52, 0.0])
shelf_heights = rack_cfg.get("shelf_heights", [0.25, 0.55, 0.90])
thickness = float(rack_cfg.get("shelf_thickness", 0.02))
depth = float(rack_cfg.get("depth", 0.28))
sh_z = float(shelf_heights[shelf_idx]) + thickness / 2.0
# Place slightly inboard from rack centre toward the robot corridor
y_sign = -1.0 if pos[1] < 0 else 1.0
y_place = float(pos[1]) - y_sign * depth * 0.15
return np.array([float(pos[0]), y_place, sh_z], dtype=float)
def _print_task_banner(task, task_num: int, total: int) -> None:
w = 88
print("\n" + "─" * w)
print(f" TASK [{task_num}/{total}] {task.task_id}: {task.task_title}")
print(f" Scenario : {task.scenario}")
print(f" Mode : {task.transfer_mode.upper()}")
print(f" Route : {task.source_rack}[shelf {task.source_shelf_idx}]"
f" → {task.dest_rack}[shelf {task.dest_shelf_idx}]")
print(f" Dest : X={task.dest_pos[0]:.3f} Y={task.dest_pos[1]:.3f} Z={task.dest_pos[2]:.3f}")
print(f" Asset : {task.asset_hint}")
print(f" Notes : {task.notes}")
print("─" * w)
def _save_run_summary(results: list, out_path: Path) -> None:
"""Writes a JSON summary of all executed task results."""
out_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"run_timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"total_tasks": len(results),
"successful": sum(1 for r in results if r.get("success")),
"results": results,
}
with open(out_path, "w") as f:
json.dump(payload, f, indent=2)
print(f"\n Run summary saved → {out_path}")
# ─────────────────────────────────────────────────────────────────────────────
# Main
# ─────────────────────────────────────────────────────────────────────────────
def main():
carb.log_info("[App] Initializing simulation...")
# ── 1. Configuration & Stage ─────────────────────────────────────────────
cfg = ConfigManager()
sim_mgr = CoreSimulationManager(cfg)
sim_mgr.setup_stage()
stage = omni.usd.get_context().get_stage()
# ── 2. Task Schedule ─────────────────────────────────────────────────────
task_loader = TaskLoader()
task_loader.print_summary()
if args.task_id:
task = task_loader.get_task_by_id(args.task_id)
if task is None:
print(f"[App] ERROR: task_id '{args.task_id}' not found in CSV.")
simulation_app.close()
return
tasks_to_run = [task]
elif args.auto_start:
hi = task_loader.get_enabled_tasks(priority_filter="HIGH")
tasks_to_run = [hi[0]] if hi else task_loader.get_enabled_tasks()[:1]
else:
# Default (with or without --multi-movement): execute all enabled tasks from CSV
tasks_to_run = task_loader.get_enabled_tasks()
if max_tasks_arg is not None and max_tasks_arg > 0:
tasks_to_run = tasks_to_run[:max_tasks_arg]
# ── 3. Build Warehouse ───────────────────────────────────────────────────
builder = WarehouseSceneBuilder(stage, cfg)
env_info = builder.build_warehouse_environment()
carb.log_info(
f"[App] Warehouse built: {env_info['total_objects']} target objects, "
f"{env_info['total_inventory_boxes']} inventory items."
)
# ── 4. Spawn Robot ───────────────────────────────────────────────────────
robot = FrankaRobot(cfg, stage=stage)
robot.spawn()
# ── 5. Viewport Camera ───────────────────────────────────────────────────
if not args.headless:
set_camera_view(
eye=[1.80, 0.30, 1.40],
target=[0.46, 0.0, 0.56],
camera_prim_path="/OmniverseKit_Persp",
)
# ── 6. Physics Warmup ────────────────────────────────────────────────────
sim_mgr.play()
sim_mgr.step(5)
robot.initialize()
robot.set_home_pose()
sim_mgr.step(60) # First settle pass — USD references finish loading children
carb.log_info("[App] USD references loaded. Re-applying semantics to all children...")
# Re-apply semantics after USD references have loaded their child prims.
# In GUI mode, referenced assets load asynchronously; child prims only exist
# a few frames after AddReference(). Tagging them now guarantees the RTX
# annotator sees the correct semantic class for every mesh sub-prim.
_semantic_stage = omni.usd.get_context().get_stage()
for obj in builder.spawned_objects:
_prim = _semantic_stage.GetPrimAtPath(obj.prim_path)
if _prim.IsValid():
builder.object_generator._apply_semantics(_prim, obj.prim_path, obj.semantic_label)
carb.log_info(f" [Semantics] Re-tagged '{obj.prim_path}' → '{obj.semantic_label}'")
sim_mgr.step(120) # Second settle pass — objects reach resting position (total 3 s)
carb.log_info("[App] Physics warmup complete. Robot at home pose.")
# ── 7. Perception & Planning Stack ───────────────────────────────────────
gripper = ParallelJawGripper(robot, config_manager=cfg)
cam_mgr = CameraManager(cfg, stage=stage)
detector = SyntheticObjectDetector(cam_mgr)
pose_estimator = PoseEstimator6D(cam_mgr, shelf_height=0.56)
kinematics = FrankaKinematics()
grasp_planner = GraspPlanner(
kinematics=kinematics,
max_gripper_aperture=0.080,
standoff_distance=0.100,
lift_distance=0.120,
robot_base_pos=[0.0, 0.0, 0.0],
)
cumotion_planner = CuMotionPlanner(cfg, kinematics=kinematics)
telemetry = TelemetryCollector()
# ── 8. Manipulation FSM ───────────────────────────────────────────────────
fsm = ManipulationFSM(
robot=robot,
gripper=gripper,
cam_mgr=cam_mgr,
detector=detector,
pose_estimator=pose_estimator,
grasp_planner=grasp_planner,
cumotion_planner=cumotion_planner,
config_manager=cfg,
)
# ── 9. omni.ui Dashboard ─────────────────────────────────────────────────
ui_window = None
if not args.headless and PickPlaceWindow is not None:
try:
ui_window = PickPlaceWindow(
title="John Deere Pick & Place Controller",
fsm=fsm,
telemetry_collector=telemetry,
sim_manager=sim_mgr,
robot=robot,
scene_builder=builder,
)
carb.log_info("[App] PickPlaceWindow dashboard loaded.")
except Exception as e:
carb.log_warn(f"[App] Dashboard creation failed (non-fatal): {e}")
kit_app = omni.kit.app.get_app()
print("\n" + "=" * 80)
print(" APPLICATION READY")
if tasks_to_run:
print(f" Executing {len(tasks_to_run)} task(s) from simulation_tasks.csv ...")
else:
print(" Interactive mode — use the dashboard or re-run with --auto-start / --multi-movement")
print("=" * 80 + "\n")
# ── 10. Autonomous Task Execution Loop ────────────────────────────────────
run_results = []
if tasks_to_run:
total = len(tasks_to_run)
for task_num, task in enumerate(tasks_to_run, start=1):
_print_task_banner(task, task_num, total)
# Resolve destination — task CSV value takes priority over config default
dest_pos = task.dest_pos.copy()
dest_quat = task.dest_quat.copy()
# For same_rack tasks: force destination Y to same side as source rack
if task.transfer_mode == "same_rack":
src_cfg = cfg.warehouse.get("racks", {}).get(task.source_rack, {})
src_pos = src_cfg.get("position", [0.46, -0.52, 0.0])
dest_pos[1] = float(src_pos[1]) * 0.85
# ── Reset FSM cleanly before every task ──────────────────────────
# Use reset_for_next_movement() instead of reset() so the completed-objects
# set is preserved across tasks — prevents picking the same object twice.
fsm.reset_for_next_movement(
dest_pos=dest_pos,
dest_quat=dest_quat,
transfer_mode=task.transfer_mode,
asset_hint=task.asset_hint,
)
fsm.set_task_info(
task_index=task_num,
total_tasks=total,
task_title=task.task_title,
task_description=task.description,
task_id=task.task_id,
seed=42,
)
# Brief physics settling between tasks (robot returns to home)
sim_mgr.step(30)
# Start telemetry trial
telemetry.start_trial(
target_name=task.task_id,
shape_type=task.transfer_mode,
)
# Kick off FSM from IDLE → PERCEPTION_AND_PLANNING
fsm.transition_to(ManipulationState.PERCEPTION_AND_PLANNING)
frame = 0
last_state = None
t_start = time.time()
# Inner per-frame loop
while simulation_app.is_running():
frame += 1
# Step the FSM
curr_state = fsm.step()
# Log state transitions
if curr_state != last_state:
elapsed = time.time() - t_start
print(f" [{frame:>5} {elapsed:>6.1f}s] {curr_state.value}")
last_state = curr_state
# Record TCP trajectory for KPI_8
ee_pos, _ = robot.get_end_effector_pose()
telemetry.record_tcp_waypoint(ee_pos)
# Update UI
if ui_window is not None:
ui_window.update()
# Step physics + rendering (sim_mgr.step advances timeline & viewport rendering)
sim_mgr.step(1)
# Task complete or faulted
if curr_state in (ManipulationState.COMPLETE, ManipulationState.FAULT):
is_success = (curr_state == ManipulationState.COMPLETE)
if fsm._target_obj_pose is not None:
telemetry.record_detection(
detected=True,
est_position=fsm._target_obj_pose.position,
est_yaw_deg=0.0,
)
telemetry.record_grasp(attempted=True, success=fsm._grasped_verified)
telemetry.record_pick(success=fsm._grasped_verified)
telemetry.record_placement(
attempted=True,
success=is_success,
final_pos=fsm._final_placement_pos,
target_dest_pos=dest_pos,
)
trial_rec = telemetry.end_trial(
final_state=curr_state.value,
overall_success=is_success,
sim_frames=frame,
notes=fsm._error_msg or "",
)
telemetry.export_trial_json(trial_rec)
result = {
"task_id": task.task_id,
"task_title": task.task_title,
"transfer_mode": task.transfer_mode,
"success": is_success,
"frames": frame,
"elapsed_s": round(time.time() - t_start, 2),
"grasped": bool(fsm._grasped_verified),
"placement_pos": fsm._final_placement_pos.tolist() if fsm._final_placement_pos is not None else None,
"fault": fsm._error_msg,
}
run_results.append(result)
status_icon = "✓ SUCCESS" if is_success else "✗ FAULT"
print(f"\n {status_icon} — {task.task_id}: {task.task_title}")
if not is_success:
print(f" Fault: {fsm._error_msg}")
print()
break
# Safety timeout
if frame >= task.max_frames:
fsm._error_msg = f"Timeout: exceeded {task.max_frames} frames."
carb.log_error(f"[App] {fsm._error_msg}")
fsm.transition_to(ManipulationState.FAULT)
# Brief settling pause between tasks
sim_mgr.step(45)
time.sleep(0.1)
# ── All tasks done ───────────────────────────────────────────────────
_save_run_summary(
run_results,
project_root / "docs" / "run_summary.json",
)
csv_path = telemetry.export_summary_csv()
print(f" KPI Telemetry summary CSV saved → {csv_path}")
# Print final summary table
print("\n" + "=" * 80)
print(" RUN COMPLETE — TASK SUMMARY")
print("=" * 80)
print(f" {'ID':<6} {'Title':<38} {'Mode':<12} {'Result':<10} {'Frames':<8} {'Time(s)'}")
print(" " + "-" * 78)
for r in run_results:
icon = "✓" if r["success"] else "✗"
print(
f" {r['task_id']:<6} {r['task_title'][:37]:<38} "
f"{r['transfer_mode']:<12} {icon + ' ' + ('SUCCESS' if r['success'] else 'FAULT'):<10} "
f"{r['frames']:<8} {r['elapsed_s']}"
)
passed = sum(1 for r in run_results if r["success"])
print("=" * 80)
print(f" {passed}/{len(run_results)} tasks completed successfully.\n")
# In GUI mode, keep the window open so user can inspect final placement & KPIs
if not args.headless:
print(" Simulation completed. Interactive viewport open (close window to exit)...")
while simulation_app.is_running():
sim_mgr.step(1)
if ui_window is not None:
ui_window.update()
# ── 11. Keep app open in interactive mode ─────────────────────────────────
else:
last_fsm_state = None
active_trial = None
while simulation_app.is_running():
if fsm.state != ManipulationState.IDLE:
if active_trial is None:
active_trial = telemetry.start_trial(
target_name=fsm.target_object_name or "target_item",
shape_type=fsm._target_shape_type or "cuboid",
)
curr_state = fsm.step()
ee_pos, _ = robot.get_end_effector_pose()
telemetry.record_tcp_waypoint(ee_pos)
if curr_state != last_fsm_state:
print(f" [Frame {fsm._step_counter:>4}] FSM State -> {curr_state.value}")
last_fsm_state = curr_state
if curr_state in (ManipulationState.COMPLETE, ManipulationState.FAULT):
is_success = (curr_state == ManipulationState.COMPLETE)
telemetry.record_grasp(attempted=True, success=fsm._grasped_verified)
telemetry.record_pick(success=fsm._grasped_verified)
telemetry.record_placement(
attempted=True,
success=is_success,
final_pos=fsm._final_placement_pos,
target_dest_pos=fsm._dest_shelf_pos,
)
telemetry.end_trial(
final_state=curr_state.value,
overall_success=is_success,
sim_frames=fsm._step_counter,
)
active_trial = None
print(f" Cycle finished: {curr_state.value} (Success={is_success})")
sim_mgr.step(1)
if ui_window is not None:
ui_window.update()
# ── Cleanup ───────────────────────────────────────────────────────────────
carb.log_info("[App] Shutting down cleanly.")
sim_mgr.stop()
simulation_app.close()
if __name__ == "__main__":
main()