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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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#!/usr/bin/env python3
"""
OOD stem-based CLAP heatmaps — all 3 splits × 2 models.

Metric: CLAP cosine similarity between model output crop and isolated
        distractor stem crop (from evaluate_event_detection.py).

  High CLAP sim  →  distractor present in output  →  KEPT  (green)
  Low  CLAP sim  →  distractor removed             →  REMOVED (red)

Only no_input command type (unambiguous: no user command given).

Outputs (one figure per OOD split, two subplots per figure):
  heatmap_ood_stem_OOD_backgrounds.png
  heatmap_ood_stem_OOD_distractors.png
  heatmap_ood_stem_OOD_both.png
"""

import re
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

# ── Config ────────────────────────────────────────────────────────────────────
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_backgrounds": ("eval_outputs_OOD_backgrounds",
                        "Background scene (OOD)",
                        "Distractor class (in-distribution)"),
    "OOD_distractors": ("eval_outputs_OOD_distractors",
                        "Background scene (in-distribution)",
                        "Distractor class (OOD)"),
    "OOD_both":        ("eval_outputs_OOD_both",
                        "Background scene (OOD)",
                        "Distractor class (OOD)"),
}

CMD_TYPE = "no_input"
CSV_NAME = "event_detection_scores.csv"

# ── Distractor ordering + display names (matches reference figure) ─────────────
# Order: left-to-right as in the reference heatmap image
DISTRACTOR_CANONICAL_ORDER = [
    "computer_typing", "drill", "cricket", "sneeze", "cough",
    "jackhammer", "hammer", "engine", "applause", "birds_chirping",
    "fireworks", "helicopter", "dog", "car_horn", "footsteps",
    "alarm_clock", "slam", "baby_cry", "train_horn", "cat",
    "ringtone", "cellphone_buzz_vibrating_alert", "car_alarm",
    "glass_breaking", "door_knock", "siren", "boom",
    "doorbell", "fire_alarm", "gunshot",
]

DISPLAY_NAMES = {
    "computer_typing":               "Computer Typing",
    "drill":                         "Drill",
    "cricket":                       "Cricket",
    "sneeze":                        "Sneeze",
    "cough":                         "Cough",
    "jackhammer":                    "Jackhammer",
    "hammer":                        "Hammer",
    "engine":                        "Engine",
    "applause":                      "Applause",
    "birds_chirping":                "Birds Chirping",
    "fireworks":                     "Fireworks",
    "helicopter":                    "Helicopter",
    "dog":                           "Dog",
    "car_horn":                      "Car Horn",
    "footsteps":                     "Footsteps",
    "alarm_clock":                   "Alarm Clock",
    "slam":                          "Slam",
    "baby_cry":                      "Baby Cry",
    "train_horn":                    "Train Horn",
    "cat":                           "Cat",
    "ringtone":                      "Ringtone",
    "cellphone_buzz_vibrating_alert":"Smartphone Vibration",
    "car_alarm":                     "Car Alarm",
    "glass_breaking":                "Glass Breaking",
    "door_knock":                    "Door Knock",
    "siren":                         "Siren",
    "boom":                          "Boom",
    "doorbell":                      "Doorbell",
    "fire_alarm":                    "Fire Alarm",
    "gunshot":                       "Gunshot",
}

# Scene display names (title-case with spaces)
SCENE_DISPLAY_NAMES = {
    "airplane":      "Airplane",
    "bus_station":   "Bus Station",
    "gym":           "Gym",
    "harbour":       "Harbour",
    "library":       "Library",
    "museum":        "Museum",
    "office":        "Office",
    "park":          "Park",
    "shopping_mall": "Shopping Mall",
    "train_station": "Train Station",
    "airport":       "Airport",
    "beach":         "Beach",
    "bus":           "Bus",
    "cafe":          "Cafe",
    "coffee_shop":   "Coffee Shop",
    "city":          "City",
    "forest":        "Forest",
    "home":          "Home",
    "kitchen":       "Kitchen",
    "restaurant":    "Restaurant",
    "supermarket":   "Supermarket",
    "train":         "Train",
}


