#!/usr/bin/env python3 """ Complement-based GT event detection analysis. Metric: success rate = fraction of samples where score(model output, GT) > score(model output, complement_GT) GT and complement are constructed from spatially-rendered stems: - REMOVED: GT = speech only, complement = speech + distractor - PRESENT: GT = speech + dist, complement = speech only This removes the background-noise bias of the old mixture-based metric. Three metrics reported: SI-SNR, NXCorr, CLAP similarity. Only eval_outputs_test_3k (non-OOD) is used. Usage: python analyze_detection_scores_gt_relative_complement.py """ import json from pathlib import Path import numpy as np import pandas as pd # ── Paths ───────────────────────────────────────────────────────────────────── BASE_DIR = Path(__file__).parent JSON_DIR = BASE_DIR / "data/audio_mixtures_old/test" # ── SNR bins ────────────────────────────────────────────────────────────────── SNR_BINS = [-np.inf, -5, 0, 5, 10, 15, np.inf] SNR_LABELS = ["< -5 dB", "-5 to 0 dB", "0 to 5 dB", "5 to 10 dB", "10 to 15 dB", "≥ 15 dB"] MODELS_FINAL = { "combined_v1_broken_left_ch": BASE_DIR / "experiments_v2/combined_v1_broken_left_ch", "combined_v1_large": BASE_DIR / "experiments_v2/combined_v1_large", "no_TSDL_old_mixtures": BASE_DIR / "experiments_v2/no_TSDL_old_mixtures", "no_TSDL_old_mixtures_large": BASE_DIR / "experiments_v2/no_TSDL_old_mixtures_large", } TEST_3K_CSV = "eval_outputs_test_3k/event_detection_scores_complement.csv" METRICS = [ ("SI-SNR", "success_sisnr"), ("NXCorr", "success_nxcorr"), ("CLAP sim", "success_clap"), ("Pooled", "success_pooled"), ] # ═══════════════════════════════════════════════════════════════════════════════ def _load_snr_lookup() -> dict: """Build {(mixture_id, distractor_name): target_snr_db} from JSON files.""" lookup = {} for jpath in JSON_DIR.glob("*.json"): try: meta = json.loads(jpath.read_text()) mid = meta.get("mixture_id", jpath.stem) for dist_name, info in meta.get("snr_info", {}).items(): if dist_name in ("speech", "background"): continue snr = info.get("target_snr_db") if snr is not None: lookup[(mid, dist_name)] = snr except Exception: pass return lookup _SNR_LOOKUP = None # type: dict def load_csv(path: Path) -> pd.DataFrame: global _SNR_LOOKUP if _SNR_LOOKUP is None: _SNR_LOOKUP = _load_snr_lookup() df = pd.read_csv(path) df = df[df["error"].isna() | (df["error"] == "")] for _, col in METRICS: if col != "success_pooled": df[col] = pd.to_numeric(df[col], errors="coerce") # Pooled: per-sample mean of the 3 binary success flags df["success_pooled"] = df[["success_sisnr", "success_nxcorr", "success_clap"]].mean(axis=1) # Parse number of distractors from mixture_id (e.g. "airport_1dist_005_rep1_v0" → 1) df["num_distractors"] = ( df["mixture_id"].str.extract(r"(\d+)dist", expand=False) .astype(float).astype("Int64") ) # Join per-distractor SNR from JSON metadata df["distractor_snr_db"] = df.apply( lambda r: _SNR_LOOKUP.get((r["mixture_id"], r["distractor_name"]), np.nan), axis=1, ) df["snr_bin"] = pd.cut( df["distractor_snr_db"], bins=SNR_BINS, labels=SNR_LABELS, right=True ) return df def print_section(title: str): print(f"\n{'═'*70}") print(f" {title}") print(f"{'═'*70}") def success_rate(df: pd.DataFrame, col: str) -> float: """Fraction of rows where success == 1 (output closer to GT than complement).""" valid = df[col].notna() if valid.sum() == 0: return float("nan") return df.loc[valid, col].mean() * 100.0 # ═══════════════════════════════════════════════════════════════════════════════ # Score statistics (out→GT vs out→complement absolute values) # ═══════════════════════════════════════════════════════════════════════════════ def print_score_stats(dfs: dict): print_section("Score statistics (output→GT and output→complement)") score_cols = [ ("out_si_snr_db", "out→GT SI-SNR"), ("comp_si_snr_db", "out→comp SI-SNR"), ("out_nxcorr", "out→GT NXCorr"), ("comp_nxcorr", "out→comp NXCorr"), ("out_clap_sim", "out→GT CLAP"), ("comp_clap_sim", "out→comp CLAP"), ("success_sisnr", "success SI-SNR"), ("success_nxcorr", "success NXCorr"), ("success_clap", "success CLAP"), ("success_pooled", "success Pooled"), ] model_names = list(dfs.keys()) header = f" {'column':<16} {'stat':<8}" for name in model_names: header += f" {name:>26}" print(header) print(" " + "─" * (26 + len(model_names) * 28)) for col, label in score_cols: for stat, fn in [("mean", np.nanmean), ("median", np.nanmedian)]: row = f" {label:<16} {stat:<8}" for df in dfs.values(): if col in df.columns: df[col] = pd.to_numeric(df[col], errors="coerce") row += f" {fn(df[col].dropna().values):>26.4f}" else: row += f" {'N/A':>26}" print(row) print() # ═══════════════════════════════════════════════════════════════════════════════ # Overall success rate # ═══════════════════════════════════════════════════════════════════════════════ def print_overall(dfs: dict): print_section( "Overall success rate (% samples where output closer to GT than complement)\n" " Threshold-free — no operating-point tuning required" ) model_names = list(dfs.keys()) print(f"\n {'Metric':<12} {'N':>6}", end="") for name in model_names: print(f" {name:>26}", end="") print() print(" " + "─" * (20 + len(model_names) * 28)) for m_label, col in METRICS: first_df = list(dfs.values())[0] n = first_df[col].notna().sum() print(f" {m_label:<12} {n:>6}", end="") for df in dfs.values(): sr = success_rate(df, col) print(f" {'%.2f%%' % sr:>26}", end="") print() # ═══════════════════════════════════════════════════════════════════════════════ # By gt_label (REMOVED / PRESENT) # ═══════════════════════════════════════════════════════════════════════════════ def print_by_gt_label(dfs: dict): print_section("Success rate by gt_label (REMOVED = model should remove; PRESENT = keep)") model_names = list(dfs.keys()) for m_label, col in METRICS: print(f"\n [ {m_label} ]") print(f" {'gt_label':<12} {'N':>6}", end="") for name in model_names: print(f" {name:>26}", end="") print() print(" " + "─" * (20 + len(model_names) * 28)) for lbl in ["REMOVED", "PRESENT"]: n_shown = False row_str = f" {lbl:<12}" for df in dfs.values(): sub = df[df["gt_label"] == lbl] valid = sub[col].notna() if not n_shown: row_str += f" {valid.sum():>6}" n_shown = True sr = sub.loc[valid, col].mean() * 100.0 if valid.sum() > 0 else float("nan") row_str += f" {'%.2f%%' % sr if not np.isnan(sr) else 'N/A':>26}" print(row_str) # ═══════════════════════════════════════════════════════════════════════════════ # By command_type # ═══════════════════════════════════════════════════════════════════════════════ def print_by_command_type(dfs: dict): print_section("Success rate by command_type") model_names = list(dfs.keys()) command_types = sorted( set().union(*[set(df["command_type"].dropna()) for df in dfs.values()]) ) for m_label, col in METRICS: print(f"\n [ {m_label} ]\n") print(f" {'command_type':<22} {'N':>6}", end="") for name in model_names: print(f" {name:>26}", end="") print() print(" " + "─" * (30 + len(model_names) * 28)) for ct in command_types: n_shown = False row_str = f" {ct:<22}" for df in dfs.values(): sub = df[df["command_type"] == ct] valid = sub[col].notna() if not n_shown: row_str += f" {valid.sum():>6}" n_shown = True sr = sub.loc[valid, col].mean() * 100.0 if valid.sum() > 0 else float("nan") row_str += f" {'%.2f%%' % sr if not np.isnan(sr) else 'N/A':>26}" print(row_str) # ═══════════════════════════════════════════════════════════════════════════════ # By number of distractors in mixture # ═══════════════════════════════════════════════════════════════════════════════ def print_by_num_distractors(dfs: dict): print_section( "Success rate by number of distractors in mixture\n" " (does the model struggle more with more distractors?)" ) model_names = list(dfs.keys()) all_counts = sorted( set().union(*[set(df["num_distractors"].dropna().unique()) for df in dfs.values()]) ) for m_label, col in METRICS: print(f"\n [ {m_label} ]\n") print(f" {'num_distractors':<18} {'N':>6}", end="") for name in model_names: print(f" {name:>26}", end="") print() print(" " + "─" * (26 + len(model_names) * 28)) for nd in all_counts: n_shown = False row_str = f" {str(int(nd)) + ' distractor(s)':<18}" for df in dfs.values(): sub = df[df["num_distractors"] == nd] valid = sub[col].notna() if not n_shown: row_str += f" {valid.sum():>6}" n_shown = True sr = sub.loc[valid, col].mean() * 100.0 if valid.sum() > 0 else float("nan") row_str += f" {'%.2f%%' % sr if not np.isnan(sr) else 'N/A':>26}" print(row_str) # Also show the cross-tab: num_distractors × command_type for CLAP print_section("Success rate: num_distractors × command_type (CLAP sim, combined_v1)") col = "success_clap" first_df = list(dfs.values())[0] command_types = sorted(first_df["command_type"].dropna().unique()) header_label = "num_dist / cmd_type" print(f"\n {header_label:<20}", end="") for ct in command_types: print(f" {ct:>18}", end="") print(f" {'ALL':>18}") print(" " + "─" * (22 + (len(command_types) + 1) * 20)) for nd in all_counts: row_str = f" {str(int(nd)) + ' dist':<20}" sub_nd = first_df[first_df["num_distractors"] == nd] for ct in command_types: sub = sub_nd[sub_nd["command_type"] == ct] valid = sub[col].notna() sr = sub.loc[valid, col].mean() * 100.0 if valid.sum() > 0 else float("nan") row_str += f" {'%.1f%%' % sr if not np.isnan(sr) else 'N/A':>18}" valid_all = sub_nd[col].notna() sr_all = sub_nd.loc[valid_all, col].mean() * 100.0 if valid_all.sum() > 0 else float("nan") row_str += f" {'%.1f%%' % sr_all:>18}" print(row_str) # ═══════════════════════════════════════════════════════════════════════════════ # By distractor (CLAP — sorted by first model) # ═══════════════════════════════════════════════════════════════════════════════ def print_by_distractor(dfs: dict): model_names = list(dfs.keys()) print_section( f"Success rate by distractor_name (CLAP) sorted by {model_names[0]}" ) col = "success_clap" dist_names = sorted(list(dfs.values())[0]["distractor_name"].dropna().unique()) rows = [] for dname in dist_names: row = {"distractor": dname} for name, df in dfs.items(): sub = df[df["distractor_name"] == dname] valid = sub[col].notna() n = valid.sum() sr = sub.loc[valid, col].mean() * 100.0 if n > 0 else float("nan") row[name] = sr row[f"{name}_n"] = n rows.append(row) dist_df = pd.DataFrame(rows).sort_values(model_names[0], ascending=False) print(f"\n {'distractor':<32} {'N':>5}", end="") for name in model_names: print(f" {name:>26}", end="") print() print(" " + "─" * (39 + len(model_names) * 28)) for _, r in dist_df.iterrows(): n = int(r[f"{model_names[0]}_n"]) print(f" {r['distractor']:<32} {n:>5}", end="") for name in model_names: v = r[name] print(f" {'%.2f%%' % v if not np.isnan(v) else 'N/A':>26}", end="") print() # ═══════════════════════════════════════════════════════════════════════════════ # By distractor SNR bin # ═══════════════════════════════════════════════════════════════════════════════ def print_by_snr(dfs: dict): print_section( "Success rate by distractor SNR bin (target_snr_db from JSON metadata)\n" " SNR = distractor level relative to speech at mixing time" ) model_names = list(dfs.keys()) # Coverage report first_df = list(dfs.values())[0] n_total = len(first_df) n_matched = first_df["distractor_snr_db"].notna().sum() print(f"\n SNR lookup coverage: {n_matched}/{n_total} rows " f"({100*n_matched/n_total:.1f}%)") for m_label, col in METRICS: print(f"\n [ {m_label} ]\n") print(f" {'SNR bin':<16} {'N':>6}", end="") for name in model_names: print(f" {name:>26}", end="") print() print(" " + "─" * (24 + len(model_names) * 28)) for lbl in SNR_LABELS: n_shown = False row_str = f" {lbl:<16}" for df in dfs.values(): sub = df[df["snr_bin"] == lbl] valid = sub[col].notna() if not n_shown: row_str += f" {valid.sum():>6}" n_shown = True sr = sub.loc[valid, col].mean() * 100.0 if valid.sum() > 0 else float("nan") row_str += f" {'%.2f%%' % sr if not np.isnan(sr) else 'N/A':>26}" print(row_str) # ═══════════════════════════════════════════════════════════════════════════════ def main(): dfs = {} for name, model_path in MODELS_FINAL.items(): p = model_path / TEST_3K_CSV if not p.exists(): print(f"[WARN] CSV not found: {p}") continue df = load_csv(p) print(f"Loaded {len(df):>5} rows ← {name}") dfs[name] = df if not dfs: print("No CSVs found. Run the GT-relative eval jobs first.") return print_score_stats(dfs) print_overall(dfs) print_by_gt_label(dfs) print_by_command_type(dfs) print_by_num_distractors(dfs) print_by_distractor(dfs) print_by_snr(dfs) if __name__ == "__main__": main()