File size: 9,626 Bytes
c22b544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env python3
"""
OOD no_input heatmap: scene × distractor coloured by KEPT (+1) vs REMOVED (-1).

Filters command_type == "no_input" from each OOD eval set.

Logic (GT is always speech-only in OOD):
    success_clap = 1  →  output closer to speech-only GT  →  model REMOVED  →  score = -1
    success_clap = 0  →  output closer to mixture          →  model KEPT     →  score = +1

Cell value = mean score across all samples in that scene × distractor cell.
    +1.0  = always kept
    -1.0  = always removed
     0.0  = 50 / 50

Three heatmaps — one per OOD split — two subplots per figure (one per model).

Usage:
    python plot_ood_no_input_heatmap.py
"""

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":          "experiments_final/combined_v1",
    "no_TSDL_old_mixtures": "experiments_final/no_TSDL_old_mixtures",
}

OOD_SPLITS = {
    "OOD_distractors":  "eval_outputs_OOD_distractors",   # unseen distractor classes
    "OOD_backgrounds":  "eval_outputs_OOD_backgrounds",   # unseen background scenes
    "OOD_both":         "eval_outputs_OOD_both",           # both unseen
}

CSV_NAME   = "event_detection_scores_gt_relative.csv"
CMD_TYPE   = "no_input"
SUCCESS_COL = "success_clap"


# ═══════════════════════════════════════════════════════════════════════════════

def load(path: Path) -> pd.DataFrame:
    df = pd.read_csv(path)
    df = df[df["error"].isna() | (df["error"] == "")]
    df = df[df["command_type"] == CMD_TYPE].copy()
    df[SUCCESS_COL] = pd.to_numeric(df[SUCCESS_COL], errors="coerce")
    # kept_score: +1 = kept, -1 = removed
    df["kept_score"] = 1 - 2 * df[SUCCESS_COL]   # success=1→-1, success=0→+1
    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"])["kept_score"]
          .mean()
          .unstack("distractor_name")
          .reindex(index=scene_order, columns=dist_order)
    )
    return pivot


def annot_array(pivot: pd.DataFrame) -> np.ndarray:
    """Return string array: +value with KEPT/REM label."""
    arr = np.empty(pivot.shape, dtype=object)
    for i, row in enumerate(pivot.index):
        for j, col in enumerate(pivot.columns):
            v = pivot.iloc[i, j]
            if np.isnan(v):
                arr[i, j] = ""
            else:
                pct = abs(v) * 100
                label = "KEPT" if v > 0 else "REM"
                arr[i, j] = f"{label}\n{pct:.0f}%"
    return arr


def plot_split(split_name: str, dfs: dict, out_path: Path):
    """
    dfs: {model_name: DataFrame}  — already filtered to no_input for this split.
    """
    # Shared distractor + scene ordering by pooled kept_score (most-kept first)
    all_df = pd.concat(dfs.values(), ignore_index=True)
    if all_df.empty:
        print(f"  [SKIP] No no_input data for {split_name}")
        return

    dist_order = (
        all_df.groupby("distractor_name")["kept_score"]
              .mean()
              .sort_values(ascending=False)   # most-kept → most-removed
              .index.tolist()
    )
    scene_order = (
        all_df.groupby("scene")["kept_score"]
              .mean()
              .sort_values(ascending=False)
              .index.tolist()
    )
    if not scene_order:
        scene_order = ["(all)"]

    n_models = len(dfs)
    n_dist   = max(len(dist_order), 1)
    n_scene  = max(len(scene_order), 1)

    fig, axes = plt.subplots(
        1, n_models,
        figsize=(max(10, n_dist * 0.55) * n_models, max(4, n_scene * 0.55 + 3)),
        squeeze=False,
    )
    fig.suptitle(
        f"OOD no_input  |  {split_name}\n"
        f"KEPT (+1) vs REMOVED (−1) — model default behaviour on unseen sounds",
        fontsize=12, fontweight="bold", y=1.02,
    )

    for ax, (model_name, df) in zip(axes[0], dfs.items()):
        if df.empty:
            ax.set_title(f"{model_name}\n(no data)")
            ax.axis("off")
            continue

        pivot  = build_pivot(df, scene_order, dist_order)
        annots = annot_array(pivot)
        mask   = pivot.isna()

        sns.heatmap(
            pivot,
            ax=ax,
            mask=mask,
            annot=annots,
            fmt="",
            annot_kws={"size": 7, "weight": "bold"},
            vmin=-1, vmax=1,
            center=0,
            cmap="RdYlGn",          # green = kept, red = removed
            linewidths=0.4,
            linecolor="#cccccc",
            cbar_kws={
                "label": "←  REMOVED   |   KEPT  →",
                "shrink": 0.6,
                "ticks": [-1, -0.5, 0, 0.5, 1],
            },
        )

        # Overall kept % per distractor (column header)
        dist_overall = df.groupby("distractor_name")["kept_score"].mean()
        xlabels = []
        for d in dist_order:
            v = dist_overall.get(d, float("nan"))
            if np.isnan(v):
                xlabels.append(d)
            else:
                pct = abs(v) * 100
                tag = "K" if v > 0 else "R"
                xlabels.append(f"{d}\n({tag}{pct:.0f}%)")
        ax.set_xticklabels(xlabels, fontsize=7.5, rotation=45, ha="right")

        # Overall kept % per scene (row header)
        scene_overall = df.groupby("scene")["kept_score"].mean()
        ylabels = []
        for s in scene_order:
            v = scene_overall.get(s, float("nan"))
            if np.isnan(v):
                ylabels.append(s)
            else:
                pct = abs(v) * 100
                tag = "K" if v > 0 else "R"
                ylabels.append(f"{s}  ({tag}{pct:.0f}%)")
        ax.set_yticklabels(ylabels, fontsize=9, rotation=0)

        ax.set_title(model_name, fontsize=10, fontweight="bold", pad=8)
        ax.set_xlabel("Distractor (OOD)", fontsize=10)
        ax.set_ylabel("Scene", fontsize=10)

    plt.tight_layout()
    fig.savefig(out_path, dpi=150, bbox_inches="tight")
    plt.close(fig)
    print(f"Saved: {out_path}")


