File size: 8,125 Bytes
849f535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2871b55
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""Table 16: how raters used the rating scale, by condition.

    python analysis/08_cross_study/05_scale_usage.py

The table answers one question: is B1's low ICC caused by raters
DISAGREEING with each other, or by raters not DIFFERENTIATING the stimuli at
all? Those look identical in an ICC -- both shrink the stimulus share of
variance -- but they mean opposite things, so the columns here separate them.

    Mean rating          leniency: where on the 0-100 scale the condition sits
    Per-rater SD         spread: how much of the scale a typical rater used
    Raters with SD < 10  how many used almost none of it
    Tie rate             how often no winner was declared
    Variance components  the ICC's own numerator and denominator, split out

THE BASIS PROBLEM, and why two of these are computed differently.

The four conditions do not have the same data available. B1 and B2 raters each
did 15 trials on the 30 audio-context prompts -- 30 ratings, their whole session.
The original text and audio raters each did 20 trials drawn from 100 prompts,
so restricting them to the same 30 prompts leaves roughly 6 prompts, i.e. 12
ratings each.

A standard deviation estimated from 12 numbers is far noisier than one from 30.
Ordinary raters cross an "SD < 10" line by chance. Computed on the ctx-30
subset the counts are 6/46 text and 7/46 audio; computed on each rater's full
session they are 2/47 and 1/46. The subset version is measurement noise, not
behaviour, so the RATER-LEVEL columns use full sessions.

The VARIANCE COMPONENTS cannot do that. They are the decomposition behind the
ICCs in Table 13, and an ICC is a property of a specific stimulus set, so all
four conditions must be fit on the shared 30 audio-context prompts or the numbers
are not comparable to each other or to Table 13.

