from __future__ import annotations from pathlib import Path import re, json import pandas as pd import matplotlib.pyplot as plt class Visualizer: """ Liest results_{dataset}_{technique}.json und hält ein langes DataFrame. • ein Record pro (dataset, technique, category, metric) • keine Aggregation nötig – jede Datei enthält EINEN Wert je Metrik """ _PTN = re.compile(r"results_(?P[^_]+)_(?P[^.]+)\.json$") def __init__(self, json_dir: str | Path): self.json_dir = Path(json_dir) if not self.json_dir.exists(): raise FileNotFoundError(self.json_dir) self.df = self._load_jsons() # ------------------------------------------------------------------ # Public helpers # ------------------------------------------------------------------ def datasets(self) -> list[str]: return sorted(self.df["dataset"].unique()) def categories(self) -> list[str]: return sorted(self.df["category"].unique()) def metrics_of(self, category: str) -> list[str]: return sorted(self.df[self.df["category"] == category]["metric"].unique()) # -- Kernplot ------------------------------------------------------- def plot_category_by_tech(self, dataset: str, category: str, figsize=(9, 5), save: str | Path | None = None): """ Ein Balkendiagramm: alle Metriken dieser Kategorie, gruppiert nach Technik, nur für EIN Dataset. """ sub = self.df[(self.df["dataset"] == dataset) & (self.df["category"] == category)] if sub.empty: print(f"[⚠] Kein Eintrag für Dataset={dataset}, Cat={category}") return # Pivot: index = technique, columns = metrics pivot = sub.pivot(index="technique", columns="metric", values="value") print(pivot) fig, ax = plt.subplots(figsize=figsize) pivot.plot(kind="bar", ax=ax) ax.set_title(f"{dataset} – {category.capitalize()} metrics") ax.set_xlabel("Technique") ax.set_ylabel("score") ax.grid(axis="y", linestyle="--", alpha=0.4) ax.legend(title="metric", bbox_to_anchor=(1.02, 1), loc="upper left") plt.tight_layout() if save: fig.savefig(save, dpi=150, bbox_inches="tight") plt.close(fig) return fig, ax # ------------------------------------------------------------------ # intern # ------------------------------------------------------------------ def _load_jsons(self) -> pd.DataFrame: recs = [] for file in self.json_dir.glob("results_*_*.json"): m = self._PTN.match(file.name) if not m: continue dataset, tech = m.group("dataset"), m.group("technique") data = json.load(open(file, "r")) for cat, metrics in data.items(): for metric, val in metrics.items(): recs.append({"dataset": dataset, "technique": tech, "category": cat, "metric": metric, "value": val}) if not recs: raise RuntimeError("Keine passenden JSON-Dateien gefunden.") return pd.DataFrame.from_records(recs)