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

159 lines
6.0 KiB
Python

"""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) == 10
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"]) == 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