def canonical_dist_order(present: list) -> list:
    """Return distractors in canonical order; extras appended at end."""
    ordered = [d for d in DISTRACTOR_CANONICAL_ORDER if d in present]
    extras  = [d for d in present if d not in DISTRACTOR_CANONICAL_ORDER]
    return ordered + extras


# ── Helpers ───────────────────────────────────────────────────────────────────
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["clap_sim"] = pd.to_numeric(df["clap_sim"], errors="coerce")
    df["scene"]    = df["mixture_id"].str.extract(r"^(.+?)_\d+dist_")
    return df.dropna(subset=["clap_sim", "scene"])


def build_pivot(df: pd.DataFrame, scene_order, dist_order) -> pd.DataFrame:
    return (
        df.groupby(["scene", "distractor_name"])["clap_sim"]
          .mean()
          .unstack("distractor_name")
          .reindex(index=scene_order, columns=dist_order)
    )


def annot_array(pivot: pd.DataFrame) -> np.ndarray:
    """Single-line value annotation — colour already conveys K/R."""
    arr = np.empty(pivot.shape, dtype=object)
    for i in range(pivot.shape[0]):
        for j in range(pivot.shape[1]):
            v = pivot.iloc[i, j]
            arr[i, j] = "" if np.isnan(v) else f"{v:.2f}"
    return arr


def dist_xlabel(name, mean_val, threshold):
    tag = "K" if mean_val >= threshold else "R"
    disp = DISPLAY_NAMES.get(name, name)
    return f"{disp}\n({tag} {mean_val:.2f})"


def scene_ylabel(name, mean_val, threshold):
    tag = "K" if mean_val >= threshold else "R"
    disp = SCENE_DISPLAY_NAMES.get(name, name.replace("_", " ").title())
    return f"{disp}  ({tag} {mean_val:.2f})"


