Update warehouse digital twin and robot fleet optimization

This commit is contained in:
DnyaneshwariP13
2026-11-25 11:54:38 +05:30
parent e9c573ddc2
commit acab3a1f5b
367 changed files with 4411504 additions and 110561 deletions
@@ -29,35 +29,48 @@ except ImportError:
class ExtBase: # type: ignore
pass
# Discover repository root dynamically and ensure src is on sys.path
_p = Path(__file__).resolve()
REPO_ROOT: Optional[Path] = None
while _p != _p.parent:
_candidate = _p / "src"
if (_candidate / "warehouse_twin").exists():
REPO_ROOT = _p
_src_str = str(_candidate)
if _src_str not in sys.path:
sys.path.insert(0, _src_str)
break
_p = _p.parent
if REPO_ROOT is None:
_fb = Path("/home/dmhai/warehouse-digital-twin")
if (_fb / "src" / "warehouse_twin").exists():
REPO_ROOT = _fb
_fb_str = str(_fb / "src")
if _fb_str not in sys.path:
sys.path.insert(0, _fb_str)
# Import core simulation visualization player
try:
from warehouse_twin.visualization.trajectory_player import (
RobotPlaybackState,
TrajectoryData,
TrajectoryPlayer,
interpolate_robot_state,
)
except ImportError:
# Handle sys.path when running standalone inside Kit Python
current_dir = Path(__file__).resolve().parent
repo_root = current_dir.parents[4]
src_path = repo_root / "src"
if str(src_path) not in sys.path:
sys.path.insert(0, str(src_path))
from warehouse_twin.visualization.trajectory_player import (
RobotPlaybackState,
TrajectoryData,
TrajectoryPlayer,
interpolate_robot_state,
)
from warehouse_twin.visualization.trajectory_player import (
RobotPlaybackState,
TrajectoryData,
TrajectoryPlayer,
interpolate_robot_state,
)
class WarehouseVisualizerExtension(ExtBase):
"""Main Omniverse Kit Extension managing trajectory playback and stage updates."""
"""Main Omniverse Kit Extension managing trajectory playback, stage switching, and fleet HUD."""
FROZEN_WORKLOAD_PATH = "data/input/demo_orders.csv"
FROZEN_WORKLOAD_SHA256 = "f4eff4790759dd243337db1ec3c57ea41546f7f4db47d642acdb3708702ba238"
FROZEN_WORKLOAD_TASKS = 86
def __init__(self) -> None:
super().__init__()
self._repo_root: Path = REPO_ROOT or Path("/home/dmhai/warehouse-digital-twin").resolve()
self._window: Any = None
self._menu_item: Any = None
self._player: Optional[TrajectoryPlayer] = None
self._update_sub: Any = None
self._last_wall_time: float = 0.0
@@ -69,21 +82,34 @@ class WarehouseVisualizerExtension(ExtBase):
self._robot_labels: Dict[str, Any] = {}
self.is_active: bool = False
# Staged Demo HUD state
self._selected_stage: int = 1
self._stage_info_label: Any = None
self._kpi_thru_label: Any = None
self._kpi_turnaround_label: Any = None
self._kpi_distance_label: Any = None
self._kpi_energy_label: Any = None
self._kpi_conflicts_label: Any = None
self._kpi_wait_label: Any = None
self._kpi_tasks_label: Any = None
self._stage_data_cache: Dict[int, Dict[str, Any]] = {}
self._stage_event_sub: Any = None
def on_startup(self, ext_id: str) -> None:
"""Invoked when the Omniverse Kit extension is activated."""
print(f"[omni.warehouse.twin.visualizer] Starting up extension: {ext_id}")
self.is_active = True
self._last_wall_time = time.time()
# Pre-cache staged demo metrics
self._load_staged_data()
# Locate default trajectory file if available
default_traj = Path("results/trajectories/trajectory_default.json").resolve()
default_traj = (self._repo_root / "results/demo_staged/stage_01_baseline/trajectory.json").resolve()
if not default_traj.exists():
# Check baseline experiment directory
alt = Path("results/experiments/baseline_1hr/events.jsonl").resolve()
# Search for any trajectory json in results/
found = list(Path("results").glob("**/trajectory*.json"))
if found:
default_traj = found[0].resolve()
default_traj = (self._repo_root / "results/demo/initial/trajectory.json").resolve()
if not default_traj.exists():
default_traj = (self._repo_root / "results/trajectories/trajectory_default.json").resolve()
if default_traj.exists():
self.load_trajectory(str(default_traj))
@@ -92,15 +118,22 @@ class WarehouseVisualizerExtension(ExtBase):
if HAS_KIT:
self._build_ui()
self._start_update_loop()
self._subscribe_stage_events()
self._register_menu()
def on_shutdown(self) -> None:
"""Invoked when the Omniverse Kit extension is deactivated. Guarantees clean resource teardown."""
print("[omni.warehouse.twin.visualizer] Shutting down extension and releasing subscriptions")
self.is_active = False
# 1. Cancel Kit update loop subscription
# Unregister custom Kit menu item
self._unregister_menu()
# 1. Cancel Kit update loop and stage event subscriptions
if self._update_sub is not None:
self._update_sub = None
if self._stage_event_sub is not None:
self._stage_event_sub = None
# 2. Halt playback and clear player callbacks
if self._player is not None:
@@ -114,6 +147,302 @@ class WarehouseVisualizerExtension(ExtBase):
self._robot_labels.clear()
def _register_menu(self) -> None:
"""Add menu item under Window to toggle HUD window visibility."""
try:
import omni.kit.menu.utils
def _toggle_menu_cb():
if self._window is not None:
self._window.visible = not self._window.visible
if self._window.visible:
self._window.focus()
else:
self._build_ui()
self._menu_item = [
omni.kit.menu.utils.MenuItemDescription(
name="Warehouse Twin Visualizer & Optimization HUD",
onclick_fn=_toggle_menu_cb,
)
]
omni.kit.menu.utils.add_menu_items(self._menu_item, "Window")
print("[omni.warehouse.twin.visualizer] Registered menu item: Window -> Warehouse Twin Visualizer & Optimization HUD")
except Exception as e:
self._menu_item = None
print(f"[omni.warehouse.twin.visualizer] Menu registration note: {e}")
def _unregister_menu(self) -> None:
"""Unregister menu item on extension shutdown."""
if hasattr(self, "_menu_item") and self._menu_item:
try:
import omni.kit.menu.utils
omni.kit.menu.utils.remove_menu_items(self._menu_item, "Window")
except Exception:
pass
self._menu_item = None
def _subscribe_stage_events(self) -> None:
"""Subscribe to USD Context stage open events to auto-detect loaded stage."""
if not HAS_KIT:
return
try:
usd_context = omni.usd.get_context()
self._stage_event_sub = usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.warehouse.twin.visualizer.stage_event"
)
print("[omni.warehouse.twin.visualizer] Subscribed to USD stage open events.")
except Exception as e:
print(f"[omni.warehouse.twin.visualizer] Failed to subscribe to stage events: {e}")
def _on_stage_event(self, event: Any) -> None:
"""Auto-detect active stage when a USD file is loaded in Omniverse Kit."""
if not HAS_KIT:
return
try:
if event.type == int(omni.usd.StageEventType.OPENED):
stage_url = omni.usd.get_context().get_stage_url() or ""
print(f"[omni.warehouse.twin.visualizer] USD Stage Opened: {stage_url}")
if "stage_03_1" in stage_url or "efficiency" in stage_url:
self.select_stage(4)
self.load_current_stage_trajectory()
elif "stage_03" in stage_url or "stage_03_final" in stage_url:
self.select_stage(3)
self.load_current_stage_trajectory()
elif "stage_02" in stage_url:
self.select_stage(2)
elif "stage_01" in stage_url or "baseline" in stage_url:
self.select_stage(1)
self.load_current_stage_trajectory()
# Ensure HUD window is visible and focused
if self._window is not None:
self._window.visible = True
try:
self._window.focus()
except Exception:
pass
except Exception as e:
print(f"[omni.warehouse.twin.visualizer] Error in stage event handler: {e}")
def _load_staged_data(self) -> None:
"""Inspect demo output directories and load KPI data for HUD display."""
base_paths = [
self._repo_root / "results/demo_staged",
self._repo_root / "results/demo",
self._repo_root / "results/demonstration/staged_demo",
Path("results/demo_staged").resolve(),
Path("results/demo").resolve(),
]
active_base = None
for bp in base_paths:
if bp.exists():
active_base = bp
break
if not active_base:
return
# Stage 1
s1_dirs = [active_base / "stage_01_baseline", active_base / "initial"]
for d in s1_dirs:
kpi_p = d / "kpis.json" if (d / "kpis.json").exists() else (d / "kpi_summary.json")
if kpi_p.exists():
try:
with open(kpi_p, "r", encoding="utf-8") as f:
kpi_data = json.load(f)
usd_p = active_base / "usd" / "stage_01_baseline.usda"
if not usd_p.exists():
usd_p = d / "warehouse.usda"
traj_p = d / "trajectory.json"
self._stage_data_cache[1] = {
"name": "Stage 1: Centralized Baseline",
"kpis": kpi_data,
"usd": str(usd_p) if usd_p.exists() else "",
"trajectory": str(traj_p) if traj_p.exists() else "",
"coordination": "Passive Conflict Monitoring (Unmitigated)",
"chargers": "8 Bays (Centralized NW Cluster)",
"slotting": "Default Catalog Layout",
}
break
except Exception:
pass
# Stage 2
s2_dirs = [active_base / "stage_02_optimization_progress", active_base / "optimizing"]
for d in s2_dirs:
cand_p = d / "candidate_results.json"
if cand_p.exists():
try:
with open(cand_p, "r", encoding="utf-8") as f:
cand_data = json.load(f)
usd_p = active_base / "usd" / "stage_02_optimization_progress.usda"
if not usd_p.exists():
usd_p = d / "warehouse.usda"
self._stage_data_cache[2] = {
"name": "Stage 2: Systematic 5-Candidate Search",
"candidates": cand_data,
"usd": str(usd_p) if usd_p.exists() else "",
"trajectory": "",
"coordination": "Preventive Coordination Active Across All Candidates",
"chargers": "Decentralized Zone Placement Tested",
"slotting": "Velocity ABC Slotting Evaluated",
}
break
except Exception:
pass
# Stage 3
s3_dirs = [active_base / "stage_03_final_optimized", active_base / "optimized"]
for d in s3_dirs:
kpi_p = d / "kpis.json" if (d / "kpis.json").exists() else (d / "kpi_summary.json")
if kpi_p.exists():
try:
with open(kpi_p, "r", encoding="utf-8") as f:
kpi_data = json.load(f)
usd_p = active_base / "usd" / "stage_03_final_optimized.usda"
if not usd_p.exists():
usd_p = d / "warehouse.usda"
traj_p = d / "trajectory.json"
self._stage_data_cache[3] = {
"name": "Stage 3: Hybrid Optimal Facility",
"kpis": kpi_data,
"usd": str(usd_p) if usd_p.exists() else "",
"trajectory": str(traj_p) if traj_p.exists() else "",
"coordination": "Preventive Traffic Coordination (0 Unresolved)",
"chargers": "8 Bays (Decentralized Zones A, B, C)",
"slotting": "Velocity ABC Slotting (-21.5% Distance)",
}
break
except Exception:
pass
# Stage 3.1: Efficiency-Optimized Hybrid Facility
s3_1_dirs = [active_base / "stage_03_1_efficiency_optimized", active_base / "stage_03_1"]
for d in s3_1_dirs:
kpi_p = d / "kpis.json" if (d / "kpis.json").exists() else (d / "kpi_summary.json")
if kpi_p.exists():
try:
with open(kpi_p, "r", encoding="utf-8") as f:
kpi_data = json.load(f)
usd_p = active_base / "usd" / "stage_03_1_efficiency_optimized.usda"
if not usd_p.exists():
usd_p = d / "warehouse_efficiency_optimized.usda"
traj_p = d / "trajectory.json"
self._stage_data_cache[4] = {
"name": "Stage 3.1: Efficiency-Optimized Hybrid Facility",
"kpis": kpi_data,
"usd": str(usd_p) if usd_p.exists() else "",
"trajectory": str(traj_p) if traj_p.exists() else "",
"coordination": "Dedicated Northbound Arterial & Preventive Traffic Coordination (0 Unresolved)",
"chargers": "8 Bays (Decentralized 3/3/2 Across Zones A, B, C)",
"slotting": "Velocity ABC Slotting (-33.8% Travel Distance)",
}
break
except Exception:
pass
def select_stage(self, stage_num: int) -> None:
"""Select active demonstration stage and refresh HUD indicators."""
self._selected_stage = stage_num
self._load_staged_data()
data = self._stage_data_cache.get(stage_num)
if not data:
if self._stage_info_label:
self._stage_info_label.text = f"Stage {stage_num}: No simulation telemetry loaded yet."
return
if self._stage_info_label:
self._stage_info_label.text = f"{data['name']}\n{data.get('coordination', '')}"
if stage_num in (1, 3, 4):
kpi = data.get("kpis", {})
thru = kpi.get("throughput_tasks_per_hour", 0.0)
tt = kpi.get("turnaround_time") or kpi.get("turnaround_time_seconds") or {}
t_mean = tt.get("mean", 0.0) if isinstance(tt, dict) else 0.0
t_p50 = tt.get("p50", 0.0) if isinstance(tt, dict) else (float(tt) if isinstance(tt, (int, float)) else 0.0)
t_p90 = tt.get("p90", 0.0) if isinstance(tt, dict) else (float(tt) if isinstance(tt, (int, float)) else 0.0)
conflicts = kpi.get("conflicts_detected", 0)
unresolved = kpi.get("unresolved_conflicts", 0)
wait = kpi.get("total_yield_wait_time_seconds", kpi.get("total_yield_wait_seconds", 0.0))
tasks_comp = kpi.get("tasks_completed", kpi.get("completed_tasks", 0))
tasks_tot = kpi.get("tasks_created", kpi.get("total_tasks", self.FROZEN_WORKLOAD_TASKS))
dist = kpi.get("total_travel_distance_meters", kpi.get("total_distance_meters", 0.0))
empty_dist = kpi.get("empty_travel_distance_meters", 0.0)
loaded_dist = kpi.get("loaded_travel_distance_meters", 0.0)
energy = kpi.get("total_energy_consumed_kwh", kpi.get("total_energy_kwh", 0.0))
energy_per_task = kpi.get("energy_intensity_kwh_per_task", 0.0)
if self._kpi_thru_label:
self._kpi_thru_label.text = f"Throughput: {thru:.1f} tasks/hr"
if self._kpi_turnaround_label:
self._kpi_turnaround_label.text = f"Turnaround: mean={t_mean:.1f}s | p50={t_p50:.1f}s | p90={t_p90:.1f}s"
if self._kpi_distance_label:
self._kpi_distance_label.text = f"Travel Distance: {dist:.1f}m (Loaded: {loaded_dist:.1f}m | Empty: {empty_dist:.1f}m)"
if self._kpi_energy_label:
self._kpi_energy_label.text = f"Fleet Energy: {energy:.4f} kWh ({energy_per_task:.4f} kWh/task)"
if self._kpi_conflicts_label:
self._kpi_conflicts_label.text = f"Conflicts: {conflicts} detected | {unresolved} unmitigated"
if self._kpi_wait_label:
self._kpi_wait_label.text = f"Yield Contention Wait: {wait:.2f}s"
if self._kpi_tasks_label:
self._kpi_tasks_label.text = f"Tasks: {tasks_comp}/{tasks_tot} completed"
elif stage_num == 2:
cands = data.get("candidates", [])
cand_count = len(cands)
if self._kpi_thru_label:
self._kpi_thru_label.text = f"Candidates Evaluated: {cand_count} architectures"
if self._kpi_turnaround_label:
self._kpi_turnaround_label.text = "Variants: Baseline, Decentr Charger, Highways, Slotting, Hybrid"
if self._kpi_distance_label:
self._kpi_distance_label.text = "Circulation: One-Way High-Speed Perimeter Arterials"
if self._kpi_energy_label:
self._kpi_energy_label.text = "Charging: Decentralized 3-Zone Clusters (A, B, C)"
if self._kpi_conflicts_label:
self._kpi_conflicts_label.text = "Traffic Policy: Preventive Arbitration on all candidates"
if self._kpi_wait_label:
self._kpi_wait_label.text = "Winning Selection: Candidate 5 (Hybrid Optimal Facility)"
if self._kpi_tasks_label:
self._kpi_tasks_label.text = f"Workload: {self.FROZEN_WORKLOAD_TASKS} frozen tasks tested"
if self._window is not None:
self._window.visible = True
try:
self._window.focus()
except Exception:
pass
def open_current_stage_usd(self) -> None:
"""Open the selected stage's OpenUSD scene in Omniverse Kit viewport."""
data = self._stage_data_cache.get(self._selected_stage, {})
usd_path = data.get("usd", "")
if not usd_path or not Path(usd_path).exists():
print(f"[omni.warehouse.twin.visualizer] Stage USD not found: {usd_path}")
if self._status_label:
self._status_label.text = "Stage USD file not found."
return
if HAS_KIT:
try:
omni.usd.get_context().open_stage(str(Path(usd_path).resolve()))
print(f"[omni.warehouse.twin.visualizer] Opened USD scene in Kit: {usd_path}")
if self._status_label:
self._status_label.text = f"Loaded Stage {self._selected_stage} USD"
except Exception as e:
print(f"[omni.warehouse.twin.visualizer] Error opening USD stage: {e}")
def load_current_stage_trajectory(self) -> None:
"""Load selected stage's trajectory file into the visualizer player."""
data = self._stage_data_cache.get(self._selected_stage, {})
traj_path = data.get("trajectory", "")
if not traj_path or not Path(traj_path).exists():
print(f"[omni.warehouse.twin.visualizer] Trajectory file not found for Stage {self._selected_stage}: {traj_path}")
if self._status_label:
self._status_label.text = "Stage trajectory not found."
return
self.load_trajectory(traj_path)
def load_trajectory(self, filepath: str) -> bool:
"""Load and initialize trajectory data from JSON file."""
try:
@@ -274,25 +603,54 @@ class WarehouseVisualizerExtension(ExtBase):
)
def _build_ui(self) -> None:
"""Construct the interactive Omniverse UI window."""
self._window = ui.Window("Warehouse Twin Visualizer", width=440, height=480)
"""Construct the interactive Omniverse UI window with Staged Demo HUD."""
self._window = ui.Window("Warehouse Twin Visualizer & Optimization HUD", width=480, height=640)
self._window.visible = True
try:
self._window.focus()
except Exception:
pass
print("[omni.warehouse.twin.visualizer] Built and displayed Warehouse Twin Visualizer & Optimization HUD window.")
with self._window.frame:
with ui.VStack(spacing=8):
ui.Label("Warehouse Fleet Trajectory Playback", style={"font_size": 18})
with ui.VStack(spacing=6):
ui.Label("Warehouse Digital Twin: 3-Stage Optimization", style={"font_size": 18, "font_weight": "bold"})
# Status & File Info
# Section 1: Frozen Workload & Fleet Configuration Card
with ui.CollapsableFrame("Workload & Fleet Specification", collapsed=False):
with ui.VStack(spacing=3):
ui.Label(f"Workload: {self.FROZEN_WORKLOAD_PATH} ({self.FROZEN_WORKLOAD_TASKS} orders)", style={"color": 0xFF00DDFF})
ui.Label(f"SHA-256: {self.FROZEN_WORKLOAD_SHA256[:20]}...", style={"color": 0xFF888888, "font_size": 11})
ui.Label("Fleet: 10 AMRs (5 Light amr_light_01..05 + 5 Heavy amr_heavy_01..05)")
ui.Label("Charging: 8 Charging Bays (charge_bay_1..08 in all stages)")
# Section 2: Stage Selector & KPI Scorecard
with ui.CollapsableFrame("Three-Stage Optimization & KPI Scorecard", collapsed=False):
with ui.VStack(spacing=4):
with ui.HStack(height=32):
ui.Button("Stage 1: Baseline", clicked_fn=lambda: self.select_stage(1))
ui.Button("Stage 2: Candidates", clicked_fn=lambda: self.select_stage(2))
ui.Button("Stage 3: Optimal", clicked_fn=lambda: self.select_stage(3))
ui.Button("Stage 3.1: Efficiency", clicked_fn=lambda: self.select_stage(4))
self._stage_info_label = ui.Label("Select a stage above to view metrics", style={"font_size": 13, "font_weight": "bold"})
self._kpi_thru_label = ui.Label("Throughput: --")
self._kpi_turnaround_label = ui.Label("Turnaround: --")
self._kpi_distance_label = ui.Label("Travel Distance: --")
self._kpi_energy_label = ui.Label("Fleet Energy: --")
self._kpi_conflicts_label = ui.Label("Conflicts: --")
self._kpi_wait_label = ui.Label("Yield Wait: --")
self._kpi_tasks_label = ui.Label("Tasks: --")
with ui.HStack(height=28):
ui.Button("Load USD Scene in Kit", clicked_fn=self.open_current_stage_usd)
ui.Button("Load Stage Trajectory", clicked_fn=self.load_current_stage_trajectory)
ui.Line()
# Section 3: Interactive Trajectory Playback
ui.Label("Dynamic Kinematic AMR Playback", style={"font_size": 15, "font_weight": "bold"})
self._status_label = ui.Label("No trajectory loaded", style={"color": 0xFF888888})
# File load button
with ui.HStack(height=30):
traj_field = ui.StringField()
traj_field.model.set_value(self._trajectory_path or "results/trajectories/trajectory_default.json")
def on_load_clicked():
self.load_trajectory(traj_field.model.get_value_as_string())
ui.Button("Load", clicked_fn=on_load_clicked, width=70)
# Playback Controls
with ui.HStack(height=32):
ui.Button("▶ Play", clicked_fn=self.play)
@@ -319,13 +677,16 @@ class WarehouseVisualizerExtension(ExtBase):
self._time_slider.model.add_value_changed_fn(on_slider_changed)
ui.Line()
ui.Label("Active AMR Fleet Telemetry", style={"font_size": 14})
# Fleet HUD List
with ui.ScrollingFrame(height=180):
with ui.VStack(spacing=4):
# Section 4: AMR Fleet Live Telemetry (10 AMRs)
ui.Label("Active AMR Fleet Telemetry (10 Robots)", style={"font_size": 13})
with ui.ScrollingFrame(height=140):
with ui.VStack(spacing=3):
if self._player:
for r_id in self._player.data.get_robot_ids():
with ui.HStack():
ui.Label(f"[{r_id}]", width=110, style={"font_weight": "bold"})
self._robot_labels[r_id] = ui.Label("IDLE | Bat: 100.0% | EMPTY | (0.0, 0.0)")
# Initialize with Stage 1
self.select_stage(1)