Files
obfuscation_platform/project/visualization/visualizer.py
T
2025-07-28 14:37:52 +02:00

157 lines
6.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
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<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_by_tech(
self,
dataset: str,
category: str,
figsize=(10, 5),
save: str | Path | None = None,
*,
# ---- Styling options ------------------------------------------
font_sizes: dict | None = None, # {'axes':12,'ticks':10,'legend':10,'barlabel':8,'title':13}
hatch_cycle: tuple[str, ...] = ("///", "..", "**", "++", "..", "oo", "**"),
bar_alpha: float = 1,
annotate: bool = True,
annotate_fmt: str = "{v:.1f}", # no % sign as requested
barlabel_padding: int = 2,
top_padding: float = 0.01, # 6% headroom
legend_ncols: int | None = None,
percent_axis: bool = True, # keep % on the y-axis ticks
):
"""
Ein Balkendiagramm: alle Metriken dieser Kategorie,
gruppiert nach Technik, nur für EIN Dataset.
Alle gewünschten Anpassungen (Fonts, Muster, Werte-Beschriftungen) sind parametrisiert.
"""
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")
# Interpret metric names as LaTeX math for nicer typesetting
pivot.columns = [f"${c}$" for c in pivot.columns]
fig, ax = plt.subplots(figsize=figsize)
# draw bars
pivot.plot(kind="bar", ax=ax, edgecolor="black", linewidth=0.6)
# ---------------- Font sizes ------------------------------------
fs = dict(title=13, axes=13, ticks=13, legend=11, barlabel=6.3)
if font_sizes:
fs.update(font_sizes)
ax.set_xlabel("", fontsize=fs["axes"])
ax.set_ylabel("Score [%]" if percent_axis else "Score", fontsize=fs["axes"])
ax.tick_params(axis='x', rotation=0, labelsize=fs["ticks"])
ax.tick_params(axis='y', labelsize=fs["ticks"])
# Percent ticks on y-axis (keeps the % there)
if percent_axis:
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=100))
# ---------------- Grid ------------------------------------------
#ax.grid(axis="y", linestyle="--", alpha=0.4)
# ---------------- Hatches/patterns (per series/metric) ----------
# ax.containers: one BarContainer per column/metric
for container, hatch in zip(ax.containers, itertools.cycle(hatch_cycle)):
for patch in container.patches:
patch.set_hatch(hatch)
patch.set_alpha(bar_alpha)
# ---------------- Legend below ---------------------------------
handles, labels = ax.get_legend_handles_labels()
if ax.get_legend():
ax.get_legend().remove()
if legend_ncols is None:
legend_ncols = min(len(labels), 4)
fig.legend(handles, labels,
loc="lower center",
bbox_to_anchor=(0.5, -0.05),
ncol=legend_ncols,
frameon=True,
fontsize=fs["legend"])
fig.subplots_adjust(bottom=0.1) # space for legend
# ---------------- Value labels on bars --------------------------
if annotate:
for container in ax.containers:
ax.bar_label(container,
#labels=[annotate_fmt.format(v=v) for v in container.datavalues],
fmt="%.0f",
padding=barlabel_padding,
fontsize=fs["barlabel"])
# ---------------- Extra headroom --------------------------------
ymax = max(pivot.values.max(), ax.get_ylim()[1])
ax.set_ylim(0, ymax * (1 + top_padding))
# Optional: fig.suptitle(f"{dataset} – {category}", fontsize=fs['title'])
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)