#!/usr/bin/env python3 """ Plot score distributions (REMOVED vs PRESENT) for each model. Two figures — one per model — each with 3 subplots (SI-SNR, NXCorr, CLAP sim). REMOVED and PRESENT distributions are overlaid with a vertical Youden T* line. """ from pathlib import Path import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from sklearn.metrics import roc_auc_score, roc_curve BASE_DIR = Path(__file__).parent MODELS = { "combined_v1": BASE_DIR / "experiments_final/combined_v1/eval_outputs_test_3k/event_detection_scores_gt.csv", "no_TSDL_old_mixtures": BASE_DIR / "experiments_final/no_TSDL_old_mixtures/eval_outputs_test_3k/event_detection_scores_gt.csv", } METRICS = [ ("si_snr_db", "SI-SNR (dB)", (-40, 20), 1.0), ("nxcorr", "NXCorr", (0, 1.0), 0.02), ("clap_sim", "CLAP similarity", (0, 1.0), 0.02), ] COLORS = {"REMOVED": "#E05C5C", "PRESENT": "#4C9BE8"} ALPHA = 0.55 def load(path): df = pd.read_csv(path) df = df[df["error"].isna() | (df["error"] == "")] for col, *_ in METRICS: df[col] = pd.to_numeric(df[col], errors="coerce") df["gt_binary"] = df["gt_label"].map({"PRESENT": 1, "REMOVED": 0}) return df def youden_t(df, col): valid = df[col].notna() & df["gt_binary"].notna() fpr, tpr, thresholds = roc_curve( df.loc[valid, "gt_binary"], df.loc[valid, col] ) j = tpr + (1 - fpr) - 1 return float(thresholds[np.argmax(j)]) def dprime(present, removed): sigma_pooled = np.sqrt((present.std()**2 + removed.std()**2) / 2) return (present.mean() - removed.mean()) / sigma_pooled def pooled_youden_t(dfs, col): all_s = pd.concat([df[col].dropna() for df in dfs.values()]) all_l = pd.concat([ df.loc[df[col].notna(), "gt_binary"].dropna() for df in dfs.values() ]) valid = all_s.notna() & all_l.notna() fpr, tpr, thresholds = roc_curve(all_l[valid].values, all_s[valid].values) j = tpr + (1 - fpr) - 1 return float(thresholds[np.argmax(j)]) def plot_model(df, model_name, pooled_thresholds, out_path): fig, axes = plt.subplots(1, 3, figsize=(15, 5.0)) fig.suptitle( f"Score distributions: REMOVED vs PRESENT | Model: {model_name}", fontsize=13, fontweight="bold", y=1.01, ) for ax, (col, xlabel, xlim, bw) in zip(axes, METRICS): present = df.loc[df["gt_label"] == "PRESENT", col].dropna() removed = df.loc[df["gt_label"] == "REMOVED", col].dropna() bins = np.arange(xlim[0], xlim[1] + bw, bw) for vals, label in [(removed, "REMOVED"), (present, "PRESENT")]: ax.hist(vals, bins=bins, color=COLORS[label], alpha=ALPHA, label=f"{label} (n={len(vals)})", density=True, edgecolor="none") # Youden T* line t = pooled_thresholds[col] ax.axvline(t, color="black", linewidth=1.5, linestyle="--", label=f"Youden T*={t:.3f}") # AUC and d' annotation valid = df[col].notna() & df["gt_binary"].notna() auc = roc_auc_score(df.loc[valid, "gt_binary"], df.loc[valid, col]) dp = dprime(present.values, removed.values) ax.text(0.97, 0.97, f"AUC = {auc:.4f}\nd′ = {dp:.4f}", transform=ax.transAxes, fontsize=9, verticalalignment="top", horizontalalignment="right", bbox=dict(boxstyle="round,pad=0.3", facecolor="white", edgecolor="grey", alpha=0.8)) ax.set_xlabel(xlabel, fontsize=11) ax.set_ylabel("Density", fontsize=10) ax.set_xlim(xlim) ax.legend(fontsize=8.5, framealpha=0.7) ax.set_title(xlabel, fontsize=11) ax.spines[["top", "right"]].set_visible(False) 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 pooled Youden thresholds (same for both plots) pooled_t = {col: pooled_youden_t(dfs, col) for col, *_ in METRICS} print("Pooled Youden T*:") for col, label, *_ in METRICS: print(f" {label:<20}: {pooled_t[col]:.4f}") for model_name, df in dfs.items(): out = BASE_DIR / f"gt_score_hist_{model_name}.png" plot_model(df, model_name, pooled_t, out) if __name__ == "__main__": main()