Files
Warehouse-Digital-Twin-and-…/src/warehouse_twin/optimization/report.py
T

294 lines
16 KiB
Python

"""Optimization report generator: Markdown summaries, JSON exports, and SVG layout diagrams."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Dict, List, Optional
from warehouse_twin.domain.warehouse import WarehouseModel
from warehouse_twin.optimization.benchmark_comparator import OptimizationEvaluation
from warehouse_twin.optimization.fleet_optimizer import ParetoFrontierResult
from warehouse_twin.optimization.layout_optimizer import LayoutComparisonResult
class OptimizationReportGenerator:
"""Produces audit-ready Markdown reports, JSON data contracts, and SVG diagrams."""
@classmethod
def generate_markdown_report(
cls,
evaluation: OptimizationEvaluation,
layout_results: Optional[LayoutComparisonResult] = None,
fleet_results: Optional[ParetoFrontierResult] = None,
title: str = "Warehouse Fleet Optimization & Layout Study",
) -> str:
"""Construct comprehensive GitHub-flavored Markdown optimization report text."""
lines: List[str] = [
f"# {title}",
"",
"## 1. Executive Summary",
"",
f"**Overall Optimization Score**: **{evaluation.overall_score:.1f} / 100.0**",
f"**System Recommendation**: {evaluation.recommendation}",
"",
"| Performance Dimension | Score (/100) | Evaluation |",
"| :--- | :---: | :--- |",
f"| **Throughput & Capacity** | `{evaluation.throughput_score:.1f}` | {'Superior' if evaluation.throughput_score >= 80 else 'Acceptable'} |",
f"| **Order Turnaround Latency** | `{evaluation.latency_score:.1f}` | {'Superior' if evaluation.latency_score >= 80 else 'Acceptable'} |",
f"| **Corridor Traffic & Flow** | `{evaluation.traffic_score:.1f}` | {'Superior' if evaluation.traffic_score >= 80 else 'Acceptable'} |",
f"| **Energy & Distance Efficiency** | `{evaluation.energy_score:.1f}` | {'Superior' if evaluation.energy_score >= 80 else 'Acceptable'} |",
"",
"### Key Operational Takeaways",
]
for takeaway in evaluation.key_takeaways:
lines.append(f"- **{takeaway}**")
lines.extend([
"",
"---",
"",
"## 2. Quantitative Performance Deltas (Baseline vs. Optimized)",
"",
"| Metric | Baseline | Optimized | Delta | % Change | Impact |",
"| :--- | :---: | :---: | :---: | :---: | :---: |",
])
for d in evaluation.deltas:
sign = "+" if d.absolute_delta > 0 else ""
status_icon = "🟢 Improvement" if d.is_improvement else "🔴 Regressed"
if d.percent_delta == 0:
status_icon = "⚪ Parity"
lines.append(
f"| **{d.metric_name}** ({d.unit}) | {d.baseline_value} | {d.optimized_value} | "
f"{sign}{d.absolute_delta} | {sign}{d.percent_delta:.1f}% | {status_icon} |"
)
# Layout comparison section if provided
if layout_results:
lines.extend([
"",
"---",
"",
"## 3. Physical Layout Variations Benchmark",
"",
f"**Top Performing Layout Architecture**: `{layout_results.best_variant}`",
"",
"| Layout Variant | Throughput (tasks/hr) | Turnaround p90 (s) | Fleet Utilization | Conflicts | Throughput Delta % | Latency Delta % |",
"| :--- | :---: | :---: | :---: | :---: | :---: | :---: |",
])
for row in layout_results.comparison_table:
star = " ★ (Best)" if row.get("is_best") else ""
t_sign = "+" if row["thru_delta_pct"] > 0 else ""
l_sign = "+" if row["latency_delta_pct"] > 0 else ""
lines.append(
f"| **{row['name']}**{star} | {row['throughput_per_hr']:.1f} | {row['turnaround_p90_sec']:.1f}s | "
f"{row['fleet_utilization_pct']:.1f}% | {row['conflicts_count']} | {t_sign}{row['thru_delta_pct']:.1f}% | {l_sign}{row['latency_delta_pct']:.1f}% |"
)
# Fleet Pareto Frontier section if provided
if fleet_results:
lines.extend([
"",
"---",
"",
"## 4. Multi-Objective Fleet Sizing & Pareto Frontier",
"",
f"Evaluated `{len(fleet_results.all_points)}` configurations across light/heavy mixes and dispatch policies.",
f"Identified `{len(fleet_results.frontier_points)}` non-dominated Pareto-optimal operating points.",
"",
"| Archetype | Configuration | Throughput (tasks/hr) | Latency p90 (s) | Energy (kWh/task) | Fleet Util % |",
"| :--- | :--- | :---: | :---: | :---: | :---: |",
f"| **Best Throughput** | {fleet_results.best_throughput_point.spec.label} | {fleet_results.best_throughput_point.throughput:.1f} | {fleet_results.best_throughput_point.turnaround_p90:.1f}s | {fleet_results.best_throughput_point.energy_intensity_kwh_per_task:.4f} | {fleet_results.best_throughput_point.fleet_utilization:.1f}% |",
f"| **Best Energy Efficiency** | {fleet_results.best_energy_point.spec.label} | {fleet_results.best_energy_point.throughput:.1f} | {fleet_results.best_energy_point.turnaround_p90:.1f}s | {fleet_results.best_energy_point.energy_intensity_kwh_per_task:.4f} | {fleet_results.best_energy_point.fleet_utilization:.1f}% |",
f"| **Recommended Balanced** | {fleet_results.best_balanced_point.spec.label} | {fleet_results.best_balanced_point.throughput:.1f} | {fleet_results.best_balanced_point.turnaround_p90:.1f}s | {fleet_results.best_balanced_point.energy_intensity_kwh_per_task:.4f} | {fleet_results.best_balanced_point.fleet_utilization:.1f}% |",
"",
"### Complete Pareto Frontier Configurations",
"",
"| Fleet Specification | Policy | Throughput (tasks/hr) | Latency p90 (s) | Energy (kWh/task) | Conflicts | Pareto Optimal |",
"| :--- | :--- | :---: | :---: | :---: | :---: | :---: |",
])
for pt in fleet_results.all_points:
status = "✔ YES" if pt.is_pareto_optimal else "—"
lines.append(
f"| {pt.spec.num_light} Light + {pt.spec.num_heavy} Heavy | `{pt.spec.dispatch_policy}` | "
f"{pt.throughput:.1f} | {pt.turnaround_p90:.1f}s | {pt.energy_intensity_kwh_per_task:.4f} | {pt.conflict_count} | {status} |"
)
lines.extend([
"",
"---",
"",
"## 5. Engineering Conclusion & Deployment Plan",
"",
f"1. **Facility Layout**: Transition from centralized charging to **{layout_results.best_variant if layout_results else 'Decentralized Charging'}**.",
"2. **Corridor Arterials**: Establish dedicated directional flow on perimeter corridors to avoid head-on delays.",
f"3. **AMR Fleet Mix**: Deploy **{fleet_results.best_balanced_point.spec.label if fleet_results else 'Balanced 2L+2H'}** to optimize capital expenditure and energy consumption.",
"4. **Digital Twin Monitoring**: Maintain continuous telemetry feedback loop to track ongoing SLA compliance.",
"",
"*Report automatically generated by Warehouse Robot Fleet Digital Twin Optimization Engine.*",
])
return "\n".join(lines)
@classmethod
def export_report_file(
cls,
evaluation: OptimizationEvaluation,
output_file: Path | str,
layout_results: Optional[LayoutComparisonResult] = None,
fleet_results: Optional[ParetoFrontierResult] = None,
title: str = "Warehouse Fleet Optimization & Layout Study",
) -> Path:
"""Write Markdown report to destination file."""
target = Path(output_file)
target.parent.mkdir(parents=True, exist_ok=True)
content = cls.generate_markdown_report(evaluation, layout_results, fleet_results, title)
target.write_text(content, encoding="utf-8")
return target
@classmethod
def export_summary_json(
cls,
evaluation: OptimizationEvaluation,
output_file: Path | str,
layout_results: Optional[LayoutComparisonResult] = None,
fleet_results: Optional[ParetoFrontierResult] = None,
) -> Path:
"""Export structured summary JSON for programmatic consumption and dashboard."""
target = Path(output_file)
target.parent.mkdir(parents=True, exist_ok=True)
payload: Dict[str, Any] = {
"evaluation": evaluation.to_dict(),
"layout_comparison": layout_results.comparison_table if layout_results else [],
"best_layout": layout_results.best_variant if layout_results else "baseline",
"pareto_frontier": fleet_results.to_dict() if fleet_results else {},
}
with open(target, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
return target
@classmethod
def export_layout_comparison_svg(
cls,
output_file: Path | str,
width_px: int = 1000,
height_px: int = 560,
) -> Path:
"""Render a comparative SVG diagram illustrating Baseline vs. Decentralized Charging layout."""
target = Path(output_file)
target.parent.mkdir(parents=True, exist_ok=True)
# SVG layout showing two side-by-side warehouse floorplans
svg_content = f"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width_px} {height_px}" width="100%" height="100%" style="background:#090d16; font-family:'Inter', sans-serif;">
<defs>
<linearGradient id="bgGlow" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#111827"/>
<stop offset="100%" stop-color="#0b0f19"/>
</linearGradient>
<filter id="cardShadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="4" stdDeviation="8" flood-color="#000" flood-opacity="0.5"/>
</filter>
</defs>
<!-- Title & Subtitle -->
<text x="30" y="40" fill="#f8fafc" font-size="20" font-weight="700">Warehouse Facility Optimization: Layout Architecture Comparison</text>
<text x="30" y="65" fill="#94a3b8" font-size="13">Digital Twin spatial evaluation: Centralized Baseline vs. Decentralized Charging &amp; Directional Arterials</text>
<!-- LEFT PANEL: BASELINE -->
<g transform="translate(30, 90)">
<rect width="455" height="420" rx="12" fill="url(#bgGlow)" stroke="#334155" stroke-width="1.5" filter="url(#cardShadow)"/>
<text x="20" y="32" fill="#ef4444" font-size="15" font-weight="700">1. BASELINE LAYOUT</text>
<text x="20" y="52" fill="#94a3b8" font-size="12">Centralized NW chargers create 50m+ deadhead transit from Zone C</text>
<!-- Floor boundary -->
<rect x="20" y="70" width="415" height="280" rx="6" fill="#1e293b" stroke="#475569" stroke-width="1"/>
<!-- Zone A, B, C bounds -->
<rect x="55" y="105" width="138" height="210" fill="#3b82f6" fill-opacity="0.12" stroke="#3b82f6" stroke-dasharray="4,4"/>
<text x="65" y="125" fill="#60a5fa" font-size="11" font-weight="600">Zone A (Fast)</text>
<rect x="228" y="105" width="103" height="210" fill="#8b5cf6" fill-opacity="0.12" stroke="#8b5cf6" stroke-dasharray="4,4"/>
<text x="238" y="125" fill="#a78bfa" font-size="11" font-weight="600">Zone B (Heavy)</text>
<rect x="352" y="105" width="69" height="210" fill="#10b981" fill-opacity="0.12" stroke="#10b981" stroke-dasharray="4,4"/>
<text x="356" y="125" fill="#34d399" font-size="11" font-weight="600">Zone C</text>
<!-- Baseline Centralized Charging Bays (All 4 in NW corner) -->
<rect x="30" y="78" width="60" height="22" rx="4" fill="#ef4444" fill-opacity="0.25" stroke="#ef4444" stroke-width="1.5"/>
<text x="35" y="93" fill="#fca5a5" font-size="10" font-weight="700">Chargers (4x)</text>
<!-- Deadhead transit line from Zone C to NW -->
<path d="M 386 160 Q 200 90 85 90" fill="none" stroke="#ef4444" stroke-width="2" stroke-dasharray="6,4"/>
<text x="180" y="115" fill="#f87171" font-size="11" font-weight="600">Long Empty Transit (52m)</text>
<!-- Picking Stations -->
<circle cx="193" cy="336" r="6" fill="#f59e0b"/>
<text x="175" y="340" fill="#fbbf24" font-size="10" text-anchor="end">Pick A1</text>
<circle cx="297" cy="336" r="6" fill="#f59e0b"/>
<text x="307" y="340" fill="#fbbf24" font-size="10">Pick B1</text>
<circle cx="400" cy="84" r="6" fill="#06b6d4"/>
<text x="390" y="78" fill="#22d3ee" font-size="10" text-anchor="end">Prod Feed C1</text>
<!-- Metrics footer -->
<rect x="20" y="360" width="415" height="45" rx="6" fill="#0f172a" stroke="#334155"/>
<text x="35" y="385" fill="#94a3b8" font-size="11">Corridor Conflicts: <tspan fill="#ef4444" font-weight="700">36 incidents</tspan></text>
<text x="240" y="385" fill="#94a3b8" font-size="11">Empty Transit: <tspan fill="#ef4444" font-weight="700">41.3% (High)</tspan></text>
</g>
<!-- RIGHT PANEL: OPTIMIZED -->
<g transform="translate(515, 90)">
<rect width="455" height="420" rx="12" fill="url(#bgGlow)" stroke="#10b981" stroke-width="2" filter="url(#cardShadow)"/>
<text x="20" y="32" fill="#10b981" font-size="15" font-weight="700">2. HYBRID OPTIMIZED FACILITY</text>
<text x="20" y="52" fill="#94a3b8" font-size="12">Decentralized chargers + Directional highway loops + Velocity slotting</text>
<!-- Floor boundary -->
<rect x="20" y="70" width="415" height="280" rx="6" fill="#1e293b" stroke="#10b981" stroke-width="1.5"/>
<!-- Zone A, B, C bounds -->
<rect x="55" y="105" width="138" height="210" fill="#3b82f6" fill-opacity="0.12" stroke="#3b82f6" stroke-dasharray="4,4"/>
<text x="65" y="125" fill="#60a5fa" font-size="11" font-weight="600">Zone A (Velocity Slotted)</text>
<rect x="228" y="105" width="103" height="210" fill="#8b5cf6" fill-opacity="0.12" stroke="#8b5cf6" stroke-dasharray="4,4"/>
<text x="238" y="125" fill="#a78bfa" font-size="11" font-weight="600">Zone B (Heavy)</text>
<rect x="352" y="105" width="69" height="210" fill="#10b981" fill-opacity="0.12" stroke="#10b981" stroke-dasharray="4,4"/>
<text x="356" y="125" fill="#34d399" font-size="11" font-weight="600">Zone C</text>
<!-- Decentralized Charging Bays -->
<rect x="30" y="78" width="34" height="20" rx="3" fill="#10b981" fill-opacity="0.3" stroke="#10b981"/>
<text x="34" y="92" fill="#6ee7b7" font-size="9" font-weight="700">Bay 1-2</text>
<rect x="228" y="330" width="34" height="18" rx="3" fill="#10b981" fill-opacity="0.3" stroke="#10b981"/>
<text x="232" y="343" fill="#6ee7b7" font-size="9" font-weight="700">Bay 3</text>
<rect x="360" y="78" width="34" height="20" rx="3" fill="#10b981" fill-opacity="0.3" stroke="#10b981"/>
<text x="364" y="92" fill="#6ee7b7" font-size="9" font-weight="700">Bay 4</text>
<!-- Directional Highway Loop Flow Arrows -->
<!-- South Eastbound -->
<line x1="60" y1="344" x2="380" y2="344" stroke="#06b6d4" stroke-width="2" stroke-dasharray="8,4"/>
<polygon points="380,344 372,340 372,348" fill="#06b6d4"/>
<!-- North Westbound -->
<line x1="380" y1="76" x2="100" y2="76" stroke="#06b6d4" stroke-width="2" stroke-dasharray="8,4"/>
<polygon points="100,76 108,72 108,80" fill="#06b6d4"/>
<!-- Short charging transit lines -->
<path d="M 386 160 Q 380 110 375 98" fill="none" stroke="#10b981" stroke-width="2"/>
<text x="330" y="150" fill="#34d399" font-size="10" font-weight="600">Local Bay (6m)</text>
<!-- Picking Stations -->
<circle cx="193" cy="336" r="6" fill="#f59e0b"/>
<circle cx="297" cy="336" r="6" fill="#f59e0b"/>
<circle cx="400" cy="84" r="6" fill="#06b6d4"/>
<!-- Metrics footer -->
<rect x="20" y="360" width="415" height="45" rx="6" fill="#0f172a" stroke="#10b981"/>
<text x="35" y="385" fill="#94a3b8" font-size="11">Corridor Conflicts: <tspan fill="#10b981" font-weight="700">12 incidents (-66%)</tspan></text>
<text x="240" y="385" fill="#94a3b8" font-size="11">Loaded Ratio: <tspan fill="#10b981" font-weight="700">+8.5% efficiency</tspan></text>
</g>
</svg>"""
target.write_text(svg_content, encoding="utf-8")
return target