# ═══════════════════════════════════════════════════════════════════════════════

def main():
    for split_name, split_dir in OOD_SPLITS.items():
        dfs = {}
        for model_name, model_dir in MODELS.items():
            path = BASE_DIR / model_dir / split_dir / CSV_NAME
            if not path.exists():
                print(f"[WARN] missing: {path}")
                continue
            df = load(path)
            print(f"  {model_name} / {split_name}: {len(df)} no_input rows, "
                  f"{df['distractor_name'].nunique()} distractors, "
                  f"{df['scene'].nunique()} scenes")
            dfs[model_name] = df

        if not dfs:
            print(f"[SKIP] {split_name} — no data found")
            continue

        out = BASE_DIR / f"heatmap_ood_no_input_{split_name}.png"
        plot_split(split_name, dfs, out)

    # ── Print summary table ────────────────────────────────────────────────────
    print(f"\n{'═'*70}")
    print("  OOD no_input summary: % KEPT per model per split (CLAP)")
    print(f"{'═'*70}")
    print(f"  {'split':<25} {'combined_v1':>20} {'no_TSDL_old_mixtures':>22}")
    print("  " + "─" * 70)
    for split_name, split_dir in OOD_SPLITS.items():
        row = f"  {split_name:<25}"
        for model_name, model_dir in MODELS.items():
            path = BASE_DIR / model_dir / split_dir / CSV_NAME
            if not path.exists():
                row += f"  {'N/A':>20}"
                continue
            df = load(path)
            if df.empty:
                row += f"  {'N/A':>20}"
            else:
                kept_pct = (df["kept_score"] > 0).mean() * 100
                row += f"  {kept_pct:>19.1f}%"
        print(row)

    # ── Per-distractor breakdown (OOD_distractors only, combined_v1) ──────────
    path = BASE_DIR / "experiments_final/combined_v1" / OOD_SPLITS["OOD_distractors"] / CSV_NAME
    if path.exists():
        df = load(path)
        if not df.empty:
            print(f"\n{'═'*70}")
            print("  Per-distractor breakdown  (OOD_distractors, combined_v1)")
            print("  sorted by kept_score  (green = model tends to keep, red = tends to remove)")
            print(f"{'═'*70}")
            print(f"  {'distractor':<36} {'N':>4}  {'kept_score':>10}  {'behaviour'}")
            print("  " + "─" * 65)
            stats = (
                df.groupby("distractor_name")["kept_score"]
                  .agg(["mean", "count"])
                  .sort_values("mean", ascending=False)
            )
            for name, row in stats.iterrows():
                v   = row["mean"]
                n   = int(row["count"])
                pct = abs(v) * 100
                beh = f"KEPT    ({pct:.0f}%)" if v > 0 else f"REMOVED ({pct:.0f}%)"
                bar = ("█" * int(pct / 5)).ljust(20)
                print(f"  {name:<36} {n:>4}  {v:>+10.3f}  {beh}  {bar}")


if __name__ == "__main__":
    main()