Update warehouse digital twin and robot fleet optimization

This commit is contained in:
DnyaneshwariP13
2026-11-25 11:54:38 +05:30
parent e9c573ddc2
commit acab3a1f5b
367 changed files with 4411504 additions and 110561 deletions
+49
View File
@@ -129,3 +129,52 @@ def sample_inventory_catalog():
"""Return an initialized InventoryCatalog instance."""
from tests.fixtures.sample_models import create_sample_inventory_catalog
return create_sample_inventory_catalog()
@pytest.fixture
def sample_warehouse_config(project_config_dir: Path) -> Dict[str, Any]:
"""Return the raw dictionary from project warehouse.json."""
with open(project_config_dir / "warehouse.json", "r", encoding="utf-8") as f:
return json.load(f)
@pytest.fixture
def sim_env_builder(project_config_dir: Path, tmp_path: Path):
"""Fixture builder providing initialized SimulationEnvironment instances."""
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 _create_env(seed: int = 42, event_log: bool = False):
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)
log_file = tmp_path / f"events_seed_{seed}.jsonl" if event_log else None
return SimulationEnvironment(
warehouse=warehouse,
catalog=catalog,
fleet=fleet,
workload_config=workload,
dispatcher_settings=dispatch_settings,
event_log_path=log_file,
seed=seed,
)
return _create_env
@@ -0,0 +1,86 @@
"""Integration tests for Three-Stage Demonstration video generation and FFmpeg encoding."""
import os
from pathlib import Path
import pytest
from warehouse_twin.demo.staged_video_generator import StagedVideoGenerator, verify_video
from warehouse_twin.visualization.trajectory_player import TrajectoryData
def test_staged_demo_video_rendering_and_ffmpeg_encoding(tmp_path: Path):
"""Verify that StagedVideoGenerator produces broadcast-quality 1080p MP4 videos validated by ffprobe."""
# 1. Prepare minimal valid trajectory data
mock_traj = {
"metadata": {
"simulation_duration": 6.0,
"random_seed": 42,
},
"robots": {
"amr_light_01": [
{"t": 0.0, "pos": [2.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "IDLE", "battery_percent": 100.0, "is_loaded": False},
{"t": 2.0, "pos": [8.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "MOVING_EMPTY", "battery_percent": 99.0, "is_loaded": False},
{"t": 4.0, "pos": [14.0, 36.0, 0.0], "yaw_deg": 90.0, "state": "LOADED_TRANSIT", "battery_percent": 98.0, "is_loaded": True},
{"t": 6.0, "pos": [14.0, 30.0, 0.0], "yaw_deg": 90.0, "state": "DROPPING", "battery_percent": 97.0, "is_loaded": True},
],
"amr_heavy_01": [
{"t": 0.0, "pos": [2.0, 38.0, 0.0], "yaw_deg": 0.0, "state": "IDLE", "battery_percent": 100.0, "is_loaded": False},
{"t": 3.0, "pos": [10.0, 38.0, 0.0], "yaw_deg": 0.0, "state": "CHARGING", "battery_percent": 80.0, "is_loaded": False},
{"t": 6.0, "pos": [10.0, 38.0, 0.0], "yaw_deg": 0.0, "state": "CHARGING", "battery_percent": 85.0, "is_loaded": False},
],
},
}
traj_data = TrajectoryData.from_dict(mock_traj)
# 2. Configure video generator and inputs
from warehouse_twin.config.loader import ConfigLoader
from warehouse_twin.analytics.kpi_calculator import ComprehensiveKPIReport, DistributionStats
project_root = Path(__file__).resolve().parent.parent.parent
loader = ConfigLoader(project_root / "config")
bundle = loader.load_all()
out_video = tmp_path / "test_stage1_preview.mp4"
generator = StagedVideoGenerator(
width=1920,
height=1080,
fps=15, # Faster for test execution
playback_speed=2.0,
)
kpi_report = ComprehensiveKPIReport(
throughput_tasks_per_hour=78.5,
turnaround_time=DistributionStats(p50=35.0, p90=45.2),
on_time_delivery_percent=100.0,
total_travel_distance_meters=420.5,
loaded_distance_ratio_percent=58.2,
fleet_utilization_percent=68.4,
conflicts_detected=0,
total_yield_wait_time_seconds=0.0,
energy_intensity_kwh_per_task=0.042,
total_energy_consumed_kwh=1.25,
tasks_completed=12,
bay_occupancy_percent=25.0,
avg_charging_queue_wait_seconds=0.0,
)
# 3. Render video
result_path = generator.render_baseline_video(
output_mp4=out_video,
wh_cfg=bundle.warehouse,
trajectory_data=traj_data,
kpi_report=kpi_report,
duration_seconds=6.0,
)
# 4. Assert video file was written
assert result_path.exists(), f"Rendered video should exist at {result_path}"
assert result_path.stat().st_size > 5000, "Rendered video file size must exceed 5KB"
# 5. Validate video with ffprobe
probe = verify_video(str(result_path))
assert probe["valid"] is True, f"Video verification failed: {probe.get('error')}"
assert probe["width"] == 1920, f"Expected width 1920, got {probe.get('width')}"
assert probe["height"] == 1080, f"Expected height 1080, got {probe.get('height')}"
assert probe["codec"] in ("h264", "libx264"), f"Expected h264 codec, got {probe.get('codec')}"
assert probe["duration_seconds"] > 0, "Video duration must be positive"
+1
View File
@@ -33,6 +33,7 @@ def test_asset_manifest_structure_and_completeness(manifest_path: Path):
"amr_light",
"amr_heavy",
"dock_inbound",
"dock_outbound",
"picking_station",
"charging_station",
"safety_barrier",
+55
View File
@@ -0,0 +1,55 @@
"""Unit tests for intelligent, distributed charging station placement and layout planner."""
import pytest
from warehouse_twin.domain.warehouse import Position3D, StorageLocation
from warehouse_twin.layout.charging_planner import ChargingPlannerConfig, ChargingStationPlanner
def test_charging_planner_distributed_placement():
"""Verify charging planner distributes stations across perimeter alcoves without rack collision."""
planner = ChargingStationPlanner(
ChargingPlannerConfig(
num_stations=4,
charging_rates_kw=[25.0, 25.0, 50.0, 50.0],
min_station_separation=3.0,
approach_clearance=1.0,
)
)
# Sample storage locations in warehouse center
storage_locs = [
StorageLocation(
location_id=f"rack_{i}",
zone="zone_a",
position=Position3D(10.0 + (i % 3) * 4.0, 10.0 + (i // 3) * 3.0, 0.0),
rack_dimensions=(2.4, 1.0, 3.0),
)
for i in range(6)
]
stations = planner.plan_charging_stations(
warehouse_width=40.0,
warehouse_depth=30.0,
storage_locations=storage_locs,
)
# 1. Count and capacity assertions
assert len(stations) == 4
for st in stations:
assert st.capacity == 1 # Single berth only
assert st.charging_rate_kw in (25.0, 50.0)
# 2. Minimum separation assertion
for i in range(len(stations)):
for j in range(i + 1, len(stations)):
dist = stations[i].position.distance_to(stations[j].position)
assert dist >= 2.8, f"Stations {stations[i].station_id} and {stations[j].station_id} too close ({dist:.2f}m)"
# 3. Not inside any rack footprint
for st in stations:
for r in storage_locs:
half_w = r.rack_dimensions[0] / 2.0
half_d = r.rack_dimensions[1] / 2.0
inside_x = (r.position.x - half_w <= st.position.x <= r.position.x + half_w)
inside_y = (r.position.y - half_d <= st.position.y <= r.position.y + half_d)
assert not (inside_x and inside_y), f"Station {st.station_id} inside rack {r.location_id}"
+70
View File
@@ -0,0 +1,70 @@
"""Unit tests for multi-robot collision avoidance, footprint clearance, and headway enforcement."""
import pytest
from warehouse_twin.domain.warehouse import Position3D
from warehouse_twin.routing.reservations import TimeSpaceReservationGrid
def test_footprint_aware_spatial_clearance_conflict():
"""Verify two robots attempting to reserve nearby nodes within footprint distance trigger conflict."""
# Define node positions with wp_1 at (10.0, 10.0) and wp_2 at (10.5, 10.0) -> distance 0.5m
node_positions = {
"wp_1": Position3D(10.0, 10.0, 0.0),
"wp_2": Position3D(10.5, 10.0, 0.0),
"wp_far": Position3D(15.0, 10.0, 0.0),
}
grid = TimeSpaceReservationGrid(
safety_buffer_seconds=1.0,
node_positions=node_positions,
robot_footprint_radius=0.5, # 2 * 0.5 = 1.0m min safe distance
)
# Robot 1 reserves wp_1 from t=10.0 to t=15.0
r1 = grid.reserve_node("wp_1", t_start=10.0, t_end=15.0, robot_id="amr_01")
assert r1 is True
# Robot 2 attempts to reserve wp_2 (0.5m away, < 1.0m safe distance) at overlapping time [11.0, 14.0]
is_free_nearby, conflict_id = grid.is_node_free("wp_2", t_start=11.0, t_end=14.0, ignore_robot_id="amr_02")
assert is_free_nearby is False
assert conflict_id == "amr_01"
# Robot 2 attempts to reserve wp_far (5.0m away, > 1.0m) at overlapping time -> Free!
is_free_far, _ = grid.is_node_free("wp_far", t_start=11.0, t_end=14.0, ignore_robot_id="amr_02")
assert is_free_far is True
def test_exclusive_berth_occupancy():
"""Verify only one robot can reserve a charging berth or picking point at a time."""
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
# Robot 1 reserves charge bay 1
assert grid.reserve_node("charge_bay_1", 20.0, 50.0, robot_id="amr_01") is True
# Robot 2 requests same berth during charging window -> Rejected
is_free, conflict_id = grid.is_node_free("charge_bay_1", 30.0, 60.0, ignore_robot_id="amr_02")
assert is_free is False
assert conflict_id == "amr_01"
# Robot 2 requests berth after Robot 1 completes + safety buffer [52.0, 80.0] -> Approved
is_free_after, _ = grid.is_node_free("charge_bay_1", 52.0, 80.0, ignore_robot_id="amr_02")
assert is_free_after is True
def test_reservation_release_on_task_finish_or_reassignment():
"""Verify releasing reservations for a robot immediately frees the slot for other fleet members."""
grid = TimeSpaceReservationGrid(safety_buffer_seconds=1.0)
# Robot 1 reserves nodes wp_a, wp_b, wp_c
grid.reserve_node("wp_a", 10.0, 15.0, robot_id="amr_01")
grid.reserve_node("wp_b", 15.0, 20.0, robot_id="amr_01")
# Robot 2 is blocked at wp_a
assert grid.is_node_free("wp_a", 11.0, 14.0, ignore_robot_id="amr_02")[0] is False
# Robot 1 cancels task / aborts: release reservations
released = grid.release_reservations_for_robot("amr_01")
assert released == 2
# Now wp_a is immediately available for Robot 2
assert grid.is_node_free("wp_a", 11.0, 14.0, ignore_robot_id="amr_02")[0] is True
+56
View File
@@ -0,0 +1,56 @@
"""Unit tests for DeadlockManager wait-for graph cycle detection and recovery arbitration."""
import pytest
from warehouse_twin.routing.deadlock_manager import DeadlockManager, DeadlockRecord
def test_deadlock_manager_no_cycle_normal_queue():
"""Verify linear wait queue (A waits for B, B waits for C) does not trigger false deadlock."""
dm = DeadlockManager(deadlock_timeout_seconds=20.0)
# Robot 1 waits for Robot 2
r1 = dm.register_wait("amr_01", current_node="wp_1", waiting_for_robot_id="amr_02", current_time=10.0)
assert r1 is None
# Robot 2 waits for Robot 3
r2 = dm.register_wait("amr_02", current_node="wp_2", waiting_for_robot_id="amr_03", current_time=11.0)
assert r2 is None
assert dm.deadlocks_detected == 0
def test_deadlock_manager_detects_and_resolves_circular_deadlock():
"""Verify circular dependency (A -> B -> A) triggers immediate deadlock detection and victim selection."""
dm = DeadlockManager(deadlock_timeout_seconds=20.0)
# Robot 1 waits for Robot 2
dm.register_wait("amr_01", current_node="wp_1", waiting_for_robot_id="amr_02", current_time=10.0)
# Robot 2 waits for Robot 1 -> Circular Deadlock!
record = dm.register_wait("amr_02", current_node="wp_2", waiting_for_robot_id="amr_01", current_time=12.0)
assert record is not None
assert isinstance(record, DeadlockRecord)
assert dm.deadlocks_detected == 1
assert dm.deadlocks_resolved == 1
assert set(record.involved_robots) == {"amr_01", "amr_02"}
assert record.resolution_action == "REPLAN_VICTIM"
assert record.victim_robot_id == "amr_02" # Deterministic max ID selection
def test_deadlock_manager_prolonged_wait_detection():
"""Verify prolonged wait exceeding timeout threshold is identified."""
dm = DeadlockManager(deadlock_timeout_seconds=15.0)
dm.register_wait("amr_01", current_node="wp_1", waiting_for_robot_id="amr_02", current_time=10.0)
# At t=20.0 (elapsed 10s < 15s timeout)
assert len(dm.check_prolonged_waits(current_time=20.0)) == 0
# At t=26.0 (elapsed 16s > 15s timeout)
timed_out = dm.check_prolonged_waits(current_time=26.0)
assert timed_out == ["amr_01"]
# When wait is cleared, it no longer triggers timeout
dm.clear_wait("amr_01")
assert len(dm.check_prolonged_waits(current_time=30.0)) == 0
+4 -4
View File
@@ -104,22 +104,22 @@ def test_inventory_catalog_loading(project_config_dir: Path):
bundle = loader.load_all()
catalog = InventoryCatalog.from_config_dict(bundle.inventory)
assert catalog.total_sku_count() == 13
assert catalog.total_sku_count() == 28
# Check Zone A items
zone_a_items = catalog.get_items_by_zone("zone_a")
assert len(zone_a_items) == 5
assert len(zone_a_items) == 12
assert any(i.item_id == "filter_hydraulic_hf1" for i in zone_a_items)
assert any(i.item_id == "belt_drive_bd10" for i in zone_a_items)
# Check Zone B items
zone_b_items = catalog.get_items_by_zone("zone_b")
assert len(zone_b_items) == 4
assert len(zone_b_items) == 8
assert any(i.item_id == "transmission_combine_ct8" for i in zone_b_items)
assert any(i.item_id == "structural_chassis_frame_sf3" for i in zone_b_items)
# Check Zone C items
zone_c_items = catalog.get_items_by_zone("zone_c")
assert len(zone_c_items) == 4
assert len(zone_c_items) == 8
assert any(i.item_id == "raw_steel_coil_sc5" for i in zone_c_items)
assert any(i.item_id == "electronic_control_module_ecm9" for i in zone_c_items)
+117
View File
@@ -0,0 +1,117 @@
"""Unit tests for configurable multi-row warehouse layout generation, boundaries, and validation."""
import pytest
from warehouse_twin.domain.grid import CellType
from warehouse_twin.domain.warehouse import WarehouseDimensions
from warehouse_twin.layout.layout_generator import ModularWarehouseBuilder, WarehouseLayoutConfig
from warehouse_twin.layout.layout_validator import LayoutValidator
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
def test_modular_warehouse_builder_creates_valid_test_layout():
"""Verify test warehouse generation with 2 parallel rack rows, cross aisles, and chargers."""
cfg = WarehouseLayoutConfig(
warehouse_length=30.0,
warehouse_width=20.0,
warehouse_height=6.0,
grid_cell_size=0.5,
rack_length=2.4,
rack_depth=1.0,
rack_height=3.0,
num_shelf_levels=3,
num_rows=2,
bays_per_row=4,
clear_aisle_width=2.0,
num_chargers=2,
)
builder = ModularWarehouseBuilder(cfg)
model, grid, report = builder.build_test_layout()
# 1. Structural assertions
assert model.dimensions.width == 30.0
assert model.dimensions.depth == 20.0
assert len(model.storage_locations) == 8 # 2 rows * 4 bays
assert len(model.picking_points) == 8
assert len(model.charging_stations) == 2
# 2. Layout validation report must pass cleanly without errors
assert report.is_valid is True
assert len(report.errors) == 0
assert report.num_racks == 8
assert report.num_picking_points == 8
def test_layout_validator_detects_boundary_and_overlap_violations():
"""Verify LayoutValidator flags racks outside boundaries and intersecting footprints."""
validator = LayoutValidator()
# Test 1: Rack exceeding boundary
from warehouse_twin.domain.warehouse import Position3D, StorageLocation, WarehouseModel
dims = WarehouseDimensions(width=20.0, depth=15.0, height=5.0)
rack_outside = StorageLocation(
location_id="rack_out",
zone="zone_a",
position=Position3D(19.5, 14.5, 0.0),
rack_dimensions=(2.4, 1.0, 3.0), # extends to x=20.7, y=15.0
)
model_bad = WarehouseModel(
dimensions=dims,
zones={},
stations={},
charging_stations={},
storage_locations={"rack_out": rack_outside},
)
rep1 = validator.validate_warehouse_model(model_bad)
assert rep1.is_valid is False
assert any("exceeds warehouse boundary" in err for err in rep1.errors)
# Test 2: Overlapping racks
r1 = StorageLocation(
location_id="r1",
zone="zone_a",
position=Position3D(10.0, 8.0, 0.0),
rack_dimensions=(2.4, 1.0, 3.0),
)
r2 = StorageLocation(
location_id="r2",
zone="zone_a",
position=Position3D(10.5, 8.2, 0.0), # Direct overlap
rack_dimensions=(2.4, 1.0, 3.0),
)
model_overlap = WarehouseModel(
dimensions=dims,
zones={},
stations={},
charging_stations={},
storage_locations={"r1": r1, "r2": r2},
)
rep2 = validator.validate_warehouse_model(model_overlap)
assert rep2.is_valid is False
assert any("footprint collision" in err for err in rep2.errors)
def test_generated_layout_graph_connectivity():
"""Verify WarehouseGraphBuilder successfully builds a connected graph for generated layout."""
cfg = WarehouseLayoutConfig(
warehouse_length=30.0,
warehouse_width=20.0,
num_rows=2,
bays_per_row=3,
num_chargers=2,
)
builder = ModularWarehouseBuilder(cfg)
model, grid, _ = builder.build_test_layout()
config_dict = builder.export_to_config_dict(model)
graph_builder = WarehouseGraphBuilder.from_config_dict(config_dict)
graph = graph_builder.build_graph()
# Validate reachability
report = builder.validator.validate_warehouse_model(model, graph=graph)
assert report.is_valid is True
assert len(report.errors) == 0
# Ensure all picking points are in the graph and reachable
for loc_id in model.storage_locations:
assert graph.has_node(f"pick_{loc_id}")
+9 -8
View File
@@ -31,21 +31,21 @@ def test_decentralized_charging_layout_configuration(project_config_dir: Path):
base_cfg = optimizer.get_warehouse_config(LayoutVariant.BASELINE)
base_bays = base_cfg["charging_stations"]
assert len(base_bays) == 4
# Baseline chargers are all grouped in the NW corner (x <= 8.0, y = 36.0)
assert len(base_bays) == 8
# Baseline chargers are all grouped in the NW corner (x <= 16.0, y = 36.0)
for b in base_bays:
assert b["position"][0] <= 8.0
assert b["position"][0] <= 16.0
assert b["position"][1] == 36.0
decent_cfg = optimizer.get_warehouse_config(LayoutVariant.DECENTRALIZED_CHARGING)
decent_bays = decent_cfg["charging_stations"]
assert len(decent_bays) == 4
assert len(decent_bays) == 8
positions = [b["position"] for b in decent_bays]
# Bay 3 should be in Zone B picking area (x=30.0, y=2.0)
# Bay 5 should be in Zone B picking area (x=30.0, y=2.0)
assert [30.0, 2.0, 0.0] in positions
# Bay 4 should be in Zone C production feed area (x=52.0, y=36.0)
assert [52.0, 36.0, 0.0] in positions
# Bay 7 should be in Zone C production feed area (x=48.0, y=36.0, non-overlapping with dropoff dock)
assert [48.0, 36.0, 0.0] in positions
def test_velocity_slotting_inventory_configuration(project_config_dir: Path):
@@ -108,6 +108,7 @@ def test_layout_comparison_simulation(project_config_dir: Path, tmp_path: Path):
# Export layout configs
cfgs = optimizer.export_layout_configs(tmp_path / "configs")
assert len(cfgs) == 5
assert len(cfgs) == len(LayoutVariant)
assert (tmp_path / "configs" / "warehouse_baseline.json").exists()
assert (tmp_path / "configs" / "warehouse_hybrid_optimal.json").exists()
assert (tmp_path / "configs" / "warehouse_efficiency_optimized.json").exists()
+66
View File
@@ -0,0 +1,66 @@
"""Unit tests for LayoutValidator geometric rules, reachability, and validation reporting."""
import pytest
import networkx as nx
from warehouse_twin.domain.warehouse import (
ChargingStation,
Position3D,
StorageLocation,
WarehouseDimensions,
WarehouseModel,
)
from warehouse_twin.layout.layout_validator import LayoutValidator, LayoutValidationReport
def test_layout_validator_unreachable_station_in_graph():
"""Verify LayoutValidator identifies stations missing from or disconnected in graph."""
dims = WarehouseDimensions(width=30.0, depth=20.0, height=6.0)
loc = StorageLocation(
location_id="rack_isolated",
zone="zone_a",
position=Position3D(10.0, 10.0, 0.0),
rack_dimensions=(2.4, 1.0, 3.0),
)
ch = ChargingStation(
station_id="ch_isolated",
position=Position3D(2.0, 18.0, 0.0),
charging_rate_kw=25.0,
capacity=1,
)
model = WarehouseModel(
dimensions=dims,
zones={},
stations={},
charging_stations={"ch_isolated": ch},
storage_locations={"rack_isolated": loc},
)
# Graph with aisle node, but without connections to pick_rack_isolated or charge_ch_isolated
graph = nx.DiGraph()
graph.add_node("aisle_root", node_type="aisle", pos=[5.0, 5.0, 0.0])
validator = LayoutValidator()
report = validator.validate_warehouse_model(model, graph=graph)
assert report.is_valid is False
assert any("Graph missing picking point node 'pick_rack_isolated'" in err for err in report.errors)
assert any("Graph missing charging station node 'charge_ch_isolated'" in err for err in report.errors)
def test_layout_validator_report_serialization():
"""Verify LayoutValidationReport converts cleanly to audit dictionary."""
rep = LayoutValidationReport(
is_valid=True,
errors=[],
warnings=["Aisle width is narrow near Zone B"],
num_racks=12,
num_picking_points=12,
num_charging_stations=3,
summary={"total_area_sqm": 600.0},
)
d = rep.to_dict()
assert d["is_valid"] is True
assert d["error_count"] == 0
assert d["warning_count"] == 1
assert d["num_racks"] == 12
assert d["summary"]["total_area_sqm"] == 600.0
+3 -3
View File
@@ -25,9 +25,9 @@ def order_gen_fixtures(project_config_dir: Path):
def test_order_generator_initialization(order_gen_fixtures):
gen, workload, catalog, warehouse = order_gen_fixtures
assert len(gen.zone_a_items) == 5
assert len(gen.zone_b_items) == 4
assert len(gen.zone_c_items) == 4
assert len(gen.zone_a_items) == 12
assert len(gen.zone_b_items) == 8
assert len(gen.zone_c_items) == 8
def test_zone_a_task_generation(order_gen_fixtures):
+81
View File
@@ -204,3 +204,84 @@ def test_closest_node_lookup(planner_setup):
# 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}"
)
+199
View File
@@ -0,0 +1,199 @@
"""Unit tests for rack-side picking points, approach positions, and grid coordinate conventions."""
import pytest
from warehouse_twin.domain.grid import CellType, GridConfig, WarehouseGrid
from warehouse_twin.domain.warehouse import (
NodeType,
PickingPoint,
Position3D,
StorageLocation,
WarehouseDimensions,
WarehouseModel,
)
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
from warehouse_twin.routing.path_planner import PathPlanner
from warehouse_twin.simulation.dispatcher import FleetDispatcher
from warehouse_twin.simulation.sim_engine import SimulationEnvironment
from warehouse_twin.domain.robot import Robot, RobotState, RobotTypeSpec
from warehouse_twin.domain.task import Task, TaskType
def test_picking_point_calculation_all_orientations():
"""Verify front-facing picking point coordinates and yaw across all 4 rack orientations."""
center = Position3D(10.0, 20.0, 0.0)
dims = (2.8, 1.2, 4.5) # length (X), depth (Y), height (Z)
clearance = 0.8
# 1. Facing South (aisle is at negative Y)
loc_south = StorageLocation(
location_id="rack_south",
zone="zone_b",
position=center,
rack_dimensions=dims,
facing_direction="south",
approach_clearance=clearance,
)
pt_south = loc_south.get_picking_point()
expected_y_south = 20.0 - (1.2 / 2.0 + clearance) # 20.0 - 1.4 = 18.6
assert pt_south.position.x == pytest.approx(10.0)
assert pt_south.position.y == pytest.approx(expected_y_south)
assert pt_south.approach_yaw_degrees == 90.0 # Robot at south faces North (+Y)
assert pt_south.rack_id == "rack_south"
assert pt_south.prim_path == "/World/Warehouse/PickingPoints/rack_south_Front"
# 2. Facing North (aisle is at positive Y)
loc_north = StorageLocation(
location_id="rack_north",
zone="zone_b",
position=center,
rack_dimensions=dims,
facing_direction="north",
approach_clearance=clearance,
)
pt_north = loc_north.get_picking_point()
expected_y_north = 20.0 + (1.2 / 2.0 + clearance) # 20.0 + 1.4 = 21.4
assert pt_north.position.x == pytest.approx(10.0)
assert pt_north.position.y == pytest.approx(expected_y_north)
assert pt_north.approach_yaw_degrees == -90.0 # Robot at north faces South (-Y)
# 3. Facing West (aisle is at negative X)
loc_west = StorageLocation(
location_id="rack_west",
zone="zone_b",
position=center,
rack_dimensions=dims,
facing_direction="west",
approach_clearance=clearance,
)
pt_west = loc_west.get_picking_point()
expected_x_west = 10.0 - (2.8 / 2.0 + clearance) # 10.0 - 2.2 = 7.8
assert pt_west.position.x == pytest.approx(expected_x_west)
assert pt_west.position.y == pytest.approx(20.0)
assert pt_west.approach_yaw_degrees == 0.0 # Robot at west faces East (+X)
# 4. Facing East (aisle is at positive X)
loc_east = StorageLocation(
location_id="rack_east",
zone="zone_b",
position=center,
rack_dimensions=dims,
facing_direction="east",
approach_clearance=clearance,
)
pt_east = loc_east.get_picking_point()
expected_x_east = 10.0 + (2.8 / 2.0 + clearance) # 10.0 + 2.2 = 12.2
assert pt_east.position.x == pytest.approx(expected_x_east)
assert pt_east.position.y == pytest.approx(20.0)
assert pt_east.approach_yaw_degrees == 180.0 # Robot at east faces West (-X)
from warehouse_twin.domain.events import SimulationEventType
def test_picking_point_outside_rack_footprint():
"""Ensure picking points have safe clearance distance strictly outside physical rack footprint."""
loc = StorageLocation(
location_id="rack_test",
zone="zone_a",
position=Position3D(15.0, 25.0, 0.0),
rack_dimensions=(1.9, 0.8, 3.2),
facing_direction="south",
approach_clearance=0.8,
)
pt = loc.get_picking_point()
half_depth = 0.8 / 2.0
dist = loc.position.distance_to(pt.position)
assert dist == pytest.approx(half_depth + 0.8)
assert pt.position.y < (loc.position.y - half_depth)
def test_warehouse_grid_coordinate_mapping_and_marking():
"""Test WarehouseGrid conversion between continuous world coords and discrete cell matrix."""
cfg = GridConfig(
cell_size=0.5,
warehouse_width=30.0,
warehouse_depth=20.0,
)
grid = WarehouseGrid(cfg)
assert grid.cols == 60
assert grid.rows == 40
# Test coordinate mapping
r, c = grid.world_to_cell(1.2, 2.7)
assert c == 2 # 1.2 / 0.5 = 2.4 -> 2
assert r == 5 # 2.7 / 0.5 = 5.4 -> 5
wx, wy = grid.cell_to_world(5, 2)
assert wx == pytest.approx(1.25)
assert wy == pytest.approx(2.75)
# Test marking rack footprint as non-traversable
grid.mark_rect(8.0, 10.8, 10.0, 11.2, CellType.RACK_FOOTPRINT, occupant_id="rack_1")
cell_inside = grid.get_cell_at_world(9.0, 10.5)
assert cell_inside is not None
assert cell_inside.cell_type == CellType.RACK_FOOTPRINT
assert cell_inside.is_traversable is False
assert grid.is_traversable(9.0, 10.5) is False
# Aisle cell is traversable
grid.mark_cell(10, 10, CellType.AISLE)
cell_aisle = grid.get_cell(10, 10)
assert cell_aisle is not None
assert cell_aisle.is_traversable is True
def test_graph_builder_instantiates_picking_points(sample_warehouse_config):
"""Verify WarehouseGraphBuilder adds PICKING_POINT nodes connected to traversable aisles."""
builder = WarehouseGraphBuilder.from_config_dict(sample_warehouse_config)
graph = builder.build_graph()
for loc_id in builder.model.storage_locations:
pick_node = f"pick_{loc_id}"
assert graph.has_node(pick_node), f"Graph missing picking point {pick_node}"
data = graph.nodes[pick_node]
assert data["node_type"] == NodeType.PICKING_POINT.value
assert "approach_yaw" in data
assert "prim_path" in data
assert graph.degree(pick_node) >= 2 # Connected to aisle and rack
def test_dispatcher_resolves_rack_to_front_picking_point(sample_warehouse_config):
"""Verify FleetDispatcher resolves rack target IDs to the front-facing picking waypoint."""
builder = WarehouseGraphBuilder.from_config_dict(sample_warehouse_config)
graph = builder.build_graph()
dispatcher = FleetDispatcher(graph=graph)
# When querying rack_a_01, dispatcher must return pick_rack_a_01 in the aisle
target_node = dispatcher.get_node_for_entity("rack_a_01")
assert target_node == "pick_rack_a_01"
def test_robot_navigates_to_picking_point_not_rack_center(sim_env_builder):
"""Simulate a picking mission and assert robot stops at picking point outside rack footprint."""
env = sim_env_builder(seed=42)
env.run(until=120.0)
# Inspect ROBOT_ARRIVED events for rack picks
arrival_events = [
e for e in env.events
if e.event_type == SimulationEventType.ROBOT_ARRIVED and e.metadata.get("station", "").startswith("rack_")
]
assert len(arrival_events) > 0
for ev in arrival_events:
rack_id = ev.metadata["station"]
picking_node = ev.metadata.get("picking_point")
assert picking_node is not None
assert picking_node.startswith("pick_rack_")
# Position of robot at pick must match picking point, NOT solid rack center
loc = env.warehouse.storage_locations[rack_id]
pick_pt = loc.get_picking_point()
node_pos = env.path_planner.get_node_position(picking_node)
assert node_pos.x == pytest.approx(pick_pt.position.x, abs=0.1)
assert node_pos.y == pytest.approx(pick_pt.position.y, abs=0.1)
# Distance from solid rack center must be >= 0.8m
dist_to_center = loc.position.distance_to(node_pos)
assert dist_to_center >= 0.8, f"Robot stopped too close ({dist_to_center}m) to rack center {rack_id}"
+64 -2
View File
@@ -113,7 +113,7 @@ def test_warehouse_builder_generates_valid_scene(sample_bundle, manifest_file: P
assert 'def Xform "dock_inbound_1"' in content
assert 'def Xform "picking_station_a1"' in content
assert "dock_inbound.usda" in content
assert "picking_station.usda" in content
assert "dock_outbound.usda" in content
# Charging Bays
assert 'def Scope "ChargingStations"' in content
@@ -144,7 +144,8 @@ def test_robot_animator_single_and_multi_robot(sample_bundle, manifest_file: Pat
"amr_light_01": [
{"t": 0.0, "pos": [2.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "IDLE", "battery_percent": 100.0, "is_loaded": False},
{"t": 5.0, "pos": [12.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "LOADED_TRANSIT", "battery_percent": 98.0, "is_loaded": True},
{"t": 10.0, "pos": [20.0, 36.0, 0.0], "yaw_deg": 90.0, "state": "DROPPING", "battery_percent": 96.0, "is_loaded": True},
{"t": 8.0, "pos": [2.0, 30.0, 0.0], "yaw_deg": 90.0, "state": "DROPPING", "battery_percent": 96.0, "is_loaded": True},
{"t": 10.0, "pos": [2.0, 30.0, 0.0], "yaw_deg": 90.0, "state": "IDLE", "battery_percent": 96.0, "is_loaded": False},
],
"amr_heavy_01": [
{"t": 0.0, "pos": [6.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "IDLE", "battery_percent": 100.0, "is_loaded": False},
@@ -186,3 +187,64 @@ def test_robot_animator_single_and_multi_robot(sample_bundle, manifest_file: Pat
assert 'def Xform "amr_heavy_01"' in fleet_content
assert "amr_light.usda" in fleet_content
assert "amr_heavy.usda" in fleet_content
# Delivered cargo appears at stations post-dropoff
assert 'def Scope "DeliveredCargo"' in fleet_content
assert "Delivered_outbound_pack_1_0" in fleet_content
def test_rack_inventory_depletion_and_dock_vertical_stacking(sample_bundle, manifest_file: Path, tmp_path: Path):
"""Verify rack inventory depletes with time-sampled visibility and dock boxes stack vertically."""
# Mock trajectory with a pick at rack_a_01 and multiple dropoffs at outbound_pack_1
mock_trajectory = {
"metadata": {"simulation_duration": 40.0},
"robots": {
"amr_light_01": [
{"t": 0.0, "pos": [8.0, 8.8, 0.0], "yaw_deg": 90.0, "state": "PICKING", "battery_percent": 100.0, "is_loaded": False},
{"t": 5.0, "pos": [8.0, 8.8, 0.0], "yaw_deg": 90.0, "state": "LOADED_TRANSIT", "battery_percent": 99.0, "is_loaded": True},
{"t": 15.0, "pos": [2.0, 30.0, 0.0], "yaw_deg": -90.0, "state": "DROPPING", "battery_percent": 97.0, "is_loaded": True},
{"t": 18.0, "pos": [2.0, 30.0, 0.0], "yaw_deg": -90.0, "state": "IDLE", "battery_percent": 97.0, "is_loaded": False},
{"t": 20.0, "pos": [8.0, 8.8, 0.0], "yaw_deg": 90.0, "state": "PICKING", "battery_percent": 96.0, "is_loaded": False},
{"t": 25.0, "pos": [8.0, 8.8, 0.0], "yaw_deg": 90.0, "state": "LOADED_TRANSIT", "battery_percent": 95.0, "is_loaded": True},
{"t": 35.0, "pos": [2.0, 30.0, 0.0], "yaw_deg": -90.0, "state": "DROPPING", "battery_percent": 93.0, "is_loaded": True},
{"t": 38.0, "pos": [2.0, 30.0, 0.0], "yaw_deg": -90.0, "state": "IDLE", "battery_percent": 93.0, "is_loaded": False},
],
},
}
traj_data = TrajectoryData.from_dict(mock_trajectory)
animator = Robot3DAnimator.from_config_and_trajectory(
bundle=sample_bundle,
trajectory_data=traj_data,
manifest_path=manifest_file,
sample_step_seconds=1.0,
timecodes_per_second=24.0,
)
stage_file = tmp_path / "depletion_demo.usda"
saved = animator.export_usda(stage_file)
assert saved.exists()
content = saved.read_text(encoding="utf-8")
# 1. Verify rack inventory depletion on rack_a_01
assert 'def Xform "rack_a_01_Cartons_L1"' in content
assert 'token visibility.timeSamples = {' in content
assert '"invisible"' in content
# 2. Verify inbound dock has multi-tier vertical staging stacks
assert 'def Xform "dock_inbound_1_StagedPallet_0_Tier_0"' in content
assert 'def Xform "dock_inbound_1_StagedPallet_0_Tier_1"' in content
assert "(wx, wy, wz) = (2.100, 10.450, 0.150)" in content or "0.150)" in content
assert "1.100)" in content # Second tier stacked on top of first tier
# 3. Verify delivered boxes at outbound_pack_1 stack vertically on top of each other
assert 'def Scope "DeliveredCargo"' in content
assert 'def Xform "Delivered_outbound_pack_1_0"' in content
assert 'def Xform "Delivered_outbound_pack_1_1"' in content
# Box 0 is Tier 0 at z=0.150, Box 1 is Tier 1 directly on top at z=1.100
assert "Delivered_outbound_pack_1_0" in content
assert "Delivered_outbound_pack_1_1" in content
assert "0.150" in content
assert "1.100" in content
+53 -2
View File
@@ -49,7 +49,7 @@ def sim_env_builder(project_config_dir: Path, tmp_path: Path):
def test_simulation_environment_creation(sim_env_builder):
env = sim_env_builder(seed=42)
assert len(env.robots) == 4
assert len(env.robots) == 10
assert env.env.now == 0.0
assert len(env.all_tasks) == 0
@@ -104,4 +104,55 @@ def test_metrics_serialization(sim_env_builder):
assert "throughput_tasks_per_hour" in data
assert "fleet_utilization_percent" in data
assert "robot_metrics" in data
assert len(data["robot_metrics"]) == 4
assert len(data["robot_metrics"]) == 10
def test_robot_moves_away_from_rack_after_picking(sim_env_builder):
"""Verify that robots picking from storage racks move away into the aisle before loaded transit."""
env = sim_env_builder(seed=42)
env.run(until=300.0)
# Filter for move_away_from_rack events
move_away_events = [
e for e in env.events
if e.metadata.get("action") == "move_away_from_rack"
]
assert len(move_away_events) > 0, "No move_away_from_rack events were recorded after picking"
# Verify each move-away event details
for ev in move_away_events:
source_rack = ev.metadata.get("source_rack")
aisle_wp = ev.metadata.get("aisle_waypoint")
assert source_rack in env.warehouse.storage_locations
assert env.graph.has_node(aisle_wp)
assert env.graph.nodes[aisle_wp].get("node_type") != "storage_rack"
# The aisle waypoint must be at a distance >= 1.0m from the source rack
rack_pos = env.warehouse.storage_locations[source_rack].position
wp_pos = env.path_planner.get_node_position(aisle_wp)
assert rack_pos.distance_to(wp_pos) >= 1.0
def test_multi_task_traffic_coordination_and_unoptimized_charging(sim_env_builder):
"""Verify that multi-task execution with unoptimized charging stations triggers collision avoidance, yielding, and charging visits."""
env = sim_env_builder(seed=42)
# Configure robots with operational battery levels to trigger visits to the unoptimized charging bays
env.robots["amr_light_01"].battery_level = (55.0 / 100.0) * env.robots["amr_light_01"].battery_capacity
env.robots["amr_heavy_01"].battery_level = (48.0 / 100.0) * env.robots["amr_heavy_01"].battery_capacity
metrics = env.run(until=1800.0)
# 1. Multiple tasks completed across warehouse zones
assert metrics.tasks_completed >= 35
assert metrics.throughput_tasks_per_hour >= 70.0
# 2. Collision avoidance and traffic coordination active
assert metrics.conflicts_detected > 0
assert metrics.yield_waits_count > 0
assert metrics.total_wait_time_seconds > 0.0
# 3. Charging visits executed at unoptimized bays
assert (metrics.opportunity_charges + metrics.mandatory_charges) >= 1
assert metrics.total_energy_charged_kwh > 0.0
+146
View File
@@ -0,0 +1,146 @@
"""Automated Regression and Safety Validation Tests for Stage 3.1 Efficiency-Optimized Hybrid Facility."""
import json
from pathlib import Path
import pytest
import networkx as nx
from warehouse_twin.optimization.layout_optimizer import (
LayoutOptimizer,
LayoutVariant,
LAYOUT_REGISTRY,
)
from warehouse_twin.domain.warehouse import WarehouseModel, NodeType
from warehouse_twin.routing.path_planner import PathPlanner, NoPathFoundError
from warehouse_twin.simulation.sim_engine import SimulationEnvironment
from warehouse_twin.analytics.experiment_runner import ExperimentRunner, ExperimentConfig
@pytest.fixture
def opt_fixture():
return LayoutOptimizer()
def test_stage_03_1_variant_registration(opt_fixture):
"""Verify LayoutVariant.EFFICIENCY_OPTIMIZED is registered with complete specification."""
assert LayoutVariant.EFFICIENCY_OPTIMIZED in LAYOUT_REGISTRY
spec = LAYOUT_REGISTRY[LayoutVariant.EFFICIENCY_OPTIMIZED]
assert spec.decentralized_charging is True
assert spec.directional_highways is True
assert spec.velocity_slotting is True
assert "Efficiency-Optimized" in spec.name
def test_stage_03_1_charging_station_configuration(opt_fixture):
"""Verify 3/3/2 decentralized charging distribution across Zones A, B, and C."""
cfg = opt_fixture.get_warehouse_config(LayoutVariant.EFFICIENCY_OPTIMIZED)
chargers = cfg.get("charging_stations", [])
assert len(chargers) == 8
zone_a_chargers = [c for c in chargers if c["position"][0] < 26.0]
zone_b_chargers = [c for c in chargers if 26.0 <= c["position"][0] < 46.0]
zone_c_chargers = [c for c in chargers if c["position"][0] >= 46.0]
assert len(zone_a_chargers) == 3, "Zone A must contain 3 charging bays"
assert len(zone_b_chargers) == 3, "Zone B must contain 3 charging bays"
assert len(zone_c_chargers) == 2, "Zone C must contain 2 charging bays"
for c in zone_a_chargers:
assert c["charging_rate_kw"] == 25.0
for c in zone_b_chargers + zone_c_chargers:
assert c["charging_rate_kw"] == 50.0
def test_stage_03_1_graph_connectivity_and_reachability(opt_fixture):
"""Verify graph connectivity and reachability of all stations, chargers, and racks."""
model, graph = opt_fixture.build_graph_for_variant(LayoutVariant.EFFICIENCY_OPTIMIZED)
planner = PathPlanner(graph)
# Stations must all be reachable by heavy AMRs
for st_id in model.stations.keys():
st_node = planner.resolve_node_id(st_id)
assert graph.has_node(st_node)
# Charging bays must all be reachable
for ch_id in model.charging_stations.keys():
ch_node = planner.resolve_node_id(ch_id)
assert graph.has_node(ch_node)
# Test path from station_picking_station_a1 to Zone A rack
path_light = planner.find_shortest_path(
"station_picking_station_a1", "rack_rack_a_01", robot_type="light_amr"
)
assert len(path_light) >= 2
dist = planner.compute_path_distance(path_light)
assert dist < 35.0, f"Expected return distance < 35m, got {dist:.1f}m"
def test_stage_03_1_light_amr_circulation_not_trapped(opt_fixture):
"""Verify Light AMRs never enter Zone B and have complete clockwise circulation loop."""
model, graph = opt_fixture.build_graph_for_variant(LayoutVariant.EFFICIENCY_OPTIMIZED)
planner = PathPlanner(graph)
# From picking station A1 back to rack_a_01:
path = planner.find_shortest_path(
"station_picking_station_a1", "rack_rack_a_01", robot_type="light_amr"
)
for nid in path:
node_data = graph.nodes[nid]
assert node_data.get("zone") != "zone_b", (
f"Light AMR improperly routed through Zone B at node {nid}"
)
def test_stage_03_1_safety_and_acceptance_targets(opt_fixture):
"""Verify simulation KPIs satisfy all proposed acceptance targets."""
kpi_file = Path("results/demo_staged/stage_03_1_efficiency_optimized/kpis.json")
if not kpi_file.exists():
pytest.skip("Stage 3.1 KPIs file not yet generated")
with open(kpi_file, "r", encoding="utf-8") as f:
kpi = json.load(f)
# Acceptance Targets from prompt:
assert kpi["unresolved_conflicts"] == 0, "Must have zero unresolved traffic conflicts"
assert kpi["throughput_tasks_per_hour"] >= 85.0, "Throughput must be at or above 85 tasks/hr"
assert kpi["turnaround_time"]["mean"] <= 105.0, "Mean turnaround time must be <= 105s"
assert kpi["turnaround_time"]["p90"] < 150.0, "p90 turnaround time must be < 150s"
assert kpi["total_travel_distance_meters"] <= 6500.0, "Total distance must be <= 6,500m"
assert kpi["total_energy_consumed_kwh"] < 1.6, "Total energy must be < 1.6 kWh"
assert kpi["min_fleet_battery_percent"] >= 95.0, "Minimum battery must maintain safety reserve"
def test_stage_03_1_artifacts_integrity():
"""Verify all machine-readable and human-readable artifacts exist and are consistent."""
base = Path("results/demo_staged/stage_03_1_efficiency_optimized")
assert (base / "kpis.json").exists()
assert (base / "manifest.json").exists()
assert (base / "candidate_comparison.json").exists()
assert (base / "stage3_vs_stage3_1.json").exists()
assert (base / "optimization_report.md").exists()
assert (base / "trajectory.json").exists()
assert (base / "conflicts.json").exists()
assert (base / "warehouse_efficiency_optimized.usda").exists()
assert Path("results/demo_staged/usd/stage_03_1_efficiency_optimized.usda").exists()
with open(base / "manifest.json", "r") as f:
manifest = json.load(f)
assert manifest["stage"] == "3.1"
assert manifest["unresolved_conflicts"] == 0
with open(base / "candidate_comparison.json", "r") as f:
cands = json.load(f)
assert len(cands) == 6, "Expected 6 ablation candidates (A through F)"
def test_stage_1_and_3_baseline_non_regression():
"""Verify that Stage 1 and Stage 3 baseline artifacts exist and were not overwritten."""
s1_kpi = Path("results/demo_staged/stage_01_baseline/kpis.json")
s3_kpi = Path("results/demo_staged/stage_03_final_optimized/kpis.json")
assert s1_kpi.exists(), "Stage 1 KPIs must remain intact"
assert s3_kpi.exists(), "Stage 3 KPIs must remain intact"
with open(s3_kpi, "r") as f:
data = json.load(f)
assert data["total_travel_distance_meters"] == 7644.34
assert data["turnaround_time"]["mean"] == 126.71
+408
View File
@@ -0,0 +1,408 @@
"""Unit tests for the Three-Stage Omniverse Digital Twin Demo and Synchronized KPI Analytics."""
import os
import tempfile
import pytest
from pathlib import Path
from unittest.mock import patch, MagicMock
from warehouse_twin.demo.staged_demo_runner import StagedDemoConfig, StagedDemoRunner, StagedDemoResult
from warehouse_twin.demo.staged_video_generator import StagedVideoGenerator, verify_video
from warehouse_twin.dashboard.data_provider import DashboardDataProvider
from warehouse_twin.layout.layout_generator import ModularWarehouseBuilder, WarehouseLayoutConfig
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
def test_staged_demo_config_validation():
"""Verify StagedDemoConfig defaults, validation, and quick mode presets."""
cfg = StagedDemoConfig(quick_mode=True)
assert cfg.duration_seconds == 300.0
assert cfg.seed == 42
assert cfg.fps == 30
assert cfg.playback_speed == 8.0
assert cfg.width == 1920
assert cfg.height == 1080
assert cfg.skip_video is False
assert cfg.stage is None
cfg_custom = StagedDemoConfig(duration_seconds=900.0, seed=123, fps=24, quick_mode=False)
assert cfg_custom.duration_seconds == 900.0
assert cfg_custom.seed == 123
assert cfg_custom.fps == 24
def test_kpi_delta_formulas_and_zero_baseline():
"""Verify directional improvement math, higher/lower logic, and zero-baseline handling."""
runner = StagedDemoRunner(StagedDemoConfig(quick_mode=True))
# Higher is better: Throughput 60 -> 75 => +25%
delta_high = runner._compute_delta(60.0, 75.0, higher_is_better=True)
assert delta_high["absolute_delta"] == 15.0
assert delta_high["percent_delta"] == 25.0
assert delta_high["status"] == "IMPROVED"
# Higher is better: Throughput 60 -> 45 => -25%
delta_high_regress = runner._compute_delta(60.0, 45.0, higher_is_better=True)
assert delta_high_regress["absolute_delta"] == -15.0
assert delta_high_regress["percent_delta"] == -25.0
assert delta_high_regress["status"] == "REGRESSED"
# Lower is better: Turnaround 120 -> 90 => +25% improvement
delta_low = runner._compute_delta(120.0, 90.0, higher_is_better=False)
assert delta_low["absolute_delta"] == -30.0
assert delta_low["percent_delta"] == 25.0
assert delta_low["status"] == "IMPROVED"
# Lower is better: Conflicts 10 -> 15 => -50% regression
delta_low_regress = runner._compute_delta(10.0, 15.0, higher_is_better=False)
assert delta_low_regress["absolute_delta"] == 5.0
assert delta_low_regress["percent_delta"] == -50.0
assert delta_low_regress["status"] == "REGRESSED"
# Zero baseline handling: baseline 0 -> optimized 10 (higher is better)
delta_zero_base = runner._compute_delta(0.0, 10.0, higher_is_better=True)
assert delta_zero_base["percent_delta"] == 100.0
assert delta_zero_base["status"] == "IMPROVED"
# Zero baseline handling: baseline 0 -> optimized 0
delta_zero_parity = runner._compute_delta(0.0, 0.0, higher_is_better=False)
assert delta_zero_parity["percent_delta"] == 0.0
assert delta_zero_parity["status"] == "PARITY"
# Zero baseline with regression: baseline 0 -> optimized 5 (lower is better, e.g. errors)
delta_zero_err = runner._compute_delta(0.0, 5.0, higher_is_better=False)
assert delta_zero_err["percent_delta"] == -100.0
assert delta_zero_err["status"] == "REGRESSED"
def test_layout_reachability_and_charging_feasibility():
"""Verify that candidate layout configurations maintain full AMR reachability and valid charging positions."""
cfg = WarehouseLayoutConfig(
warehouse_length=30.0,
warehouse_width=20.0,
warehouse_height=6.0,
grid_cell_size=0.5,
rack_length=2.4,
rack_depth=1.0,
rack_height=3.0,
num_shelf_levels=3,
num_rows=2,
bays_per_row=4,
clear_aisle_width=2.0,
num_chargers=2,
)
builder = ModularWarehouseBuilder(cfg)
model, grid, report = builder.build_test_layout()
# 1. Structural assertions
assert len(model.charging_stations) >= 2
assert len(model.storage_locations) > 0
assert report.is_valid is True
# 2. Graph reachability
graph_builder = WarehouseGraphBuilder(model)
graph = graph_builder.build_graph()
assert graph.number_of_nodes() > 0
assert graph.number_of_edges() > 0
for c_id, station in model.charging_stations.items():
assert f"charger_{c_id}" in graph.nodes or f"charge_{c_id}" in graph.nodes or c_id in graph.nodes
def test_usd_stages_and_references_resolution(tmp_path):
"""Verify that the generated USD stages contain valid OpenUSD headers and prim structures."""
from warehouse_twin.config.loader import ConfigLoader
from warehouse_twin.visualization.robot_animator import Robot3DAnimator
from warehouse_twin.visualization.trajectory_player import TrajectoryData
project_root = Path(__file__).resolve().parent.parent.parent
loader = ConfigLoader(project_root / "config")
bundle = loader.load_all()
mock_traj = {
"metadata": {"simulation_duration": 5.0},
"robots": {
"amr_light_01": [
{"t": 0.0, "pos": [2.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "IDLE", "battery_percent": 100.0, "is_loaded": False},
{"t": 5.0, "pos": [5.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "MOVING_EMPTY", "battery_percent": 99.0, "is_loaded": False},
]
}
}
traj_data = TrajectoryData.from_dict(mock_traj)
animator = Robot3DAnimator.from_config_and_trajectory(
bundle=bundle,
trajectory_data=traj_data,
sample_step_seconds=1.0,
timecodes_per_second=24.0,
)
out_file = tmp_path / "test_stage.usda"
saved = animator.export_usda(out_file)
assert saved.exists()
content = saved.read_text(encoding="utf-8")
assert "#usda 1.0" in content
assert 'upAxis = "Z"' in content
# OpenUSD layer header requires customLayerData, not illegal customData on root layer
header_part = content.split("def ", 1)[0]
assert "customLayerData = {" in header_part
assert "customData = {" not in header_part
def test_copy_and_adjust_usd_references_depth(tmp_path):
"""Verify that _copy_and_adjust_usd_references rewrites relative asset paths for 3-level demo dirs."""
source_dir = tmp_path / "results" / "demonstration" / "staged_demo" / "stage_01_baseline"
source_dir.mkdir(parents=True)
source_usda = source_dir / "warehouse_baseline.usda"
source_content = (
'#usda 1.0\n'
'(\n'
' customLayerData = {\n'
' string title = "Test"\n'
' }\n'
')\n'
'def Xform "World"\n'
'{\n'
' def "Rack" (prepend references = @../../../../assets/shelves/pallet_rack.usda@)\n'
' {\n'
' }\n'
'}\n'
)
source_usda.write_text(source_content, encoding="utf-8")
dest_dir = tmp_path / "results" / "demo" / "initial"
dest_dir.mkdir(parents=True)
dest_usda = dest_dir / "warehouse.usda"
StagedDemoRunner._copy_and_adjust_usd_references(source_usda, dest_usda)
assert dest_usda.exists()
dest_content = dest_usda.read_text(encoding="utf-8")
assert "@../../../assets/shelves/pallet_rack.usda@" in dest_content
assert "@../../../../assets/" not in dest_content
assert "customLayerData = {" in dest_content
def test_existing_demo_stages_references_resolve_on_disk():
"""Verify that all relative asset references in existing demo stages resolve to actual files."""
import re
project_root = Path(__file__).resolve().parent.parent.parent
demo_dirs = [
project_root / "results" / "demo" / "initial" / "warehouse.usda",
project_root / "results" / "demo" / "optimizing" / "warehouse.usda",
project_root / "results" / "demo" / "optimized" / "warehouse.usda",
project_root / "results" / "demonstration" / "staged_demo" / "stage_01_baseline" / "warehouse_baseline.usda",
project_root / "results" / "demonstration" / "staged_demo" / "stage_02_optimization_progress" / "optimization_progress.usda",
project_root / "results" / "demonstration" / "staged_demo" / "stage_03_final_optimized" / "warehouse_final_optimized.usda",
]
ref_pattern = re.compile(r"@([^@]+)@")
for usda_file in demo_dirs:
if not usda_file.exists():
continue
text = usda_file.read_text(encoding="utf-8")
header = text.split("def ", 1)[0]
assert "customData = {" not in header, f"Found illegal customData in header of {usda_file}"
assert "customLayerData = {" in header, f"Missing customLayerData in header of {usda_file}"
for match in ref_pattern.finditer(text):
ref_path = match.group(1)
# resolve relative to usda_file directory
target_file = (usda_file.parent / ref_path).resolve()
assert target_file.exists(), f"Reference '{ref_path}' in {usda_file} resolves to non-existent {target_file}"
def test_staged_video_verification_helper(tmp_path):
"""Verify video verification helper handles missing, empty, and non-video files properly."""
non_existent = tmp_path / "does_not_exist.mp4"
assert verify_video(str(non_existent))["valid"] is False
empty_file = tmp_path / "empty.mp4"
empty_file.write_bytes(b"")
assert verify_video(str(empty_file))["valid"] is False
garbage_file = tmp_path / "garbage.mp4"
garbage_file.write_text("not a video")
assert verify_video(str(garbage_file))["valid"] is False
import socket
import threading
import time
import urllib.request
import urllib.error
import json
from warehouse_twin.dashboard.server import DashboardServer
def find_free_port() -> int:
"""Find a random available port on localhost."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def test_dashboard_staged_demo_api_endpoints(tmp_path):
"""Verify Dashboard HTTP API endpoints for demo manifest, data, and video streaming."""
# Create dummy video file
demo_video_dir = tmp_path / "demo" / "videos"
demo_video_dir.mkdir(parents=True, exist_ok=True)
dummy_video = demo_video_dir / "01_baseline.mp4"
dummy_payload = b"0123456789" * 100
dummy_video.write_bytes(dummy_payload)
port = find_free_port()
server = DashboardServer(results_dir=tmp_path, host="127.0.0.1", port=port)
server_thread = threading.Thread(target=lambda: server.start(blocking=True), daemon=True)
server_thread.start()
time.sleep(0.2)
base_url = f"http://127.0.0.1:{port}"
try:
# 1. Manifest endpoint
with urllib.request.urlopen(f"{base_url}/api/demo/manifest") as resp:
assert resp.status == 200
manifest = json.loads(resp.read().decode("utf-8"))
assert "stages" in manifest
assert "initial" in manifest["stages"]
assert "optimizing" in manifest["stages"]
assert "optimized" in manifest["stages"]
# 2. Main demo data endpoint
with urllib.request.urlopen(f"{base_url}/api/demo") as resp:
assert resp.status == 200
data = json.loads(resp.read().decode("utf-8"))
assert "manifest" in data
assert "active_stage" in data
# 3. Missing video returns 404
with pytest.raises(urllib.error.HTTPError) as exc_info:
urllib.request.urlopen(f"{base_url}/api/demo/video/nonexistent_video.mp4")
assert exc_info.value.code == 404
# 4. Full request
with urllib.request.urlopen(f"{base_url}/api/demo/video/01_baseline.mp4") as resp:
assert resp.status == 200
assert resp.read() == dummy_payload
assert resp.headers.get("Content-Type") == "video/mp4"
# 5. Range request (HTTP 206)
req = urllib.request.Request(
f"{base_url}/api/demo/video/01_baseline.mp4",
headers={"Range": "bytes=0-49"}
)
with urllib.request.urlopen(req) as resp:
assert resp.status == 206
range_bytes = resp.read()
assert len(range_bytes) == 50
assert resp.headers.get("Content-Range") == "bytes 0-49/1000"
finally:
server.stop()
server_thread.join(timeout=1.0)
def test_graceful_handling_of_missing_artifacts(tmp_path):
"""Verify data provider returns stable empty-state structures when no runs exist."""
empty_provider = DashboardDataProvider(results_dir=str(tmp_path / "nonexistent"))
manifest = empty_provider.get_staged_demo_manifest()
assert manifest is not None
assert "stages" in manifest
data = empty_provider.get_staged_demo_data()
assert data is not None
assert data["manifest"] is not None
assert data["comparison"] is None or isinstance(data["comparison"], dict)
def test_frozen_workload_loading_and_hash():
"""Verify frozen workload CSV loads exactly 86 tasks with the mandated SHA-256 checksum."""
import hashlib
orders_p = Path("data/input/demo_orders.csv")
assert orders_p.exists(), "demo_orders.csv must exist in data/input/"
content = orders_p.read_bytes()
computed_sha256 = hashlib.sha256(content).hexdigest()
expected_sha256 = "f4eff4790759dd243337db1ec3c57ea41546f7f4db47d642acdb3708702ba238"
assert computed_sha256 == expected_sha256, f"Checksum mismatch: {computed_sha256} != {expected_sha256}"
# Verify line count: 1 header + 86 tasks
lines = [ln.strip() for ln in orders_p.read_text(encoding="utf-8").splitlines() if ln.strip()]
assert len(lines) == 87
header = lines[0].split(",")
assert "task_id" in header and "release_time_s" in header and "item_id" in header
def test_traffic_manager_passive_vs_preventive_coordination():
"""Verify passive conflict auditing logs unmitigated conflicts vs preventive resolution."""
from warehouse_twin.routing.traffic_manager import TrafficManager
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
from warehouse_twin.config import ConfigLoader
from warehouse_twin.routing.reservations import TimeSpaceReservationGrid
from warehouse_twin.routing.path_planner import PathPlanner
loader = ConfigLoader()
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
planner = PathPlanner(graph)
from warehouse_twin.domain.robot import Robot, RobotTypeSpec
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)
# 1. Passive coordination (Stage 1): Preventive coordination False
grid_passive = TimeSpaceReservationGrid()
passive_tm = TrafficManager(reservation_grid=grid_passive, path_planner=planner, preventive_coordination=False)
assert passive_tm.preventive_coordination is False
# Simulate AMR 1 reserving edge
grid_passive.reserve_edge("wp_20_20", "wp_20_40", 10.0, 14.0, robot_id=r1.robot_id)
# AMR 2 attempts step traversal into contested edge
action = passive_tm.evaluate_step_traversal(
robot=r2,
current_node="wp_20_20",
next_node="wp_20_40",
start_time=10.0,
traversal_duration=2.0,
)
# Under passive coordination, AMR proceeds unmitigated and conflict is logged
assert action.action == "PROCEED"
audit = passive_tm.get_conflict_audit()
assert audit["total_potential_conflicts"] == 1
assert audit["unresolved_conflicts"] == 1
assert audit["preventive_coordination_active"] is False
# 2. Preventive coordination (Stage 3): Preventive coordination True
grid_prev = TimeSpaceReservationGrid()
preventive_tm = TrafficManager(reservation_grid=grid_prev, path_planner=planner, preventive_coordination=True)
assert preventive_tm.preventive_coordination is True
grid_prev.reserve_edge("wp_20_20", "wp_20_40", 10.0, 14.0, robot_id=r1.robot_id)
action_prev = preventive_tm.evaluate_step_traversal(
robot=r2,
current_node="wp_20_20",
next_node="wp_20_40",
start_time=10.0,
traversal_duration=2.0,
)
# Under preventive coordination, AMR yields to resolve conflict
assert action_prev.action in ("YIELD_WAIT", "REPLAN")
audit_prev = preventive_tm.get_conflict_audit()
assert audit_prev["total_potential_conflicts"] == 1
assert audit_prev["unresolved_conflicts"] == 0
assert audit_prev["preventive_coordination_active"] is True
def test_staged_demo_config_fleet_and_chargers():
"""Verify StagedDemoConfig specifies exactly 10 AMRs and 8 chargers."""
cfg = StagedDemoConfig()
assert cfg.total_fleet == 10
assert cfg.light_robots == 5
assert cfg.heavy_robots == 5
assert cfg.charging_stations == 8
assert Path(cfg.orders_path).name == "demo_orders.csv"
+2 -2
View File
@@ -69,6 +69,6 @@ def test_trajectory_recording_and_export(project_config_dir: Path, tmp_path: Pat
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_robots"] == 10
assert meta["total_trajectory_points"] > 10
assert len(data["robots"]) == 4
assert len(data["robots"]) == 10
+3 -3
View File
@@ -63,7 +63,7 @@ def test_warehouse_model_parsing(project_config_dir: Path):
assert len(model.stations) >= 6
assert len(model.charging_stations) >= 4
assert len(model.storage_locations) == 13
assert len(model.storage_locations) == 28
def test_build_graph_structure(project_config_dir: Path):
@@ -115,8 +115,8 @@ def test_graph_connectivity_report(project_config_dir: Path):
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 == 4
assert report.storage_racks_reachable == report.total_storage_racks == 13
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