feat(phase-6): implement analytics, kpi calculator, event store, heatmaps, and experiment runner

This commit is contained in:
2026-10-21 12:19:15 +05:30
parent 1e50508f53
commit 4c4419a06c
25 changed files with 2725 additions and 63 deletions
+124
View File
@@ -0,0 +1,124 @@
"""Unit tests for EventStore serialization and tabular CSV/JSONL exports."""
import json
from pathlib import Path
import pytest
from warehouse_twin.analytics.kpi_calculator import ComprehensiveKPIReport
from warehouse_twin.domain.events import SimulationEvent, SimulationEventType
from warehouse_twin.domain.robot import Robot
from warehouse_twin.domain.task import Task, TaskPriority, TaskStatus, TaskType
from warehouse_twin.domain.warehouse import Position3D
from warehouse_twin.storage.event_store import EventStore
def test_event_store_exports_jsonl(tmp_path: Path) -> None:
"""EventStore should stream simulation events to JSONL."""
store = EventStore(tmp_path)
events = [
SimulationEvent(
event_id="evt_01",
simulation_time=12.5,
event_type=SimulationEventType.TASK_CREATED,
entity_id="task_01",
task_id="task_01",
metadata={"priority": 1},
),
SimulationEvent(
event_id="evt_02",
simulation_time=15.0,
event_type=SimulationEventType.ROBOT_DISPATCHED,
entity_id="amr_01",
task_id="task_01",
),
]
jsonl_path = store.export_events_jsonl(events)
assert jsonl_path.exists()
loaded = store.load_events(jsonl_path)
assert len(loaded) == 2
assert loaded[0]["simulation_time"] == 12.5
assert loaded[0]["event_type"] == "TASK_RELEASED"
assert loaded[1]["entity_id"] == "amr_01"
def test_event_store_exports_tasks_csv(tmp_path: Path) -> None:
"""EventStore should export task records with lifecycle timestamps to CSV."""
store = EventStore(tmp_path)
tasks = [
Task(
task_id="t100",
task_type=TaskType.OUTBOUND_PICKING,
source="rack_A",
destination="pack_01",
priority=1,
status=TaskStatus.COMPLETED,
release_time=10.0,
start_time=14.0,
completion_time=54.0,
assigned_robot_id="amr_light_01",
)
]
csv_path = store.export_tasks_csv(tasks, sim_duration=100.0)
assert csv_path.exists()
loaded_tasks = store.load_tasks(csv_path)
assert len(loaded_tasks) == 1
t = loaded_tasks[0]
assert t["task_id"] == "t100"
assert t["task_type"] == "ORDER_PICK"
assert t["waiting_time_seconds"] == 4.0
assert t["turnaround_time_seconds"] == 44.0
assert t["assigned_robot_id"] == "amr_light_01"
def test_event_store_exports_robots_csv(tmp_path: Path) -> None:
"""EventStore should export robot metrics to CSV."""
store = EventStore(tmp_path)
r = Robot(
robot_id="amr_01",
robot_type="heavy_amr",
position=Position3D(0.0, 0.0, 0.0),
maximum_speed=1.0,
payload_capacity=1500.0,
battery_level=12.0,
battery_capacity=15.0,
energy_consumption={"idle": 0.1, "moving_empty": 0.8, "moving_loaded": 2.0, "handling": 0.5},
accumulated_distance=500.0,
loaded_distance=300.0,
empty_distance=200.0,
busy_time=250.0,
charging_time=50.0,
total_energy_consumed_kwh=1.25,
total_energy_charged_kwh=3.5,
)
csv_path = store.export_robots_csv({"amr_01": r}, sim_duration=1000.0)
assert csv_path.exists()
with open(csv_path, "r", encoding="utf-8") as f:
content = f.read()
assert "amr_01" in content
assert "500.0" in content
assert "300.0" in content
assert "60.0" in content # loaded_ratio_percent (300/500 * 100)
def test_event_store_exports_kpi_summary_json(tmp_path: Path) -> None:
"""EventStore should serialize ComprehensiveKPIReport to JSON."""
store = EventStore(tmp_path)
rep = ComprehensiveKPIReport(
duration_seconds=3600.0,
tasks_created=100,
tasks_completed=95,
throughput_tasks_per_hour=95.0,
)
json_path = store.export_kpi_summary_json(rep)
assert json_path.exists()
loaded = store.load_kpis(json_path)
assert loaded["tasks_completed"] == 95
assert loaded["throughput_tasks_per_hour"] == 95.0
+101
View File
@@ -0,0 +1,101 @@
"""Unit tests for ExperimentRunner, repeatability, fleet scaling, and Monte Carlo execution."""
from pathlib import Path
import pytest
from warehouse_twin.analytics.experiment_runner import ExperimentConfig, ExperimentRunner
def test_experiment_runner_single_execution(tmp_path: Path) -> None:
"""ExperimentRunner should execute a short simulation and write all artifacts."""
runner = ExperimentRunner()
cfg = ExperimentConfig(
experiment_id="test_exp_01",
name="Short Test Experiment",
seed=42,
duration_seconds=300.0,
output_dir=str(tmp_path / "test_exp_01"),
)
result = runner.run_single(cfg)
assert result.output_dir.exists()
assert (result.output_dir / "events.jsonl").exists()
assert (result.output_dir / "tasks.csv").exists()
assert (result.output_dir / "robots.csv").exists()
assert (result.output_dir / "aisle_congestion.csv").exists()
assert (result.output_dir / "kpi_summary.json").exists()
assert (result.output_dir / "report.md").exists()
assert (result.output_dir / "congestion_heatmap.svg").exists()
assert (result.output_dir / "config.json").exists()
rep = result.kpi_report
assert rep.tasks_created > 0
assert rep.random_seed == 42
def test_experiment_reproducibility(tmp_path: Path) -> None:
"""Two independent simulation runs with the same random seed must produce identical results."""
runner = ExperimentRunner()
cfg1 = ExperimentConfig(
experiment_id="rep_1",
seed=999,
duration_seconds=300.0,
output_dir=str(tmp_path / "rep_1"),
)
cfg2 = ExperimentConfig(
experiment_id="rep_2",
seed=999,
duration_seconds=300.0,
output_dir=str(tmp_path / "rep_2"),
)
res1 = runner.run_single(cfg1)
res2 = runner.run_single(cfg2)
assert res1.kpi_report.tasks_created == res2.kpi_report.tasks_created
assert res1.kpi_report.tasks_completed == res2.kpi_report.tasks_completed
assert res1.kpi_report.throughput_tasks_per_hour == res2.kpi_report.throughput_tasks_per_hour
assert res1.kpi_report.total_travel_distance_meters == res2.kpi_report.total_travel_distance_meters
def test_experiment_fleet_size_scaling(tmp_path: Path) -> None:
"""ExperimentRunner should scale AMR fleet to specified fleet size."""
runner = ExperimentRunner()
cfg_small = ExperimentConfig(
experiment_id="fleet_2",
fleet_size=2,
duration_seconds=120.0,
output_dir=str(tmp_path / "fleet_2"),
)
res_small = runner.run_single(cfg_small)
assert res_small.kpi_report.fleet_size == 2
cfg_large = ExperimentConfig(
experiment_id="fleet_6",
fleet_size=6,
duration_seconds=120.0,
output_dir=str(tmp_path / "fleet_6"),
)
res_large = runner.run_single(cfg_large)
assert res_large.kpi_report.fleet_size == 6
def test_monte_carlo_execution(tmp_path: Path) -> None:
"""Monte Carlo execution should run across multiple seeds and compute confidence intervals."""
runner = ExperimentRunner()
cfg = ExperimentConfig(
experiment_id="mc_test",
duration_seconds=120.0,
output_dir=str(tmp_path / "mc_test"),
)
mc_summary = runner.run_monte_carlo(cfg, seeds=[101, 102])
assert mc_summary["replications"] == 2
assert "mean" in mc_summary["throughput_tasks_per_hour"]
assert "ci95" in mc_summary["throughput_tasks_per_hour"]
assert (tmp_path / "mc_test" / "monte_carlo_summary.json").exists()
+87
View File
@@ -0,0 +1,87 @@
"""Unit tests for CongestionHeatmapGenerator (SVG, ASCII, and bottleneck diagnosis)."""
from pathlib import Path
import networkx as nx
import pytest
from warehouse_twin.analytics.heatmap import CongestionHeatmapGenerator
def _build_simple_test_graph() -> nx.DiGraph:
"""Build a minimal test graph with coordinates and stations."""
g = nx.DiGraph()
g.add_node("n1", pos=(10.0, 10.0, 0.0), station_id="pick_01")
g.add_node("n2", pos=(20.0, 10.0, 0.0))
g.add_node("n3", pos=(20.0, 20.0, 0.0), charger_id="ch_01")
g.add_edge("n1", "n2", distance=10.0)
g.add_edge("n2", "n1", distance=10.0)
g.add_edge("n2", "n3", distance=10.0)
g.add_edge("n3", "n2", distance=10.0)
return g
def test_heatmap_score_computation_and_colors() -> None:
"""Congestion scores should map into appropriate RGB color hex values."""
g = _build_simple_test_graph()
edge_metrics = [
{"source": "n1", "target": "n2", "traversals": 100, "conflicts": 20, "total_wait_time_seconds": 50.0},
{"source": "n2", "target": "n3", "traversals": 5, "conflicts": 0, "total_wait_time_seconds": 0.0},
]
gen = CongestionHeatmapGenerator(g, edge_metrics, width_meters=60.0, length_meters=40.0)
assert ("n1", "n2") in gen.edge_scores
score_hot = gen.edge_scores[("n1", "n2")]
score_cold = gen.edge_scores[("n2", "n3")]
assert score_hot > score_cold
assert gen.get_color_for_score(0.05) == "#22c55e" # Green
assert gen.get_color_for_score(0.85) == "#ef4444" # Red
def test_heatmap_bottleneck_diagnosis() -> None:
"""Diagnoses should flag severe corridors with critical severity and recommendations."""
g = _build_simple_test_graph()
edge_metrics = [
{"source": "n1", "target": "n2", "traversals": 50, "conflicts": 15, "total_wait_time_seconds": 45.0},
{"source": "n2", "target": "n3", "traversals": 20, "conflicts": 2, "total_wait_time_seconds": 5.0},
]
gen = CongestionHeatmapGenerator(g, edge_metrics)
diagnoses = gen.diagnose_bottlenecks(top_k=2)
assert len(diagnoses) == 2
top = diagnoses[0]
assert top["source"] == "n1"
assert top["target"] == "n2"
assert top["severity"] == "CRITICAL"
assert "bidirectional contention" in top["recommendation"].lower()
def test_heatmap_render_ascii() -> None:
"""ASCII render should return a non-empty string grid containing stations and legend."""
g = _build_simple_test_graph()
edge_metrics = [{"source": "n1", "target": "n2", "traversals": 30, "conflicts": 5, "total_wait_time_seconds": 12.0}]
gen = CongestionHeatmapGenerator(g, edge_metrics)
ascii_map = gen.render_ascii_heatmap()
assert "Warehouse Floorplan Congestion Heatmap" in ascii_map
assert "[S] Station" in ascii_map
assert "S" in ascii_map # station
assert "C" in ascii_map # charger
def test_heatmap_render_svg(tmp_path: Path) -> None:
"""SVG render should output a well-formed SVG XML file with graphic prims."""
g = _build_simple_test_graph()
edge_metrics = [{"source": "n1", "target": "n2", "traversals": 40, "conflicts": 8, "total_wait_time_seconds": 18.0}]
gen = CongestionHeatmapGenerator(g, edge_metrics)
svg_file = tmp_path / "test_heatmap.svg"
gen.render_svg_heatmap(svg_file)
assert svg_file.exists()
content = svg_file.read_text(encoding="utf-8")
assert "<svg" in content
assert "</svg>" in content
assert "Warehouse Traffic & Congestion Heatmap" in content
assert "pick_01" in content
assert "ch_01" in content
+162
View File
@@ -0,0 +1,162 @@
"""Unit tests for the KPICalculator and mathematical aggregation functions."""
import pytest
from warehouse_twin.analytics.kpi_calculator import (
ComprehensiveKPIReport,
DistributionStats,
KPICalculator,
compute_percentile,
)
from warehouse_twin.domain.robot import Robot
from warehouse_twin.domain.task import Task, TaskPriority, TaskStatus, TaskType
from warehouse_twin.domain.warehouse import Position3D
from warehouse_twin.simulation.sim_engine import SimulationMetrics
def test_compute_percentile_empty_and_single() -> None:
"""Empty and single-element sequences should return expected percentiles without errors."""
assert compute_percentile([], 50.0) == 0.0
assert compute_percentile([42.0], 50.0) == 42.0
assert compute_percentile([42.0], 99.0) == 42.0
def test_compute_percentile_interpolation() -> None:
"""Percentile function should correctly interpolate across sorted ranks."""
data = [10.0, 20.0, 30.0, 40.0, 50.0]
assert compute_percentile(data, 0.0) == 10.0
assert compute_percentile(data, 50.0) == 30.0
assert compute_percentile(data, 100.0) == 50.0
# Interpolated rank between 20 and 30
p25 = compute_percentile(data, 25.0)
assert 15.0 <= p25 <= 25.0
def test_distribution_stats_from_values() -> None:
"""DistributionStats should compute mean, std_dev, min, max, and percentiles."""
data = [100.0, 200.0, 300.0, 400.0, 500.0]
stats = DistributionStats.from_values(data)
assert stats.count == 5
assert stats.mean == 300.0
assert stats.min == 100.0
assert stats.max == 500.0
assert stats.p50 == 300.0
assert stats.p90 > 400.0
assert stats.p99 <= 500.0
assert stats.std_dev > 0.0
def test_kpi_calculator_isolates_incomplete_tasks() -> None:
"""Incomplete tasks (pending, in-progress, failed) must be excluded from completion distributions."""
t_comp1 = Task(
task_id="t1",
task_type=TaskType.OUTBOUND_PICKING,
source="s1",
destination="d1",
release_time=10.0,
start_time=20.0,
completion_time=60.0,
status=TaskStatus.COMPLETED,
)
t_comp2 = Task(
task_id="t2",
task_type=TaskType.INBOUND_TRANSPORT,
source="s1",
destination="d1",
release_time=20.0,
start_time=35.0,
completion_time=80.0,
status=TaskStatus.COMPLETED,
)
t_pending = Task(
task_id="t3",
task_type=TaskType.OUTBOUND_PICKING,
source="s1",
destination="d1",
release_time=40.0,
status=TaskStatus.PENDING,
)
t_in_progress = Task(
task_id="t4",
task_type=TaskType.PRODUCTION_FEED,
source="s1",
destination="d1",
release_time=50.0,
start_time=60.0,
status=TaskStatus.IN_PROGRESS,
)
all_tasks = [t_comp1, t_comp2, t_pending, t_in_progress]
r1 = Robot(
robot_id="r1",
robot_type="light_amr",
position=Position3D(0.0, 0.0, 0.0),
maximum_speed=1.5,
payload_capacity=150.0,
battery_level=2.5,
battery_capacity=3.0,
energy_consumption={"idle": 0.05, "moving_empty": 0.35, "moving_loaded": 0.65, "handling": 0.15},
allowed_zones={"zone_a"},
accumulated_distance=200.0,
loaded_distance=120.0,
empty_distance=80.0,
busy_time=60.0,
total_energy_consumed_kwh=0.5,
)
sim_metrics = SimulationMetrics(
duration_seconds=100.0,
tasks_created=4,
tasks_completed=2,
)
report = KPICalculator.evaluate(
sim_metrics=sim_metrics,
all_tasks=all_tasks,
robots={"r1": r1},
wall_clock_seconds=0.05,
random_seed=42,
)
assert report.tasks_created == 4
assert report.tasks_completed == 2
assert report.tasks_pending == 1
assert report.tasks_in_progress == 1
assert report.completion_rate_percent == 50.0
# Turnaround distribution should only consider t1 (50s) and t2 (60s)
assert report.turnaround_time.count == 2
assert report.turnaround_time.mean == 55.0
assert report.turnaround_time.min == 50.0
assert report.turnaround_time.max == 60.0
# Spatial distance check
assert report.total_travel_distance_meters == 200.0
assert report.loaded_travel_distance_meters == 120.0
assert report.empty_travel_distance_meters == 80.0
assert report.loaded_distance_ratio_percent == 60.0
def test_kpi_task_type_breakdowns() -> None:
"""KPI calculator should generate operational metrics grouped by task type."""
t1 = Task(
task_id="t1",
task_type=TaskType.PRODUCTION_FEED,
source="s1",
destination="d1",
release_time=0.0,
start_time=10.0,
completion_time=50.0,
deadline=100.0,
status=TaskStatus.COMPLETED,
)
sim_metrics = SimulationMetrics(duration_seconds=3600.0)
report = KPICalculator.evaluate(sim_metrics, [t1], {})
assert TaskType.PRODUCTION_FEED.value in report.task_type_breakdowns
feed_bd = report.task_type_breakdowns[TaskType.PRODUCTION_FEED.value]
assert feed_bd.created_count == 1
assert feed_bd.completed_count == 1
assert feed_bd.avg_turnaround_seconds == 50.0
assert feed_bd.on_time_percent == 100.0
+56
View File
@@ -0,0 +1,56 @@
"""Unit tests for ScenarioComparator (fleet sizing and dispatch policy parameter sweeps)."""
from pathlib import Path
import pytest
from warehouse_twin.analytics.experiment_runner import ScenarioComparator
def test_compare_fleet_sizes(tmp_path: Path) -> None:
"""ScenarioComparator should run fleet size sweep and generate markdown report."""
comparator = ScenarioComparator()
report_file = tmp_path / "fleet_comparison.md"
res = comparator.compare_fleet_sizes(
fleet_sizes=[2, 4],
seed=42,
duration=120.0,
output_report=report_file,
)
assert res.scenario_type == "fleet_size"
assert len(res.experiments) == 2
assert len(res.comparison_table) == 2
assert res.comparison_table[0]["fleet_size"] == 2
assert res.comparison_table[1]["fleet_size"] == 4
assert report_file.exists()
content = report_file.read_text(encoding="utf-8")
assert "Scenario Comparison: Fleet Sizing Analysis" in content
assert "2 AMRs" in content
assert "4 AMRs" in content
def test_compare_dispatch_policies(tmp_path: Path) -> None:
"""ScenarioComparator should evaluate dispatch heuristics under identical workloads."""
comparator = ScenarioComparator()
report_file = tmp_path / "policy_comparison.md"
res = comparator.compare_dispatch_policies(
policies=["priority_nearest_idle", "nearest_idle"],
seed=42,
duration=120.0,
output_report=report_file,
)
assert res.scenario_type == "dispatch_policy"
assert len(res.experiments) == 2
assert res.comparison_table[0]["policy"] == "priority_nearest_idle"
assert res.comparison_table[1]["policy"] == "nearest_idle"
assert report_file.exists()
content = report_file.read_text(encoding="utf-8")
assert "Scenario Comparison: Dispatch Policy Evaluation" in content
assert "priority_nearest_idle" in content
assert "nearest_idle" in content