""" Shared helpers for the synthetic-rater sampling analyses (scripts 19-21). These live in their own module because the analysis scripts carry numeric filename prefixes (`19_...py`), which are not importable as Python modules. Anything more than one script needs goes here. human_panel per prompt x rater signed preference, plus the panel gold synth_gaps per prompt mean synthetic margin and its absolute gap prompt_matrix per-prompt rater-preference vectors, aligned to a prompt list """ from __future__ import annotations import numpy as np def human_panel(long_df): """ Per prompt x rater signed preference (clip0 - clip1), plus panel gold. Returns (wide, gold). `wide` has one row per (prompt, rater) with the signed preference in `pref`; `gold` has one row per prompt with the full-panel mean margin, the within-prompt rater SD, the panel size, and the gold winner (sign of the mean margin). """ df = long_df[long_df["IsAttentionCheck"] == False].copy() df["ClipIndex"] = df["AudioClip"].str.extract(r"_(\d+)\.mp3$")[0].astype(int) wide = df.pivot_table( index=["PromptID", "ParticipantID"], columns="ClipIndex", values="Rating", aggfunc="first", ).reset_index() wide.columns.name = None wide = wide.rename(columns={0: "r0", 1: "r1"}).dropna(subset=["r0", "r1"]) wide["pref"] = wide["r0"] - wide["r1"] gold = wide.groupby("PromptID")["pref"].agg( gold_margin="mean", sd_within="std", n_raters="size" ).reset_index() gold["gold_winner"] = np.sign(gold["gold_margin"]) return wide, gold def synth_gaps(synth_df): """Per prompt mean synthetic margin over repeated samples, and its gap.""" s = synth_df.copy() s["ClipIndex"] = s["AudioClip"].str.extract(r"_(\d+)\.(?:mp3|wav)$")[0].astype(int) wide = s.pivot_table( index=["PromptID", "synthNo"], columns="ClipIndex", values="Rating", aggfunc="first", ).reset_index() wide.columns.name = None wide = wide.rename(columns={0: "s0", 1: "s1"}).dropna(subset=["s0", "s1"]) wide["margin"] = wide["s0"] - wide["s1"] out = wide.groupby("PromptID")["margin"].agg( synth_margin="mean", n_synth="size" ).reset_index() out["synth_gap"] = out["synth_margin"].abs() out["synth_winner"] = np.sign(out["synth_margin"]) return out def prompt_matrix(panel, prompt_ids): """List of per-prompt rater-preference vectors, aligned to prompt_ids.""" by_prompt = {p: g["pref"].to_numpy() for p, g in panel.groupby("PromptID")} return [by_prompt[p] for p in prompt_ids]