HarvestForTwo / export_timing.py
princessamygdala's picture
Claude Opus 5
Carry the answer and whether it was right into the timing rows
ecc987b
Raw History Blame Contribute Delete
5.7 kB
"""<base>_timing.csv: one row per screen, in the order the participant saw them.
The Qualtrics export is one wide row per participant, which is the right shape for the
analysis it feeds and the wrong shape for "where did the session go". This writes the
screen records that screens.py logs, long, one row each, so the question can be answered
with a group-by instead of a reconstruction.
Screens come from two places. Every stage goes through effort_stages._fb or
questionnaires._fb, both of which wrap their display in screens.watch, and the intro pages
are wrapped where they are shown. A session collected before any of that existed yields an
empty file with a header, not a crash.
uv run python export_timing.py data/user_data_<seed>.msgpack
"""
import csv
import glob
import sys
from datetime import datetime
from nicewebrl.utils import read_all_records_sync
#: PsychoPy's own export carries, for every component, <name>.started and <name>.stopped in
#: seconds from the experiment clock, plus <name>.keys / .rt / .duration where the component
#: took a response, and repeats a session-metadata block on every row: date, expName,
#: psychopyVersion, OS, frameRate. See the task's own
#: example_sub-TEST3_task-sociallearning-hp_*.csv for the original. This file carries the
#: same quantities in long form: one row per component, the component named in a column
#: instead of in the column name. to_psychopy.py pivots it into the wide shape when an
#: analysis written against a Pavlovia export needs it verbatim.
#:
#: ONE CLOCK. started, stopped, duration and rt are all seconds from the earliest timestamp
#: in the session, computed here from the ISO stamps, so every row shares a zero. screens.py
#: also logs its own monotonic reading of started/stopped; that is a drift check, not the
#: number used. The ISO stamps stay in enter_iso/exit_iso, because a wall clock is what
#: tells you a participant came back the next day and a session clock is not.
#: PsychoPy's expName, repeated on every row.
EXP_NAME = "Harvest for Two"
COLUMNS = [
# ---- who and what, repeated on every row the way PsychoPy repeats it ----
"pid", "gid", "role", "rando", "STUDY_ID", "SESSION_ID",
"date", "expName", "taskVersion", "gitCommit", "OS", "browser", "frameRate",
# ---- the component ----
"component", "component_kind", "component_index",
"thisN", "thisRepN",
# ---- its clock, in seconds, PsychoPy's names ----
"started", "stopped", "duration", "rt", "keys", "corr", "n_clicks",
# ---- and the wall clock, which the session clock cannot replace ----
"enter_iso", "exit_iso",
]
def _t(s):
try:
return datetime.fromisoformat(str(s).replace("Z", ""))
except Exception:
return None
def _secs(t0, s):
"""Seconds from the session clock, PsychoPy's unit. "" when the stamp is missing."""
x = _t(s)
return "" if (x is None or t0 is None) else round((x - t0).total_seconds(), 4)
def read_screens(path):
"""(screen records oldest first, the tech record, the session clock zero)."""
screens, tech, stamps = [], {}, []
for rec in read_all_records_sync(path):
d = rec.get("data") or {}
for k in ("t", "enter", "exit"):
if d.get(k):
stamps.append(d[k])
if d.get("kind") == "tech":
tech = d
elif d.get("kind") == "screen":
screens.append(d)
t0 = min((x for x in (_t(s) for s in stamps) if x), default=None)
screens.sort(key=lambda d: d.get("exit") or "")
return screens, tech, t0
def export(path, pid=None):
screens, tech, t0 = read_screens(path)
meta = {
"gid": "", "role": tech.get("role", ""), "rando": tech.get("rando", ""),
"STUDY_ID": tech.get("study_id", ""), "SESSION_ID": tech.get("session_id", ""),
"date": (t0.isoformat(timespec="milliseconds") if t0 else ""),
"expName": EXP_NAME, "taskVersion": tech.get("game_version", ""),
"gitCommit": tech.get("git_commit", ""),
"OS": tech.get("platform", ""), "browser": tech.get("user_agent", "")[:60],
"frameRate": tech.get("framerate_fps", ""),
}
rows = []
for i, d in enumerate(screens):
started, stopped = _secs(t0, d.get("enter")), _secs(t0, d.get("exit"))
fc = d.get("first_click_ms")
rows.append({**meta,
"pid": d.get("pid", "") or (str(pid) if pid else ""),
"component": d.get("screen", ""),
"component_kind": d.get("screen_kind", ""),
"component_index": d.get("screen_index", ""),
"thisN": i, "thisRepN": d.get("screen_index", ""),
"started": started, "stopped": stopped,
"duration": ("" if "" in (started, stopped)
else round(stopped - started, 4)),
"rt": (round(fc / 1000, 4) if isinstance(fc, (int, float)) else ""),
"keys": (d.get("keys") if d.get("keys") not in (None, "")
else d.get("action", "")),
"corr": d.get("corr", ""),
"n_clicks": d.get("n_clicks", ""),
"enter_iso": d.get("enter", ""), "exit_iso": d.get("exit", "")})
out = path.rsplit(".", 1)[0] + "_timing.csv"
with open(out, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=COLUMNS)
w.writeheader()
w.writerows(rows)
print(f" wrote {out} ({len(rows)} components)")
return out
if __name__ == "__main__":
paths = sys.argv[1:] or sorted(glob.glob("data/user_data_*.msgpack"))
for p in paths:
export(p)