# ── Main ──────────────────────────────────────────────────────────────────────
def plot_split(split_key: str, dist_order_override=None):
    split_dir, ylabel, xlabel = OOD_SPLITS[split_key]

    # Load both models
    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_key}: {len(df)} rows, "
              f"{df['scene'].nunique()} scenes, "
              f"{df['distractor_name'].nunique()} distractors")
        dfs[model_name] = df

    if not dfs:
        print(f"  [SKIP] {split_key} — no data")
        return

    # Shared ordering + threshold (pooled across both models)
    all_df    = pd.concat(dfs.values(), ignore_index=True)
    threshold = all_df["clap_sim"].median()
    print(f"  Threshold (pooled median): {threshold:.3f}")

    # Fixed canonical distractor order; scenes sorted by mean CLAP sim
    present_dists = all_df["distractor_name"].unique().tolist()
    if dist_order_override is not None:
        # Use shared override; keep only those actually present in this split
        dist_order = [d for d in dist_order_override if d in present_dists]
        # Append any extras not in the canonical override (safety net)
        extras = [d for d in present_dists if d not in dist_order_override]
        dist_order = dist_order + canonical_dist_order(extras)
    else:
        dist_order = canonical_dist_order(present_dists)
    scene_order   = (
        all_df.groupby("scene")["clap_sim"]
              .mean().sort_values(ascending=False).index.tolist()
    )

    n_dist   = len(dist_order)
    n_scene  = len(scene_order)

    ood_tag = {
        "OOD_backgrounds": "OOD: background scenes unseen, distractors known",
        "OOD_distractors": "OOD: distractor classes unseen, backgrounds known",
        "OOD_both":        "OOD: both background scenes and distractor classes unseen",
    }[split_key]

    # ── One figure per model ──────────────────────────────────────────────────
    for model_name, df in dfs.items():

        # Layout
        cell_w     = 0.62
        cell_h     = 0.28
        margin_w   = 3.5
        hm_title   = 0.8
        bp_h       = 2.8
        xlbl_h     = 2.5
        suptitle_h = 0.9

        fw = n_dist * cell_w + margin_w
        heatmap_h  = n_scene * cell_h + hm_title
        fh = suptitle_h + heatmap_h + bp_h + xlbl_h

        fig, axes = plt.subplots(
            2, 1,
            figsize=(fw, fh),
            gridspec_kw={"height_ratios": [heatmap_h, bp_h + xlbl_h],
                         "hspace": 0.02},
            squeeze=False,
        )
        ax_hm  = axes[0][0]
        ax_box = axes[1][0]

        fig.suptitle(
            f"{split_key}  |  {model_name}  |  no_input  |  stem-based CLAP similarity\n"
            f"{ood_tag}\n"
            f"green = KEPT (distractor present), red = REMOVED  "
            f"|  K/R boundary = pooled median ({threshold:.3f})",
            fontsize=11, fontweight="bold", y=1.01,
        )

        # ── Heatmap ───────────────────────────────────────────────────────────
        pivot  = build_pivot(df, scene_order, dist_order)
        annots = annot_array(pivot)

        sns.heatmap(
            pivot, ax=ax_hm, mask=pivot.isna(),
            annot=annots, fmt="",
            annot_kws={"size": 7, "weight": "bold"},
            vmin=0.20, vmax=0.70, center=threshold,
            cmap="RdYlGn", linewidths=0.4, linecolor="#cccccc",
            cbar_kws={
                "label": "CLAP sim  ←  REMOVED  |  KEPT  →",
                "shrink": 0.7,
                "ticks": [0.20, 0.30, threshold, 0.50, 0.60, 0.70],
            },
        )

        scene_means = df.groupby("scene")["clap_sim"].mean()
        ax_hm.set_xticklabels([])
        ax_hm.set_xlabel("")
        ax_hm.set_yticklabels(
            [scene_ylabel(s, scene_means.get(s, np.nan), threshold)
             for s in scene_order],
            fontsize=9, rotation=0,
        )
        kept_pct = (df["clap_sim"] >= threshold).mean() * 100
        ax_hm.set_title(f"KEPT {kept_pct:.0f}% overall",
                        fontsize=10, fontweight="bold", pad=6)
        ax_hm.set_ylabel(ylabel, fontsize=9)

        # ── Bar chart: mean kept rate (%) per distractor ──────────────────────
        # Use only distractors present in this model — same column order as heatmap
        model_dists      = df["distractor_name"].unique()
        model_dist_order = [d for d in dist_order if d in model_dists]

        bp_df = df[["distractor_name", "clap_sim"]].copy()
        bp_df["kept"] = (bp_df["clap_sim"] >= threshold).astype(float)
        mean_kept = bp_df.groupby("distractor_name")["kept"].mean() * 100  # percentage

        # Map each distractor to its column centre in dist_order
        col_idx      = {d: i for i, d in enumerate(dist_order)}
        bar_positions = np.array([col_idx[d] + 0.5 for d in model_dist_order])
        bar_values    = [mean_kept.get(d, np.nan) for d in model_dist_order]
        bar_colors    = [
            "#2ca02c" if (not np.isnan(v) and v >= 50) else "#d62728"
            for v in bar_values
        ]

        ax_box.bar(
            bar_positions, bar_values,
            width=0.6, color=bar_colors, alpha=0.85, zorder=3,
            edgecolor="white", linewidth=0.4,
        )

        # Annotate each bar with its value
        for pos, val, color in zip(bar_positions, bar_values, bar_colors):
            if not np.isnan(val):
                ax_box.text(
                    pos, val + 1.5, f"{val:.0f}%",
                    ha="center", va="bottom", fontsize=5.5,
                    fontweight="bold", color="black",
                )

        ax_box.axhline(50, color="gray", linestyle="--",
                       linewidth=1.0, alpha=0.8, label="50% boundary (K/R)")

        # Both axes share [0, n_dist] so column i is at [i, i+1]
        ax_hm.set_xlim(0, n_dist)
        ax_box.set_xlim(0, n_dist)

        ax_box.set_ylim(0, 115)
        ax_box.set_yticks([0, 25, 50, 75, 100])
        ax_box.set_yticklabels(["0%", "25%", "50%", "75%", "100%"], fontsize=8)
        # Tick at each heatmap column centre
        ax_box.set_xticks(np.arange(n_dist) + 0.5)
        ax_box.set_xticklabels(
            [DISPLAY_NAMES.get(d, d) for d in dist_order],
            fontsize=7.5, rotation=45, ha="right",
        )
        ax_box.set_xlabel(xlabel, fontsize=10)
        ax_box.set_ylabel("Mean Kept Rate (%)", fontsize=9)
        ax_box.set_title("Mean kept rate per distractor across scenes  "
                         "(green ≥ 50%, red < 50%)",
                         fontsize=10, fontweight="bold", pad=6)
        ax_box.yaxis.grid(True, linestyle="--", linewidth=0.5, alpha=0.5, zorder=0)
        ax_box.set_axisbelow(True)
        ax_box.legend(fontsize=8, loc="upper left", framealpha=0.85)

        # ── Force exact horizontal alignment: boxplot width = heatmap width ───
        # tight_layout makes the colorbar steal space from ax_hm; ax_box ends up
        # wider. After layout is resolved, snap ax_box to ax_hm's x-extent.
        plt.tight_layout()
        fig.canvas.draw()
        pos_hm  = ax_hm.get_position()
        pos_box = ax_box.get_position()
        ax_box.set_position([pos_hm.x0, pos_box.y0,
                              pos_hm.width, pos_box.height])

        out = BASE_DIR / f"heatmap_ood_stem_{split_key}_{model_name}.png"
        fig.savefig(out, dpi=150, bbox_inches="tight")
        plt.close(fig)
        print(f"  Saved: {out}")