So the table mixes bases deliberately, and says so in its caption. Note this is
a real trade-off rather than a bug being papered over: matching on stimuli costs
precision, matching on precision costs stimulus comparability. Mean rating and
tie rate also shift between bases, but for a different reason -- the 30
The audio-context prompts were selected for conversation history and capped duration,
so they genuinely tie more often than the corpus average. The conclusion is
unchanged either way: B1's share of non-differentiating raters is 45% against
9-15% (subset) or 2-9% (full session).
"""

from __future__ import annotations

import sys
from pathlib import Path

import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common"))
from _lme4 import lmer_varcomp  # noqa: E402

SD_DIR = ROOT / "data/main_study"
VOICE_DATA = ROOT / "data/voice_study"
CONTEXT_DATA = ROOT / "data/audio_context_study"
DERIVED = ROOT / "results/08_cross_study"

SOURCES = [
    ("Text (reference)",  SD_DIR / "long_text_table_normalized.csv"),
    ("Audio (baseline)",  SD_DIR / "long_audio_table_normalized.csv"),
    ("Ablation B1",       CONTEXT_DATA / "long_audiocontext_onevoice_normalized.csv"),
    ("Ablation B2",       CONTEXT_DATA / "long_audiocontext_normalized.csv"),
]


def load(path: Path) -> pd.DataFrame:
    d = pd.read_csv(path)
    if "IsAttentionCheck" in d.columns:
        d = d[~d["IsAttentionCheck"].astype(bool)]
    return d.dropna(subset=["Rating"])


def rater_columns(d: pd.DataFrame) -> dict:
    """Leniency and spread, one rater at a time then averaged.

    Per-rater SD is the MEAN of each rater's own SD, not the SD of all ratings
    pooled. Pooling would fold between-rater differences in leniency into the
    number, which is the opposite of what the column is for -- it is meant to
    say how much scale an individual used.
    """
    per_rater_sd = d.groupby("ParticipantID")["Rating"].std()
    trials = d.drop_duplicates(["ParticipantID", "PromptID"])
    return dict(
        raters=len(per_rater_sd),
        ratings_per_rater=d.groupby("ParticipantID").size().median(),
        mean_rating=d["Rating"].mean(),
        per_rater_sd=per_rater_sd.mean(),
        n_low=(per_rater_sd < 10).sum(),
        pct_low=(per_rater_sd < 10).mean() * 100,
        tie_rate=(trials["overallPreference"] == "Tie").mean(),
    )


def variance_components(d: pd.DataFrame) -> dict:
    """The ICC decomposition from Table 13's model, on raw ratings.

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

    Same specification as the paper's ICC (02_main_study/02_reliability_icc_alpha.py calc_icc), so the pieces
    add up to the ICCs reported in Table 13.
    """
    g = d.dropna(subset=["Rating", "TrialNumber", "AudioClip"]).copy()
    g["pf"] = g["PresentedFirst"].astype(int)
    g["trial_z"] = (g["TrialNumber"] - g["TrialNumber"].mean()) / g["TrialNumber"].std()
    rv = lmer_varcomp(g, "Rating ~ pf + trial_z + (1|AudioClip) + (1|ParticipantID)")
    # lmer_varcomp returns VarCorr's vcov column, i.e. variances already -- no
    # squaring here. (pymer4's .ranef_var reports SDs and does need squaring;
    # see 02_main_study/02_reliability_icc_alpha.py calc_icc.)
    v = {k: float(rv.get(k, np.nan))
         for k in ("AudioClip", "ParticipantID", "Residual")}
    k = g.groupby("AudioClip").size().mean()
    tot = v["AudioClip"] + v["ParticipantID"] + v["Residual"]
    return dict(v_stim=v["AudioClip"], v_rater=v["ParticipantID"],
                v_resid=v["Residual"], k=k,
                icc1=v["AudioClip"] / tot,
                icck=v["AudioClip"] / (v["AudioClip"] + (tot - v["AudioClip"]) / k))


def main() -> None:
    ctx = set(pd.read_csv(ROOT / "stimuli/audio_context_study/prompts.csv")["PromptID"])

    print("RATER-LEVEL COLUMNS — each rater's FULL session")
    print("(so every rater's SD rests on a comparable number of ratings)\n")
    hdr = f"{'condition':20}{'raters':>7}{'ratings ea':>11}{'mean':>7}{'perRaterSD':>12}{'SD<10':>10}{'tie':>7}"
    print(hdr + "\n" + "-" * len(hdr))
    full = {}
    usage_rows = []
    for lbl, path in SOURCES:
        r = rater_columns(load(path))
        full[lbl] = r
        usage_rows.append(dict(condition=lbl, scope="full session", **r))
        print(f"{lbl:20}{r['raters']:7}{r['ratings_per_rater']:11.0f}{r['mean_rating']:7.1f}"
              f"{r['per_rater_sd']:12.1f}{r['n_low']:5}/{r['raters']:<4}{r['pct_low']:3.0f}%{r['tie_rate']:7.2f}")

    print("\n\nSAME COLUMNS on the ctx-30 subset — shown only to document the artifact")
    print("(reference raters drop to ~12 ratings each, so low-SD counts inflate)\n")
    print(hdr + "\n" + "-" * len(hdr))
    for lbl, path in SOURCES:
        d = load(path)
        d = d[d["PromptID"].isin(ctx)]
        r = rater_columns(d)
        usage_rows.append(dict(condition=lbl, scope="ctx-30 subset", **r))
        print(f"{lbl:20}{r['raters']:7}{r['ratings_per_rater']:11.0f}{r['mean_rating']:7.1f}"
              f"{r['per_rater_sd']:12.1f}{r['n_low']:5}/{r['raters']:<4}{r['pct_low']:3.0f}%{r['tie_rate']:7.2f}")

    print("\n\nVARIANCE COMPONENTS — all four fit on the shared 30 audio-context prompts")
    print("(must match Table 13's ICCs, which are a property of that stimulus set)\n")
    hdr2 = f"{'condition':20}{'v_stim':>9}{'v_rater':>10}{'v_resid':>10}{'k':>7}{'ICC(2,1)':>10}{'ICC(2,k)':>10}"
    print(hdr2 + "\n" + "-" * len(hdr2))
    vc_rows = []
    for lbl, path in SOURCES:
        d = load(path)
        d = d[d["PromptID"].isin(ctx)]
        v = variance_components(d)
        print(f"{lbl:20}{v['v_stim']:9.1f}{v['v_rater']:10.1f}{v['v_resid']:10.1f}"
              f"{v['k']:7.1f}{v['icc1']:10.3f}{v['icck']:10.3f}")
        vc_rows.append(dict(condition=lbl, **v))

    print("\nICC(2,1) = v_stim / (v_stim + v_rater + v_resid)")
    print("ICC(2,k) = v_stim / (v_stim + (v_rater + v_resid) / k),  k = mean raters per clip")
    pd.DataFrame(usage_rows).to_csv(DERIVED / "scale_usage.csv", index=False)
    pd.DataFrame(vc_rows).to_csv(DERIVED / "variance_components.csv", index=False)
    print(" -> results/08_cross_study/scale_usage.csv, variance_components.csv")


if __name__ == "__main__":
    main()