Skip to content

sweetbean.util.data_process

parse_autora_observations(observations, *, flatten_bot_detection=True, bot_detection_key=DEFAULT_BOT_DETECTION_KEY)

Flatten autora-collected observations into a one-row-per-trial frame.

subject_id is assigned by input order (0-indexed). prolific_pid and slot_key are pulled from the envelope when present (the patched firebase-prolific runner). bot_detection.<field> is unfolded to bot_detection_<field> columns when flatten_bot_detection=True (the default).

No filtering is applied here — that is the job of :func:participant_quality_report + :func:split_by_quality.

Source code in sweetbean/util/data_process.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def parse_autora_observations(
    observations: Iterable[Any],
    *,
    flatten_bot_detection: bool = True,
    bot_detection_key: str = DEFAULT_BOT_DETECTION_KEY,
) -> "pd.DataFrame":
    """Flatten autora-collected observations into a one-row-per-trial frame.

    `subject_id` is assigned by input order (0-indexed). `prolific_pid`
    and `slot_key` are pulled from the envelope when present (the patched
    firebase-prolific runner). `bot_detection.<field>` is unfolded to
    ``bot_detection_<field>`` columns when `flatten_bot_detection=True`
    (the default).

    No filtering is applied here — that is the job of
    :func:`participant_quality_report` + :func:`split_by_quality`.
    """
    rows: list[dict] = []
    for subject_id, obs in enumerate(observations):
        env = _normalize_observation_envelope(obs)
        for trial in env["trials"]:
            row = dict(trial)
            row["subject_id"] = subject_id
            row["prolific_pid"] = env["prolific_pid"]
            row["slot_key"] = env["slot_key"]
            if flatten_bot_detection:
                row = _flatten_bot_detection(row, key=bot_detection_key)
            rows.append(row)
    return pd.DataFrame(rows)

participant_quality_report(trials_df, *, subject_col='subject_id', response_col='bean_response', rt_col='bean_rt', valid_responses=None, single_key_threshold=0.95, min_mean_rt_ms=1200.0, alternation_threshold=0.95, drop_on_bot_flag=True, drop_on_suspicious_browser=True, drop_on_honeypot_filled=True)

Per-subject quality report with drop flags.

The report has one row per subject and includes prolific_pid / slot_key (when available on the trials frame) so that downstream code can pay every recruited participant — including those marked as drop=True — and correlate drops with their Prolific id.

Drop signals (any one true → drop=True, with the specific reason appended to drop_reason): * suspicious_browser (BotDetection) * honeypot (BotDetection) * bot_flag (BotDetection composite) * single_key — dominant_response_rate >= single_key_threshold * fast_rt — mean_rt_ms < min_mean_rt_ms * strict_alternation — strict_alternation_rate >= alternation_threshold

valid_responses, if given, restricts response-based stats (single-key rate, alternation rate, mean RT) to trials whose response_col value is in the set — i.e. screens out instructions / consent / feedback rows.

