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:
@@ -0,0 +1,206 @@
|
||||
"""Unit tests for NetworkX-powered PathPlanner and reachability subsystem."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.config.loader import ConfigLoader
|
||||
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,
|
||||
PathPlanningError,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def planner_setup(project_config_dir: Path):
|
||||
"""Fixture providing initialized PathPlanner and WarehouseGraphBuilder."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
planner = PathPlanner(graph)
|
||||
return planner, builder, graph
|
||||
|
||||
|
||||
def test_path_planner_initialization(planner_setup):
|
||||
"""Verify PathPlanner properly caches node positions and initializes."""
|
||||
planner, _, graph = planner_setup
|
||||
assert len(planner._node_positions) == graph.number_of_nodes()
|
||||
|
||||
# Query arbitrary node
|
||||
wp_pos = planner.get_node_position("wp_20_20")
|
||||
assert isinstance(wp_pos, Position3D)
|
||||
assert wp_pos.x == 2.0
|
||||
assert wp_pos.y == 2.0
|
||||
|
||||
|
||||
def test_find_shortest_path_standard(planner_setup):
|
||||
"""Verify standard shortest path calculation between dock and picking station."""
|
||||
planner, _, _ = planner_setup
|
||||
|
||||
path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="station_picking_station_a1",
|
||||
robot_type="light_amr",
|
||||
)
|
||||
|
||||
assert len(path) > 3
|
||||
assert path[0] == "station_dock_inbound_1"
|
||||
assert path[-1] == "station_picking_station_a1"
|
||||
|
||||
dist = planner.compute_path_distance(path)
|
||||
assert dist > 10.0
|
||||
|
||||
duration = planner.compute_path_duration(path, robot_speed=1.5)
|
||||
assert duration > 5.0
|
||||
|
||||
|
||||
def test_same_source_and_target_path(planner_setup):
|
||||
"""Verify path planning when source equals target returns single-element path."""
|
||||
planner, _, _ = planner_setup
|
||||
path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="station_dock_inbound_1",
|
||||
)
|
||||
assert path == ["station_dock_inbound_1"]
|
||||
assert planner.compute_path_distance(path) == 0.0
|
||||
|
||||
|
||||
def test_light_amr_restricted_from_zone_b(planner_setup):
|
||||
"""Verify light AMRs cannot plan paths to Zone B storage locations."""
|
||||
planner, _, _ = planner_setup
|
||||
|
||||
# rack_b_01 is situated in Zone B with 4.0m aisles restricted to heavy AMRs
|
||||
with pytest.raises(NoPathFoundError) as exc_info:
|
||||
planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="rack_b_01",
|
||||
robot_type="light_amr",
|
||||
)
|
||||
|
||||
assert "light_amr" in str(exc_info.value)
|
||||
assert "rack_b_01" in str(exc_info.value)
|
||||
assert not planner.is_destination_reachable(
|
||||
source="station_dock_inbound_1",
|
||||
target="rack_b_01",
|
||||
robot_type="light_amr",
|
||||
)
|
||||
|
||||
|
||||
def test_heavy_amr_allowed_in_zone_b(planner_setup):
|
||||
"""Verify heavy AMRs can freely plan paths to Zone B wide aisle racks."""
|
||||
planner, _, _ = planner_setup
|
||||
|
||||
assert planner.is_destination_reachable(
|
||||
source="station_dock_inbound_1",
|
||||
target="rack_b_01",
|
||||
robot_type="heavy_amr",
|
||||
)
|
||||
|
||||
path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="rack_b_01",
|
||||
robot_type="heavy_amr",
|
||||
)
|
||||
|
||||
assert path[0] == "station_dock_inbound_1"
|
||||
assert path[-1] in ("rack_b_01", planner.resolve_node_id("rack_b_01"))
|
||||
assert len(path) > 5
|
||||
|
||||
|
||||
def test_unreachable_destination_raises_error(planner_setup):
|
||||
"""Verify non-existent or severed node triggers NoPathFoundError."""
|
||||
planner, _, graph = planner_setup
|
||||
|
||||
# Query with missing target
|
||||
with pytest.raises(KeyError):
|
||||
planner.find_shortest_path("station_dock_inbound_1", "non_existent_node")
|
||||
|
||||
# Isolate an internal node
|
||||
isolated = "wp_100_100"
|
||||
graph.remove_edges_from(list(graph.in_edges(isolated)) + list(graph.out_edges(isolated)))
|
||||
|
||||
with pytest.raises(NoPathFoundError):
|
||||
planner.find_shortest_path("station_dock_inbound_1", isolated, robot_type="heavy_amr")
|
||||
|
||||
|
||||
def test_path_avoid_nodes_and_edges(planner_setup):
|
||||
"""Verify dynamic rerouting avoids specific congested nodes or edges."""
|
||||
planner, _, _ = planner_setup
|
||||
|
||||
base_path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="station_picking_station_a1",
|
||||
robot_type="light_amr",
|
||||
)
|
||||
|
||||
# Pick an intermediate node to block
|
||||
intermediate_node = base_path[2]
|
||||
detour_path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="station_picking_station_a1",
|
||||
robot_type="light_amr",
|
||||
avoid_nodes={intermediate_node},
|
||||
)
|
||||
|
||||
assert intermediate_node not in detour_path
|
||||
assert detour_path[0] == "station_dock_inbound_1"
|
||||
assert detour_path[-1] == "station_picking_station_a1"
|
||||
|
||||
# Block an edge
|
||||
u, v = base_path[1], base_path[2]
|
||||
edge_detour_path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="station_picking_station_a1",
|
||||
robot_type="light_amr",
|
||||
avoid_edges={(u, v)},
|
||||
)
|
||||
# Verify (u, v) is not consecutive in edge_detour_path
|
||||
pairs = list(zip(edge_detour_path[:-1], edge_detour_path[1:]))
|
||||
assert (u, v) not in pairs
|
||||
|
||||
|
||||
def test_dynamic_edge_congestion_weights(planner_setup):
|
||||
"""Verify edge with high congestion penalty is steered around if an alternate route exists."""
|
||||
planner, _, _ = planner_setup
|
||||
|
||||
base_path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="station_picking_station_a1",
|
||||
robot_type="light_amr",
|
||||
)
|
||||
|
||||
# Heavily penalize first edge
|
||||
penalized_edge = (base_path[1], base_path[2])
|
||||
penalties = {penalized_edge: 500.0}
|
||||
|
||||
penalized_path = planner.find_shortest_path(
|
||||
source="station_dock_inbound_1",
|
||||
target="station_picking_station_a1",
|
||||
robot_type="light_amr",
|
||||
dynamic_edge_weights=penalties,
|
||||
)
|
||||
|
||||
pairs = list(zip(penalized_path[:-1], penalized_path[1:]))
|
||||
assert penalized_edge not in pairs
|
||||
|
||||
|
||||
def test_closest_node_lookup(planner_setup):
|
||||
"""Verify closest node lookup with spatial accuracy."""
|
||||
planner, _, _ = planner_setup
|
||||
|
||||
query_pos = Position3D(2.1, 2.2, 0.0)
|
||||
closest = planner.get_closest_node(query_pos)
|
||||
assert closest == "wp_20_20"
|
||||
|
||||
# Zone B filtering for light AMR
|
||||
zone_b_pos = Position3D(35.0, 20.0, 0.0)
|
||||
closest_heavy = planner.get_closest_node(zone_b_pos, robot_type="heavy_amr")
|
||||
closest_light = planner.get_closest_node(zone_b_pos, robot_type="light_amr")
|
||||
|
||||
# Light AMR node must NOT be inside Zone B internal aisles
|
||||
assert planner.graph.nodes[closest_light].get("zone") != "zone_b"
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Unit tests for TimeSpaceReservationGrid: collision avoidance, aisle reservations, and headway."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.routing.reservations import (
|
||||
EdgeReservation,
|
||||
NodeReservation,
|
||||
TimeSpaceReservationGrid,
|
||||
)
|
||||
|
||||
|
||||
def test_node_reservation_overlap_detection():
|
||||
"""Verify overlapping time windows at the same node trigger conflict."""
|
||||
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
|
||||
|
||||
# Robot 1 reserves node wp_1 from t=10.0 to t=15.0
|
||||
res = grid.reserve_node("wp_1", t_start=10.0, t_end=15.0, robot_id="amr_01")
|
||||
assert res is True
|
||||
|
||||
# Same robot can query or overlap without self-conflict
|
||||
free_self, _ = grid.is_node_free("wp_1", 11.0, 14.0, ignore_robot_id="amr_01")
|
||||
assert free_self is True
|
||||
|
||||
# Robot 2 requests overlapping slot [12.0, 16.0] -> Conflict!
|
||||
free_other, conflict_id = grid.is_node_free("wp_1", 12.0, 16.0, ignore_robot_id="amr_02")
|
||||
assert free_other is False
|
||||
assert conflict_id == "amr_01"
|
||||
|
||||
# Robot 2 requests slot [15.5, 18.0] -> Violates 1.0s safety buffer -> Conflict!
|
||||
free_buffer, _ = grid.is_node_free("wp_1", 15.5, 18.0, ignore_robot_id="amr_02")
|
||||
assert free_buffer is False
|
||||
|
||||
# Robot 2 requests slot after buffer [16.5, 20.0] -> Free!
|
||||
free_valid, _ = grid.is_node_free("wp_1", 16.5, 20.0, ignore_robot_id="amr_02")
|
||||
assert free_valid is True
|
||||
|
||||
|
||||
def test_edge_head_on_collision_avoidance():
|
||||
"""Verify opposite-direction traversal on shared physical aisle triggers hard conflict."""
|
||||
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
|
||||
|
||||
# Robot 1 traverses aisle A->B from t=20.0 to t=25.0
|
||||
reserved = grid.reserve_edge("node_a", "node_b", t_start=20.0, t_end=25.0, robot_id="amr_01")
|
||||
assert reserved is True
|
||||
|
||||
# Robot 2 attempts to traverse opposite direction B->A at overlapping time [22.0, 27.0]
|
||||
is_free, conflict_id = grid.is_edge_free("node_b", "node_a", t_start=22.0, t_end=27.0, ignore_robot_id="amr_02")
|
||||
assert is_free is False
|
||||
assert conflict_id == "amr_01"
|
||||
|
||||
# Robot 2 attempts B->A well after Robot 1 clears [27.0, 32.0] -> Safe!
|
||||
is_free_after, _ = grid.is_edge_free("node_b", "node_a", t_start=27.0, t_end=32.0, ignore_robot_id="amr_02")
|
||||
assert is_free_after is True
|
||||
|
||||
|
||||
def test_edge_following_headway_enforcement():
|
||||
"""Verify same-direction traversal respects minimum time headway."""
|
||||
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
|
||||
|
||||
# Robot 1 enters edge A->B at t=10.0, exits at t=14.0
|
||||
grid.reserve_edge("node_a", "node_b", t_start=10.0, t_end=14.0, robot_id="amr_01")
|
||||
|
||||
# Robot 2 attempts same direction A->B at t=10.5 (within 1.0s headway) -> Conflict!
|
||||
is_free_too_close, _ = grid.is_edge_free("node_a", "node_b", t_start=10.5, t_end=14.5, ignore_robot_id="amr_02")
|
||||
assert is_free_too_close is False
|
||||
|
||||
# Robot 2 enters at t=12.0 (outside 1.0s headway) -> Permitted
|
||||
is_free_headway, _ = grid.is_edge_free("node_a", "node_b", t_start=12.0, t_end=16.0, ignore_robot_id="amr_02")
|
||||
assert is_free_headway is True
|
||||
|
||||
|
||||
def test_earliest_free_departure_search():
|
||||
"""Verify finding earliest free time slot when an edge/node is currently blocked."""
|
||||
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
|
||||
|
||||
# Node and edge busy from t=10.0 to t=15.0
|
||||
grid.reserve_edge("u", "v", 10.0, 15.0, robot_id="amr_01")
|
||||
grid.reserve_node("v", 15.0, 16.0, robot_id="amr_01")
|
||||
|
||||
# Robot 2 wants to leave at t=11.0, duration 3.0s
|
||||
earliest = grid.find_earliest_free_departure(
|
||||
u="u",
|
||||
v="v",
|
||||
desired_start=11.0,
|
||||
duration=3.0,
|
||||
robot_id="amr_02",
|
||||
step_seconds=0.5,
|
||||
)
|
||||
|
||||
# Earliest departure from u must be >= 14.0s (so arrival at v at t=17.0s is after Robot 1 clears at t=16.0s + 1.0s buffer)
|
||||
assert earliest >= 14.0
|
||||
|
||||
|
||||
def test_release_reservations_for_robot():
|
||||
"""Verify cancelling reservations when a robot replans or aborts."""
|
||||
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
|
||||
|
||||
grid.reserve_node("wp_1", 10.0, 15.0, robot_id="amr_01")
|
||||
grid.reserve_node("wp_2", 15.0, 20.0, robot_id="amr_01")
|
||||
grid.reserve_node("wp_3", 20.0, 25.0, robot_id="amr_01")
|
||||
|
||||
# Release reservations after t=15.0
|
||||
cancelled = grid.release_reservations_for_robot("amr_01", after_time=15.0)
|
||||
assert cancelled == 2
|
||||
|
||||
# wp_1 (10-15) still reserved; wp_3 (20-25) now free
|
||||
free_wp1, _ = grid.is_node_free("wp_1", 11.0, 14.0, ignore_robot_id="amr_02")
|
||||
assert free_wp1 is False
|
||||
|
||||
free_wp3, _ = grid.is_node_free("wp_3", 21.0, 24.0, ignore_robot_id="amr_02")
|
||||
assert free_wp3 is True
|
||||
|
||||
|
||||
def test_clear_expired_reservations():
|
||||
"""Verify memory pruning removes past reservations without affecting future ones."""
|
||||
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
|
||||
|
||||
grid.reserve_node("wp_old", 0.0, 10.0, robot_id="amr_01")
|
||||
grid.reserve_node("wp_future", 50.0, 60.0, robot_id="amr_02")
|
||||
grid.reserve_edge("u", "v", 0.0, 10.0, robot_id="amr_01")
|
||||
grid.reserve_edge("v", "w", 50.0, 60.0, robot_id="amr_02")
|
||||
|
||||
pruned = grid.clear_expired_reservations(current_time=20.0)
|
||||
assert pruned == 2
|
||||
|
||||
# Past reservation pruned
|
||||
assert "wp_old" not in grid.node_reservations
|
||||
# Future reservation preserved
|
||||
assert "wp_future" in grid.node_reservations
|
||||
@@ -0,0 +1,194 @@
|
||||
"""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
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Unit tests for AMR motion trajectory recording and JSON export."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
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.simulation.dispatcher import DispatcherSettings
|
||||
from warehouse_twin.simulation.order_generator import WorkloadConfig
|
||||
from warehouse_twin.simulation.sim_engine import SimulationEnvironment
|
||||
|
||||
|
||||
def test_trajectory_recording_and_export(project_config_dir: Path, tmp_path: Path):
|
||||
"""Verify trajectory recording during simulation and JSON export schema compliance."""
|
||||
loader = ConfigLoader(project_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["robot_types"].items()
|
||||
}
|
||||
fleet = [
|
||||
Robot.from_fleet_dict(r_data, type_specs)
|
||||
for r_data in bundle.robots["fleet"]
|
||||
]
|
||||
workload = WorkloadConfig.from_dict(bundle.simulation)
|
||||
dispatch_settings = DispatcherSettings.from_dict(bundle.dispatch_policies)
|
||||
|
||||
env = SimulationEnvironment(
|
||||
warehouse=warehouse,
|
||||
catalog=catalog,
|
||||
fleet=fleet,
|
||||
workload_config=workload,
|
||||
dispatcher_settings=dispatch_settings,
|
||||
seed=42,
|
||||
)
|
||||
|
||||
env.run(until=300.0)
|
||||
|
||||
# Verify trajectory recording in memory
|
||||
for r_id in env.robots:
|
||||
assert r_id in env.trajectories
|
||||
assert len(env.trajectories[r_id]) > 0
|
||||
point = env.trajectories[r_id][0]
|
||||
assert "t" in point
|
||||
assert "pos" in point
|
||||
assert "yaw_deg" in point
|
||||
assert "state" in point
|
||||
assert len(point["pos"]) == 3
|
||||
|
||||
# Export trajectory
|
||||
out_file = tmp_path / "test_trajectory.json"
|
||||
exported_path = env.export_trajectories(out_file)
|
||||
|
||||
assert exported_path.exists()
|
||||
assert exported_path.stat().st_size > 1000
|
||||
|
||||
with open(exported_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
assert "metadata" in data
|
||||
assert "robots" in data
|
||||
meta = data["metadata"]
|
||||
assert meta["coordinate_system"] == "right_handed_cartesian_meters_z_up"
|
||||
assert meta["total_robots"] == 4
|
||||
assert meta["total_trajectory_points"] > 10
|
||||
assert len(data["robots"]) == 4
|
||||
Reference in New Issue
Block a user