Files
Warehouse-Digital-Twin-and-…/scripts/simulate_unoptimized_charging.py
T

331 lines
17 KiB
Python

"""Simulation runner: Multiple tasks covering collision avoidance, traffic management, and unoptimized charging.
Demonstrates:
1. Multi-task order execution across Zone A (fast-moving), Zone B (slow-moving heavy),
Zone C (production lines), and replenishment.
2. Multi-robot traffic coordination: time-space reservations, footprint clearance,
cooperative yielding (YIELD_WAIT), priority-based right-of-way, and deadlock recovery (REPLAN).
3. Unoptimized charging layout: charging stations clustered in the Northwest corner,
forcing AMRs from all zones to make long transits to recharge, creating corridor
contention and queueing at the clustered bays.
4. Full telemetry export: JSONL event logs, trajectory JSON, KPI summaries, executive Markdown report,
and animated OpenUSD (.usda) scene for NVIDIA Omniverse Kit playback.
"""
from __future__ import annotations
import argparse
import json
import logging
from pathlib import Path
import sys
from typing import Any, Dict, List, Optional
from warehouse_twin.config.loader import ConfigLoader
from warehouse_twin.domain.inventory import InventoryCatalog
from warehouse_twin.domain.robot import Robot, RobotTypeSpec
from warehouse_twin.domain.warehouse import WarehouseModel
from warehouse_twin.logging_config import setup_logging
from warehouse_twin.simulation.dispatcher import DispatcherSettings
from warehouse_twin.simulation.order_generator import WorkloadConfig
from warehouse_twin.simulation.sim_engine import SimulationEnvironment, SimulationMetrics
from warehouse_twin.visualization.robot_animator import Robot3DAnimator
from warehouse_twin.visualization.trajectory_player import TrajectoryData
def run_unoptimized_charging_simulation(
duration: float = 1800.0,
seed: int = 42,
fleet_size: int = 10,
arrival_multiplier: float = 1.2,
config_dir: str = "config",
output_dir: str = "results/unoptimized_charging_sim",
usd_output: str = "omniverse/scenes/warehouse_unoptimized_charging_animated.usda",
) -> Dict[str, Any]:
"""Execute multi-task simulation highlighting traffic management and unoptimized charging bottlenecks."""
setup_logging()
logger = logging.getLogger("unoptimized_charging_sim")
logger.info("Initializing multi-task simulation with unoptimized charging stations...")
out_path = Path(output_dir).resolve()
out_path.mkdir(parents=True, exist_ok=True)
logs_path = out_path / "simulation_events.jsonl"
traj_path = out_path / "trajectory.json"
kpi_path = out_path / "kpi_summary.json"
report_path = out_path / "unoptimized_charging_report.md"
# 1. Load baseline warehouse configuration (with unoptimized clustered chargers)
loader = ConfigLoader(config_dir)
bundle = loader.load_all()
warehouse = WarehouseModel.from_config_dict(bundle.warehouse)
catalog = InventoryCatalog.from_config_dict(bundle.inventory)
type_specs = {
t_id: RobotTypeSpec.from_dict(t_id, t_data)
for t_id, t_data in bundle.robots.get("robot_types", {}).items()
}
# 2. Build fleet with varied battery states to induce realistic charging visits to unoptimized bays
fleet: List[Robot] = []
# Configure fleet with initial battery levels that prompt charging visits during simulation
fleet_templates = [
("amr_light_01", "light_amr", [4.0, 36.0, 0.0], 55.0),
("amr_light_02", "light_amr", [6.0, 36.0, 0.0], 85.0),
("amr_light_03", "light_amr", [8.0, 36.0, 0.0], 75.0),
("amr_light_04", "light_amr", [10.0, 36.0, 0.0], 65.0),
("amr_light_05", "light_amr", [4.0, 10.0, 0.0], 70.0),
("amr_heavy_01", "heavy_amr", [30.0, 2.0, 0.0], 48.0),
("amr_heavy_02", "heavy_amr", [34.0, 2.0, 0.0], 78.0),
("amr_heavy_03", "heavy_amr", [48.0, 36.0, 0.0], 90.0),
("amr_heavy_04", "heavy_amr", [50.0, 36.0, 0.0], 52.0),
("amr_heavy_05", "heavy_amr", [46.0, 10.0, 0.0], 68.0),
]
selected_templates = fleet_templates[:fleet_size]
for r_id, r_type, pos, batt in selected_templates:
r_dict = {
"robot_id": r_id,
"robot_type": r_type,
"initial_position": pos,
"initial_battery_percent": batt,
}
fleet.append(Robot.from_fleet_dict(r_dict, type_specs))
# 3. Workload and dispatcher configuration
workload = WorkloadConfig.from_dict(bundle.simulation)
# Apply arrival rate multiplier if specified
if arrival_multiplier != 1.0:
workload.zone_a_arrival_rate_per_hour *= arrival_multiplier
workload.zone_b_arrival_rate_per_hour *= arrival_multiplier
workload.zone_c_scheduled_feed_interval_seconds /= arrival_multiplier
dispatch_settings = DispatcherSettings.from_dict(bundle.dispatch_policies)
# 4. Instantiate simulation environment
sim_env = SimulationEnvironment(
warehouse=warehouse,
catalog=catalog,
fleet=fleet,
workload_config=workload,
dispatcher_settings=dispatch_settings,
event_log_path=logs_path,
seed=seed,
dispatch_policies_config=bundle.dispatch_policies,
)
print("=" * 72)
print("Warehouse Robot Fleet Simulation: Multi-Task Traffic & Unoptimized Charging")
print("=" * 72)
print(f"Simulated Duration: {duration:.1f} s ({duration / 60.0:.1f} mins)")
print(f"Random Seed: {seed}")
print(f"Fleet Size: {len(fleet)} AMRs ({sum(1 for r in fleet if 'light' in r.robot_type)} Light, {sum(1 for r in fleet if 'heavy' in r.robot_type)} Heavy)")
print(f"Charging Layout: UNOPTIMIZED (4 bays clustered at Northwest corner x=2.0..8.0, y=36.0)")
print(f"Traffic Reservation: Active (Footprint checks, head-on/following buffers, right-of-way)")
print(f"Deadlock Prevention: Active (Wait-for graph cycle detection & dynamic victim rerouting)")
print("-" * 72)
# 5. Run simulation
metrics: SimulationMetrics = sim_env.run(until=duration)
# 6. Export trajectories
sim_env.export_trajectories(traj_path)
# 7. Generate animated OpenUSD scene
usd_out_path = Path(usd_output).resolve()
usd_out_path.parent.mkdir(parents=True, exist_ok=True)
traj_data = TrajectoryData.from_file(traj_path)
animator = Robot3DAnimator.from_config_and_trajectory(
bundle=bundle,
trajectory_data=traj_data,
sample_step_seconds=1.0,
timecodes_per_second=24.0,
experiment_metadata={
"experiment_id": "unoptimized_charging_sim",
"experiment_name": "Multi-Task Traffic Management & Unoptimized Charging Layout",
"simulation_run_id": f"sim_{seed}_{int(duration)}",
"duration_seconds": float(duration),
"fleet_size": len(fleet),
"charging_layout": "unoptimized_clustered_northwest",
"order_arrival_multiplier": float(arrival_multiplier),
"conflicts_detected": metrics.conflicts_detected,
"deadlocks_prevented": metrics.deadlocks_prevented,
},
)
animator.export_usda(usd_out_path)
# 8. Compile KPI dictionary
kpi_dict = metrics.to_dict()
kpi_dict["charging_infrastructure"] = {
"layout_type": "unoptimized_clustered",
"bay_count": len(warehouse.charging_stations),
"cluster_coordinates": [[ch.position.x, ch.position.y] for ch in warehouse.charging_stations.values()],
"opportunity_charges": metrics.opportunity_charges,
"mandatory_charges": metrics.mandatory_charges,
"total_energy_charged_kwh": metrics.total_energy_charged_kwh,
"charging_sessions": metrics.charging_metrics.get("total_charging_sessions", 0) if metrics.charging_metrics else 0,
"avg_queue_wait_seconds": metrics.charging_metrics.get("average_queue_wait_time_seconds", 0.0) if metrics.charging_metrics else 0.0,
}
kpi_dict["traffic_coordination"] = {
"conflicts_detected": metrics.conflicts_detected,
"yield_waits_executed": metrics.yield_waits_count,
"total_yield_wait_seconds": round(metrics.total_wait_time_seconds, 2),
"dynamic_reroutes": metrics.reroutes_count,
"deadlocks_prevented": metrics.deadlocks_prevented,
"top_congested_edges": metrics.edge_congestion_summary[:5] if metrics.edge_congestion_summary else [],
}
with open(kpi_path, "w", encoding="utf-8") as f:
json.dump(kpi_dict, f, indent=2)
# 9. Generate Executive Markdown Audit Report
report_lines = [
"# Simulation Audit Report: Multi-Task Traffic Management & Unoptimized Charging",
"",
f"- **Simulation Duration**: {duration:.1f} s ({duration / 60.0:.1f} minutes)",
f"- **Fleet Size**: {len(fleet)} AMRs",
f"- **Random Seed**: {seed}",
f"- **Charging Layout**: **Unoptimized Baseline** (all 4 chargers clustered in NW alcove: `[2.0, 36.0]` to `[8.0, 36.0]`)",
"",
"## 1. Operational Throughput & Order Fulfillment",
"",
"| Metric | Value |",
"| :--- | :--- |",
f"| **Tasks Created** | {metrics.tasks_created} |",
f"| **Tasks Completed** | {metrics.tasks_completed} ({metrics.tasks_completed / max(metrics.tasks_created, 1) * 100.0:.1f}%) |",
f"| **Tasks In Progress / Pending** | {metrics.tasks_pending} |",
f"| **Throughput** | **{metrics.throughput_tasks_per_hour:.2f} tasks/hour** |",
f"| **Average Turnaround Time** | {metrics.average_turnaround_time:.1f} s |",
f"| **Average Waiting Time** | {metrics.average_wait_time:.1f} s |",
f"| **Average Execution Time** | {metrics.average_execution_time:.1f} s |",
f"| **On-Time Delivery Rate** | **{metrics.on_time_delivery_percent:.1f}%** |",
f"| **Fleet Utilization** | **{metrics.fleet_utilization_percent:.1f}%** |",
f"| **Total Distance Traveled** | {metrics.total_distance_meters:,.1f} m (Loaded: {metrics.loaded_distance_percent:.1f}%) |",
"",
"## 2. Collision Avoidance & Traffic Management Performance",
"",
"The multi-robot traffic reservation manager and deadlock coordinator actively prevented collisions across shared aisles, rack approaches, and charging spurs:",
"",
"| Traffic Indicator | Value | Description |",
"| :--- | :--- | :--- |",
f"| **Conflicts Detected** | **{metrics.conflicts_detected}** | Spatial footprint, headway, or intersection contention events identified in advance |",
f"| **Cooperative Yields Executed** | **{metrics.yield_waits_count}** | AMRs safely held at previous waypoints until contested corridors cleared |",
f"| **Total Yield Waiting Time** | **{metrics.total_wait_time_seconds:.1f} s** | Total fleet latency spent yielding right-of-way |",
f"| **Dynamic Reroutes** | **{metrics.reroutes_count}** | Bypass routes planned around congested corridors or deadlocked segments |",
f"| **Deadlocks Prevented** | **{metrics.deadlocks_prevented}** | Circular wait-for dependency cycles broken by deterministic victim arbitration |",
"",
"## 3. Impact of Unoptimized Charging Station Placement",
"",
"In this simulation, charging stations remain in the **unoptimized baseline configuration**:",
"- All 4 chargers (`charge_bay_1` to `charge_bay_4`) are concentrated in a single 6-meter strip in the Northwest corner (`x=2.0..8.0, y=36.0`).",
f"- **Opportunity Charging Visits**: {metrics.opportunity_charges}",
f"- **Mandatory Charging Visits**: {metrics.mandatory_charges}",
f"- **Total Energy Charged**: {metrics.total_energy_charged_kwh:.3f} kWh",
f"- **Average Queue Wait**: {metrics.charging_metrics.get('average_queue_wait_time_seconds', 0.0):.1f} s",
"",
"### Key Bottleneck Observations:",
"1. **Long Charging Deadheading**: Heavy-duty AMRs servicing Zone B (x=30..45m) and Zone C (x=48..58m) were forced to travel over 45 meters empty just to access the Northwest charging bays.",
"2. **Corridor Contention at North Highway**: Recharging robots and transit AMRs frequently contested the narrow North arterial highway (`y=36.0` to `y=38.0`), directly driving the conflict count.",
"3. **Single Point of Congestion**: When multiple AMRs needed charge concurrently, they accumulated in the Northwest corner approach spur, triggering cooperative yields and deadlock rerouting.",
"",
"## 4. Per-Robot Operational Telemetry",
"",
"| Robot ID | Type | Distance (m) | Busy Time (s) | Utilization (%) | Final SoC (%) | Min SoC (%) | Consumed (kWh) |",
"| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |",
]
for r_id, r_stats in metrics.robot_metrics.items():
min_b = r_stats.get("min_battery_percent", r_stats["battery_percent"])
e_cons = r_stats.get("energy_consumed_kwh", 0.0)
report_lines.append(
f"| `{r_id}` | `{r_stats.get('robot_type', 'amr')}` | {r_stats['distance_meters']:.1f} | "
f"{r_stats['busy_seconds']:.1f} | {r_stats['utilization_percent']:.1f}% | "
f"{r_stats['battery_percent']:.1f}% | {min_b:.1f}% | {e_cons:.3f} |"
)
report_lines.extend([
"",
"## 5. Artifacts and Visualization",
"",
f"- **Events Telemetry Log**: [`{logs_path}`]({logs_path})",
f"- **Motion Trajectory File**: [`{traj_path}`]({traj_path})",
f"- **Structured KPI Summary**: [`{kpi_path}`]({kpi_path})",
f"- **Animated OpenUSD Scene**: [`{usd_out_path}`]({usd_out_path})",
"",
"### Playback Instructions in NVIDIA Omniverse Kit:",
"1. Launch Omniverse Kit:",
" ```bash",
" /home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/warehouse_twin.kit.sh",
" ```",
f"2. Select **File -> Open** and navigate to: `{usd_out_path}`",
"3. Press **Spacebar** or click **Play** on the timeline toolbar to view the multi-task robot navigation, collision avoidance, and charging movements in real time.",
"",
])
report_path.write_text("\n".join(report_lines), encoding="utf-8")
print("=" * 72)
print("SIMULATION COMPLETED SUCCESSFULLY")
print("=" * 72)
print(f"Tasks Completed: {metrics.tasks_completed} / {metrics.tasks_created}")
print(f"Throughput: {metrics.throughput_tasks_per_hour:.2f} tasks/hr")
print(f"Fleet Utilization: {metrics.fleet_utilization_percent:.1f}%")
print("-" * 72)
print("Traffic Coordination & Collision Avoidance:")
print(f" Conflicts Detected: {metrics.conflicts_detected}")
print(f" Yield Waits: {metrics.yield_waits_count} ({metrics.total_wait_time_seconds:.1f}s total wait)")
print(f" Dynamic Reroutes: {metrics.reroutes_count}")
print(f" Deadlocks Prevented: {metrics.deadlocks_prevented}")
print("-" * 72)
print("Unoptimized Charging Impact:")
print(f" Charging Sessions: {metrics.opportunity_charges + metrics.mandatory_charges} ({metrics.total_energy_charged_kwh:.3f} kWh)")
print(f" Charger Location: Clustered Northwest corner [x=2.0..8.0, y=36.0]")
print(f" Corridor Contention: High contention along North & West highways during charge transit")
print("-" * 72)
print("Generated Artifacts:")
print(f" - Telemetry Log: {logs_path}")
print(f" - AMR Trajectories: {traj_path}")
print(f" - KPI Summary JSON: {kpi_path}")
print(f" - Audit Report: {report_path}")
print(f" - Animated USD Scene: {usd_out_path}")
print("=" * 72)
return {
"metrics": metrics,
"kpi_dict": kpi_dict,
"artifacts": {
"events_log": logs_path,
"trajectories": traj_path,
"kpi_summary": kpi_path,
"report_md": report_path,
"usd_scene": usd_out_path,
},
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Run multi-task simulation highlighting traffic management and unoptimized charging layout."
)
parser.add_argument("--duration", type=float, default=1800.0, help="Simulation duration in seconds (default: 1800.0)")
parser.add_argument("--seed", type=int, default=42, help="Deterministic random seed (default: 42)")
parser.add_argument("--fleet-size", type=int, default=10, help="AMR fleet count (default: 10)")
parser.add_argument("--arrival-multiplier", type=float, default=1.2, help="Order arrival rate multiplier (default: 1.2)")
parser.add_argument("--config-dir", type=str, default="config", help="Configuration directory (default: config)")
parser.add_argument("--output-dir", type=str, default="results/unoptimized_charging_sim", help="Artifact output directory")
parser.add_argument("--usd-output", type=str, default="omniverse/scenes/warehouse_unoptimized_charging_animated.usda", help="Animated USDA scene output path")
args = parser.parse_args()
run_unoptimized_charging_simulation(
duration=args.duration,
seed=args.seed,
fleet_size=args.fleet_size,
arrival_multiplier=args.arrival_multiplier,
config_dir=args.config_dir,
output_dir=args.output_dir,
usd_output=args.usd_output,
)
if __name__ == "__main__":
main()