Download analysis/common/_condition_contrasts.py from sciminds/same-words-different-judgements: direct link, hf CLI and curl.
- Browser
- Download file 7.7 kB
-
https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/analysis/common/_condition_contrasts.py
- Command line
-
hf download hf://datasets/sciminds/same-words-different-judgements/analysis/common/_condition_contrasts.py
-
curl -L -o _condition_contrasts.py https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/analysis/common/_condition_contrasts.py
7.7 kB
| """Direct between-condition contrasts on the decision threshold. | |
| python analysis/08_cross_study/02_condition_contrasts.py | |
| Tables 10 and 13 test each arm against text separately. Comparing arms to | |
| each other by whether those separate tests reached significance -- e.g. | |
| concluding that Chatterbox differs from am_michael because Chatterbox is n.s. | |
| against text while am_michael is not -- would be invalid (Tables 17-18 give the | |
| direct tests): the | |
| difference between "significant" and "not significant" is not itself | |
| significant. Two one-sample comparisons against a shared baseline do not | |
| substitute for a direct two-sample test. | |
| So this fits ONE model per study with condition as a fixed effect and reports | |
| every pairwise contrast with a confidence interval: | |
| gap ~ Arm + (1|PromptID) + (1|ParticipantID) | |
| Outcome is the paper's threshold quantity -- the per-trial rating gap on | |
| non-tie trials (Section 4.1), not a per-rater or per-prompt aggregate of it, so | |
| each trial is one row and the random intercepts carry the clustering. | |
| Random effects. Raters are nested in condition (the design is between-subjects: | |
| a rater sees exactly one arm), so the rater intercept absorbs rater-level scale | |
| use but cannot be crossed with condition. Prompt IS crossed with condition -- | |
| every arm covers the same 30 prompts -- which is what makes the contrasts | |
| paired at the stimulus level and is the whole reason to model prompt rather | |
| than aggregate over it. | |
| Two models, not one. The voice study (A) and audio-context study (B) use different 30-prompt sets | |
| (15 overlap) and each recomputes its own text and audio references on its own | |
| set, so pooling them would confound condition with stimulus sample. | |
| Both Tukey-adjusted and unadjusted intervals are printed. The adjusted ones are | |
| the honest default across all pairs; the unadjusted ones are appropriate for the | |
| contrasts named in advance (Chatterbox vs. each other voice; B2 vs. B1), and | |
| the two are reported side by side rather than choosing silently. | |
| """ | |
| from __future__ import annotations | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import _audio_context_replication as C # noqa: E402 | |
| import _voice_variation_replication as V # 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/08_cross_study" | |
| def _r(): | |
| import rpy2.robjects as ro | |
| ro.r("suppressMessages({library(lme4); library(lmerTest); library(emmeans)})") | |
| return ro | |
| def trial_gaps(df: pd.DataFrame) -> pd.DataFrame: | |
| """One row per non-tie trial: the gap between the two responses. | |
| A trial contributes two rows to the long table (one per clip), so the gap is | |
| taken within (Arm, participant, prompt). Ties are excluded because the | |
| paper's threshold is defined on trials where a winner was declared. | |
| Two outcomes: | |
| gap raw rating points -- the paper's definition (Section 4.1) and | |
| the quantity in Tables 10 and 11. | |
| gap_scaled the same gap divided by that rater's own rating SD. | |
| The scaled version exists because a rater confined to a narrow band cannot | |
| produce a large gap, so a small raw threshold from them confounds "commits | |
| at small perceived differences" with "uses little of the scale". That is not | |
| hypothetical here: 45% of B1's raters have a rating SD below 10, against | |
| 2-13% in every other condition, and half of B1 yields zero stimulus | |
| variance. The B2 - B1 contrast is therefore reported on both outcomes; if it | |
| only survives on raw gaps it is a statement about B1's scale use rather than | |
| about audio context. | |
| """ | |
| d = df[df["overallPreference"].isin(["A", "B"])].copy() | |
| d["_sd"] = d.groupby("ParticipantID")["Rating"].transform("std") | |
| g = (d.groupby(["Arm", "ParticipantID", "PromptID"]) | |
| .apply(lambda x: pd.Series({ | |
| "gap": x["Rating"].max() - x["Rating"].min(), | |
| "gap_scaled": ((x["Rating"].max() - x["Rating"].min()) / x["_sd"].iloc[0] | |
| if x["_sd"].iloc[0] > 0 else np.nan), | |
| }) if len(x) == 2 else pd.Series({"gap": np.nan, "gap_scaled": np.nan}), | |
| include_groups=False) | |
| .dropna(subset=["gap"]).reset_index()) | |
| return g | |
| def fit_and_contrast(tag: str, df: pd.DataFrame, order: list[str], | |
| slug: str) -> pd.DataFrame: | |
| ro = _r() | |
| g = trial_gaps(df) | |
| g = g[g["Arm"].isin(order)] | |
| print(f"\n{'=' * 88}\n{tag}") | |
| print(f" {len(g)} non-tie trials, {g.ParticipantID.nunique()} raters, " | |
| f"{g.PromptID.nunique()} prompts, {g.Arm.nunique()} conditions\n{'=' * 88}") | |
| with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as fh: | |
| path = Path(fh.name) | |
| try: | |
| g.to_csv(path, index=False) | |
| levels = ",".join(f'"{o}"' for o in order) | |
| ro.r(f'd <- read.csv("{path}", stringsAsFactors = FALSE)') | |
| ro.r(f"d$Arm <- factor(d$Arm, levels = c({levels}))") | |
| for outcome, label in (("gap", "RAW gap (rating points) -- paper's definition"), | |
| ("gap_scaled", "SCALED gap (rater's own SDs)")): | |
| print(f"\n{'-' * 88}\n-- {label}\n{'-' * 88}") | |
| ro.r(f"dd <- d[!is.na(d${outcome}), ]") | |
| ro.r(f"m <- lmer({outcome} ~ Arm + (1|PromptID) + (1|ParticipantID), data = dd)") | |
| print("\nestimated marginal means") | |
| ro.r("print(as.data.frame(emmeans(m, ~Arm)))") | |
| ro.r(f'write.csv(as.data.frame(emmeans(m, ~Arm)), ' | |
| f'"{DERIVED}/emmeans_{slug}_{outcome}.csv", row.names = FALSE)') | |
| ro.r("ct <- pairs(emmeans(m, ~Arm))") | |
| ro.r("ctu <- pairs(emmeans(m, ~Arm), adjust = 'none')") | |
| print("\npairwise contrasts (estimate, Tukey CI, Tukey p, unadjusted p)") | |
| ro.r("print(cbind(as.data.frame(ct)[,c('contrast','estimate','SE')]," | |
| "as.data.frame(confint(ct))[,c('lower.CL','upper.CL')]," | |
| "adj_p = as.data.frame(ct)$p.value," | |
| "unadj_p = as.data.frame(ctu)$p.value))") | |
| ro.r(f'write.csv(cbind(as.data.frame(ct)[,c("contrast","estimate","SE","df","t.ratio","p.value")],' | |
| f'adj_lower = as.data.frame(confint(ct))$lower.CL,' | |
| f'adj_upper = as.data.frame(confint(ct))$upper.CL,' | |
| f'unadj_p = as.data.frame(ctu)$p.value,' | |
| f'unadj_lower = as.data.frame(confint(ctu, adjust="none"))$lower.CL,' | |
| f'unadj_upper = as.data.frame(confint(ctu, adjust="none"))$upper.CL),' | |
| f'"{DERIVED}/contrasts_{slug}_{outcome}.csv", row.names = FALSE)') | |
| print(f" -> results/08_cross_study/contrasts_{slug}_{outcome}.csv") | |
| finally: | |
| path.unlink(missing_ok=True) | |
| def main() -> None: | |
| DERIVED.mkdir(parents=True, exist_ok=True) | |
| voice = set(pd.read_csv(ROOT / "stimuli/voice_study/prompts.csv")["PromptID"]) | |
| fit_and_contrast( | |
| "ABLATION A -- voice variation (30 Ablation-A prompts)", | |
| V.load_arms(voice), | |
| ["ORIGINAL af_heart", "ORIGINAL text", "kokoro_am_michael", | |
| "chatterbox", "qwen3tts_serena"], | |
| "voice", | |
| ) | |
| ctx = set(pd.read_csv(ROOT / "stimuli/audio_context_study/prompts.csv")["PromptID"]) | |
| fit_and_contrast( | |
| "ABLATION B -- audio context (30 Ablation-B prompts)", | |
| C.load_arms(ctx), | |
| ["ORIGINAL af_heart", "ORIGINAL text", | |
| "B1 one-voice context", "B2 two-voice context"], | |
| "context", | |
| ) | |
| if __name__ == "__main__": | |
| main() | |