def print_summary():
    print(f"\n{'═'*72}")
    print("  OOD no_input summary — % KEPT (CLAP sim ≥ pooled median)")
    print(f"{'═'*72}")
    print(f"  {'split':<20} {'combined_v1':>20} {'no_TSDL_old_mixtures':>22}")
    print("  " + "─" * 65)

    for split_key, (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 path.exists():
                dfs[model_name] = load(path)

        if not dfs:
            continue

        threshold = pd.concat(dfs.values())["clap_sim"].median()
        row = f"  {split_key:<20}"
        for model_name in MODELS:
            if model_name in dfs:
                pct = (dfs[model_name]["clap_sim"] >= threshold).mean() * 100
                row += f"  {pct:>19.1f}%"
            else:
                row += f"  {'N/A':>20}"
        print(row)


if __name__ == "__main__":
    # Pre-compute a shared distractor ordering for OOD_distractors + OOD_both
    # so that the same distractor always appears in the same column in both figures.
    SHARED_SPLITS = {"OOD_distractors", "OOD_both"}
    shared_all_dists = set()
    for sk in SHARED_SPLITS:
        split_dir = OOD_SPLITS[sk][0]
        for model_dir in MODELS.values():
            path = BASE_DIR / model_dir / split_dir / CSV_NAME
            if path.exists():
                df_tmp = load(path)
                shared_all_dists.update(df_tmp["distractor_name"].unique())
    shared_dist_order = canonical_dist_order(list(shared_all_dists))
    print(f"\nShared distractor order (OOD_distractors + OOD_both): "
          f"{len(shared_dist_order)} classes")

    for split_key in OOD_SPLITS:
        print(f"\n{'─'*60}")
        print(f"  Plotting {split_key} ...")
        override = shared_dist_order if split_key in SHARED_SPLITS else None
        plot_split(split_key, dist_order_override=override)

    print_summary()