Files
Warehouse-Digital-Twin-and-…/src/warehouse_twin/dashboard/data_provider.py
T

308 lines
12 KiB
Python

"""Data provider and parser for operational dashboard telemetry."""
from __future__ import annotations
import csv
import json
import re
from pathlib import Path
from typing import Any, Dict, List, Optional
class DashboardDataProvider:
"""Reads, caches, and aggregates simulation results for dashboard presentation."""
def __init__(self, results_dir: Path | str = "results") -> None:
self.results_dir = Path(results_dir).resolve()
self.experiments_dir = self.results_dir / "experiments"
self.reports_dir = self.results_dir / "reports"
def list_experiments(self) -> List[Dict[str, Any]]:
"""List all discovered experiment runs in the experiments directory."""
if not self.experiments_dir.exists():
return []
experiments: List[Dict[str, Any]] = []
for exp_path in sorted(self.experiments_dir.iterdir()):
if not exp_path.is_dir():
continue
exp_id = exp_path.name
kpi_file = exp_path / "kpi_summary.json"
cfg_file = exp_path / "config.json"
# Skip hidden or empty dirs
if not kpi_file.exists() and not cfg_file.exists():
continue
entry: Dict[str, Any] = {
"id": exp_id,
"name": exp_id.replace("_", " ").title(),
"has_kpis": kpi_file.exists(),
"has_heatmap": (exp_path / "congestion_heatmap.svg").exists(),
"has_report": (exp_path / "report.md").exists(),
"throughput": 0.0,
"fleet_size": 4,
"duration": 3600.0,
"policy": "priority_nearest_idle",
"seed": 42,
}
if cfg_file.exists():
try:
with open(cfg_file, "r", encoding="utf-8") as f:
cfg = json.load(f)
entry["name"] = cfg.get("name", entry["name"])
entry["duration"] = float(cfg.get("duration", 3600.0))
entry["seed"] = int(cfg.get("seed", 42))
entry["fleet_size"] = cfg.get("fleet_size", 4)
entry["policy"] = cfg.get("dispatch_policy", "priority_nearest_idle")
except Exception:
pass
if kpi_file.exists():
try:
with open(kpi_file, "r", encoding="utf-8") as f:
kpis = json.load(f)
tp = kpis.get("throughput", {})
entry["throughput"] = float(tp.get("completed_per_hour", 0.0))
meta = kpis.get("metadata", {})
if "fleet_size" in meta:
entry["fleet_size"] = meta["fleet_size"]
except Exception:
pass
experiments.append(entry)
return sorted(experiments, key=lambda e: (e["id"] != "baseline_1hr", e["id"]))
def get_experiment_detail(self, exp_id: str) -> Optional[Dict[str, Any]]:
"""Return comprehensive telemetry payload for a specific experiment."""
exp_path = (self.experiments_dir / exp_id).resolve()
if not exp_path.exists() or not exp_path.is_dir():
return None
payload: Dict[str, Any] = {
"id": exp_id,
"path": str(exp_path),
"config": {},
"kpis": {},
"robots": [],
"tasks_summary": {
"total": 0,
"completed": 0,
"in_progress": 0,
"pending": 0,
"on_time": 0,
"late": 0,
},
"bottlenecks": [],
"has_heatmap": (exp_path / "congestion_heatmap.svg").exists(),
"has_report": (exp_path / "report.md").exists(),
}
# 1. Config
cfg_file = exp_path / "config.json"
if cfg_file.exists():
try:
with open(cfg_file, "r", encoding="utf-8") as f:
payload["config"] = json.load(f)
except Exception:
pass
# 2. KPIs
kpi_file = exp_path / "kpi_summary.json"
if kpi_file.exists():
try:
with open(kpi_file, "r", encoding="utf-8") as f:
payload["kpis"] = json.load(f)
except Exception:
pass
# 3. Robots tabular CSV
robots_file = exp_path / "robots.csv"
if robots_file.exists():
try:
with open(robots_file, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
# Clean and cast numeric values
payload["robots"].append({
"robot_id": row.get("robot_id", ""),
"robot_type": row.get("robot_type", ""),
"state": row.get("current_state", "IDLE"),
"battery_percent": float(row.get("battery_percent", 100.0)),
"utilization_pct": float(row.get("utilization_pct", 0.0)),
"total_distance_m": float(row.get("total_distance_m", 0.0)),
"loaded_distance_m": float(row.get("loaded_distance_m", 0.0)),
"empty_distance_m": float(row.get("empty_distance_m", 0.0)),
"energy_consumed_kwh": float(row.get("energy_consumed_kwh", 0.0)),
"charging_sessions": int(row.get("charging_sessions", 0)),
})
except Exception:
pass
# 4. Tasks CSV summary
tasks_file = exp_path / "tasks.csv"
if tasks_file.exists():
try:
total, completed, in_progress, pending = 0, 0, 0, 0
on_time, late = 0, 0
with open(tasks_file, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
total += 1
st = row.get("status", "")
if st == "COMPLETED":
completed += 1
if row.get("is_overdue", "False").lower() in ("true", "1"):
late += 1
else:
on_time += 1
elif st == "IN_PROGRESS":
in_progress += 1
elif st == "PENDING":
pending += 1
payload["tasks_summary"] = {
"total": total,
"completed": completed,
"in_progress": in_progress,
"pending": pending,
"on_time": on_time,
"late": late,
}
except Exception:
pass
# 5. Aisle Congestion CSV
aisle_file = exp_path / "aisle_congestion.csv"
if aisle_file.exists():
try:
bottlenecks = []
with open(aisle_file, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
score = float(row.get("congestion_score", 0.0))
severity = "INFO"
if score >= 0.7:
severity = "CRITICAL"
elif score >= 0.4:
severity = "WARNING"
bottlenecks.append({
"edge": f"{row.get('u', '')} -> {row.get('v', '')}",
"traversals": int(row.get("traversals", 0)),
"conflicts": int(row.get("conflicts", 0)),
"wait_time_sec": float(row.get("wait_time_sec", 0.0)),
"congestion_score": score,
"severity": severity,
"recommendation": row.get("recommendation", "Normal transit flow."),
})
# Sort by congestion score descending
bottlenecks.sort(key=lambda b: b["congestion_score"], reverse=True)
payload["bottlenecks"] = bottlenecks[:15] # Top 15 corridors
except Exception:
pass
return payload
def get_heatmap_svg(self, exp_id: str) -> Optional[str]:
"""Return raw SVG content of congestion heatmap for an experiment."""
svg_file = (self.experiments_dir / exp_id / "congestion_heatmap.svg").resolve()
if not svg_file.exists():
return None
return svg_file.read_text(encoding="utf-8")
def get_report_markdown(self, exp_id: str) -> Optional[str]:
"""Return Markdown report content for an experiment."""
md_file = (self.experiments_dir / exp_id / "report.md").resolve()
if not md_file.exists():
return None
return md_file.read_text(encoding="utf-8")
def get_scenario_comparisons(self) -> Dict[str, Any]:
"""Read and parse parameter sweep reports for fleet sizing and dispatch policies."""
comparisons: Dict[str, Any] = {
"fleet_sizing": [],
"dispatch_policies": [],
}
# 1. Parse fleet_size_comparison.md
fleet_md = self.reports_dir / "fleet_size_comparison.md"
if fleet_md.exists():
comparisons["fleet_sizing"] = self._parse_markdown_table(fleet_md.read_text(encoding="utf-8"))
# 2. Parse dispatch_policy_comparison.md
policy_md = self.reports_dir / "dispatch_policy_comparison.md"
if policy_md.exists():
comparisons["dispatch_policies"] = self._parse_markdown_table(policy_md.read_text(encoding="utf-8"))
return comparisons
def get_optimization_data(self) -> Dict[str, Any]:
"""Read optimization summary JSON, or parse markdown if JSON is absent."""
opt_dir = self.results_dir / "optimization"
json_file = opt_dir / "optimization_summary.json"
if not json_file.exists():
json_file = opt_dir / "final_demonstration_summary.json"
if json_file.exists():
try:
with open(json_file, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
# Fallback or default empty structure
return {
"evaluation": {
"overall_score": 0.0,
"recommendation": "Run 'warehouse-twin optimize' to generate optimization benchmarks.",
"deltas": [],
"key_takeaways": [],
},
"layout_comparison": [],
"best_layout": "baseline",
"pareto_frontier": {},
}
def get_optimization_svg(self) -> Optional[str]:
"""Return raw SVG content for layout optimization comparison."""
opt_dir = self.results_dir / "optimization"
svg_file = opt_dir / "layout_comparison.svg"
if not svg_file.exists():
svg_file = self.results_dir / "demonstration" / "layout_comparison.svg"
if svg_file.exists():
try:
return svg_file.read_text(encoding="utf-8")
except Exception:
pass
return None
@staticmethod
def _parse_markdown_table(markdown_text: str) -> List[Dict[str, str]]:
"""Extract table rows from a Markdown document into list of dictionaries."""
lines = markdown_text.strip().split("\n")
table_lines = [l.strip() for l in lines if l.strip().startswith("|") and l.strip().endswith("|")]
if len(table_lines) < 3:
return []
# Header
raw_headers = [c.strip() for c in table_lines[0].strip("|").split("|")]
headers = [re.sub(r"[\*\_]", "", h).strip() for h in raw_headers]
rows: List[Dict[str, str]] = []
for line in table_lines[2:]: # Skip separator line
cols = [c.strip() for c in line.strip("|").split("|")]
if len(cols) == len(headers):
row_dict = {}
for h, val in zip(headers, cols):
# Clean markdown bold/italics
clean_val = re.sub(r"[\*\_]", "", val).strip()
row_dict[h] = clean_val
rows.append(row_dict)
return rows