"""Prompt-clustered bootstrap CIs for Table 12's alignment correlations. python analysis/06_voice_study/07_synth_alignment_bootstrap.py [--reps 5000] Table 12's correlations are computed over 60 clips that come in 30 prompt pairs, so clip-level CIs would overstate precision. Here the bootstrap resamples the 30 PROMPTS with replacement and both of a prompt's clips travel together, giving cluster-robust percentile CIs for r and rho per (voice, rater), plus CIs for each voice's difference from the af_heart baseline within the same rater. Read the differences before claiming voice dependence: a baseline-vs-voice difference whose CI covers zero "varied descriptively across renderers", no more. """ from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np import pandas as pd from scipy import stats sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common")) from _voice_synth_alignment import MODELS, clip_means # noqa: E402 ROOT = Path(__file__).resolve().parent.parent.parent VOICE_DATA = ROOT / "data/voice_study" CONTEXT_DATA = ROOT / "data/audio_context_study" DERIVED = ROOT / "results/06_voice_study" SD = ROOT / "data/main_study" def load_pairs() -> dict[tuple[str, str], pd.DataFrame]: """(voice, rater) -> per-clip h/s means with a PromptID column.""" prompts = set(pd.read_csv(ROOT / "stimuli/voice_study/prompts.csv")["PromptID"]) human = {} voice = pd.read_csv(VOICE_DATA / "long_voice_normalized.csv") for arm, g in voice.groupby("Arm"): human[arm] = clip_means(g) base = pd.read_csv(SD / "long_audio_table_normalized.csv") base = base[~base["IsAttentionCheck"].astype(bool)] human["kokoro_af_heart (baseline)"] = clip_means( base[base["PromptID"].isin(prompts)]) out = {} for voice_name, h in human.items(): for model in MODELS: path = (SD / f"synth_long_audio_table_{model}.csv" if "baseline" in voice_name else VOICE_DATA / "synth" / f"synth_long_audio_table_{voice_name}_{model}.csv") if not path.exists(): continue s = pd.read_csv(path) s = s[s["PromptID"].astype(str).isin(prompts)] m = pd.concat([h.rename("h"), clip_means(s).rename("s")], axis=1).dropna().reset_index() m["PromptID"] = m["AudioClip"].str.rsplit("_", n=1).str[0] out[(voice_name, model)] = m return out def corrs(m: pd.DataFrame) -> tuple[float, float]: if m["h"].nunique() < 2 or m["s"].nunique() < 2: return np.nan, np.nan return (stats.pearsonr(m.h, m.s)[0], stats.spearmanr(m.h, m.s)[0]) def boot(m: pd.DataFrame, reps: int, rng) -> np.ndarray: groups = {p: g[["h", "s"]] for p, g in m.groupby("PromptID")} ids = np.array(list(groups)) out = np.empty((reps, 2)) for i in range(reps): take = rng.choice(ids, size=len(ids), replace=True) out[i] = corrs(pd.concat([groups[p] for p in take], ignore_index=True)) return out def ci(x: np.ndarray) -> tuple[float, float]: x = x[~np.isnan(x)] return np.percentile(x, 2.5), np.percentile(x, 97.5) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--reps", type=int, default=5000) ap.add_argument("--seed", type=int, default=0) args = ap.parse_args() rng = np.random.default_rng(args.seed) pairs = load_pairs() draws = {k: boot(m, args.reps, rng) for k, m in pairs.items()} rows = [] for (voice_name, model), m in pairs.items(): r, rho = corrs(m) d = draws[(voice_name, model)] r_lo, r_hi = ci(d[:, 0]) rho_lo, rho_hi = ci(d[:, 1]) row = dict(voice=voice_name, rater=model, r=r, r_lo=r_lo, r_hi=r_hi, rho=rho, rho_lo=rho_lo, rho_hi=rho_hi) basekey = ("kokoro_af_heart (baseline)", model) if "baseline" not in voice_name and basekey in draws: # Same seed but independent resamples of the two voices' prompt # sets; the difference CI is therefore slightly conservative # relative to jointly resampling prompts across voices. dd = draws[(voice_name, model)] - draws[basekey] row["dr_vs_base"] = r - corrs(pairs[basekey])[0] row["dr_lo"], row["dr_hi"] = ci(dd[:, 0]) rows.append(row) out = pd.DataFrame(rows) print(out.to_string(index=False, float_format=lambda v: f"{v:.3f}")) out.to_csv(DERIVED / "synth_alignment_bootstrap.csv", index=False) print(f"\n({args.reps} prompt-cluster resamples, seed {args.seed})") print(f" -> results/06_voice_study/synth_alignment_bootstrap.csv") if __name__ == "__main__": main()