feat(phase3): implement SimPy discrete-event simulation engine, multi-zone order generation, fleet dispatcher, and wider Zone B aisles
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
"""Unit tests for FleetDispatcher task prioritization and robot allocation."""
|
||||
|
||||
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, TaskStatus, TaskType
|
||||
from warehouse_twin.domain.warehouse import Position3D, WarehouseModel
|
||||
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
|
||||
from warehouse_twin.simulation.dispatcher import DispatcherSettings, FleetDispatcher
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dispatcher_fixture(project_config_dir: Path):
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
warehouse = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
|
||||
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"]
|
||||
]
|
||||
|
||||
settings = DispatcherSettings.from_dict(bundle.dispatch_policies)
|
||||
dispatcher = FleetDispatcher(settings, graph)
|
||||
return dispatcher, fleet, graph
|
||||
|
||||
|
||||
def test_dispatcher_priority_queue_sorting(dispatcher_fixture):
|
||||
dispatcher, _, _ = dispatcher_fixture
|
||||
|
||||
# Enqueue tasks in random priority order
|
||||
t_low = Task("t_low", TaskType.ORDER_PICK, "rack_a_01", "picking_station_a1", priority=4, release_time=10.0)
|
||||
t_high = Task("t_high", TaskType.REPLENISHMENT, "dock_inbound_1", "rack_a_01", priority=2, release_time=20.0)
|
||||
t_crit = Task("t_crit", TaskType.PRODUCTION_FEED, "rack_c_01", "production_dropoff_c1", priority=1, release_time=30.0)
|
||||
|
||||
dispatcher.enqueue_task(t_low)
|
||||
dispatcher.enqueue_task(t_high)
|
||||
dispatcher.enqueue_task(t_crit)
|
||||
|
||||
assert dispatcher.queue_length == 3
|
||||
# Critical should be first, then High, then Low
|
||||
assert dispatcher.queue[0].task_id == "t_crit"
|
||||
assert dispatcher.queue[1].task_id == "t_high"
|
||||
assert dispatcher.queue[2].task_id == "t_low"
|
||||
|
||||
|
||||
def test_dispatcher_payload_compatibility_matching(dispatcher_fixture):
|
||||
dispatcher, fleet, _ = dispatcher_fixture
|
||||
# Task with heavy transmission (650kg)
|
||||
heavy_task = Task(
|
||||
"t_heavy",
|
||||
TaskType.ORDER_PICK,
|
||||
"rack_b_01",
|
||||
"picking_station_b1",
|
||||
required_payload=650.0,
|
||||
target_zone="zone_b",
|
||||
)
|
||||
|
||||
available_robots = [r for r in fleet if r.is_available]
|
||||
chosen = dispatcher.select_best_robot(heavy_task, available_robots, sim_time=0.0)
|
||||
|
||||
# Must choose heavy_amr, cannot choose light_amr (max 150kg)
|
||||
assert chosen is not None
|
||||
assert "heavy" in chosen.robot_type
|
||||
assert chosen.payload_capacity >= 650.0
|
||||
|
||||
|
||||
def test_dispatcher_zone_b_restriction(dispatcher_fixture):
|
||||
dispatcher, fleet, _ = dispatcher_fixture
|
||||
# Light payload in Zone B (45kg engine piston set)
|
||||
piston_task = Task(
|
||||
"t_piston",
|
||||
TaskType.ORDER_PICK,
|
||||
"rack_b_03",
|
||||
"picking_station_b1",
|
||||
required_payload=45.0,
|
||||
target_zone="zone_b",
|
||||
)
|
||||
|
||||
available_robots = [r for r in fleet if r.is_available]
|
||||
chosen = dispatcher.select_best_robot(piston_task, available_robots, sim_time=0.0)
|
||||
|
||||
# Must be heavy AMR because Zone B restricted to heavy AMRs
|
||||
assert chosen is not None
|
||||
assert "heavy" in chosen.robot_type
|
||||
|
||||
|
||||
def test_dispatcher_battery_headroom_filter(dispatcher_fixture):
|
||||
dispatcher, fleet, _ = dispatcher_fixture
|
||||
task = Task("t_light", TaskType.ORDER_PICK, "rack_a_01", "picking_station_a1", required_payload=5.0)
|
||||
|
||||
# Discharge all light AMRs below minimum headroom (20%)
|
||||
for r in fleet:
|
||||
if "light" in r.robot_type:
|
||||
r.battery_level = 0.10 * r.battery_capacity
|
||||
|
||||
available_robots = [r for r in fleet if r.is_available]
|
||||
chosen = dispatcher.select_best_robot(task, available_robots, sim_time=0.0)
|
||||
|
||||
# Light AMRs excluded due to low battery; heavy AMR selected
|
||||
assert chosen is not None
|
||||
assert chosen.battery_percent >= 20.0
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Unit tests for multi-zone workload order generation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.config.loader import ConfigLoader
|
||||
from warehouse_twin.domain.inventory import InventoryCatalog
|
||||
from warehouse_twin.domain.task import TaskPriority, TaskType
|
||||
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||
from warehouse_twin.simulation.order_generator import OrderGenerator, WorkloadConfig
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def order_gen_fixtures(project_config_dir: Path):
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
warehouse = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
catalog = InventoryCatalog.from_config_dict(bundle.inventory)
|
||||
workload = WorkloadConfig.from_dict(bundle.simulation)
|
||||
gen = OrderGenerator(workload, catalog, warehouse, seed=42)
|
||||
return gen, workload, catalog, warehouse
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_zone_a_task_generation(order_gen_fixtures):
|
||||
gen, _, _, _ = order_gen_fixtures
|
||||
task = gen.generate_zone_a_task(sim_time=100.0)
|
||||
|
||||
assert task.task_id.startswith("task_za_")
|
||||
assert task.task_type == TaskType.ORDER_PICK
|
||||
assert task.target_zone == "zone_a"
|
||||
assert task.priority == TaskPriority.LOW.value
|
||||
assert task.release_time == 100.0
|
||||
assert task.deadline == 580.0
|
||||
assert task.source.startswith("rack_a_")
|
||||
assert task.destination in ("picking_station_a1", "outbound_pack_1")
|
||||
|
||||
|
||||
def test_zone_b_task_generation(order_gen_fixtures):
|
||||
gen, _, _, _ = order_gen_fixtures
|
||||
task = gen.generate_zone_b_task(sim_time=200.0)
|
||||
|
||||
assert task.task_id.startswith("task_zb_")
|
||||
assert task.task_type == TaskType.ORDER_PICK
|
||||
assert task.target_zone == "zone_b" # Wider aisles zone
|
||||
assert task.priority == TaskPriority.MEDIUM.value
|
||||
assert task.source.startswith("rack_b_")
|
||||
assert task.destination == "picking_station_b1"
|
||||
assert task.required_payload >= 45.0 # Heavy specialized components
|
||||
|
||||
|
||||
def test_zone_c_task_generation(order_gen_fixtures):
|
||||
gen, _, _, _ = order_gen_fixtures
|
||||
task = gen.generate_zone_c_task(sim_time=300.0)
|
||||
|
||||
assert task.task_id.startswith("task_zc_")
|
||||
assert task.task_type == TaskType.PRODUCTION_FEED
|
||||
assert task.target_zone == "zone_c"
|
||||
assert task.priority == TaskPriority.CRITICAL.value
|
||||
assert task.destination == "production_dropoff_c1"
|
||||
assert task.deadline == pytest.approx(600.0) # 300s lead time
|
||||
|
||||
|
||||
def test_replenishment_task_generation(order_gen_fixtures):
|
||||
gen, _, catalog, _ = order_gen_fixtures
|
||||
item = catalog.get_item("transmission_combine_ct8")
|
||||
assert item is not None
|
||||
|
||||
task = gen.generate_replenishment_task(item, sim_time=500.0)
|
||||
assert task.task_id.startswith("task_repl_")
|
||||
assert task.task_type == TaskType.REPLENISHMENT
|
||||
assert task.target_zone == "zone_b"
|
||||
assert task.priority == TaskPriority.HIGH.value
|
||||
assert task.destination == item.storage_location
|
||||
assert task.source in ("dock_inbound_1", "dock_inbound_2")
|
||||
|
||||
|
||||
def test_peak_demand_multiplier(order_gen_fixtures):
|
||||
gen, workload, _, _ = order_gen_fixtures
|
||||
# Before peak
|
||||
assert gen.is_peak_demand(1000.0) is False
|
||||
assert gen.get_arrival_multiplier(1000.0) == 1.0
|
||||
|
||||
# During peak (1200s to 2400s)
|
||||
assert gen.is_peak_demand(1500.0) is True
|
||||
assert gen.get_arrival_multiplier(1500.0) == workload.peak_demand_multiplier
|
||||
|
||||
# After peak
|
||||
assert gen.is_peak_demand(3000.0) is False
|
||||
assert gen.get_arrival_multiplier(3000.0) == 1.0
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Unit tests for SimPy discrete-event simulation engine and metrics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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, SimulationMetrics
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sim_env_builder(project_config_dir: Path, tmp_path: Path):
|
||||
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
|
||||
|
||||
|
||||
def test_simulation_environment_creation(sim_env_builder):
|
||||
env = sim_env_builder(seed=42)
|
||||
assert len(env.robots) == 4
|
||||
assert env.env.now == 0.0
|
||||
assert len(env.all_tasks) == 0
|
||||
|
||||
|
||||
def test_short_simulation_run(sim_env_builder):
|
||||
env = sim_env_builder(seed=42)
|
||||
metrics: SimulationMetrics = env.run(until=300.0)
|
||||
|
||||
assert metrics.duration_seconds == 300.0
|
||||
assert metrics.tasks_created > 0
|
||||
assert metrics.tasks_completed > 0
|
||||
assert metrics.throughput_tasks_per_hour > 0.0
|
||||
assert metrics.fleet_utilization_percent > 0.0
|
||||
assert metrics.average_turnaround_time > 0.0
|
||||
assert metrics.on_time_delivery_percent == 100.0
|
||||
|
||||
|
||||
def test_deterministic_simulation_runs(sim_env_builder):
|
||||
"""Verify that runs with identical random seed yield identical metrics and events."""
|
||||
env1 = sim_env_builder(seed=42)
|
||||
metrics1 = env1.run(until=600.0)
|
||||
|
||||
env2 = sim_env_builder(seed=42)
|
||||
metrics2 = env2.run(until=600.0)
|
||||
|
||||
assert metrics1.tasks_created == metrics2.tasks_created
|
||||
assert metrics1.tasks_completed == metrics2.tasks_completed
|
||||
assert metrics1.throughput_tasks_per_hour == pytest.approx(metrics2.throughput_tasks_per_hour)
|
||||
assert metrics1.average_turnaround_time == pytest.approx(metrics2.average_turnaround_time)
|
||||
assert len(env1.events) == len(env2.events)
|
||||
|
||||
|
||||
def test_simulation_event_logging(sim_env_builder, tmp_path: Path):
|
||||
env = sim_env_builder(seed=42, event_log=True)
|
||||
env.run(until=300.0)
|
||||
|
||||
log_file = tmp_path / "events_seed_42.jsonl"
|
||||
assert log_file.exists()
|
||||
assert log_file.stat().st_size > 500
|
||||
|
||||
lines = log_file.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) > 10
|
||||
|
||||
|
||||
def test_metrics_serialization(sim_env_builder):
|
||||
env = sim_env_builder(seed=42)
|
||||
metrics = env.run(until=300.0)
|
||||
data = metrics.to_dict()
|
||||
|
||||
assert "tasks_created" in data
|
||||
assert "tasks_completed" in data
|
||||
assert "throughput_tasks_per_hour" in data
|
||||
assert "fleet_utilization_percent" in data
|
||||
assert "robot_metrics" in data
|
||||
assert len(data["robot_metrics"]) == 4
|
||||
@@ -73,8 +73,8 @@ def test_build_graph_structure(project_config_dir: Path):
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
|
||||
assert graph.number_of_nodes() > 500
|
||||
assert graph.number_of_edges() > 1500
|
||||
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")
|
||||
@@ -203,8 +203,8 @@ def test_export_topology_dict_and_json(project_config_dir: Path, tmp_path: Path)
|
||||
assert "nodes" in topo
|
||||
assert "edges" in topo
|
||||
|
||||
assert topo["metadata"]["node_count"] > 500
|
||||
assert topo["metadata"]["edge_count"] > 1500
|
||||
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)
|
||||
@@ -274,3 +274,30 @@ def test_export_usda_with_robots(project_config_dir: Path, tmp_path: Path):
|
||||
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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user