#!/usr/bin/env python3 """ Heatmap of CLAP success rate: scene × distractor. success = score(output, GT) > score(mixture, GT) — threshold-free. Two figures (one per model), each showing an 11 × 30 heatmap. Cells are coloured by success rate; white = no data. Distractors sorted by overall success rate (descending). Scenes sorted by overall success rate (descending). """ from pathlib import Path import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import seaborn as sns BASE_DIR = Path(__file__).parent MODELS = { "combined_v1": BASE_DIR / "experiments_final/combined_v1/eval_outputs_test_3k/event_detection_scores_gt_relative.csv", "no_TSDL_old_mixtures": BASE_DIR / "experiments_final/no_TSDL_old_mixtures/eval_outputs_test_3k/event_detection_scores_gt_relative.csv", } SUCCESS_COL = "success_clap" def load(path: Path) -> pd.DataFrame: df = pd.read_csv(path) df = df[df["error"].isna() | (df["error"] == "")] df[SUCCESS_COL] = pd.to_numeric(df[SUCCESS_COL], errors="coerce") df["scene"] = df["mixture_id"].str.extract(r"^(.+?)_\d+dist_") return df def build_pivot(df: pd.DataFrame, scene_order: list, dist_order: list) -> pd.DataFrame: pivot = ( df.groupby(["scene", "distractor_name"])[SUCCESS_COL] .mean() .mul(100) .unstack("distractor_name") .reindex(index=scene_order, columns=dist_order) ) return pivot def plot_heatmap(pivot: pd.DataFrame, model_name: str, overall_scene: pd.Series, overall_dist: pd.Series, out_path: Path): n_scenes = len(pivot.index) n_dist = len(pivot.columns) fig, ax = plt.subplots(figsize=(max(14, n_dist * 0.55), max(5, n_scenes * 0.55 + 2))) # Mask NaN cells (no data) mask = pivot.isna() sns.heatmap( pivot, ax=ax, mask=mask, annot=True, fmt=".0f", annot_kws={"size": 7}, vmin=50, vmax=100, cmap="RdYlGn", linewidths=0.4, linecolor="#cccccc", cbar_kws={"label": "CLAP success rate (%)", "shrink": 0.6}, ) # Y-axis: scene + overall rate ylabels = [ f"{s} ({overall_scene.get(s, float('nan')):.1f}%)" for s in pivot.index ] ax.set_yticklabels(ylabels, fontsize=9, rotation=0) # X-axis: distractor + overall rate xlabels = [ f"{d}\n({overall_dist.get(d, float('nan')):.1f}%)" for d in pivot.columns ] ax.set_xticklabels(xlabels, fontsize=8, rotation=45, ha="right") ax.set_xlabel("Distractor", fontsize=11) ax.set_ylabel("Scene", fontsize=11) ax.set_title( f"CLAP success rate: scene × distractor | {model_name}\n" f"success = output closer to GT than raw mixture (no threshold)", fontsize=11, fontweight="bold", pad=12, ) plt.tight_layout() fig.savefig(out_path, dpi=150, bbox_inches="tight") plt.close(fig) print(f"Saved: {out_path}") def main(): dfs = {name: load(path) for name, path in MODELS.items() if path.exists()} if not dfs: print("No CSVs found.") return # Compute shared distractor and scene order based on pooled success rate all_df = pd.concat(dfs.values(), ignore_index=True) dist_order = ( all_df.groupby("distractor_name")[SUCCESS_COL] .mean() .sort_values(ascending=False) .index.tolist() ) scene_order = ( all_df.groupby("scene")[SUCCESS_COL] .mean() .sort_values(ascending=False) .index.tolist() ) # Per-model plots for model_name, df in dfs.items(): overall_dist = ( df.groupby("distractor_name")[SUCCESS_COL].mean().mul(100) ) overall_scene = ( df.groupby("scene")[SUCCESS_COL].mean().mul(100) ) pivot = build_pivot(df, scene_order, dist_order) out = BASE_DIR / f"heatmap_scene_distractor_{model_name}.png" plot_heatmap(pivot, model_name, overall_scene, overall_dist, out) # Difference heatmap (combined_v1 − no_TSDL_old_mixtures) if len(dfs) == 2: names = list(dfs.keys()) p0 = build_pivot(dfs[names[0]], scene_order, dist_order) p1 = build_pivot(dfs[names[1]], scene_order, dist_order) diff = p0 - p1 # positive = combined_v1 better fig, ax = plt.subplots(figsize=(max(14, len(dist_order) * 0.55), max(5, len(scene_order) * 0.55 + 2))) mask = diff.isna() lim = max(abs(diff.min().min()), abs(diff.max().max()), 5) sns.heatmap( diff, ax=ax, mask=mask, annot=True, fmt=".1f", annot_kws={"size": 7}, vmin=-lim, vmax=lim, cmap="coolwarm", center=0, linewidths=0.4, linecolor="#cccccc", cbar_kws={"label": "Δ success rate pp (combined_v1 − no_TSDL)", "shrink": 0.6}, ) ax.set_yticklabels(scene_order, fontsize=9, rotation=0) ax.set_xticklabels( dist_order, fontsize=8, rotation=45, ha="right" ) ax.set_xlabel("Distractor", fontsize=11) ax.set_ylabel("Scene", fontsize=11) ax.set_title( f"Δ CLAP success rate: {names[0]} − {names[1]}\n" f"Red = combined_v1 better | Blue = no_TSDL better", fontsize=11, fontweight="bold", pad=12, ) plt.tight_layout() out = BASE_DIR / "heatmap_scene_distractor_diff.png" fig.savefig(out, dpi=150, bbox_inches="tight") plt.close(fig) print(f"Saved: {out}") if __name__ == "__main__": main()