"""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" def test_paths_never_pass_through_intermediate_racks(planner_setup): """Verify that paths from racks to stations never pass through other storage racks.""" planner, builder, graph = planner_setup warehouse = builder.model rack_positions = {k: (v.position.x, v.position.y) for k, v in warehouse.storage_locations.items()} for loc_id, pos in rack_positions.items(): src = f"rack_{loc_id}" for st_id in warehouse.stations.keys(): dest = f"station_{st_id}" for rtype in ["heavy_amr", "light_amr"]: if rtype == "light_amr" and ("_b_" in loc_id or "picking_station_b1" in st_id): continue path = planner.find_shortest_path(src, dest, robot_type=rtype) assert len(path) >= 2 assert path[0] in (src, planner.resolve_node_id(src)) assert path[-1] == dest # Check intermediate nodes: must not coincide with any other rack for intermediate_nid in path[1:-1]: assert graph.nodes[intermediate_nid].get("node_type") != "storage_rack" int_pos = (graph.nodes[intermediate_nid]["pos"][0], graph.nodes[intermediate_nid]["pos"][1]) for other_loc_id, other_pos in rack_positions.items(): if other_loc_id != loc_id: dist = ( (int_pos[0] - other_pos[0]) ** 2 + (int_pos[1] - other_pos[1]) ** 2 ) ** 0.5 assert dist >= 0.5, ( f"Path from {src} to {dest} ({rtype}) improperly cuts through {other_loc_id} " f"at node {intermediate_nid} {int_pos}" ) def test_rack_aisle_waypoint_lookup(planner_setup): """Verify get_rack_aisle_waypoint identifies traversable aisle waypoint outside rack footprint.""" planner, builder, graph = planner_setup warehouse = builder.model for loc_id, loc in warehouse.storage_locations.items(): rnid = f"rack_{loc_id}" aisle_wp = planner.get_rack_aisle_waypoint(rnid) assert aisle_wp is not None assert graph.has_node(aisle_wp) assert graph.nodes[aisle_wp].get("node_type") != "storage_rack" wp_pos = planner.get_node_position(aisle_wp) dist = loc.position.distance_to(wp_pos) # Aisle waypoint must be at least 1.0m away from the rack structure assert dist >= 1.0 def test_paths_never_pass_through_intermediate_stations(planner_setup): """Verify that paths between stations/chargers never pass through intermediate docking stations.""" planner, builder, graph = planner_setup warehouse = builder.model station_nodes = [f"station_{s}" for s in warehouse.stations.keys()] # Test routes between station pairs and between stations and chargers for src in station_nodes: for dst in station_nodes: if src == dst: continue path = planner.find_shortest_path(src, dst, robot_type="heavy_amr") assert len(path) >= 2 assert path[0] == src assert path[-1] == dst # Intermediate nodes must not be any other station or coincident station waypoint for intermediate_nid in path[1:-1]: assert intermediate_nid not in station_nodes for other_st in station_nodes: if other_st != src and other_st != dst: coinc = planner._nodes_at_station_locations.get(other_st, set()) assert intermediate_nid not in coinc, ( f"Path from {src} to {dst} improperly passed through intermediate dock {other_st} " f"at node {intermediate_nid}" )