185 lines
7.2 KiB
Python
185 lines
7.2 KiB
Python
from __future__ import annotations
|
||
from pathlib import Path
|
||
import re, json, itertools
|
||
import pandas as pd
|
||
import matplotlib.pyplot as plt
|
||
import matplotlib.ticker as mtick
|
||
from matplotlib.lines import Line2D
|
||
from matplotlib.patches import Patch
|
||
import numpy as np
|
||
|
||
|
||
class Visualizer2:
|
||
"""
|
||
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<dataset>[^_]+)_(?P<technique>[^.]+)\.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_range(
|
||
self,
|
||
category: str,
|
||
figsize=(11, 5),
|
||
save: str | Path | None = None,
|
||
*,
|
||
font_sizes: dict | None = None, # {'axes':13,'ticks':11,'legend':11,'title':14,'annot':7}
|
||
cmap: str = "tab10",
|
||
hatches: tuple[str, ...] | None = None,# ("///","..","xx") or leave None
|
||
bar_width: float = .18,
|
||
metric_jitter: float = .25, # sideways spacing between metrics
|
||
group_gap: float = .6, # whitespace between technique groups
|
||
percent_axis: bool = True,
|
||
show_values: bool = False, # numeric labels at min & max
|
||
):
|
||
"""
|
||
One figure per category. Each vertical bar shows min–max across datasets.
|
||
The bar colour / hatch identifies the metric. The x‑axis shows techniques.
|
||
"""
|
||
df = self.df[self.df["category"] == category].copy()
|
||
if df.empty:
|
||
print(f"[⚠] No data for category={category!r}")
|
||
return
|
||
|
||
# ---------- aggregate min & max across datasets --------------
|
||
agg = (
|
||
df.groupby(["technique", "metric"])["value"]
|
||
.agg(["min", "max"])
|
||
.reset_index()
|
||
)
|
||
|
||
techs = sorted(agg["technique"].unique())
|
||
metrics = sorted(agg["metric"].unique())
|
||
|
||
# ---------- colour & hatch palettes --------------------------
|
||
colours = plt.get_cmap(cmap).colors
|
||
colour_map = {m: colours[i % len(colours)] for i, m in enumerate(metrics)}
|
||
hatch_map = ({m: "" for m in metrics} if hatches is None
|
||
else {m: hatches[i % len(hatches)] for i, m in enumerate(metrics)})
|
||
|
||
# ---------- figure scaffold ----------------------------------
|
||
fig, ax = plt.subplots(figsize=figsize)
|
||
fs = dict(title=14, axes=13, ticks=11, legend=11, annot=7)
|
||
if font_sizes:
|
||
fs.update(font_sizes)
|
||
|
||
# ---------- x‑positions --------------------------------------
|
||
group_centres = np.arange(len(techs)) * (1 + group_gap)
|
||
offset_range = np.linspace(
|
||
-metric_jitter * (len(metrics)-1)/2,
|
||
metric_jitter * (len(metrics)-1)/2,
|
||
len(metrics)
|
||
)
|
||
xloc = {
|
||
(tech, met): group_centres[t_idx] + offset_range[m_idx]
|
||
for t_idx, tech in enumerate(techs)
|
||
for m_idx, met in enumerate(metrics)
|
||
}
|
||
|
||
# ---------- draw bars + caps + labels ------------------------
|
||
cap_half = bar_width * 0.8 # little horizontal line ends
|
||
for _, row in agg.iterrows():
|
||
tech, met, vmin, vmax = row
|
||
x = xloc[(tech, met)]
|
||
|
||
# main bar
|
||
ax.bar(x,
|
||
height=vmax - vmin,
|
||
bottom=vmin,
|
||
width=bar_width,
|
||
color=colour_map[met],
|
||
hatch=hatch_map[met],
|
||
edgecolor="black",
|
||
linewidth=0.7,
|
||
zorder=3)
|
||
|
||
# black caps at min & max
|
||
ax.hlines([vmin, vmax],
|
||
x - cap_half, x + cap_half,
|
||
color="black",
|
||
linewidth=1.2,
|
||
zorder=4)
|
||
|
||
# numeric labels (optional)
|
||
if show_values:
|
||
ax.text(x, vmax - 1, f"{vmax:.0f}",
|
||
ha="center", va="top",
|
||
fontsize=fs["annot"])
|
||
ax.text(x, vmin + 1, f"{vmin:.0f}",
|
||
ha="center", va="bottom",
|
||
fontsize=fs["annot"])
|
||
|
||
# ---------- axes formatting ----------------------------------
|
||
ax.set_xticks(group_centres, techs, fontsize=fs["ticks"])
|
||
ax.set_xlabel("Technique", fontsize=fs["axes"])
|
||
|
||
ax.set_ylim(-1, 105)
|
||
ax.set_ylabel("Score [%]" if percent_axis else "Score",
|
||
fontsize=fs["axes"])
|
||
if percent_axis:
|
||
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=100))
|
||
ax.tick_params(axis="y", labelsize=fs["ticks"])
|
||
ax.grid(axis="y", linestyle="--", alpha=.3, zorder=0)
|
||
|
||
fig.suptitle(category.capitalize(), fontsize=fs["title"])
|
||
|
||
# ---------- legend (metrics) ---------------------------------
|
||
handles = [Patch(facecolor=colour_map[m],
|
||
edgecolor="black",
|
||
hatch=hatch_map[m],
|
||
label=f"${m}$")
|
||
for m in metrics]
|
||
ax.legend(handles=handles,
|
||
title="Metric",
|
||
loc="upper left", bbox_to_anchor=(1.02, 1),
|
||
frameon=True, fontsize=fs["legend"])
|
||
|
||
# ---------- export -------------------------------------------
|
||
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)
|