Spaces:
Running
Name the timing columns the way PsychoPy names them
Browse filesChecked against this task's own PsychoPy export,
example_sub-TEST3_task-sociallearning-hp_2025-02-05_*.csv. Its convention is
<component>.started and <component>.stopped in seconds from the experiment
clock, <component>.keys / .rt / .duration where the component took a
response, loop counters, and a metadata block repeated on every row: date,
expName, psychopyVersion, OS, frameRate.
The timing file now carries all of those, long: one row per component, the
component named in a column instead of in the column name. Both tasks write
the identical 26 columns, asserted by a test that reads the other repo's
list, so the two can be stacked.
One clock. started, stopped, duration and rt are seconds from the earliest
stamp in the session, computed in the exporter from the ISO stamps so every
row shares a zero, including the houses and ratings that are reconstructed
from env timesteps. A rating screen's enter is not logged, so its exit is
back-dated by its own rt to give it the same shape. screens.py also records
its own monotonic reading as a drift check. The ISO stamps stay in
enter_iso/exit_iso, because a wall clock is what tells you a participant came
back the next day.
to_psychopy.py pivots the long file into the wide one-column-per-component
shape, for an analysis already written against a Pavlovia export.
Harvest had no device or version record at all, so log_tech is ported there
from this task: OS, frameRate, user agent, screen and viewport, task version
and git commit, which is where its metadata block now comes from.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Files changed (5)
- export_timing.py+84-22
- screens.py+29-5
- test_screen_timing.py+26-4
- to_psychopy.pyAdded+81
- web_app.py+50
15 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575815 unmodified linesimport globimport sysfrom nicewebrl.utils import read_all_records_syncCOLUMNS = ["pid", "screen_kind", "screen_name", "screen_index", "enter", "exit","dwell_ms", "n_clicks", "first_click_ms", "action"]def read_screens(path):"""[{...}] for every screen record in the file, oldest first."""out = []for rec in read_all_records_sync(path):d = rec.get("data") or {}if d.get("kind") != "screen":continueout.append({"pid": d.get("pid", ""),"screen_kind": d.get("screen_kind", ""),"screen_name": d.get("screen", ""),"screen_index": d.get("screen_index", ""),"enter": d.get("enter", ""), "exit": d.get("exit", ""),"dwell_ms": d.get("dwell_ms", ""),"n_clicks": d.get("n_clicks", ""),"first_click_ms": d.get("first_click_ms", ""),"action": d.get("action", "")})out.sort(key=lambda r: r["exit"] or "")return outdef export(path, pid=None):rows = read_screens(path)if pid:for r in rows:r["pid"] = r["pid"] or str(pid)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)} screens)")return out15 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912015 unmodified linesimport globimport sysfrom datetime import datetimefrom 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", "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 Nonedef _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 = delif 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, t0def 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("action", ""),"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
10 unmodified lines111213141516172 unmodified lines20212223242512 unmodified lines38394041424325 unmodified lines69707172737475767714 unmodified lines929394959697989910010110210310410 unmodified linesasync with screens.watch("post_q_effort", "questionnaire", index=3):...screen_kind intro | quiz | stage | questionnaire | consent | paymentscreen_name which screenscreen_index position within its kind, for the ones that repeatenter, exit ISO timestamps2 unmodified linesfirst_click_ms enter to the first click, which is the response time for a screenwhose answer is a clickaction what closed it, e.g. next or backClicks are tagged with the open screen's name as they are logged, so a click row says whereit happened. Every stage goes through effort_stages._fb and questionnaires._fb, so wrapping12 unmodified lines#: and JSON-safe so it survives a reload.KEY = "_screen"KINDS = ("intro", "quiz", "stage", "harvest", "night", "questionnaire", "consent","demographics", "tripm", "partner_check", "payment", "other")25 unmodified linespassdef _open(name, kind, index):rec = dict(name=str(name), kind=kind, index=("" if index is None else int(index)),enter=_now(), m=time.monotonic(), n_clicks=0, first_click_ms=None, action="")app.storage.user[KEY] = recreturn rec14 unmodified linestry:if log is None:from web_app import log_event as log # late, to avoid a cycleawait log("screen", screen=rec["name"], screen_kind=rec["kind"],screen_index=rec["index"], enter=rec["enter"], exit=_now(),dwell_ms=round((time.monotonic() - rec["m"]) * 1000),n_clicks=rec.get("n_clicks", 0),first_click_ms=(rec.get("first_click_ms")if rec.get("first_click_ms") is not None else ""),action=rec.get("action", ""))except Exception:passtry:10 unmodified lines111213141516172 unmodified lines202122232425262728293031323312 unmodified lines4647484950515253545525 unmodified lines8182838485868788899091929394959697989914 unmodified lines11411511611711811912012112212312412512612712810 unmodified linesasync with screens.watch("post_q_effort", "questionnaire", index=3):...screen_kind intro | quiz | stage | harvest | night | questionnaire | consent | paymentscreen_name which screenscreen_index position within its kind, for the ones that repeatenter, exit ISO timestamps2 unmodified linesfirst_click_ms enter to the first click, which is the response time for a screenwhose answer is a clickaction what closed it, e.g. next or backstarted seconds from the session clock to the screen appearingstopped seconds from the session clock to it being replacedTHE SESSION CLOCK. `started` and `stopped` are PsychoPy's `<component>.started` and`<component>.stopped`: seconds, float, measured from the first screen of the session.PsychoPy's own files carry nothing else, so an analysis written against a Pavlovia exportreads these columns unchanged. The ISO timestamps stay alongside them, because a wallclock is what tells you a participant came back the next day and a session clock is not.Clicks are tagged with the open screen's name as they are logged, so a click row says whereit happened. Every stage goes through effort_stages._fb and questionnaires._fb, so wrapping12 unmodified lines#: and JSON-safe so it survives a reload.KEY = "_screen"#: Session clock zero, set by the first screen. PsychoPy starts its global clock when the#: experiment window opens; the first screen is this task's equivalent.T0 = "_screen_t0"KINDS = ("intro", "quiz", "stage", "harvest", "night", "questionnaire", "consent","demographics", "tripm", "partner_check", "payment", "other")25 unmodified linespassdef _elapsed():"""Seconds since the session clock started, starting it if this is the first screen."""now = time.monotonic()t0 = app.storage.user.get(T0)if t0 is None:app.storage.user[T0] = t0 = nowreturn round(now - t0, 4)def _open(name, kind, index):rec = dict(name=str(name), kind=kind, index=("" if index is None else int(index)),enter=_now(), m=time.monotonic(), started=_elapsed(),n_clicks=0, first_click_ms=None, action="")app.storage.user[KEY] = recreturn rec14 unmodified linestry:if log is None:from web_app import log_event as log # late, to avoid a cyclefc = rec.get("first_click_ms")await log("screen", screen=rec["name"], screen_kind=rec["kind"],screen_index=rec["index"], enter=rec["enter"], exit=_now(),dwell_ms=round((time.monotonic() - rec["m"]) * 1000),n_clicks=rec.get("n_clicks", 0),first_click_ms=(fc if fc is not None else ""),action=rec.get("action", ""),started=rec.get("started", ""), stopped=_elapsed(),rt=(round(fc / 1000, 4) if fc is not None else ""))except Exception:passtry:
35 unmodified lines363738394041424344458 unmodified lines54555635 unmodified linesassert used <= set(screens.KINDS)def test_the_timing_file_names_a_clock_and_a_place():for col in ("screen_kind", "screen_name", "enter", "exit", "dwell_ms","n_clicks", "first_click_ms", "action"):assert col in export_timing.COLUMNSdef test_a_session_with_no_screen_records_gives_a_header_and_no_crash(tmp_path):8 unmodified linesout = export_timing.export(str(dst), pid="test")rows = list(csv.DictReader(open(out)))assert rows == []35 unmodified lines363738394041424344454647484950515253545556575859606162636465668 unmodified lines7576777835 unmodified linesassert used <= set(screens.KINDS)def test_the_timing_columns_follow_psychopy():# PsychoPy names these five per component and repeats a metadata block on every row.for col in ("started", "stopped", "duration", "rt", "keys","date", "expName", "OS", "frameRate", "component", "component_kind"):assert col in export_timing.COLUMNS, coldef test_the_session_clock_shares_one_zero():# started/stopped are seconds from the earliest stamp in the file, like PsychoPy's# global clock, so the first component starts at or near 0.from datetime import datetimet0 = datetime(2026, 1, 1, 10, 0, 0)assert export_timing._secs(t0, "2026-01-01T10:00:00Z") == 0.0assert export_timing._secs(t0, "2026-01-01T10:00:12.500Z") == 12.5assert export_timing._secs(t0, "") == ""def test_the_wide_pivot_names_columns_the_psychopy_way():import to_psychopyrows = [{"pid": "1", "component": "Harvest1", "component_kind": "harvest","started": "3.0", "stopped": "60.0", "duration": "57.0", "rt": "1.2","keys": "next", "thisN": "0", "thisRepN": "0"}]cols, wide = to_psychopy.pivot(rows)assert "Harvest1.started" in cols and "Harvest1.rt" in colsassert wide[0]["Harvest1.stopped"] == "60.0"def test_a_session_with_no_screen_records_gives_a_header_and_no_crash(tmp_path):8 unmodified linesout = export_timing.export(str(dst), pid="test")rows = list(csv.DictReader(open(out)))assert rows == []assert open(out).readline().strip().split(",") == export_timing.COLUMNS
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Pivot a long timing CSV into PsychoPy's wide shape.
PsychoPy writes one row per trial and one column per component, named`<component>.started`, `<component>.stopped`, `<component>.duration`, `<component>.keys`,`<component>.rt`, with a session-metadata block repeated on every row. The task's ownexample_sub-TEST3_task-sociallearning-hp_*.csv is the reference.
The timing CSV holds the same numbers one row per component, which is the better shape formost questions. This exists for the ones where it is not: an analysis already writtenagainst a Pavlovia export, or a reviewer who wants the familiar file.
Repeated components (a house, a rating, a quiz question) become one row each, in order, sothe file reads like PsychoPy's trial loop. Components that appear once sit on the first row,the way PsychoPy puts an instruction screen's onset on the row that was current when it ran.
uv run python to_psychopy.py <base>_timing.csv"""import csvimport sys
#: Repeated on every row, exactly as PsychoPy repeats its own.META = ["pid", "gid", "role", "rando", "STUDY_ID", "SESSION_ID", "date", "expName", "taskVersion", "gitCommit", "OS", "browser", "frameRate"]
#: The suffixes PsychoPy hangs off a component name.SUFFIXES = [("started", "started"), ("stopped", "stopped"), ("duration", "duration"), ("keys", "keys"), ("rt", "rt")]
#: Which kinds repeat enough to deserve a row of their own, in the order they run.LOOP_KINDS = ("house", "harvest", "night", "rating", "quiz")
def pivot(rows): """(column order, wide rows).""" if not rows: return META, [] meta = {k: rows[0].get(k, "") for k in META} loop = [r for r in rows if r.get("component_kind") in LOOP_KINDS] once = [r for r in rows if r.get("component_kind") not in LOOP_KINDS]
# one row per repeated component, in order; everything else on the first row out = [dict(meta) for _ in range(max(len(loop), 1))] cols = list(META)
def put(i, comp, r): for suf, src in SUFFIXES: col = f"{comp}.{suf}" if col not in cols: cols.append(col) out[i][col] = r.get(src, "")
for r in once: put(0, r["component"], r) for i, r in enumerate(loop): put(i, r["component"], r) for extra, src in (("thisN", "thisN"), ("thisRepN", "thisRepN")): if extra not in cols: cols.append(extra) out[i][extra] = r.get(src, "") return cols, out
def convert(path): rows = list(csv.DictReader(open(path, newline=""))) cols, wide = pivot(rows) out = path.replace("_timing.csv", "_psychopy.csv") if out == path: out = path.rsplit(".", 1)[0] + "_psychopy.csv" with open(out, "w", newline="") as f: w = csv.DictWriter(f, fieldnames=cols, restval="") w.writeheader() w.writerows(wide) print(f" wrote {out} ({len(wide)} rows, {len(cols)} columns)") return out
if __name__ == "__main__": if not sys.argv[1:]: sys.exit(__doc__) for p in sys.argv[1:]: convert(p)589 unmodified lines590591592593594595353 unmodified lines949950951952953954589 unmodified lines# ========================================ui.on("key_pressed", lambda e: global_handle_key_press(e, stage_container))setup_telemetry()# dev/debug: skip every stage before the requested start pointdev_skip = set()353 unmodified lines"window.emitEvent('app_click',{label:(b?b.innerText:'').slice(0,50),""tag:(e.target.tagName||''),x:e.clientX,y:e.clientY});},true);</script>")async def log_arrival(pid, role, theme, dev, user_agent):"""Write one roster row to <repo>/randomization_log.csv the moment we know who589 unmodified lines590591592593594595596353 unmodified lines95095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004589 unmodified lines# ========================================ui.on("key_pressed", lambda e: global_handle_key_press(e, stage_container))setup_telemetry()ui.timer(0.6, log_tech, once=True)# dev/debug: skip every stage before the requested start pointdev_skip = set()353 unmodified lines"window.emitEvent('app_click',{label:(b?b.innerText:'').slice(0,50),""tag:(e.target.tagName||''),x:e.clientX,y:e.clientY});},true);</script>")GAME_VERSION = "harvest-for-two 1.0"def _git_commit():try:import subprocessreturn subprocess.run(["git", "rev-parse", "--short", "HEAD"], capture_output=True,text=True, timeout=3, cwd=os.path.dirname(os.path.abspath(__file__))).stdout.strip()except Exception:return ""GIT_COMMIT = _git_commit()async def log_tech():"""Capture the participant's device, browser, version and framerate once, via JS.PsychoPy writes OS, frameRate, expName and psychopyVersion into every row of its export.This is where the equivalents come from. Ported from task_sl-cu-nicewebrl, which has hadit since the pilot; this task had none of it."""try:raw = await ui.run_javascript('''JSON.stringify({user_agent: navigator.userAgent, platform: navigator.platform||"",language: navigator.language||"", timezone: (Intl.DateTimeFormat().resolvedOptions().timeZone)||"",cpu_cores: navigator.hardwareConcurrency||"", device_memory_gb: navigator.deviceMemory||"",screen_w: screen.width, screen_h: screen.height, device_pixel_ratio: window.devicePixelRatio,viewport_w: window.innerWidth, viewport_h: window.innerHeight })''', timeout=8)info = json.loads(raw)fps = await ui.run_javascript('''new Promise(res=>{let n=0,s=performance.now();function fr(t){n++; if(t-s>=600){res(Math.round(n*1000/(t-s)))} else requestAnimationFrame(fr);}requestAnimationFrame(fr);})''', timeout=8)import importlib.metadata as _mdtry:nv = _md.version("nicewebrl")except Exception:nv = ""await log_event("tech", game_version=GAME_VERSION, git_commit=GIT_COMMIT,nicewebrl_version=nv, framerate_fps=fps,dev_mode=int(bool(app.storage.user.get("dev_mode"))),prolific_pid=app.storage.user.get("prolific_pid", ""),study_id=app.storage.user.get("study_id", ""),session_id=app.storage.user.get("session_id", ""),role=app.storage.user.get("role", ""),**info)except Exception as e:logger.warning(f"log_tech failed: {e}")async def log_arrival(pid, role, theme, dev, user_agent):"""Write one roster row to <repo>/randomization_log.csv the moment we know who