feat(phase-9): implement layout variations, pareto fleet optimization, and final demonstration
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
"""Unit tests for benchmark comparator and optimization report generator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.analytics.kpi_calculator import (
|
||||
ComprehensiveKPIReport,
|
||||
DistributionStats,
|
||||
)
|
||||
from warehouse_twin.optimization.benchmark_comparator import (
|
||||
BenchmarkComparator,
|
||||
OptimizationDelta,
|
||||
OptimizationEvaluation,
|
||||
)
|
||||
from warehouse_twin.optimization.report import OptimizationReportGenerator
|
||||
|
||||
|
||||
def make_mock_kpi_report(
|
||||
throughput: float = 85.0,
|
||||
p90: float = 120.0,
|
||||
p50: float = 75.0,
|
||||
conflicts: int = 30,
|
||||
energy_intensity: float = 0.09,
|
||||
loaded_pct: float = 58.0,
|
||||
) -> ComprehensiveKPIReport:
|
||||
"""Construct mock KPI report for unit tests."""
|
||||
return ComprehensiveKPIReport(
|
||||
duration_seconds=3600.0,
|
||||
tasks_created=90,
|
||||
tasks_completed=85,
|
||||
completion_rate_percent=94.4,
|
||||
throughput_tasks_per_hour=throughput,
|
||||
turnaround_time=DistributionStats(mean=p50 + 10, std_dev=15.0, min=30.0, p50=p50, p90=p90, p95=p90 + 20, p99=p90 + 40, max=p90 + 50),
|
||||
waiting_time=DistributionStats(mean=20.0, std_dev=10.0, min=0.0, p50=15.0, p90=40.0, p95=50.0, p99=60.0, max=70.0),
|
||||
execution_time=DistributionStats(mean=55.0, std_dev=10.0, min=30.0, p50=50.0, p90=70.0, p95=75.0, p99=80.0, max=85.0),
|
||||
on_time_delivery_percent=100.0,
|
||||
fleet_size=4,
|
||||
fleet_utilization_percent=50.0,
|
||||
total_travel_distance_meters=4000.0,
|
||||
loaded_travel_distance_meters=2320.0,
|
||||
empty_travel_distance_meters=1680.0,
|
||||
loaded_distance_ratio_percent=loaded_pct,
|
||||
total_energy_consumed_kwh=7.65,
|
||||
energy_intensity_kwh_per_task=energy_intensity,
|
||||
conflicts_detected=conflicts,
|
||||
yield_waits_count=conflicts,
|
||||
total_yield_wait_time_seconds=conflicts * 1.5,
|
||||
)
|
||||
|
||||
|
||||
def test_benchmark_comparator_deltas_and_scoring():
|
||||
"""Verify quantitative delta calculations and operational score outputs."""
|
||||
base_kpi = make_mock_kpi_report(throughput=80.0, p90=140.0, conflicts=35, energy_intensity=0.095, loaded_pct=52.0)
|
||||
opt_kpi = make_mock_kpi_report(throughput=88.0, p90=95.0, conflicts=12, energy_intensity=0.082, loaded_pct=61.0)
|
||||
|
||||
eval_result = BenchmarkComparator.compare_kpis(
|
||||
baseline=base_kpi,
|
||||
optimized=opt_kpi,
|
||||
baseline_name="Centralized Baseline",
|
||||
optimized_name="Hybrid Optimal",
|
||||
)
|
||||
|
||||
assert eval_result.overall_score >= 80.0
|
||||
assert eval_result.throughput_score > 75.0
|
||||
assert eval_result.latency_score > 75.0
|
||||
assert eval_result.traffic_score > 75.0
|
||||
assert "RECOMMENDED" in eval_result.recommendation
|
||||
|
||||
# Check deltas
|
||||
deltas = {d.metric_name: d for d in eval_result.deltas}
|
||||
assert deltas["Throughput"].absolute_delta == 8.0
|
||||
assert deltas["Throughput"].percent_delta == 10.0
|
||||
assert deltas["Throughput"].is_improvement is True
|
||||
|
||||
assert deltas["Turnaround Latency (p90)"].absolute_delta == -45.0
|
||||
assert deltas["Turnaround Latency (p90)"].is_improvement is True
|
||||
|
||||
assert deltas["Corridor Conflicts"].absolute_delta == -23.0
|
||||
assert deltas["Corridor Conflicts"].is_improvement is True
|
||||
|
||||
assert deltas["Loaded Travel Ratio"].absolute_delta == 9.0
|
||||
assert deltas["Loaded Travel Ratio"].is_improvement is True
|
||||
|
||||
|
||||
def test_optimization_report_generator(tmp_path: Path):
|
||||
"""Verify Markdown report, summary JSON, and SVG layout comparison export."""
|
||||
base_kpi = make_mock_kpi_report()
|
||||
opt_kpi = make_mock_kpi_report(throughput=88.0, p90=100.0, conflicts=15)
|
||||
evaluation = BenchmarkComparator.compare_kpis(base_kpi, opt_kpi)
|
||||
|
||||
# 1. Export Markdown report
|
||||
md_file = tmp_path / "opt_report.md"
|
||||
OptimizationReportGenerator.export_report_file(evaluation, md_file)
|
||||
assert md_file.exists()
|
||||
md_text = md_file.read_text(encoding="utf-8")
|
||||
assert "# Warehouse Fleet Optimization" in md_text
|
||||
assert "Executive Summary" in md_text
|
||||
assert "Quantitative Performance Deltas" in md_text
|
||||
|
||||
# 2. Export JSON summary
|
||||
json_file = tmp_path / "opt_summary.json"
|
||||
OptimizationReportGenerator.export_summary_json(evaluation, json_file)
|
||||
assert json_file.exists()
|
||||
data = json.loads(json_file.read_text(encoding="utf-8"))
|
||||
assert "evaluation" in data
|
||||
assert data["evaluation"]["overall_score"] > 0
|
||||
|
||||
# 3. Export SVG diagram
|
||||
svg_file = tmp_path / "layout_comparison.svg"
|
||||
OptimizationReportGenerator.export_layout_comparison_svg(svg_file)
|
||||
assert svg_file.exists()
|
||||
svg_text = svg_file.read_text(encoding="utf-8")
|
||||
assert "<svg" in svg_text
|
||||
assert "BASELINE LAYOUT" in svg_text
|
||||
assert "HYBRID OPTIMIZED FACILITY" in svg_text
|
||||
@@ -34,6 +34,15 @@ def running_server(tmp_path: Path):
|
||||
(exp_dir / "congestion_heatmap.svg").write_text("<svg><circle r='10'/></svg>", encoding="utf-8")
|
||||
(exp_dir / "report.md").write_text("# Test Report\nContent", encoding="utf-8")
|
||||
|
||||
# Create mock optimization in tmp_path
|
||||
opt_dir = tmp_path / "optimization"
|
||||
opt_dir.mkdir(parents=True)
|
||||
(opt_dir / "optimization_summary.json").write_text(json.dumps({
|
||||
"evaluation": {"overall_score": 85.0},
|
||||
"layout_comparison": [{"variant": "baseline", "is_best": False}],
|
||||
}), encoding="utf-8")
|
||||
(opt_dir / "layout_comparison.svg").write_text("<svg><rect width='100' height='100'/></svg>", encoding="utf-8")
|
||||
|
||||
port = find_free_port()
|
||||
server = DashboardServer(results_dir=tmp_path, host="127.0.0.1", port=port)
|
||||
|
||||
@@ -97,7 +106,21 @@ def test_server_health_and_api_endpoints(running_server):
|
||||
assert "fleet_sizing" in comps
|
||||
assert "dispatch_policies" in comps
|
||||
|
||||
# 7. Static HTML page
|
||||
# 7. Optimization endpoint
|
||||
with urllib.request.urlopen(f"{base_url}/api/optimization", timeout=3.0) as resp:
|
||||
assert resp.status == 200
|
||||
opt_data = json.loads(resp.read().decode("utf-8"))
|
||||
assert "evaluation" in opt_data
|
||||
assert "layout_comparison" in opt_data
|
||||
|
||||
# 8. Optimization comparison SVG endpoint
|
||||
with urllib.request.urlopen(f"{base_url}/api/optimization/comparison.svg", timeout=3.0) as resp:
|
||||
assert resp.status == 200
|
||||
assert "image/svg+xml" in resp.headers.get("Content-Type", "")
|
||||
opt_svg = resp.read().decode("utf-8")
|
||||
assert "<svg" in opt_svg
|
||||
|
||||
# 9. Static HTML page
|
||||
with urllib.request.urlopen(f"{base_url}/", timeout=3.0) as resp:
|
||||
assert resp.status == 200
|
||||
html = resp.read().decode("utf-8")
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Unit tests for the end-to-end digital twin final demonstration workflow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.demo.demo_runner import (
|
||||
FinalDemoConfig,
|
||||
FinalDemoResult,
|
||||
FinalDemoRunner,
|
||||
)
|
||||
|
||||
|
||||
def test_final_demo_config_initialization(tmp_path: Path):
|
||||
"""Verify FinalDemoConfig default values and quick mode adjustments."""
|
||||
cfg = FinalDemoConfig(quick_mode=True, output_dir=tmp_path / "demo")
|
||||
assert cfg.quick_mode is True
|
||||
assert cfg.duration_seconds <= 300.0
|
||||
|
||||
standard_cfg = FinalDemoConfig(quick_mode=False)
|
||||
assert standard_cfg.duration_seconds == 3600.0
|
||||
|
||||
|
||||
def test_final_demo_runner_execution(project_config_dir: Path, tmp_path: Path):
|
||||
"""Verify end-to-end demonstration workflow produces all expected artifacts."""
|
||||
demo_out = tmp_path / "demonstration"
|
||||
usd_out = tmp_path / "scenes" / "warehouse_final_demo.usda"
|
||||
|
||||
cfg = FinalDemoConfig(
|
||||
duration_seconds=90.0,
|
||||
seed=42,
|
||||
output_dir=demo_out,
|
||||
usd_output_path=usd_out,
|
||||
export_usd=True,
|
||||
export_svg=True,
|
||||
quick_mode=True,
|
||||
)
|
||||
|
||||
runner = FinalDemoRunner(project_config_dir)
|
||||
res = runner.run_demonstration(cfg)
|
||||
|
||||
# 1. Verification of execution results
|
||||
assert res.baseline_result is not None
|
||||
assert res.optimized_result is not None
|
||||
assert res.evaluation is not None
|
||||
assert res.evaluation.overall_score > 0.0
|
||||
|
||||
# 2. Layout & Pareto results
|
||||
assert res.layout_results is not None
|
||||
assert len(res.layout_results.comparison_table) >= 2
|
||||
assert res.pareto_results is not None
|
||||
assert len(res.pareto_results.all_points) >= 2
|
||||
|
||||
# 3. Artifact files
|
||||
assert res.markdown_report_path.exists()
|
||||
assert res.markdown_report_path.stat().st_size > 500
|
||||
|
||||
assert res.summary_json_path.exists()
|
||||
with open(res.summary_json_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
assert "evaluation" in data
|
||||
assert "layout_comparison" in data
|
||||
|
||||
if res.svg_comparison_path:
|
||||
assert res.svg_comparison_path.exists()
|
||||
assert "<svg" in res.svg_comparison_path.read_text(encoding="utf-8")
|
||||
|
||||
if res.usd_stage_path:
|
||||
assert res.usd_stage_path.exists()
|
||||
usd_text = res.usd_stage_path.read_text(encoding="utf-8")
|
||||
assert "#usda 1.0" in usd_text
|
||||
|
||||
# 4. Result serialization
|
||||
d = res.to_dict()
|
||||
assert "evaluation" in d
|
||||
assert "markdown_report" in d
|
||||
assert "summary_json" in d
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Unit tests for multi-objective fleet optimization and Pareto frontier extraction."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.optimization.fleet_optimizer import (
|
||||
FleetCompositionSpec,
|
||||
FleetOptimizer,
|
||||
ParetoPoint,
|
||||
)
|
||||
|
||||
|
||||
def test_fleet_composition_spec_attributes():
|
||||
"""Verify fleet composition specification and label generation."""
|
||||
spec = FleetCompositionSpec(num_light=3, num_heavy=1, dispatch_policy="nearest_idle")
|
||||
assert spec.total_fleet_size == 4
|
||||
assert spec.label == "3L+1H (nearest_idle)"
|
||||
d = spec.to_dict()
|
||||
assert d["num_light"] == 3
|
||||
assert d["num_heavy"] == 1
|
||||
assert d["total_fleet_size"] == 4
|
||||
|
||||
|
||||
def test_fleet_optimizer_single_evaluation(project_config_dir: Path):
|
||||
"""Verify simulation evaluation of a specific fleet composition."""
|
||||
optimizer = FleetOptimizer(project_config_dir)
|
||||
spec = FleetCompositionSpec(num_light=2, num_heavy=1, dispatch_policy="priority_nearest_idle")
|
||||
|
||||
point = optimizer.evaluate_configuration(spec, duration_seconds=120.0, seed=42)
|
||||
assert point.spec == spec
|
||||
assert point.throughput >= 0.0
|
||||
assert point.turnaround_p90 >= 0.0
|
||||
assert point.fleet_utilization >= 0.0
|
||||
assert point.energy_intensity_kwh_per_task >= 0.0
|
||||
assert point.conflict_count >= 0
|
||||
|
||||
|
||||
def test_pareto_frontier_extraction(project_config_dir: Path):
|
||||
"""Verify Pareto frontier identification from candidate search space."""
|
||||
optimizer = FleetOptimizer(project_config_dir)
|
||||
|
||||
# Synthetic design points to test non-dominated logic
|
||||
pt1 = ParetoPoint(
|
||||
spec=FleetCompositionSpec(num_light=2, num_heavy=1),
|
||||
throughput=80.0,
|
||||
turnaround_p90=85.0,
|
||||
turnaround_mean=60.0,
|
||||
fleet_utilization=70.0,
|
||||
energy_intensity_kwh_per_task=0.08,
|
||||
conflict_count=10,
|
||||
wait_time_seconds=5.0,
|
||||
sla_compliance_percent=100.0,
|
||||
)
|
||||
# pt2 dominates pt3 (higher throughput, lower latency, lower energy)
|
||||
pt2 = ParetoPoint(
|
||||
spec=FleetCompositionSpec(num_light=3, num_heavy=2),
|
||||
throughput=95.0,
|
||||
turnaround_p90=60.0,
|
||||
turnaround_mean=45.0,
|
||||
fleet_utilization=55.0,
|
||||
energy_intensity_kwh_per_task=0.07,
|
||||
conflict_count=15,
|
||||
wait_time_seconds=8.0,
|
||||
sla_compliance_percent=100.0,
|
||||
)
|
||||
pt3 = ParetoPoint(
|
||||
spec=FleetCompositionSpec(num_light=1, num_heavy=2),
|
||||
throughput=70.0,
|
||||
turnaround_p90=95.0,
|
||||
turnaround_mean=75.0,
|
||||
fleet_utilization=90.0,
|
||||
energy_intensity_kwh_per_task=0.10,
|
||||
conflict_count=20,
|
||||
wait_time_seconds=18.0,
|
||||
sla_compliance_percent=90.0,
|
||||
)
|
||||
|
||||
frontier = optimizer._compute_pareto_frontier([pt1, pt2, pt3])
|
||||
assert pt2 in frontier
|
||||
assert pt3 not in frontier
|
||||
assert pt2.is_pareto_optimal is True
|
||||
assert pt3.is_pareto_optimal is False
|
||||
|
||||
|
||||
def test_fleet_optimizer_sweep_and_archetypes(project_config_dir: Path):
|
||||
"""Verify sweep across candidate fleet specs and selection of best archetypes."""
|
||||
optimizer = FleetOptimizer(project_config_dir)
|
||||
candidates = [
|
||||
FleetCompositionSpec(num_light=1, num_heavy=1, dispatch_policy="priority_nearest_idle", name="Mini 1L+1H"),
|
||||
FleetCompositionSpec(num_light=2, num_heavy=1, dispatch_policy="priority_nearest_idle", name="Fast 2L+1H"),
|
||||
]
|
||||
|
||||
result = optimizer.optimize_fleet(candidate_specs=candidates, duration_seconds=100.0, seed=42)
|
||||
assert len(result.all_points) == 2
|
||||
assert len(result.frontier_points) >= 1
|
||||
assert result.best_throughput_point is not None
|
||||
assert result.best_energy_point is not None
|
||||
assert result.best_balanced_point is not None
|
||||
|
||||
d = result.to_dict()
|
||||
assert d["total_evaluated"] == 2
|
||||
assert "best_balanced" in d
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Unit tests for layout variations and facility topology optimization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.domain.warehouse import Position3D, WarehouseModel
|
||||
from warehouse_twin.optimization.layout_optimizer import (
|
||||
LAYOUT_REGISTRY,
|
||||
LayoutOptimizer,
|
||||
LayoutVariant,
|
||||
)
|
||||
|
||||
|
||||
def test_layout_registry_definitions():
|
||||
"""Verify all 5 layout variants are defined with descriptions and rationales."""
|
||||
for variant in LayoutVariant:
|
||||
assert variant in LAYOUT_REGISTRY
|
||||
spec = LAYOUT_REGISTRY[variant]
|
||||
assert spec.variant == variant
|
||||
assert len(spec.name) > 0
|
||||
assert len(spec.description) > 0
|
||||
assert len(spec.rationale) > 0
|
||||
|
||||
|
||||
def test_decentralized_charging_layout_configuration(project_config_dir: Path):
|
||||
"""Verify decentralized charging distributes bays across Zones A, B, and C."""
|
||||
optimizer = LayoutOptimizer(project_config_dir)
|
||||
|
||||
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)
|
||||
for b in base_bays:
|
||||
assert b["position"][0] <= 8.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
|
||||
|
||||
positions = [b["position"] for b in decent_bays]
|
||||
# Bay 3 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
|
||||
|
||||
|
||||
def test_velocity_slotting_inventory_configuration(project_config_dir: Path):
|
||||
"""Verify velocity slotting reassigns high-frequency SKUs to front racks."""
|
||||
optimizer = LayoutOptimizer(project_config_dir)
|
||||
inv_cfg = optimizer.get_inventory_config(LayoutVariant.VELOCITY_SLOTTING)
|
||||
|
||||
items = {}
|
||||
for cat in inv_cfg.get("categories", {}).values():
|
||||
for item in cat.get("items", []):
|
||||
items[item["item_id"]] = item
|
||||
|
||||
assert items["filter_hydraulic_hf1"]["storage_location"] == "rack_a_01"
|
||||
assert items["belt_drive_bd10"]["storage_location"] == "rack_a_03"
|
||||
assert items["tractor_hood_panel_th2"]["storage_location"] == "rack_a_05"
|
||||
|
||||
|
||||
def test_directional_highways_graph_modification(project_config_dir: Path):
|
||||
"""Verify directional highways configure one-way flow on outer arterial corridors."""
|
||||
optimizer = LayoutOptimizer(project_config_dir)
|
||||
|
||||
model, graph = optimizer.build_graph_for_variant(LayoutVariant.DIRECTIONAL_HIGHWAYS)
|
||||
assert graph.number_of_nodes() > 100
|
||||
assert graph.number_of_edges() > 100
|
||||
|
||||
# Test South highway (y=2.0): should have Eastbound edges, not Westbound
|
||||
south_nodes = [
|
||||
n for n, d in graph.nodes(data=True)
|
||||
if round(float(d.get("y", 0.0)), 1) == 2.0 and d.get("node_type") == "waypoint"
|
||||
]
|
||||
assert len(south_nodes) >= 10
|
||||
|
||||
eastbound_found = False
|
||||
for u in south_nodes:
|
||||
ux = round(float(graph.nodes[u]["x"]), 1)
|
||||
for v in graph.successors(u):
|
||||
if round(float(graph.nodes[v]["y"]), 1) == 2.0 and graph.nodes[v].get("node_type") == "waypoint":
|
||||
vx = round(float(graph.nodes[v]["x"]), 1)
|
||||
assert vx >= ux, f"Disallowed Westbound edge found on South highway: {u} -> {v}"
|
||||
if vx > ux:
|
||||
eastbound_found = True
|
||||
|
||||
assert eastbound_found, "Expected Eastbound edges along South highway"
|
||||
|
||||
|
||||
def test_layout_comparison_simulation(project_config_dir: Path, tmp_path: Path):
|
||||
"""Verify short layout comparison run across Baseline and Decentralized Charging."""
|
||||
optimizer = LayoutOptimizer(project_config_dir)
|
||||
res = optimizer.compare_layouts(
|
||||
variants=[LayoutVariant.BASELINE, LayoutVariant.DECENTRALIZED_CHARGING],
|
||||
duration_seconds=120.0,
|
||||
seed=42,
|
||||
output_dir=tmp_path / "layouts",
|
||||
)
|
||||
|
||||
assert res.baseline_result is not None
|
||||
assert "decentralized_charging" in res.variant_results
|
||||
assert len(res.comparison_table) == 2
|
||||
assert res.best_variant in ("baseline", "decentralized_charging")
|
||||
|
||||
# Export layout configs
|
||||
cfgs = optimizer.export_layout_configs(tmp_path / "configs")
|
||||
assert len(cfgs) == 5
|
||||
assert (tmp_path / "configs" / "warehouse_baseline.json").exists()
|
||||
assert (tmp_path / "configs" / "warehouse_hybrid_optimal.json").exists()
|
||||
Reference in New Issue
Block a user