Source code in sweetbean/util/data_process.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def participant_quality_report(
    trials_df: "pd.DataFrame",
    *,
    subject_col: str = "subject_id",
    response_col: str = "bean_response",
    rt_col: str = "bean_rt",
    valid_responses: set | None = None,
    single_key_threshold: float = 0.95,
    min_mean_rt_ms: float = 1200.0,
    alternation_threshold: float = 0.95,
    drop_on_bot_flag: bool = True,
    drop_on_suspicious_browser: bool = True,
    drop_on_honeypot_filled: bool = True,
) -> "pd.DataFrame":
    """Per-subject quality report with drop flags.

    The report has one row per subject and includes ``prolific_pid`` /
    ``slot_key`` (when available on the trials frame) so that downstream
    code can pay every recruited participant — including those marked as
    `drop=True` — and correlate drops with their Prolific id.

    Drop signals (any one true → ``drop=True``, with the specific reason
    appended to ``drop_reason``):
        * suspicious_browser (BotDetection)
        * honeypot (BotDetection)
        * bot_flag (BotDetection composite)
        * single_key — `dominant_response_rate >= single_key_threshold`
        * fast_rt    — `mean_rt_ms < min_mean_rt_ms`
        * strict_alternation — `strict_alternation_rate >= alternation_threshold`

    `valid_responses`, if given, restricts response-based stats (single-key
    rate, alternation rate, mean RT) to trials whose `response_col` value is
    in the set — i.e. screens out instructions / consent / feedback rows.
    """
    columns = [
        subject_col, "prolific_pid", "slot_key",
        "n_trials", "n_valid_trials",
        "dominant_response", "dominant_response_rate",
        "strict_alternation_rate", "mean_rt_ms",
        "is_suspicious_browser", "honeypot_filled", "bot_flag",
        "focus_loss_count", "total_blur_duration_ms",
        "drop_suspicious_browser", "drop_honeypot", "drop_bot_flag",
        "drop_single_key", "drop_fast_rt", "drop_strict_alternation",
        "drop", "drop_reason",
    ]
    if trials_df.empty or subject_col not in trials_df.columns:
        return pd.DataFrame(columns=columns)

    rows: list[dict] = []
    for subject_id, sub in trials_df.groupby(subject_col, sort=True):
        n_trials = int(len(sub))
        if valid_responses is not None and response_col in sub.columns:
            valid = sub[sub[response_col].isin(valid_responses)]
        else:
            valid = sub
        n_valid = int(len(valid))

        if n_valid > 0 and response_col in valid.columns:
            counts = valid[response_col].value_counts(dropna=True)
            if not counts.empty:
                dominant_response = counts.index[0]
                dominant_response_rate = float(counts.iloc[0]) / max(1, n_valid)
            else:
                dominant_response = None
                dominant_response_rate = 0.0
            alt_rate = _strict_alternation_rate(list(valid[response_col].values))
        else:
            dominant_response = None
            dominant_response_rate = 0.0
            alt_rate = 0.0

        if rt_col in valid.columns and n_valid > 0:
            rts = pd.to_numeric(valid[rt_col], errors="coerce").dropna()
            mean_rt_ms = float(rts.mean()) if not rts.empty else None
        else:
            mean_rt_ms = None

        # BotDetection summary fields are cumulative — the last row has the
        # most up-to-date snapshot.
        last = sub.iloc[-1]
        is_susp = bool(last.get("bot_detection_is_suspicious_browser", False) or False)
        is_honeypot = bool(last.get("bot_detection_honeypot_filled", False) or False)
        is_bot_flag = bool(last.get("bot_detection_bot_flag", False) or False)
        focus_loss = int(last.get("bot_detection_focus_loss_count", 0) or 0)
        blur_ms = int(last.get("bot_detection_total_blur_duration_ms", 0) or 0)

        prolific_pid = None
        if "prolific_pid" in sub.columns:
            pids = sub["prolific_pid"].dropna().unique()
            if len(pids) > 0:
                prolific_pid = pids[0]
        slot_key = None
        if "slot_key" in sub.columns:
            sks = sub["slot_key"].dropna().unique()
            if len(sks) > 0:
                slot_key = sks[0]

        drop_susp = bool(drop_on_suspicious_browser and is_susp)
        drop_hp = bool(drop_on_honeypot_filled and is_honeypot)
        drop_bot = bool(drop_on_bot_flag and is_bot_flag)
        drop_single_key = dominant_response_rate >= float(single_key_threshold)
        drop_fast_rt = mean_rt_ms is not None and mean_rt_ms < float(min_mean_rt_ms)
        drop_alt = alt_rate >= float(alternation_threshold)

        reasons: list[str] = []
        if drop_susp: reasons.append("suspicious_browser")
        if drop_hp: reasons.append("honeypot")
        if drop_bot: reasons.append("bot_flag")
        if drop_single_key: reasons.append("single_key")
        if drop_fast_rt: reasons.append("fast_rt")
        if drop_alt: reasons.append("strict_alternation")

        rows.append({
            subject_col: subject_id,
            "prolific_pid": prolific_pid,
            "slot_key": slot_key,
            "n_trials": n_trials,
            "n_valid_trials": n_valid,
            "dominant_response": dominant_response,
            "dominant_response_rate": dominant_response_rate,
            "strict_alternation_rate": alt_rate,
            "mean_rt_ms": mean_rt_ms,
            "is_suspicious_browser": is_susp,
            "honeypot_filled": is_honeypot,
            "bot_flag": is_bot_flag,
            "focus_loss_count": focus_loss,
            "total_blur_duration_ms": blur_ms,
            "drop_suspicious_browser": drop_susp,
            "drop_honeypot": drop_hp,
            "drop_bot_flag": drop_bot,
            "drop_single_key": drop_single_key,
            "drop_fast_rt": drop_fast_rt,
            "drop_strict_alternation": drop_alt,
            "drop": bool(reasons),
            "drop_reason": ",".join(reasons),
        })

    return pd.DataFrame(rows, columns=columns)

