Files
Warehouse-Digital-Twin-and-…/tests/unit/test_warehouse_graph.py
T

304 lines
11 KiB
Python

"""Unit tests for warehouse graph builder, domain models, and topological connectivity."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
import networkx as nx
from warehouse_twin.config.loader import ConfigLoader
from warehouse_twin.domain.warehouse import (
NodeType,
Position3D,
StationType,
WarehouseDimensions,
WarehouseModel,
ZoneArea,
)
from warehouse_twin.routing.graph_builder import (
ConnectivityReport,
DisconnectedGraphError,
UnreachableStationError,
WarehouseGraphBuilder,
WarehouseGraphError,
)
def test_position3d_geometry():
"""Verify 3D Cartesian coordinates and Euclidean distance metric."""
p1 = Position3D(0.0, 0.0, 0.0)
p2 = Position3D(3.0, 4.0, 0.0)
assert p1.distance_to(p2) == pytest.approx(5.0)
p3 = Position3D.from_iterable([10.5, 20.5, 2.0])
assert p3.x == 10.5
assert p3.y == 20.5
assert p3.z == 2.0
assert p3.to_list() == [10.5, 20.5, 2.0]
assert p3.to_tuple() == (10.5, 20.5, 2.0)
def test_zone_area_bounds():
"""Verify 2D bounding box inclusion logic."""
area = ZoneArea(x_min=5.0, x_max=25.0, y_min=5.0, y_max=35.0)
inside = Position3D(15.0, 20.0, 0.0)
outside = Position3D(2.0, 20.0, 0.0)
assert area.contains(inside) is True
assert area.contains(outside) is False
def test_warehouse_model_parsing(project_config_dir: Path):
"""Verify WarehouseModel parses dimensions, zones, stations, and chargers."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
model = WarehouseModel.from_config_dict(bundle.warehouse)
assert model.dimensions.width == 60.0
assert model.dimensions.depth == 40.0
assert "zone_a" in model.zones
assert "zone_b" in model.zones
assert "zone_c" in model.zones
assert len(model.stations) >= 6
assert len(model.charging_stations) >= 4
assert len(model.storage_locations) == 28
def test_build_graph_structure(project_config_dir: Path):
"""Verify that graph builder constructs vertices, typed nodes, and weighted edges."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
assert graph.number_of_nodes() > 450
assert graph.number_of_edges() > 1400
# Verify key operational station nodes exist
assert graph.has_node("station_dock_inbound_1")
assert graph.nodes["station_dock_inbound_1"]["node_type"] == NodeType.INBOUND_DOCK.value
assert graph.has_node("station_picking_station_a1")
assert graph.nodes["station_picking_station_a1"]["node_type"] == NodeType.PICKING_STATION.value
assert graph.has_node("station_production_dropoff_c1")
assert graph.nodes["station_production_dropoff_c1"]["node_type"] == NodeType.PRODUCTION_FEED.value
assert graph.has_node("charger_charge_bay_1")
assert graph.nodes["charger_charge_bay_1"]["node_type"] == NodeType.CHARGING_BAY.value
# Verify rack nodes exist
assert graph.has_node("rack_rack_a_01")
assert graph.has_node("rack_rack_b_01")
assert graph.has_node("rack_rack_c_01")
# Verify edge data attributes
for u, v, d in graph.edges(data=True):
assert "distance" in d and d["distance"] > 0
assert "speed_limit" in d and d["speed_limit"] > 0
assert "traversal_time" in d and d["traversal_time"] > 0
assert "allowed_robot_types" in d
assert len(d["allowed_robot_types"]) > 0
def test_graph_connectivity_report(project_config_dir: Path):
"""Verify strong connectivity, complete station reachability, and distribution metrics."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
report: ConnectivityReport = builder.validate_connectivity(graph)
assert report.is_strongly_connected is True
assert report.component_count == 1
assert report.stations_reachable == report.total_stations == 6
assert report.chargers_reachable == report.total_chargers == 8
assert report.storage_racks_reachable == report.total_storage_racks == 28
assert report.total_lane_length_meters > 1000.0
# Check zone node distribution
assert "zone_a" in report.zone_node_distribution
assert "zone_b" in report.zone_node_distribution
assert "zone_c" in report.zone_node_distribution
assert "transit" in report.zone_node_distribution
def test_zone_b_restricted_to_heavy_amr(project_config_dir: Path):
"""Verify operational constraint: Zone B restricts light AMRs and allows heavy AMRs."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
report = builder.validate_connectivity(graph, robot_types=["light_amr", "heavy_amr"])
# Heavy AMR can access everything
assert report.robot_type_reachability["heavy_amr"] is True
# Light AMR is restricted from Zone B
assert report.robot_type_reachability["light_amr"] is True
# Manually check Zone B edges
zone_b_edges = [
(u, v, d) for u, v, d in graph.edges(data=True)
if d.get("zone") == "zone_b"
]
assert len(zone_b_edges) > 0
for _, _, d in zone_b_edges:
assert "heavy_amr" in d["allowed_robot_types"]
assert "light_amr" not in d["allowed_robot_types"]
def test_disconnected_graph_raises_error(project_config_dir: Path):
"""Verify that a partitioned graph triggers DisconnectedGraphError."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
# Artificially isolate an arbitrary waypoint by removing all its incident edges
wp_to_isolate = "wp_100_100"
in_edges = list(graph.in_edges(wp_to_isolate))
out_edges = list(graph.out_edges(wp_to_isolate))
graph.remove_edges_from(in_edges + out_edges)
with pytest.raises(DisconnectedGraphError) as exc_info:
builder.validate_connectivity(graph)
assert "Warehouse graph is disconnected" in str(exc_info.value)
def test_unreachable_station_raises_error(project_config_dir: Path):
"""Verify that an unreachable station triggers UnreachableStationError."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
# Sever all edges connecting inbound dock 1
st_node = "station_dock_inbound_1"
graph.remove_edges_from(list(graph.in_edges(st_node)) + list(graph.out_edges(st_node)))
with pytest.raises(WarehouseGraphError) as exc_info:
builder.validate_connectivity(graph)
# Could be caught by disconnected check or unreachable station check
assert "dock_inbound_1" in str(exc_info.value) or "disconnected" in str(exc_info.value)
def test_export_topology_dict_and_json(project_config_dir: Path, tmp_path: Path):
"""Verify serialization of graph topology to dictionary and JSON file."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
topo = builder.export_topology_dict()
assert "metadata" in topo
assert "zones" in topo
assert "stations" in topo
assert "charging_stations" in topo
assert "storage_locations" in topo
assert "nodes" in topo
assert "edges" in topo
assert topo["metadata"]["node_count"] > 450
assert topo["metadata"]["edge_count"] > 1400
out_file = tmp_path / "test_export_graph.json"
saved = builder.export_json(out_file)
assert saved.exists()
assert saved.stat().st_size > 10000
# Validate JSON structure
with open(saved, "r", encoding="utf-8") as f:
reloaded = json.load(f)
assert len(reloaded["nodes"]) == topo["metadata"]["node_count"]
def test_export_usda_scene(project_config_dir: Path, tmp_path: Path):
"""Verify OpenUSD (.usda) scene generation for 3D visualization."""
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
model = WarehouseModel.from_config_dict(bundle.warehouse)
generator = WarehouseUSDGenerator(model)
usda_path = tmp_path / "test_warehouse.usda"
saved = generator.export_usda(usda_path)
assert saved.exists()
content = saved.read_text(encoding="utf-8")
# Verify standard OpenUSD headers and prims
assert "#usda 1.0" in content
assert 'defaultPrim = "World"' in content
assert 'metersPerUnit = 1.0' in content
assert 'upAxis = "Z"' in content
assert 'def Xform "World"' in content
assert 'def Scope "Zones"' in content
assert 'def Scope "StorageRacks"' in content
assert 'def Scope "Stations"' in content
assert 'def Scope "ChargingStations"' in content
# Check key entity prims
assert 'def Cube "zone_a"' in content
assert 'def Cube "zone_b"' in content
assert 'def Cube "zone_c"' in content
assert 'def Xform "dock_inbound_1"' in content
assert 'def Xform "picking_station_a1"' in content
assert 'def Xform "charge_bay_1"' in content
assert 'def Xform "rack_a_01"' in content
def test_export_usda_with_robots(project_config_dir: Path, tmp_path: Path):
"""Verify OpenUSD scene generation includes AMR fleet entities when provided."""
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
generator = WarehouseUSDGenerator.from_config_bundle(bundle)
usda_path = tmp_path / "test_warehouse_phase2.usda"
saved = generator.export_usda(usda_path)
assert saved.exists()
content = saved.read_text(encoding="utf-8")
assert 'def Scope "Robots"' in content
assert 'def Xform "amr_light_01"' in content
assert 'def Xform "amr_light_02"' in content
assert 'def Xform "amr_heavy_01"' in content
assert 'def Xform "amr_heavy_02"' in content
assert 'def Cube "StatusDome"' in content
def test_slow_moving_zone_b_has_wider_aisles(project_config_dir: Path):
"""Verify that slow-moving Zone B has significantly wider aisles than fast-moving Zone A."""
loader = ConfigLoader(project_config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
# Extract unique X positions of internal aisles in Zone A and Zone B
zone_a_xs = sorted(set(
d["x"] for n, d in graph.nodes(data=True)
if d.get("zone") == "zone_a" and d.get("node_type") == NodeType.WAYPOINT.value
))
zone_b_xs = sorted(set(
d["x"] for n, d in graph.nodes(data=True)
if d.get("zone") == "zone_b" and d.get("node_type") == NodeType.WAYPOINT.value
))
# Calculate aisle spacings
zone_a_spacing = zone_a_xs[1] - zone_a_xs[0]
zone_b_spacing = zone_b_xs[1] - zone_b_xs[0]
assert zone_b_spacing > zone_a_spacing
assert zone_b_spacing == 4.0
assert zone_a_spacing == 2.0