aabroukh's picture
Add files using upload-large-folder tool
c202fc8 verified
Raw History Blame Contribute Delete
9.56 kB
"""
ROBUSTNESS CHECK: ceiling-compression diagnostics
==================================================
Tests whether audio-condition effects (smaller decision threshold,
reduced length bias) reflect a genuine evaluative shift or simply that
audio raters compress their ratings toward the 100-point ceiling.
Three diagnostics:
1. DESCRIPTIVES — proportion of ratings at/near ceiling, distribution
skew, per-participant SD. If audio is genuinely more compressed,
we expect higher mean, lower SD, more mass at ≥ 95 / = 100.
2. OMNIBUS on z-scored ratings — the same model from
01_omnibus_bias_model.py, but with within-participant z-scored
Rating as the DV. Removes per-participant location/scale, so an
effect that survives is not driven by raw-scale compression.
3. OMNIBUS on logit(Rating/100) — a non-linear transform that
expands the high end. If audio length-bias rebounds toward the
text level here, the original difference was a ceiling artifact;
if it stays smaller, the difference is genuine.
For each transform, the headline check is the *modality × char_len_z*
interaction (the length-bias-reduction-in-audio claim) and the
*modality* main effect.
"""
import ast
import warnings
import numpy as np
import pandas as pd
import polars as pl
from pymer4.models import lmer
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "common"))
from _config import DATA_DIR, save_table
warnings.filterwarnings("ignore")
# ----------------------------------------------------------------------------
# LOAD (mirrors 01_omnibus_bias_model.py)
# ----------------------------------------------------------------------------
long_audio = pd.read_csv(f"{DATA_DIR}/long_audio_table_normalized.csv")
long_text = pd.read_csv(f"{DATA_DIR}/long_text_table_normalized.csv")
prompt_stim_table = pd.read_csv(f"{DATA_DIR}/prompt_stim_table.csv")
prompt_stim_long_table = pd.read_csv(f"{DATA_DIR}/survey_long_format.csv")
# stimulus-length lookup
stimuli_long = []
for _, row in prompt_stim_table.iterrows():
pid = row["PromptID"]
a, b = ast.literal_eval(row["AudioClipNames"])
la = prompt_stim_long_table[
prompt_stim_long_table["AudioClip"] == a
]["TextLength"].values[0]
lb = prompt_stim_long_table[
prompt_stim_long_table["AudioClip"] == b
]["TextLength"].values[0]
stimuli_long.append({"PromptID": pid, "AudioClip": a, "char_len": la})
stimuli_long.append({"PromptID": pid, "AudioClip": lb, "char_len": lb})
stimuli_df = pd.DataFrame(stimuli_long).drop_duplicates(
subset=["PromptID", "AudioClip"]
)
# Repair the typo above (use clip b, not lb, as identifier)
stimuli_long2 = []
for _, row in prompt_stim_table.iterrows():
pid = row["PromptID"]
a, b = ast.literal_eval(row["AudioClipNames"])
la = prompt_stim_long_table[
prompt_stim_long_table["AudioClip"] == a
]["TextLength"].values[0]
lb = prompt_stim_long_table[
prompt_stim_long_table["AudioClip"] == b
]["TextLength"].values[0]
stimuli_long2.append({"PromptID": pid, "AudioClip": a, "char_len": la})
stimuli_long2.append({"PromptID": pid, "AudioClip": b, "char_len": lb})
stimuli_df = pd.DataFrame(stimuli_long2)
audio = long_audio.copy()
audio["modality"] = "audio"
text = long_text.copy()
text["modality"] = "text"
if "qualityRating" in audio.columns:
audio = audio.drop(columns=["qualityRating"])
combined = pd.concat([audio, text], ignore_index=True)
combined = combined.merge(stimuli_df, on=["PromptID", "AudioClip"], how="left")
combined = combined.dropna(subset=["Rating", "char_len"]).copy()
combined["presented_first"] = combined["PresentedFirst"].astype(int)
combined = combined.rename(columns={"ParticipantID": "participantID",
"PromptID": "promptID"})
combined["char_len_z"] = (
(combined["char_len"] - combined["char_len"].mean())
/ combined["char_len"].std()
)
combined["trial_number_z"] = (
(combined["TrialNumber"] - combined["TrialNumber"].mean())
/ combined["TrialNumber"].std()
)
# ----------------------------------------------------------------------------
# 1) DESCRIPTIVE CEILING DIAGNOSTICS
# ----------------------------------------------------------------------------
print("=" * 78)
print("1) DESCRIPTIVE CEILING DIAGNOSTICS")
print("=" * 78)
print(f"{'modality':<10} {'n':>6} {'mean':>6} {'SD':>6} "
f"{'med':>5} {'skew':>6} {'≥90 (%)':>8} {'≥95 (%)':>8} {'=100 (%)':>9}")
ceiling_rows = []
for mod in ["audio", "text"]:
s = combined.loc[combined["modality"] == mod, "Rating"].astype(float)
n = len(s)
pct_ge90 = (s >= 90).mean() * 100
pct_ge95 = (s >= 95).mean() * 100
pct_eq100 = (s == 100).mean() * 100
print(f"{mod:<10} {n:>6d} {s.mean():>6.2f} {s.std():>6.2f} "
f"{s.median():>5.0f} {s.skew():>6.2f} "
f"{pct_ge90:>7.1f} {pct_ge95:>7.1f} {pct_eq100:>8.1f}")
ceiling_rows.append(dict(modality=mod, n=n, mean=s.mean(), sd=s.std(), median=s.median(),
skew=s.skew(), pct_ge90=pct_ge90, pct_ge95=pct_ge95,
pct_eq100=pct_eq100))
# Within-participant SD: are audio raters genuinely using a narrower band?
print("\nWithin-participant SD of Rating (mean across participants):")
for mod in ["audio", "text"]:
per_user_sd = (
combined.loc[combined["modality"] == mod]
.groupby("participantID")["Rating"].std()
)
print(f" {mod:<10} M(within-user SD) = {per_user_sd.mean():.2f} "
f"(SD across users = {per_user_sd.std():.2f}, n = {len(per_user_sd)})")
# ----------------------------------------------------------------------------
# 2) OMNIBUS on within-participant z-scored Rating
# ----------------------------------------------------------------------------
print("\n" + "=" * 78)
print("2) OMNIBUS on within-participant z-scored Rating")
print("=" * 78)
combined["Rating_z"] = (
combined.groupby("participantID")["Rating"]
.transform(lambda s: (s - s.mean()) / s.std())
)
combined_z = combined.dropna(subset=["Rating_z"]).copy()
# NOTE: z-scoring Rating *within* participantID already removes per-user
# mean variation, so the (1|participantID) intercept goes to zero variance
# (singular fit). We drop it for this model only.
formula_z = ("Rating_z ~ presented_first * modality + char_len_z * modality "
"+ trial_number_z * modality "
"+ (1|AudioClip)")
print(f" {formula_z}\n")
m_z = lmer(formula_z, data=pl.DataFrame(combined_z))
m_z.fit(summarize=False)
res_z = m_z.result_fit.to_pandas() if hasattr(m_z.result_fit, "to_pandas") \
else pd.DataFrame(m_z.result_fit)
print(res_z.to_string(index=False))
# ----------------------------------------------------------------------------
# 3) OMNIBUS on logit(Rating/100)
# ----------------------------------------------------------------------------
print("\n" + "=" * 78)
print("3) OMNIBUS on logit((Rating + 0.5) / 101)")
print("=" * 78)
# +0.5/101 smoothing to keep 0 and 100 finite under logit
p = (combined["Rating"] + 0.5) / 101.0
combined["Rating_logit"] = np.log(p / (1 - p))
formula_l = ("Rating_logit ~ presented_first * modality + char_len_z * modality "
"+ trial_number_z * modality "
"+ (1|participantID) + (1|AudioClip)")
print(f" {formula_l}\n")
m_l = lmer(formula_l, data=pl.DataFrame(combined))
m_l.fit(summarize=False)
res_l = m_l.result_fit.to_pandas() if hasattr(m_l.result_fit, "to_pandas") \
else pd.DataFrame(m_l.result_fit)
print(res_l.to_string(index=False))
# ----------------------------------------------------------------------------
# 4) RAW omnibus (for side-by-side reference)
# ----------------------------------------------------------------------------
print("\n" + "=" * 78)
print("4) Reference: original omnibus on raw Rating")
print("=" * 78)
formula_r = ("Rating ~ presented_first * modality + char_len_z * modality "
"+ trial_number_z * modality "
"+ (1|participantID) + (1|AudioClip)")
m_r = lmer(formula_r, data=pl.DataFrame(combined))
m_r.fit(summarize=False)
res_r = m_r.result_fit.to_pandas() if hasattr(m_r.result_fit, "to_pandas") \
else pd.DataFrame(m_r.result_fit)
print(res_r.to_string(index=False))
# ----------------------------------------------------------------------------
# SIDE-BY-SIDE summary of the effects of interest
# ----------------------------------------------------------------------------
def fmt(row):
if row is None:
return "—"
return (f"b={row['estimate']:>7.3f} p={row['p_value']:.4f}")
terms = ["modalitytext", "presented_first", "char_len_z",
"trial_number_z", "presented_first:modalitytext",
"modalitytext:char_len_z", "modalitytext:trial_number_z"]
print("\n" + "=" * 78)
print("SIDE-BY-SIDE: modality-relevant fixed effects across transforms")
print("=" * 78)
print(f"{'term':<34} {'raw Rating':<24} {'within-user z':<24} {'logit':<24}")
for t in terms:
rr = res_r[res_r["term"] == t].iloc[0] if (res_r["term"] == t).any() else None
rz = res_z[res_z["term"] == t].iloc[0] if (res_z["term"] == t).any() else None
rl = res_l[res_l["term"] == t].iloc[0] if (res_l["term"] == t).any() else None
print(f"{t:<34} {fmt(rr):<24} {fmt(rz):<24} {fmt(rl):<24}")
save_table(ceiling_rows, "02_main_study", "ceiling_diagnostics.csv")
save_table({"within_user_z": res_z, "logit": res_l, "raw": res_r},
"02_main_study", "robust_ceiling.csv")
print("\nDONE.")