File size: 5,011 Bytes
849f535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""Post-hoc sensitivity split of B1 by trial duration (Appendix H).

    python analysis/07_audio_context_study/03_duration_split.py

The claim being reproduced: splitting B1's raters at the cell's median trial
duration (a criterion independent of the ratings), the faster half yields a
singular variance-components fit with ~zero stimulus variance, while the
slower half's decision threshold matches the audio baseline.

Duration is the trial's totalTaskDurationMs from the Firestore export
(data/audio_context_study/trial_durations_audiocontext_onevoice.csv), one value per
trial; a rater's speed is the median of their trial durations. The split is at
the median of those per-rater medians. Variance components use the same model
as scale_usage.py / the paper's ICC:

    Rating ~ presented_first + trial_z + (1|AudioClip) + (1|ParticipantID)

and the threshold is the trial-level mean gap on non-tie trials, as in
threshold_summary.py. Reported for both halves, alongside the audio-baseline
threshold on the same 30 prompts for reference. This is a post-hoc sensitivity
check, not a pre-specified exclusion rule.
"""

from __future__ import annotations

import sys
from pathlib import Path

import numpy as np
import pandas as pd

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common"))

from _condition_contrasts import trial_gaps  # noqa: E402
from _lme4 import lmer_varcomp  # 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/07_audio_context_study"


def durations() -> pd.Series:
    """(ParticipantID, PromptID) -> trial duration in seconds."""
    t = pd.read_csv(CONTEXT_DATA / "trial_durations_audiocontext_onevoice.csv")
    return (t.set_index(["ParticipantID", "PromptID"])["TaskDurationMs"]
            .div(1000.0).rename("seconds"))


def varcomp(g: pd.DataFrame) -> dict:
    g = g.dropna(subset=["Rating", "TrialNumber", "AudioClip"]).copy()
    g["pf"] = g["PresentedFirst"].astype(int)
    sd = g["TrialNumber"].std()
    g["trial_z"] = (g["TrialNumber"] - g["TrialNumber"].mean()) / (sd if sd else 1)
    return lmer_varcomp(
        g, "Rating ~ pf + trial_z + (1|AudioClip) + (1|ParticipantID)")


def threshold(g: pd.DataFrame) -> tuple[float, int]:
    x = trial_gaps(g)["gap"].dropna()
    return float(x.mean()), len(x)


def main() -> None:
    b1 = pd.read_csv(CONTEXT_DATA / "long_audiocontext_onevoice_raw.csv")
    b1 = b1[~b1["IsAttentionCheck"].astype(bool)].dropna(subset=["Rating"])
    # The raw table keeps attention-check failures (build_long_tables.py keeps
    # them for the pass-rate stat); the analyzed cell is the normalized one.
    analyzed = set(pd.read_csv(CONTEXT_DATA / "long_audiocontext_onevoice_normalized.csv")
                   ["ParticipantID"])
    b1 = b1[b1["ParticipantID"].isin(analyzed)]
    b1["Arm"] = "B1"
    dur = durations()

    per_rater = (b1.drop_duplicates(["ParticipantID", "PromptID"])
                 .join(dur, on=["ParticipantID", "PromptID"]))
    speed = per_rater.groupby("ParticipantID")["seconds"].median().dropna()
    b1 = b1[b1["ParticipantID"].isin(speed.index)]
    cut = speed.median()
    fast = speed[speed <= cut].index
    slow = speed[speed > cut].index
    print(f"{len(speed)} raters with durations; median of per-rater medians "
          f"{cut:.1f}s -> fast {len(fast)}, slow {len(slow)}")

    rows = []
    for name, ids in (("fast half", fast), ("slow half", slow)):
        g = b1[b1["ParticipantID"].isin(ids)]
        thr, n = threshold(g)
        vc = varcomp(g)
        print(f"\n{name}: {g['ParticipantID'].nunique()} raters, "
              f"median trial {speed[ids].median():.0f}s")
        print(f"  threshold {thr:.1f}  ({n} non-tie trials)")
        print("  variance components: " +
              ", ".join(f"{k}={v:.2f}" for k, v in vc.items()))
        if vc.get("AudioClip", 1) < 1e-6:
            print("  -> singular fit: stimulus variance is zero")
        rows.append(dict(group=name, raters=g["ParticipantID"].nunique(),
                         median_trial_s=speed[ids].median(), threshold=thr,
                         non_tie_trials=n, v_stim=vc.get("AudioClip"),
                         v_rater=vc.get("ParticipantID"), v_resid=vc.get("Residual")))

    # Reference: audio baseline threshold on the same 30 prompts.
    import _audio_context_replication as C
    prompts = set(pd.read_csv(ROOT / "stimuli/audio_context_study/prompts.csv")["PromptID"])
    base = C.load_arms(prompts)
    base = base[base["Arm"] == "ORIGINAL af_heart"]
    thr, n = threshold(base)
    print(f"\naudio baseline (same 30 prompts): threshold {thr:.1f} "
          f"({n} non-tie trials)")
    rows.append(dict(group="audio baseline", threshold=thr, non_tie_trials=n))
    pd.DataFrame(rows).to_csv(DERIVED / "duration_split.csv", index=False)
    print("-> results/07_audio_context_study/duration_split.csv")


if __name__ == "__main__":
    main()