feat(phase-4): implement spatial routing, time-space reservations, and traffic manager

- Implemented PathPlanner using NetworkX Dijkstra/A* with dynamic edge congestion weights and robot capability enforcement.
- Implemented TimeSpaceReservationGrid with head-on collision avoidance on bidirectional corridors and 1.0s following headway buffers.
- Implemented TrafficManager with multi-AMR right-of-way arbitration (task priority, loaded over empty) and deadlock timeout dynamic rerouting.
- Integrated waypoint traversal into SimPy simulation engine with real-time trajectory recording and export.
- Generated omniverse/scenes/warehouse_phase4.usda with navigation corridor overlays.
- Expanded test suite to 95 unit tests with 100% pass rate.
This commit is contained in:
2026-10-21 10:59:11 +05:30
parent 3d9fb6be66
commit 56806079a9
20 changed files with 3225 additions and 104 deletions
+24 -3
View File
@@ -198,8 +198,8 @@ def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = No
loader = ConfigLoader(config_dir)
bundle = loader.load_all()
generator = WarehouseUSDGenerator.from_config_bundle(bundle)
default_out = Path("omniverse/scenes/warehouse_phase2.usda")
generator = WarehouseUSDGenerator.from_config_bundle(bundle, include_routing_network=True)
default_out = Path("omniverse/scenes/warehouse_phase4.usda")
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
saved_path = generator.export_usda(out_file)
@@ -231,6 +231,7 @@ def run_simulation(
duration: Optional[float] = None,
seed: Optional[int] = None,
events_output: Optional[str] = None,
trajectories_output: Optional[str] = None,
) -> int:
"""Run discrete-event simulation and report operational KPIs."""
setup_logging()
@@ -277,6 +278,7 @@ def run_simulation(
print(f"Fleet Size: {len(fleet)} AMRs")
print(f"Inventory: {len(catalog.items)} SKUs")
print(f"Zone B Aisles: 4.0m wide aisles (slow-moving & specialized)")
print(f"Routing Grid: NetworkX Time-Space Reservation + Cooperative Yielding")
print(f"Telemetry Log: {log_out}")
print("-" * 65)
@@ -288,10 +290,15 @@ def run_simulation(
dispatcher_settings=dispatch_settings,
event_log_path=log_out,
seed=sim_seed,
dispatch_policies_config=bundle.dispatch_policies,
)
metrics = sim_env.run(until=sim_duration)
# Trajectory export
traj_out = Path(trajectories_output).resolve() if trajectories_output else Path("results/trajectories/trajectory_sim.json").resolve()
traj_saved = sim_env.export_trajectories(traj_out)
print("Simulation Completed Successfully!")
print("=" * 65)
print("OPERATIONAL KPI REPORT")
@@ -307,6 +314,14 @@ def run_simulation(
print(f"Fleet Utilization: {metrics.fleet_utilization_percent:.1f}%")
print(f"Replenishment Triggers: {metrics.replenishment_triggers}")
print("-" * 65)
print("Traffic Management & Collision Avoidance (Phase 4):")
print(f" Conflicts Detected: {metrics.conflicts_detected}")
print(f" Yield Waits Executed: {metrics.yield_waits_count}")
print(f" Total Yield Wait Time: {metrics.total_wait_time_seconds:.1f} s")
print(f" Dynamic Reroutes: {metrics.reroutes_count}")
print(f" Deadlocks Prevented: {metrics.deadlocks_prevented}")
print(f" Trajectory File: {traj_saved}")
print("-" * 65)
print("Per-Robot Utilization:")
for r_id, r_stats in metrics.robot_metrics.items():
print(f" {r_id:14s}: distance={r_stats['distance_meters']:.1f}m, busy={r_stats['busy_seconds']:.1f}s, util={r_stats['utilization_percent']:.1f}%, battery={r_stats['battery_percent']:.1f}%")
@@ -409,6 +424,12 @@ def main(argv: Optional[list[str]] = None) -> int:
default=None,
help="Output path for telemetry events JSONL (defaults to logs/simulation_events.jsonl)",
)
sim_parser.add_argument(
"--output-trajectories",
type=str,
default=None,
help="Output path for robot motion trajectory JSON (defaults to results/trajectories/trajectory_sim.json)",
)
args = parser.parse_args(argv)
@@ -423,7 +444,7 @@ def main(argv: Optional[list[str]] = None) -> int:
elif args.command == "export-usd":
return export_usd(args.config_dir, args.output)
elif args.command == "run-sim":
return run_simulation(args.config_dir, args.duration, args.seed, args.output_events)
return run_simulation(args.config_dir, args.duration, args.seed, args.output_events, args.output_trajectories)
else:
parser.print_help()
return 0
+6
View File
@@ -21,6 +21,12 @@ class SimulationEventType(str, Enum):
ROBOT_DISPATCHED = "ROBOT_DISPATCHED"
ROBOT_STATE_CHANGED = "ROBOT_STATE_CHANGED"
ROBOT_ARRIVED = "ROBOT_ARRIVED"
ROBOT_PATH_PLANNED = "ROBOT_PATH_PLANNED"
ROBOT_WAYPOINT_REACHED = "ROBOT_WAYPOINT_REACHED"
TRAFFIC_YIELD = "TRAFFIC_YIELD"
TRAFFIC_CONGESTION = "TRAFFIC_CONGESTION"
ROBOT_REROUTED = "ROBOT_REROUTED"
DEADLOCK_RESOLVED = "DEADLOCK_RESOLVED"
ROBOT_CHARGING_STARTED = "ROBOT_CHARGING_STARTED"
ROBOT_CHARGING_START = "ROBOT_CHARGING_STARTED"
ROBOT_CHARGING_COMPLETED = "ROBOT_CHARGING_COMPLETED"
+50 -3
View File
@@ -21,13 +21,19 @@ class WarehouseUSDGenerator:
self,
model: WarehouseModel,
robots: Optional[List[Robot]] = None,
include_routing_network: bool = True,
) -> None:
"""Initialize generator with physical warehouse layout model and optional robot fleet."""
"""Initialize generator with physical warehouse layout model, optional robot fleet, and routing visualizer."""
self.model = model
self.robots = robots or []
self.include_routing_network = include_routing_network
@classmethod
def from_config_bundle(cls, bundle: Any) -> WarehouseUSDGenerator:
def from_config_bundle(
cls,
bundle: Any,
include_routing_network: bool = True,
) -> WarehouseUSDGenerator:
"""Construct generator loading both warehouse layout and fleet from ConfigBundle."""
model = WarehouseModel.from_config_dict(bundle.warehouse)
@@ -41,7 +47,7 @@ class WarehouseUSDGenerator:
for r_data in bundle.robots.get("fleet", []):
robots.append(Robot.from_fleet_dict(r_data, type_specs))
return cls(model, robots)
return cls(model, robots, include_routing_network=include_routing_network)
def generate_usda_content(self) -> str:
"""Construct valid ASCII OpenUSD 3D stage content representing the warehouse and AMRs."""
@@ -268,6 +274,47 @@ class WarehouseUSDGenerator:
" }",
])
# -------------------------------------------------------------------------
# Topological Navigation Network & Corridor Highways (Phase 4 Addition)
# -------------------------------------------------------------------------
if self.include_routing_network:
lines.extend([
"",
" # -------------------------------------------------------------------------",
" # Topological Navigation Corridors & Wide Aisles (Phase 4)",
" # -------------------------------------------------------------------------",
' def Scope "NavigationNetwork"',
" {",
])
corridors = [
("Highway_West_Dock", 2.0, 20.0, 0.4, 36.0, "(0.25, 0.65, 0.95)"),
("Highway_Transfer_AB", 26.0, 20.0, 0.4, 36.0, "(0.35, 0.75, 0.95)"),
("Highway_Transfer_BC", 46.0, 20.0, 0.4, 36.0, "(0.35, 0.75, 0.95)"),
("Highway_East_Perimeter", 58.0, 20.0, 0.4, 36.0, "(0.25, 0.65, 0.95)"),
("Highway_South_Picking", 30.0, 2.0, 56.0, 0.4, "(0.25, 0.7, 0.85)"),
("Highway_North_Charging", 30.0, 38.0, 56.0, 0.4, "(0.25, 0.7, 0.85)"),
("Aisle_B1_Wide_Aisle", 34.0, 20.0, 0.5, 28.0, "(0.95, 0.65, 0.15)"),
("Aisle_B2_Wide_Aisle", 40.0, 20.0, 0.5, 28.0, "(0.95, 0.65, 0.15)"),
]
for name, cx, cy, sx, sy, col in corridors:
lines.extend([
f' def Xform "{name}"',
" {",
f" double3 xformOp:translate = ({cx:.2f}, {cy:.2f}, 0.01)",
f" double3 xformOp:scale = ({sx / 2.0:.3f}, {sy / 2.0:.3f}, 0.005)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
"",
' def Cube "LaneVisualizer"',
" {",
f" color3f[] primvars:displayColor = [{col}]",
" float[] primvars:displayRoughness = [0.8]",
" }",
" }",
])
lines.extend([
" }",
])
# -------------------------------------------------------------------------
# Autonomous Mobile Robot (AMR) Fleet (Phase 2 Addition)
# -------------------------------------------------------------------------
+23 -1
View File
@@ -1,4 +1,4 @@
"""Routing and warehouse topology package for Warehouse Digital Twin."""
"""Routing, path planning, and traffic coordination package for Warehouse Digital Twin."""
from warehouse_twin.routing.graph_builder import (
ConnectivityReport,
@@ -7,6 +7,20 @@ from warehouse_twin.routing.graph_builder import (
WarehouseGraphBuilder,
WarehouseGraphError,
)
from warehouse_twin.routing.path_planner import (
NoPathFoundError,
PathPlanner,
PathPlanningError,
)
from warehouse_twin.routing.reservations import (
EdgeReservation,
NodeReservation,
TimeSpaceReservationGrid,
)
from warehouse_twin.routing.traffic_manager import (
TrafficManager,
TraversalDecision,
)
__all__ = [
"ConnectivityReport",
@@ -14,4 +28,12 @@ __all__ = [
"UnreachableStationError",
"WarehouseGraphBuilder",
"WarehouseGraphError",
"NoPathFoundError",
"PathPlanner",
"PathPlanningError",
"EdgeReservation",
"NodeReservation",
"TimeSpaceReservationGrid",
"TrafficManager",
"TraversalDecision",
]
+279
View File
@@ -0,0 +1,279 @@
"""Path planning subsystem: NetworkX-powered shortest path calculation and reachability.
Enforces:
- Dijkstra / A* shortest path search on directed navigation graph.
- Robot capability and class restrictions (e.g. Zone B heavy AMR restriction).
- Dynamic edge weighting incorporating congestion and traffic load.
- Avoidance of dynamic obstacles, contested nodes, and blocked aisles.
- Fail-fast unreachable destination detection with descriptive diagnostic exceptions.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
import networkx as nx
from warehouse_twin.domain.warehouse import Position3D
class PathPlanningError(Exception):
"""Base exception for path planning errors."""
pass
class NoPathFoundError(PathPlanningError):
"""Raised when no traversable path exists between two waypoints for a robot class."""
def __init__(
self,
source: str,
target: str,
robot_type: str,
reason: Optional[str] = None,
) -> None:
self.source = source
self.target = target
self.robot_type = robot_type
self.reason = reason or "Graph topology or movement restrictions prevent traversal"
super().__init__(
f"No path found from '{source}' to '{target}' for robot type '{robot_type}': {self.reason}"
)
class PathPlanner:
"""Calculates optimal collision-free paths over the warehouse navigation graph."""
def __init__(self, graph: nx.DiGraph) -> None:
"""Initialize the path planner with a pre-built navigation graph."""
self.graph = graph
self._node_positions: Dict[str, Position3D] = {}
self._cache_positions()
def _cache_positions(self) -> None:
"""Cache Position3D representations and entity ID mappings for all graph nodes."""
self._entity_to_node: Dict[str, str] = {}
for nid, data in self.graph.nodes(data=True):
p = data.get("pos")
if p:
self._node_positions[nid] = Position3D(float(p[0]), float(p[1]), float(p[2]))
for k in ("station_id", "location_id", "rack_id", "charger_id"):
if k in data:
self._entity_to_node[data[k]] = nid
def resolve_node_id(self, entity_or_node: str) -> str:
"""Resolve an entity identifier or alias to its canonical graph node ID."""
if self.graph.has_node(entity_or_node):
return entity_or_node
if hasattr(self, "_entity_to_node") and entity_or_node in self._entity_to_node:
return self._entity_to_node[entity_or_node]
for prefix in ("station_", "rack_", "charger_"):
cand = f"{prefix}{entity_or_node}"
if self.graph.has_node(cand):
self._entity_to_node[entity_or_node] = cand
return cand
raise KeyError(f"Node or entity '{entity_or_node}' does not exist in graph")
def get_node_position(self, node_id: str) -> Position3D:
"""Return 3D coordinates for a graph node."""
nid = self.resolve_node_id(node_id) if not self.graph.has_node(node_id) else node_id
if nid in self._node_positions:
return self._node_positions[nid]
p = self.graph.nodes[nid].get("pos", (0.0, 0.0, 0.0))
pos = Position3D(float(p[0]), float(p[1]), float(p[2]))
self._node_positions[nid] = pos
return pos
def get_closest_node(
self,
position: Position3D,
robot_type: Optional[str] = None,
) -> str:
"""Find the nearest traversable node to the given coordinate.
Args:
position: Query 3D coordinate.
robot_type: Optional robot class filter to prevent picking an inaccessible node.
Returns:
Closest node ID.
Raises:
PathPlanningError: If the graph contains no nodes.
"""
if not self.graph.nodes:
raise PathPlanningError("Cannot find closest node in an empty graph")
best_node = None
best_sq_dist = float("inf")
for nid, pos in self._node_positions.items():
# If robot_type is specified and the node is restricted, check incident edges
if robot_type:
node_data = self.graph.nodes[nid]
zone = node_data.get("zone")
# Zone B internal nodes are restricted from light_amr
if zone == "zone_b" and robot_type == "light_amr":
continue
dx = pos.x - position.x
dy = pos.y - position.y
sq_dist = dx * dx + dy * dy
if sq_dist < best_sq_dist:
best_sq_dist = sq_dist
best_node = nid
if best_node is None:
# Fallback to any closest node if filter was overly restrictive
for nid, pos in self._node_positions.items():
dx = pos.x - position.x
dy = pos.y - position.y
sq_dist = dx * dx + dy * dy
if sq_dist < best_sq_dist:
best_sq_dist = sq_dist
best_node = nid
return best_node # type: ignore[return-value]
def is_destination_reachable(
self,
source: str,
target: str,
robot_type: str = "light_amr",
) -> bool:
"""Check whether a traversable path exists without raising an exception."""
try:
self.find_shortest_path(source, target, robot_type=robot_type)
return True
except (NoPathFoundError, PathPlanningError, KeyError):
return False
def find_shortest_path(
self,
source: str,
target: str,
robot_type: str = "light_amr",
weight_mode: str = "traversal_time",
avoid_nodes: Optional[Set[str]] = None,
avoid_edges: Optional[Set[Tuple[str, str]]] = None,
dynamic_edge_weights: Optional[Dict[Tuple[str, str], float]] = None,
) -> List[str]:
"""Compute the optimal path from source to target using NetworkX.
Enforces:
- Class restriction: Edges must permit `robot_type` in `allowed_robot_types`.
- Dynamic avoidance: Excludes `avoid_nodes` and `avoid_edges`.
- Dynamic weights: Injects congestion penalties from `dynamic_edge_weights`.
Args:
source: Starting waypoint node ID.
target: Destination waypoint node ID.
robot_type: AMR type ('light_amr' or 'heavy_amr').
weight_mode: 'traversal_time' (default) or 'distance'.
avoid_nodes: Optional set of node IDs to steer around.
avoid_edges: Optional set of directed or undirected edge tuples to avoid.
dynamic_edge_weights: Mapping of (u, v) -> extra cost penalty.
Returns:
List of node IDs forming the planned path [source, ..., target].
Raises:
NoPathFoundError: If no valid route exists.
KeyError: If source or target node is missing from graph.
"""
source_nid = self.resolve_node_id(source)
target_nid = self.resolve_node_id(target)
if source_nid == target_nid:
return [source_nid]
blocked_nodes = avoid_nodes or set()
blocked_edges = avoid_edges or set()
extra_weights = dynamic_edge_weights or {}
def edge_weight_evaluator(u: str, v: str, edge_data: Dict[str, Any]) -> Optional[float]:
# 1. Avoidance filters
if v != target_nid and v in blocked_nodes:
return None
if u != source_nid and u in blocked_nodes:
return None
if (u, v) in blocked_edges or (v, u) in blocked_edges:
return None
# 2. Robot type capability filter
allowed = edge_data.get("allowed_robot_types")
if allowed is not None and robot_type not in allowed:
return None
# 3. Base cost
if weight_mode == "distance":
base_cost = float(edge_data.get("distance", 1.0))
else:
base_cost = float(edge_data.get("traversal_time", 1.0))
# 4. Congestion penalty
penalty = extra_weights.get((u, v), 0.0)
return max(base_cost + penalty, 0.01)
# Build subview or filtered graph for NetworkX search
try:
path = nx.shortest_path(
self.graph,
source=source_nid,
target=target_nid,
weight=edge_weight_evaluator,
)
return path
except (nx.NetworkXNoPath, nx.NodeNotFound) as err:
raise NoPathFoundError(
source=source,
target=target,
robot_type=robot_type,
reason=f"No viable route found: {err}",
) from err
def compute_path_distance(self, path: List[str]) -> float:
"""Calculate total physical length in meters of a planned path."""
if len(path) < 2:
return 0.0
total = 0.0
for i in range(len(path) - 1):
u, v = path[i], path[i + 1]
if self.graph.has_edge(u, v):
total += self.graph[u][v].get("distance", 0.0)
else:
# Direct Euclidean fallback
p1 = self.get_node_position(u)
p2 = self.get_node_position(v)
total += p1.distance_to(p2)
return round(total, 3)
def compute_path_duration(
self,
path: List[str],
robot_speed: Optional[float] = None,
) -> float:
"""Estimate traversal duration in seconds considering edge speed limits and robot max speed."""
if len(path) < 2:
return 0.0
total_time = 0.0
for i in range(len(path) - 1):
u, v = path[i], path[i + 1]
if self.graph.has_edge(u, v):
edge = self.graph[u][v]
dist = float(edge.get("distance", 1.0))
limit = float(edge.get("speed_limit", 1.5))
effective_speed = min(limit, robot_speed) if robot_speed else limit
total_time += dist / max(effective_speed, 0.1)
else:
p1 = self.get_node_position(u)
p2 = self.get_node_position(v)
effective_speed = robot_speed or 1.5
total_time += p1.distance_to(p2) / max(effective_speed, 0.1)
return round(total_time, 3)
def path_to_positions(self, path: List[str]) -> List[Position3D]:
"""Convert a list of node IDs to a list of Position3D coordinates."""
return [self.get_node_position(nid) for nid in path]
+314
View File
@@ -0,0 +1,314 @@
"""Time-space reservation grid: collision avoidance for shared aisles and intersections.
Enforces:
- Temporal reservation of navigation nodes and directional/bidirectional edges.
- Head-on collision avoidance: Prohibits opposite-direction traversals of shared aisles.
- Rear-end collision avoidance: Enforces safety time-headway buffers between robots.
- Intersection exclusive zones: Guarantees single-occupancy of conflict waypoints.
- Dynamic slot search for earliest safe departure and conflict resolution.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set, Tuple
@dataclass
class NodeReservation:
"""Temporal reservation of a single navigation graph waypoint."""
node_id: str
start_time: float
end_time: float
robot_id: str
priority: int = 1
task_id: Optional[str] = None
def overlaps_with(
self,
t_start: float,
t_end: float,
buffer_seconds: float = 0.0,
) -> bool:
"""Check if time window [t_start - buffer, t_end + buffer] intersects this slot."""
effective_start = self.start_time - buffer_seconds
effective_end = self.end_time + buffer_seconds
return max(effective_start, t_start) < min(effective_end, t_end)
@dataclass
class EdgeReservation:
"""Temporal reservation of an aisle or corridor edge segment."""
u: str
v: str
start_time: float
end_time: float
robot_id: str
priority: int = 1
@property
def canonical_key(self) -> Tuple[str, str]:
"""Undirected edge key to detect opposite-direction traversal on physical aisle."""
return (min(self.u, self.v), max(self.u, self.v))
def is_head_on_conflict(
self,
u_req: str,
v_req: str,
t_start: float,
t_end: float,
buffer_seconds: float = 0.0,
) -> bool:
"""True if requested traversal is opposite-direction (v->u) and temporally overlapping."""
if self.u == v_req and self.v == u_req:
# Opposite direction! Any overlap in physical aisle is a head-on collision
return max(self.start_time - buffer_seconds, t_start) < min(self.end_time + buffer_seconds, t_end)
return False
def is_following_conflict(
self,
u_req: str,
v_req: str,
t_start: float,
t_end: float,
headway_buffer_seconds: float = 1.0,
) -> bool:
"""True if requested traversal is same-direction (u->v) and violates headway buffer or overtakes."""
if self.u == u_req and self.v == v_req:
# 1. Entry headway buffer
if abs(self.start_time - t_start) < headway_buffer_seconds:
return True
# 2. Exit headway buffer
if abs(self.end_time - t_end) < headway_buffer_seconds:
return True
# 3. Overtaking prevention
if self.start_time < t_start and self.end_time > t_end:
return True
if t_start < self.start_time and t_end > self.end_time:
return True
return False
class TimeSpaceReservationGrid:
"""Coordinates space-time reservations across all warehouse nodes and edges."""
def __init__(
self,
safety_buffer_seconds: float = 1.0,
intersection_exclusive_radius: float = 2.0,
) -> None:
"""Initialize reservation manager with configurable safety buffers."""
self.safety_buffer_seconds = safety_buffer_seconds
self.intersection_exclusive_radius = intersection_exclusive_radius
# Map: node_id -> list of NodeReservation
self.node_reservations: Dict[str, List[NodeReservation]] = {}
# Map: canonical_edge_key -> list of EdgeReservation
self.edge_reservations: Dict[Tuple[str, str], List[EdgeReservation]] = {}
def is_node_free(
self,
node_id: str,
t_start: float,
t_end: float,
ignore_robot_id: Optional[str] = None,
) -> Tuple[bool, Optional[str]]:
"""Check if node_id is available during [t_start, t_end].
Returns:
Tuple of (is_free, conflicting_robot_id).
"""
slots = self.node_reservations.get(node_id, [])
for slot in slots:
if ignore_robot_id and slot.robot_id == ignore_robot_id:
continue
if slot.overlaps_with(t_start, t_end, buffer_seconds=self.safety_buffer_seconds):
return False, slot.robot_id
return True, None
def is_edge_free(
self,
u: str,
v: str,
t_start: float,
t_end: float,
ignore_robot_id: Optional[str] = None,
) -> Tuple[bool, Optional[str]]:
"""Check if edge (u, v) can be safely traversed during [t_start, t_end].
Detects both head-on collisions and following headway violations.
Returns:
Tuple of (is_free, conflicting_robot_id).
"""
canon_key = (min(u, v), max(u, v))
slots = self.edge_reservations.get(canon_key, [])
for slot in slots:
if ignore_robot_id and slot.robot_id == ignore_robot_id:
continue
# 1. Opposite direction: Head-on collision check
if slot.is_head_on_conflict(u, v, t_start, t_end, self.safety_buffer_seconds):
return False, slot.robot_id
# 2. Same direction: Headway buffer check
if slot.is_following_conflict(u, v, t_start, t_end, self.safety_buffer_seconds):
return False, slot.robot_id
return True, None
def reserve_node(
self,
node_id: str,
t_start: float,
t_end: float,
robot_id: str,
priority: int = 1,
task_id: Optional[str] = None,
) -> bool:
"""Attempt to reserve a node slot. Returns True if successfully reserved."""
is_free, _ = self.is_node_free(node_id, t_start, t_end, ignore_robot_id=robot_id)
if not is_free:
return False
slot = NodeReservation(
node_id=node_id,
start_time=t_start,
end_time=t_end,
robot_id=robot_id,
priority=priority,
task_id=task_id,
)
if node_id not in self.node_reservations:
self.node_reservations[node_id] = []
self.node_reservations[node_id].append(slot)
return True
def reserve_edge(
self,
u: str,
v: str,
t_start: float,
t_end: float,
robot_id: str,
priority: int = 1,
) -> bool:
"""Attempt to reserve an edge traversal slot. Returns True if successfully reserved."""
is_free, _ = self.is_edge_free(u, v, t_start, t_end, ignore_robot_id=robot_id)
if not is_free:
return False
slot = EdgeReservation(
u=u,
v=v,
start_time=t_start,
end_time=t_end,
robot_id=robot_id,
priority=priority,
)
canon_key = slot.canonical_key
if canon_key not in self.edge_reservations:
self.edge_reservations[canon_key] = []
self.edge_reservations[canon_key].append(slot)
return True
def release_reservations_for_robot(
self,
robot_id: str,
after_time: Optional[float] = None,
) -> int:
"""Cancel and release future reservations for a robot (e.g. upon replanning or task finish).
Returns:
Number of cancelled reservations.
"""
cancelled_count = 0
for nid in list(self.node_reservations.keys()):
surviving = []
for slot in self.node_reservations[nid]:
if slot.robot_id == robot_id:
if after_time is None or slot.start_time >= after_time:
cancelled_count += 1
continue
surviving.append(slot)
if surviving:
self.node_reservations[nid] = surviving
else:
self.node_reservations.pop(nid, None)
for ekey in list(self.edge_reservations.keys()):
surviving = []
for slot in self.edge_reservations[ekey]:
if slot.robot_id == robot_id:
if after_time is None or slot.start_time >= after_time:
cancelled_count += 1
continue
surviving.append(slot)
if surviving:
self.edge_reservations[ekey] = surviving
else:
self.edge_reservations.pop(ekey, None)
return cancelled_count
def find_earliest_free_departure(
self,
u: str,
v: str,
desired_start: float,
duration: float,
robot_id: str,
step_seconds: float = 0.5,
max_lookahead: float = 60.0,
) -> float:
"""Find the earliest time >= desired_start when edge (u, v) and node v are both clear."""
t = desired_start
limit = desired_start + max_lookahead
while t <= limit:
t_end = t + duration
# Edge must be free
edge_free, _ = self.is_edge_free(u, v, t, t_end, ignore_robot_id=robot_id)
if edge_free:
# Target node v must also be free for arrival
node_free, _ = self.is_node_free(v, t_end, t_end + self.safety_buffer_seconds, ignore_robot_id=robot_id)
if node_free:
return round(t, 2)
t += step_seconds
return round(limit, 2)
def get_edge_occupancy_density(
self,
current_time: float,
horizon_seconds: float = 60.0,
) -> Dict[Tuple[str, str], int]:
"""Calculate number of active future reservations per edge for dynamic congestion weighting."""
density: Dict[Tuple[str, str], int] = {}
for (u, v), slots in self.edge_reservations.items():
count = 0
for slot in slots:
if slot.end_time >= current_time and slot.start_time <= (current_time + horizon_seconds):
count += 1
if count > 0:
density[(u, v)] = count
density[(v, u)] = count
return density
def clear_expired_reservations(self, current_time: float) -> int:
"""Prune reservations that ended before current_time to maintain low memory."""
pruned = 0
for nid in list(self.node_reservations.keys()):
surviving = [s for s in self.node_reservations[nid] if s.end_time >= current_time]
pruned += len(self.node_reservations[nid]) - len(surviving)
if surviving:
self.node_reservations[nid] = surviving
else:
self.node_reservations.pop(nid, None)
for ekey in list(self.edge_reservations.keys()):
surviving = [s for s in self.edge_reservations[ekey] if s.end_time >= current_time]
pruned += len(self.edge_reservations[ekey]) - len(surviving)
if surviving:
self.edge_reservations[ekey] = surviving
else:
self.edge_reservations.pop(ekey, None)
return pruned
@@ -0,0 +1,247 @@
"""Traffic manager subsystem: cooperative yielding, conflict resolution, and deadlock prevention.
Coordinates multi-AMR navigation through:
- Priority-aware right-of-way evaluation (e.g. production feed priority over replenishment).
- Loaded vs. empty yielding hierarchy (loaded AMRs maintain right-of-way).
- Cooperative waypoint waiting to resolve aisle contention.
- Deadlock timeout detection and dynamic rerouting around congested corridors.
- Congestion edge penalty generation for fleet-wide load balancing.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Set, Tuple
from warehouse_twin.domain.robot import Robot, RobotState
from warehouse_twin.domain.task import Task
from warehouse_twin.routing.path_planner import NoPathFoundError, PathPlanner
from warehouse_twin.routing.reservations import TimeSpaceReservationGrid
@dataclass
class TraversalDecision:
"""Decision produced by the traffic manager for a robot attempting an edge traversal."""
action: str # "PROCEED", "YIELD_WAIT", "REPLAN"
wait_time: float = 0.0
conflicting_robot_id: Optional[str] = None
blocked_edge: Optional[Tuple[str, str]] = None
class TrafficManager:
"""Oversees warehouse-wide AMR traffic flow and arbitrates path conflicts."""
def __init__(
self,
reservation_grid: TimeSpaceReservationGrid,
path_planner: PathPlanner,
deadlock_timeout_seconds: float = 30.0,
lower_priority_yields_to_higher: bool = True,
loaded_yields_to_empty: bool = False,
congestion_penalty_factor: float = 3.0,
) -> None:
"""Initialize traffic manager with reservation grid and rule policies."""
self.reservation_grid = reservation_grid
self.path_planner = path_planner
self.deadlock_timeout_seconds = deadlock_timeout_seconds
self.lower_priority_yields_to_higher = lower_priority_yields_to_higher
self.loaded_yields_to_empty = loaded_yields_to_empty
self.congestion_penalty_factor = congestion_penalty_factor
# Traffic telemetry and performance metrics
self.conflicts_detected: int = 0
self.yield_waits_count: int = 0
self.total_wait_time: float = 0.0
self.reroutes_count: int = 0
self.deadlocks_prevented: int = 0
@classmethod
def from_config_dict(
cls,
reservation_grid: TimeSpaceReservationGrid,
path_planner: PathPlanner,
dispatch_config: Dict[str, Any],
) -> TrafficManager:
"""Construct TrafficManager using dispatch_policies.json configuration."""
traf_cfg = dispatch_config.get("traffic_reservation", {})
yield_rules = traf_cfg.get("yield_rules", {})
return cls(
reservation_grid=reservation_grid,
path_planner=path_planner,
deadlock_timeout_seconds=float(traf_cfg.get("deadlock_timeout_seconds", 30.0)),
lower_priority_yields_to_higher=bool(yield_rules.get("lower_priority_yields_to_higher", True)),
loaded_yields_to_empty=bool(yield_rules.get("loaded_yields_to_empty", False)),
)
def evaluate_right_of_way(
self,
robot_a: Robot,
task_a: Optional[Task],
robot_b: Robot,
task_b: Optional[Task],
) -> bool:
"""Determine if robot_a has right-of-way over robot_b.
Returns:
True if robot_a has higher precedence, False if robot_a must yield.
"""
# 1. Task Priority Comparison (lower numerical value = higher urgency)
if self.lower_priority_yields_to_higher and task_a and task_b:
if task_a.priority < task_b.priority:
return True
if task_a.priority > task_b.priority:
return False
# 2. Loaded vs. Empty Precedence
# Loaded AMRs have right of way over empty AMRs (loaded_yields_to_empty is False)
if not self.loaded_yields_to_empty:
a_loaded = robot_a.current_state in (RobotState.LOADED_TRANSIT, RobotState.DROPPING)
b_loaded = robot_b.current_state in (RobotState.LOADED_TRANSIT, RobotState.DROPPING)
if a_loaded and not b_loaded:
return True
if b_loaded and not a_loaded:
return False
# 3. Deterministic Tie-Breaking
return robot_a.robot_id < robot_b.robot_id
def evaluate_step_traversal(
self,
robot: Robot,
current_node: str,
next_node: str,
start_time: float,
traversal_duration: float,
task: Optional[Task] = None,
other_robots: Optional[Dict[str, Robot]] = None,
other_tasks: Optional[Dict[str, Task]] = None,
) -> TraversalDecision:
"""Evaluate whether a robot can safely enter and traverse edge (current_node, next_node).
Returns:
TraversalDecision indicating PROCEED, YIELD_WAIT, or REPLAN.
"""
end_time = start_time + traversal_duration
priority = task.priority if task else 2
# 1. Check edge conflict
edge_free, conflict_robot_id = self.reservation_grid.is_edge_free(
current_node,
next_node,
start_time,
end_time,
ignore_robot_id=robot.robot_id,
)
# 2. Check next node conflict
node_free, node_conflict_id = self.reservation_grid.is_node_free(
next_node,
end_time,
end_time + self.reservation_grid.safety_buffer_seconds,
ignore_robot_id=robot.robot_id,
)
# If both edge and target node are clear: commit reservation and proceed
if edge_free and node_free:
self.reservation_grid.reserve_edge(
current_node,
next_node,
start_time,
end_time,
robot_id=robot.robot_id,
priority=priority,
)
self.reservation_grid.reserve_node(
next_node,
end_time,
end_time + self.reservation_grid.safety_buffer_seconds,
robot_id=robot.robot_id,
priority=priority,
task_id=task.task_id if task else None,
)
return TraversalDecision(action="PROCEED")
# Conflict detected!
self.conflicts_detected += 1
active_conflict_id = conflict_robot_id or node_conflict_id or "unknown"
# Determine if this robot has right-of-way
other_robot = other_robots.get(active_conflict_id) if other_robots else None
other_task = None
if other_robot and other_robot.current_task_id and other_tasks:
other_task = other_tasks.get(other_robot.current_task_id)
has_precedence = False
if other_robot:
has_precedence = self.evaluate_right_of_way(robot, task, other_robot, other_task)
# Find earliest time this edge and node become available
earliest_departure = self.reservation_grid.find_earliest_free_departure(
current_node,
next_node,
start_time,
traversal_duration,
robot_id=robot.robot_id,
max_lookahead=self.deadlock_timeout_seconds + 5.0,
)
wait_needed = max(earliest_departure - start_time, 0.5)
# If wait is acceptable within deadlock timeout threshold: yield and wait
if wait_needed <= self.deadlock_timeout_seconds:
self.yield_waits_count += 1
self.total_wait_time += wait_needed
return TraversalDecision(
action="YIELD_WAIT",
wait_time=wait_needed,
conflicting_robot_id=active_conflict_id,
)
# Wait exceeds deadlock threshold: trigger dynamic reroute!
self.deadlocks_prevented += 1
self.reroutes_count += 1
return TraversalDecision(
action="REPLAN",
wait_time=0.0,
conflicting_robot_id=active_conflict_id,
blocked_edge=(current_node, next_node),
)
def replan_path(
self,
robot: Robot,
current_node: str,
destination_node: str,
blocked_edges: Optional[Set[Tuple[str, str]]] = None,
sim_time: float = 0.0,
) -> List[str]:
"""Compute an alternative bypass route steering around contested or blocked corridors."""
penalties = self.get_congestion_weights(current_time=sim_time)
return self.path_planner.find_shortest_path(
source=current_node,
target=destination_node,
robot_type=robot.robot_type,
avoid_edges=blocked_edges,
dynamic_edge_weights=penalties,
)
def get_congestion_weights(
self,
current_time: float = 0.0,
) -> Dict[Tuple[str, str], float]:
"""Generate dynamic edge weight penalties proportional to active reservation density."""
density = self.reservation_grid.get_edge_occupancy_density(current_time)
weights: Dict[Tuple[str, str], float] = {}
for edge_key, count in density.items():
weights[edge_key] = count * self.congestion_penalty_factor
return weights
def get_metrics(self) -> Dict[str, Any]:
"""Return cumulative traffic management and conflict resolution metrics."""
return {
"conflicts_detected": self.conflicts_detected,
"yield_waits_count": self.yield_waits_count,
"total_wait_time_seconds": round(self.total_wait_time, 2),
"reroutes_count": self.reroutes_count,
"deadlocks_prevented": self.deadlocks_prevented,
}
+36 -4
View File
@@ -18,6 +18,7 @@ import networkx as nx
from warehouse_twin.domain.robot import IncompatibleRobotTaskError, Robot, RobotState
from warehouse_twin.domain.task import Task, TaskPriority, TaskStatus
from warehouse_twin.domain.warehouse import Position3D
from warehouse_twin.routing.path_planner import NoPathFoundError, PathPlanner
@dataclass
@@ -52,10 +53,12 @@ class FleetDispatcher:
self,
settings: Optional[DispatcherSettings] = None,
graph: Optional[nx.DiGraph] = None,
path_planner: Optional[PathPlanner] = None,
) -> None:
"""Initialize dispatcher with policy settings and routing graph."""
"""Initialize dispatcher with policy settings, routing graph, and path planner."""
self.settings = settings or DispatcherSettings()
self.graph = graph
self.path_planner = path_planner or (PathPlanner(graph) if graph is not None else None)
self.queue: List[Task] = []
self._station_to_node: Dict[str, str] = {}
@@ -84,9 +87,28 @@ class FleetDispatcher:
return candidate
return None
def calculate_distance(self, from_pos: Position3D, to_entity_id: str) -> float:
def calculate_distance(
self,
from_pos: Position3D,
to_entity_id: str,
robot_type: Optional[str] = None,
) -> float:
"""Compute network routing distance or fallback Euclidean distance to target entity."""
target_node = self.get_node_for_entity(to_entity_id)
if self.path_planner and target_node:
try:
start_node = self.path_planner.get_closest_node(from_pos, robot_type=robot_type)
rtype = robot_type or "heavy_amr"
path = self.path_planner.find_shortest_path(
start_node,
target_node,
robot_type=rtype,
weight_mode="distance",
)
return self.path_planner.compute_path_distance(path)
except (NoPathFoundError, KeyError):
pass
if self.graph and target_node and self.graph.has_node(target_node):
# Find nearest node to current robot position
best_node = None
@@ -152,8 +174,18 @@ class FleetDispatcher:
except IncompatibleRobotTaskError:
continue
# 4. Compute transit distance
dist = self.calculate_distance(robot.position, task.source_station)
# 4. Path reachability verification (guarantee robot can physically reach stations)
if self.path_planner:
src_node = self.get_node_for_entity(task.source_station)
dst_node = self.get_node_for_entity(task.destination_station)
cur_node = self.path_planner.get_closest_node(robot.position, robot.robot_type)
if src_node and not self.path_planner.is_destination_reachable(cur_node, src_node, robot_type=robot.robot_type):
continue
if src_node and dst_node and not self.path_planner.is_destination_reachable(src_node, dst_node, robot_type=robot.robot_type):
continue
# 5. Compute network transit distance
dist = self.calculate_distance(robot.position, task.source_station, robot_type=robot.robot_type)
# Heuristic score (lower is better)
if self.settings.policy_name == "nearest_idle":
+275 -47
View File
@@ -5,14 +5,17 @@ Orchestrates:
2. Multi-zone stochastic and scheduled order arrival processes.
3. Fleet dispatcher with AMR capability matching and wide aisle navigation in Zone B.
4. Real-time robot agent mission execution (transit, pick, loaded transit, dropoff, opportunity charging).
5. Inventory decrement, stock reservations, and automated replenishment triggers.
6. Structured simulation telemetry event streaming to JSONL.
7. High-level KPI analytics and metric aggregation.
5. Waypoint-by-waypoint path planning and dynamic routing over NetworkX navigation graph.
6. Multi-AMR traffic management, cooperative yielding, conflict detection, and deadlock prevention.
7. Inventory decrement, stock reservations, and automated replenishment triggers.
8. Structured simulation telemetry event streaming to JSONL and trajectory export.
9. High-level KPI analytics, traffic congestion tracking, and metric aggregation.
"""
from __future__ import annotations
import json
import math
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -26,6 +29,9 @@ from warehouse_twin.domain.robot import Robot, RobotState, RobotTypeSpec
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
from warehouse_twin.domain.warehouse import Position3D, WarehouseModel
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
from warehouse_twin.routing.path_planner import NoPathFoundError, PathPlanner
from warehouse_twin.routing.reservations import TimeSpaceReservationGrid
from warehouse_twin.routing.traffic_manager import TrafficManager
from warehouse_twin.simulation.dispatcher import DispatcherSettings, FleetDispatcher
from warehouse_twin.simulation.order_generator import OrderGenerator, WorkloadConfig
@@ -48,6 +54,12 @@ class SimulationMetrics:
total_energy_consumed_kwh: float = 0.0
replenishment_triggers: int = 0
robot_metrics: Dict[str, Dict[str, float]] = field(default_factory=dict)
# Phase 4 Traffic & Routing Metrics
conflicts_detected: int = 0
yield_waits_count: int = 0
total_wait_time_seconds: float = 0.0
reroutes_count: int = 0
deadlocks_prevented: int = 0
def to_dict(self) -> Dict[str, Any]:
"""Convert metrics to a structured dictionary for reporting and JSON export."""
@@ -67,6 +79,11 @@ class SimulationMetrics:
"total_energy_consumed_kwh": round(self.total_energy_consumed_kwh, 4),
"replenishment_triggers": self.replenishment_triggers,
"robot_metrics": self.robot_metrics,
"conflicts_detected": self.conflicts_detected,
"yield_waits_count": self.yield_waits_count,
"total_wait_time_seconds": round(self.total_wait_time_seconds, 2),
"reroutes_count": self.reroutes_count,
"deadlocks_prevented": self.deadlocks_prevented,
}
@@ -83,6 +100,7 @@ class SimulationEnvironment:
graph: Optional[nx.DiGraph] = None,
event_log_path: Optional[Path | str] = None,
seed: int = 42,
dispatch_policies_config: Optional[Dict[str, Any]] = None,
) -> None:
"""Initialize simulation environment with warehouse domain entities and SimPy clock."""
self.env = simpy.Environment()
@@ -99,9 +117,25 @@ class SimulationEnvironment:
builder = WarehouseGraphBuilder(warehouse)
self.graph = builder.build_graph()
# Phase 4 Routing & Traffic Coordination Subsystems
self.path_planner = PathPlanner(self.graph)
self.reservation_grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
if dispatch_policies_config:
self.traffic_manager = TrafficManager.from_config_dict(
self.reservation_grid, self.path_planner, dispatch_policies_config
)
else:
self.traffic_manager = TrafficManager(
self.reservation_grid, self.path_planner
)
# Components
self.generator = OrderGenerator(workload_config, catalog, warehouse, seed=seed)
self.dispatcher = FleetDispatcher(dispatcher_settings, self.graph)
self.dispatcher = FleetDispatcher(
settings=dispatcher_settings,
graph=self.graph,
path_planner=self.path_planner,
)
# Operational tracking
self.all_tasks: Dict[str, Task] = {}
@@ -119,6 +153,13 @@ class SimulationEnvironment:
self._entity_positions: Dict[str, Position3D] = {}
self._build_position_cache()
# Trajectory recordings for 3D visualization and playback
self.trajectories: Dict[str, List[Dict[str, Any]]] = {
r_id: [] for r_id in self.robots
}
for r in self.robots.values():
self._record_trajectory_point(r)
# SimPy wakeup event for dispatcher
self._dispatch_trigger = self.env.event()
@@ -141,6 +182,15 @@ class SimulationEnvironment:
"""Resolve entity position, falling back to warehouse origin."""
return self._entity_positions.get(entity_id, Position3D(0.0, 0.0, 0.0))
def _record_trajectory_point(self, robot: Robot) -> None:
"""Capture time-stamped position and state of an AMR for trajectory export."""
self.trajectories[robot.robot_id].append({
"t": round(self.env.now, 2),
"pos": [round(robot.position.x, 2), round(robot.position.y, 2), round(robot.position.z, 2)],
"yaw_deg": round(robot.yaw_degrees, 1),
"state": robot.current_state.value,
})
def record_event(
self,
event_type: SimulationEventType,
@@ -163,30 +213,29 @@ class SimulationEnvironment:
event_type=event_type,
entity_id=entity,
task_id=task_id,
metadata=details or {},
position=pos,
zone=zone,
metadata=details or {},
)
self.events.append(evt)
if self._log_file_handle:
self._log_file_handle.write(json.dumps(evt.to_dict()) + "\n")
self._log_file_handle.write(evt.to_jsonl() + "\n")
self._log_file_handle.flush()
def _trigger_dispatch(self) -> None:
"""Notify the dispatcher loop that new tasks or newly idle robots are available."""
"""Wake up dispatcher daemon upon new task creation or robot becoming idle."""
if not self._dispatch_trigger.triggered:
self._dispatch_trigger.succeed()
# -------------------------------------------------------------------------
# Order Arrival Processes (Zone A, Zone B, Zone C)
# Stochastic Order Generation Streams
# -------------------------------------------------------------------------
def _zone_a_order_stream(self) -> Any:
"""Stochastic Poisson arrival stream for fast-moving inventory in Zone A."""
base_rate = self.workload_config.zone_a_arrival_rate_per_hour / 3600.0 # orders/sec
while True:
# Scale by peak multiplier
multiplier = self.generator.get_arrival_multiplier(self.env.now)
effective_rate = max(base_rate * multiplier, 1e-4)
interarrival = self.generator.rng.expovariate(effective_rate)
@@ -200,7 +249,7 @@ class SimulationEnvironment:
SimulationEventType.TASK_CREATED,
task_id=task.task_id,
zone="zone_a",
details={"item_id": task.item_id, "priority": task.priority},
details={"item_id": task.item_id, "deadline": task.deadline, "priority": task.priority},
)
self._trigger_dispatch()
@@ -214,7 +263,6 @@ class SimulationEnvironment:
while True:
multiplier = self.generator.get_arrival_multiplier(self.env.now)
# Gaussian variation around interval (clamped)
interval = max(20.0, self.generator.rng.gauss(mean_interval / multiplier, mean_interval * 0.2))
yield self.env.timeout(interval)
@@ -226,7 +274,12 @@ class SimulationEnvironment:
SimulationEventType.TASK_CREATED,
task_id=task.task_id,
zone="zone_b",
details={"item_id": task.item_id, "weight_kg": task.payload_weight, "priority": task.priority},
details={
"item_id": task.item_id,
"payload_kg": task.payload_weight,
"deadline": task.deadline,
"priority": task.priority,
},
)
self._trigger_dispatch()
@@ -257,7 +310,6 @@ class SimulationEnvironment:
def _dispatcher_daemon(self) -> Any:
"""Continuous dispatcher loop matching pending tasks to idle, compatible AMRs."""
while True:
# Wait for event trigger or periodic tick (2.0s)
yield self.env.any_of([self._dispatch_trigger, self.env.timeout(2.0)])
self._dispatch_trigger = self.env.event()
@@ -271,6 +323,124 @@ class SimulationEnvironment:
)
self.env.process(self._robot_mission_process(robot, task))
# -------------------------------------------------------------------------
# Waypoint-by-Waypoint Path Traversal Process
# -------------------------------------------------------------------------
def _traverse_path(
self,
robot: Robot,
initial_path: List[str],
task: Optional[Task],
is_loaded: bool = False,
) -> Any:
"""Move robot along graph path waypoint-by-waypoint with traffic coordination and yielding."""
if len(initial_path) < 2:
return
path = list(initial_path)
robot.current_route = list(path)
curr_idx = 0
while curr_idx < len(path) - 1:
u = path[curr_idx]
v = path[curr_idx + 1]
# Calculate nominal edge traversal duration
edge_data = self.graph[u][v] if self.graph.has_edge(u, v) else {}
dist = float(edge_data.get("distance", 1.0))
speed_limit = float(edge_data.get("speed_limit", 1.5))
robot_max = robot.maximum_speed * (0.85 if is_loaded else 1.0)
speed = min(speed_limit, robot_max)
traversal_time = max(dist / speed, 0.2)
# Consult TrafficManager for conflict detection & right-of-way
decision = self.traffic_manager.evaluate_step_traversal(
robot=robot,
current_node=u,
next_node=v,
start_time=self.env.now,
traversal_duration=traversal_time,
task=task,
other_robots=self.robots,
other_tasks=self.all_tasks,
)
if decision.action == "YIELD_WAIT":
# Cooperative yielding wait
self.record_event(
SimulationEventType.TRAFFIC_YIELD,
robot_id=robot.robot_id,
task_id=task.task_id if task else None,
details={
"node": u,
"contested_edge": [u, v],
"wait_seconds": round(decision.wait_time, 2),
"conflict_with": decision.conflicting_robot_id,
},
)
yield self.env.timeout(decision.wait_time)
robot.consume_energy(decision.wait_time, mode="idle")
self._record_trajectory_point(robot)
continue # Re-evaluate edge entry now that wait has expired
elif decision.action == "REPLAN":
# Congestion / deadlock timeout - find alternative bypass route
destination_node = path[-1]
blocked = {decision.blocked_edge} if decision.blocked_edge else {(u, v)}
try:
new_path = self.traffic_manager.replan_path(
robot=robot,
current_node=u,
destination_node=destination_node,
blocked_edges=blocked,
sim_time=self.env.now,
)
self.record_event(
SimulationEventType.ROBOT_REROUTED,
robot_id=robot.robot_id,
task_id=task.task_id if task else None,
details={
"at_node": u,
"destination": destination_node,
"old_path_len": len(path),
"new_path_len": len(new_path),
"avoided_edge": [u, v],
},
)
path = new_path
robot.current_route = list(path)
curr_idx = 0
continue
except NoPathFoundError:
# No bypass route available, wait safety backoff and retry
yield self.env.timeout(2.0)
robot.consume_energy(2.0, mode="idle")
self._record_trajectory_point(robot)
continue
# Action == "PROCEED": Traverse edge
yield self.env.timeout(traversal_time)
robot.accumulated_distance += dist
power_mode = "moving_loaded" if is_loaded else "moving_empty"
robot.consume_energy(traversal_time, mode=power_mode)
# Update coordinates to waypoint v
v_coords = self.graph.nodes[v]["pos"]
robot.position = Position3D(v_coords[0], v_coords[1], v_coords[2])
# Update yaw angle
u_coords = self.graph.nodes[u]["pos"]
dx = v_coords[0] - u_coords[0]
dy = v_coords[1] - u_coords[1]
if abs(dx) > 0.01 or abs(dy) > 0.01:
robot.yaw_degrees = math.degrees(math.atan2(dy, dx))
# Record fine-grained waypoint trajectory point
self._record_trajectory_point(robot)
curr_idx += 1
robot.current_route = []
# -------------------------------------------------------------------------
# Robot Mission Execution Process
# -------------------------------------------------------------------------
@@ -279,31 +449,40 @@ class SimulationEnvironment:
# ---------------------------------------------------------------------
# 1. Travel to Pickup Location (Empty Transit)
# ---------------------------------------------------------------------
src_pos = self.get_entity_position(task.source_station)
dist_to_src = self.dispatcher.calculate_distance(robot.position, task.source_station)
speed = min(robot.maximum_speed, 1.5)
transit_time_empty = max(dist_to_src / speed, 1.0)
start_node = self.path_planner.get_closest_node(robot.position, robot.robot_type)
pickup_node = self.dispatcher.get_node_for_entity(task.source_station)
if not pickup_node:
pickup_pos = self.get_entity_position(task.source_station)
pickup_node = self.path_planner.get_closest_node(pickup_pos, robot.robot_type)
robot.transition_to(RobotState.DISPATCHED, self.env.now)
try:
path_to_pickup = self.path_planner.find_shortest_path(
start_node, pickup_node, robot_type=robot.robot_type
)
except NoPathFoundError:
path_to_pickup = [start_node, pickup_node]
dist_to_src = self.path_planner.compute_path_distance(path_to_pickup)
self.record_event(
SimulationEventType.ROBOT_DISPATCHED,
robot_id=robot.robot_id,
task_id=task.task_id,
details={"dist_meters": round(dist_to_src, 2), "eta_seconds": round(transit_time_empty, 2)},
details={
"source_station": task.source_station,
"path_length_meters": dist_to_src,
"waypoint_count": len(path_to_pickup),
},
)
yield self.env.timeout(transit_time_empty)
# Update robot position and consume empty moving power
robot.position = src_pos
robot.accumulated_distance += dist_to_src
robot.consume_energy(transit_time_empty, mode="moving_empty")
yield self.env.process(self._traverse_path(robot, path_to_pickup, task=task, is_loaded=False))
# ---------------------------------------------------------------------
# 2. Pickup / Loading Operation
# ---------------------------------------------------------------------
robot.transition_to(RobotState.PICKING, self.env.now)
task.start_execution(self.env.now)
self._record_trajectory_point(robot)
pick_duration = self.workload_config.pickup_time_seconds
if task.payload_weight > 150.0:
@@ -317,23 +496,19 @@ class SimulationEnvironment:
)
yield self.env.timeout(pick_duration)
# Consume idle/loading power
robot.consume_energy(pick_duration, mode="idle")
self._record_trajectory_point(robot)
# Handle inventory reservation and consumption
# Inventory reservation and consumption
if task.item_id and task.item_id in self.catalog.items:
item = self.catalog.items[task.item_id]
if task.task_type == TaskType.REPLENISHMENT:
# Restocking operation
item.restock(task.quantity)
else:
# Picking operation
if item.available_quantity >= task.quantity:
item.reserve(task.quantity)
item.consume(task.quantity)
# Check if stock triggers a replenishment order
if item.needs_replenishment():
repl_task = self.generator.generate_replenishment_task(item, self.env.now)
self.all_tasks[repl_task.task_id] = repl_task
@@ -347,32 +522,49 @@ class SimulationEnvironment:
# ---------------------------------------------------------------------
# 3. Loaded Transit to Destination
# ---------------------------------------------------------------------
dst_pos = self.get_entity_position(task.destination_station)
dist_to_dst = self.dispatcher.calculate_distance(robot.position, task.destination_station)
# Slower speed when fully loaded
loaded_speed = min(robot.maximum_speed * 0.85, 1.2)
transit_time_loaded = max(dist_to_dst / loaded_speed, 1.0)
start_node = self.path_planner.get_closest_node(robot.position, robot.robot_type)
drop_node = self.dispatcher.get_node_for_entity(task.destination_station)
if not drop_node:
drop_pos = self.get_entity_position(task.destination_station)
drop_node = self.path_planner.get_closest_node(drop_pos, robot.robot_type)
robot.transition_to(RobotState.LOADED_TRANSIT, self.env.now)
yield self.env.timeout(transit_time_loaded)
try:
path_to_drop = self.path_planner.find_shortest_path(
start_node, drop_node, robot_type=robot.robot_type
)
except NoPathFoundError:
path_to_drop = [start_node, drop_node]
robot.position = dst_pos
robot.accumulated_distance += dist_to_dst
robot.consume_energy(transit_time_loaded, mode="moving_loaded")
dist_to_dst = self.path_planner.compute_path_distance(path_to_drop)
self.record_event(
SimulationEventType.ROBOT_PATH_PLANNED,
robot_id=robot.robot_id,
task_id=task.task_id,
details={
"dest_station": task.destination_station,
"path_length_meters": dist_to_dst,
"waypoint_count": len(path_to_drop),
},
)
yield self.env.process(self._traverse_path(robot, path_to_drop, task=task, is_loaded=True))
# ---------------------------------------------------------------------
# 4. Dropoff Operation
# 4. Dropoff / Unloading Operation
# ---------------------------------------------------------------------
robot.transition_to(RobotState.DROPPING, self.env.now)
self._record_trajectory_point(robot)
drop_duration = self.workload_config.dropoff_time_seconds
yield self.env.timeout(drop_duration)
robot.consume_energy(drop_duration, mode="idle")
self._record_trajectory_point(robot)
# Complete task and robot
# Complete task
task.complete(self.env.now)
robot.complete_task(self.env.now)
self.completed_tasks.append(task)
robot.complete_task()
self.record_event(
SimulationEventType.TASK_COMPLETED,
@@ -392,20 +584,28 @@ class SimulationEnvironment:
yield self.env.process(self._robot_recharge_process(robot))
else:
robot.transition_to(RobotState.IDLE, self.env.now)
self._record_trajectory_point(robot)
self._trigger_dispatch()
def _robot_recharge_process(self, robot: Robot) -> Any:
"""Send robot to nearest charging bay to recharge battery back to full capacity."""
ch_id = "charge_bay_1" if "light" in robot.robot_type else "charge_bay_3"
ch_pos = self.get_entity_position(ch_id)
dist = robot.position.distance_to(ch_pos)
transit_time = max(dist / robot.maximum_speed, 2.0)
start_node = self.path_planner.get_closest_node(robot.position, robot.robot_type)
target_node = self.dispatcher.get_node_for_entity(ch_id)
if not target_node:
target_node = self.path_planner.get_closest_node(ch_pos, robot.robot_type)
robot.transition_to(RobotState.TRANSIT_TO_CHARGE, self.env.now)
yield self.env.timeout(transit_time)
try:
path = self.path_planner.find_shortest_path(start_node, target_node, robot_type=robot.robot_type)
except NoPathFoundError:
path = [start_node, target_node]
yield self.env.process(self._traverse_path(robot, path, task=None, is_loaded=False))
robot.position = ch_pos
robot.transition_to(RobotState.CHARGING, self.env.now)
self._record_trajectory_point(robot)
self.record_event(
SimulationEventType.ROBOT_CHARGING_START,
robot_id=robot.robot_id,
@@ -418,7 +618,9 @@ class SimulationEnvironment:
yield self.env.timeout(charge_duration)
robot.charge_energy(charge_duration, charging_rate_kw=10.0)
self._record_trajectory_point(robot)
robot.transition_to(RobotState.IDLE, self.env.now)
self._record_trajectory_point(robot)
self.record_event(
SimulationEventType.ROBOT_CHARGING_COMPLETE,
robot_id=robot.robot_id,
@@ -438,6 +640,25 @@ class SimulationEnvironment:
return self.collect_metrics()
def export_trajectories(self, output_path: Path | str) -> Path:
"""Export time-indexed robot trajectories to JSON format for Omniverse playback."""
out = Path(output_path).resolve()
out.parent.mkdir(parents=True, exist_ok=True)
payload = {
"metadata": {
"simulation_run_id": f"sim_{int(self.seed)}_{int(self.env.now)}",
"time_step_seconds": 0.5,
"coordinate_system": "right_handed_cartesian_meters_z_up",
"total_duration_seconds": round(self.env.now, 2),
"total_robots": len(self.robots),
"total_trajectory_points": sum(len(pts) for pts in self.trajectories.values()),
},
"robots": self.trajectories,
}
with open(out, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
return out
def collect_metrics(self) -> SimulationMetrics:
"""Compute aggregate throughput, latency, fleet utilization, and energy KPIs."""
sim_duration = max(self.env.now, 1.0)
@@ -477,6 +698,8 @@ class SimulationEnvironment:
"utilization_percent": round((r.busy_time / sim_duration) * 100.0, 1),
}
traffic_stats = self.traffic_manager.get_metrics()
return SimulationMetrics(
duration_seconds=sim_duration,
tasks_created=total_created,
@@ -493,4 +716,9 @@ class SimulationEnvironment:
total_energy_consumed_kwh=total_energy,
replenishment_triggers=repl_count,
robot_metrics=r_metrics,
conflicts_detected=traffic_stats["conflicts_detected"],
yield_waits_count=traffic_stats["yield_waits_count"],
total_wait_time_seconds=traffic_stats["total_wait_time_seconds"],
reroutes_count=traffic_stats["reroutes_count"],
deadlocks_prevented=traffic_stats["deadlocks_prevented"],
)