Files
Warehouse-Digital-Twin-and-…/tests/unit/test_traffic_manager.py
T
AyushS 56806079a9 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.
2026-10-21 10:59:11 +05:30

195 lines
6.9 KiB
Python

"""Unit tests for TrafficManager: cooperative yielding, right-of-way, and deadlock rerouting."""
from __future__ import annotations
from pathlib import Path
import pytest
from warehouse_twin.config.loader import ConfigLoader
from warehouse_twin.domain.robot import Robot, RobotState, RobotTypeSpec
from warehouse_twin.domain.task import Task, TaskPriority, TaskType
from warehouse_twin.domain.warehouse import Position3D, WarehouseModel
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
from warehouse_twin.routing.path_planner import PathPlanner
from warehouse_twin.routing.reservations import TimeSpaceReservationGrid
from warehouse_twin.routing.traffic_manager import TrafficManager, TraversalDecision
@pytest.fixture
def traffic_setup(project_config_dir: Path):
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
warehouse = WarehouseModel.from_config_dict(bundle.warehouse)
builder = WarehouseGraphBuilder(warehouse)
graph = builder.build_graph()
planner = PathPlanner(graph)
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
traffic = TrafficManager(
reservation_grid=grid,
path_planner=planner,
deadlock_timeout_seconds=20.0,
lower_priority_yields_to_higher=True,
loaded_yields_to_empty=False,
)
type_specs = {
t_id: RobotTypeSpec.from_dict(t_id, t_data)
for t_id, t_data in bundle.robots["robot_types"].items()
}
r1 = Robot.from_fleet_dict(bundle.robots["fleet"][0], type_specs)
r2 = Robot.from_fleet_dict(bundle.robots["fleet"][1], type_specs)
return traffic, grid, planner, r1, r2
def test_traffic_right_of_way_by_task_priority(traffic_setup):
"""Verify robot with higher priority task (lower number) has right-of-way."""
traffic, _, _, r1, r2 = traffic_setup
task_critical = Task(
task_id="t_crit",
task_type=TaskType.PRODUCTION_FEED,
source="loc_1",
destination="drop_1",
priority=TaskPriority.CRITICAL.value, # Priority 1
)
task_standard = Task(
task_id="t_std",
task_type=TaskType.OUTBOUND_PICKING,
source="loc_2",
destination="drop_2",
priority=TaskPriority.LOW.value, # Priority 4
)
# Robot 1 (critical) vs Robot 2 (standard) -> Robot 1 has right-of-way
assert traffic.evaluate_right_of_way(r1, task_critical, r2, task_standard) is True
assert traffic.evaluate_right_of_way(r2, task_standard, r1, task_critical) is False
def test_traffic_right_of_way_loaded_over_empty(traffic_setup):
"""Verify loaded AMR has right-of-way over empty AMR when task priorities are equal."""
traffic, _, _, r1, r2 = traffic_setup
task_a = Task("t_a", TaskType.OUTBOUND_PICKING, "l1", "d1", priority=2)
task_b = Task("t_b", TaskType.OUTBOUND_PICKING, "l2", "d2", priority=2)
r1.current_state = RobotState.LOADED_TRANSIT
r2.current_state = RobotState.DISPATCHED
# r1 is loaded, r2 is empty -> r1 has right-of-way
assert traffic.evaluate_right_of_way(r1, task_a, r2, task_b) is True
assert traffic.evaluate_right_of_way(r2, task_b, r1, task_a) is False
def test_traversal_proceed_when_aisle_is_clear(traffic_setup):
"""Verify PROCEED decision when path edge is unreserved."""
traffic, grid, _, r1, _ = traffic_setup
decision: TraversalDecision = traffic.evaluate_step_traversal(
robot=r1,
current_node="wp_20_20",
next_node="wp_20_40",
start_time=10.0,
traversal_duration=2.0,
)
assert decision.action == "PROCEED"
assert decision.wait_time == 0.0
# Verify edge and node were reserved in grid
edge_free, _ = grid.is_edge_free("wp_20_20", "wp_20_40", 10.0, 12.0)
assert edge_free is False
def test_traversal_yield_wait_on_temporary_contention(traffic_setup):
"""Verify YIELD_WAIT decision when conflicting robot frees edge before deadlock timeout."""
traffic, grid, _, r1, r2 = traffic_setup
# r1 reserves edge from t=10.0 to t=14.0
grid.reserve_edge("wp_20_20", "wp_20_40", 10.0, 14.0, robot_id=r1.robot_id)
grid.reserve_node("wp_20_40", 14.0, 15.0, robot_id=r1.robot_id)
# r2 attempts traversal at t=11.0, duration 2.0s
decision = traffic.evaluate_step_traversal(
robot=r2,
current_node="wp_20_40",
next_node="wp_20_20",
start_time=11.0,
traversal_duration=2.0,
other_robots={r1.robot_id: r1},
)
# Conflicting edge requires wait until t=15.0 (4.0s wait <= 20.0s deadlock timeout)
assert decision.action == "YIELD_WAIT"
assert decision.wait_time > 0.0
assert decision.conflicting_robot_id == r1.robot_id
assert traffic.yield_waits_count == 1
assert traffic.conflicts_detected == 1
def test_traversal_replan_on_deadlock_timeout(traffic_setup):
"""Verify REPLAN decision when blockage wait exceeds deadlock timeout."""
traffic, grid, _, r1, r2 = traffic_setup
traffic.deadlock_timeout_seconds = 5.0 # Low timeout for testing
# Long reservation on edge (30 seconds)
grid.reserve_edge("wp_20_20", "wp_20_40", 10.0, 40.0, robot_id=r1.robot_id)
grid.reserve_node("wp_20_40", 40.0, 41.0, robot_id=r1.robot_id)
decision = traffic.evaluate_step_traversal(
robot=r2,
current_node="wp_20_20",
next_node="wp_20_40",
start_time=11.0,
traversal_duration=2.0,
other_robots={r1.robot_id: r1},
)
# Wait would be ~30s > 5.0s timeout -> Triggers REPLAN
assert decision.action == "REPLAN"
assert decision.blocked_edge == ("wp_20_20", "wp_20_40")
assert traffic.deadlocks_prevented == 1
assert traffic.reroutes_count == 1
def test_replan_path_navigates_around_blocked_edge(traffic_setup):
"""Verify replan_path generates a detour avoiding blocked edge."""
traffic, _, _, r1, _ = traffic_setup
source = "station_dock_inbound_1"
target = "station_picking_station_a1"
# Base route
initial_path = traffic.path_planner.find_shortest_path(source, target, robot_type=r1.robot_type)
blocked_edge = (initial_path[1], initial_path[2])
rerouted = traffic.replan_path(
robot=r1,
current_node=initial_path[1],
destination_node=target,
blocked_edges={blocked_edge},
)
assert rerouted[0] == initial_path[1]
assert rerouted[-1] == target
pairs = list(zip(rerouted[:-1], rerouted[1:]))
assert blocked_edge not in pairs
def test_traffic_metrics_collection(traffic_setup):
"""Verify metrics dictionary contains all required Phase 4 tracking fields."""
traffic, _, _, _, _ = traffic_setup
traffic.conflicts_detected = 3
traffic.yield_waits_count = 2
traffic.total_wait_time = 14.5
traffic.reroutes_count = 1
traffic.deadlocks_prevented = 1
stats = traffic.get_metrics()
assert stats["conflicts_detected"] == 3
assert stats["yield_waits_count"] == 2
assert stats["total_wait_time_seconds"] == 14.5
assert stats["reroutes_count"] == 1
assert stats["deadlocks_prevented"] == 1