process(stimulus_data, n_stims, idx=None)

Process list of stimulus to list of trials. For example, if the stimulus sequence is [Fixation, Text, Feedback] a list of all stimuli will be processed so that Fixation, Text and Feedback are bundled into one trial. Arguments: stimulus_data: the list of stimulus data n_stims: the number of stimuli in a sequence (3 in the above example)

Source code in sweetbean/util/data_process.py
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
def process(stimulus_data, n_stims, idx=None):
    """
    Process list of stimulus to list of trials. For example, if the stimulus sequence is
    [Fixation, Text, Feedback] a list of all stimuli will be processed so that
    Fixation, Text and Feedback are bundled into one trial.
    Arguments:
        stimulus_data: the list of stimulus data
        n_stims: the number of stimuli in a sequence (3 in the above example)
    """
    if len(stimulus_data) % n_stims != 0:
        print("Stimulus data could not be processed.")
        return []

    len_timeline = len(stimulus_data) // n_stims

    if idx is not None:
        res = [{"exp_id": idx} for _ in range(len_timeline)]
    else:
        res = [{} for _ in range(len_timeline)]
    for i, stim_dict in enumerate(stimulus_data):
        stim_index = i % n_stims
        for k, v in stim_dict.items():
            new_key = f"{k}.{stim_index}"
            res[i // n_stims][new_key] = v
    return res

process_autora(data, n_stims, as_dict=True)

Process data when using AutoRA experiment runner (https://autoresearch.github.io/autora/) Arguments: data: the data to process n_stims: the number of stimuli in a sequence (3 in the above example) as_dict: whether to return a dictionary (can be used for pandas dataframe)

Source code in sweetbean/util/data_process.py
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
def process_autora(data, n_stims, as_dict=True):
    """
    Process data when using AutoRA experiment runner (https://autoresearch.github.io/autora/)
    Arguments:
        data: the data to process
        n_stims: the number of stimuli in a sequence (3 in the above example)
        as_dict: whether to return a dictionary (can be used for pandas dataframe)
    """
    res = []
    for idx, subj_d in enumerate(data):
        try:
            _subj_d = subj_d
            if type(subj_d) == str:
                _subj_d = json.loads(subj_d)
            d = _subj_d["trials"]
            processed = process(d, n_stims, idx)
            res += processed
        except Exception as e:
            print(f"ERROR with: {subj_d}, {e}")
    if as_dict:
        _as_dict = {}
        try:
            _as_dict = _list_of_dicts_to_dataframe(res)
        except Exception as e:
            print(f"ERROR with: {res}, {e}")
        return _as_dict
    return res

split_by_quality(trials_df, report_df, *, subject_col='subject_id')

Split trials_df into (kept, dropped) based on report_df.drop.

The dropped frame gets a drop_reason column propagated from the report so per-trial audit records carry the reason for exclusion.

Source code in sweetbean/util/data_process.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def split_by_quality(
    trials_df: "pd.DataFrame",
    report_df: "pd.DataFrame",
    *,
    subject_col: str = "subject_id",
) -> tuple["pd.DataFrame", "pd.DataFrame"]:
    """Split `trials_df` into ``(kept, dropped)`` based on `report_df.drop`.

    The dropped frame gets a `drop_reason` column propagated from the
    report so per-trial audit records carry the reason for exclusion.
    """
    if (
        report_df.empty
        or "drop" not in report_df.columns
        or subject_col not in trials_df.columns
    ):
        return trials_df.copy(), trials_df.iloc[0:0].copy()
    dropped_subj = set(report_df.loc[report_df["drop"], subject_col].tolist())
    kept = trials_df[~trials_df[subject_col].isin(dropped_subj)].copy()
    dropped = trials_df[trials_df[subject_col].isin(dropped_subj)].copy()
    if not dropped.empty and "drop_reason" in report_df.columns:
        reason_map = (
            report_df.set_index(subject_col)["drop_reason"].to_dict()
        )
        dropped["drop_reason"] = dropped[subject_col].map(reason_map)
    return kept, dropped