File size: 32,354 Bytes
bd2c7cd
356440a
 
 
bd2c7cd
81f9092
 
 
bd2c7cd
356440a
 
bd2c7cd
 
 
c72006e
bd2c7cd
bf22a94
bd2c7cd
 
 
81f9092
 
 
 
 
 
bd2c7cd
 
 
356440a
 
cb32d35
bd2c7cd
356440a
bf22a94
9538496
 
 
 
81f9092
4c42592
81f9092
 
 
c7a3196
 
81f9092
c7a3196
6fe78ac
 
 
 
 
 
81f9092
f137ac4
 
 
bf22a94
 
 
 
f137ac4
81f9092
3421e60
6fe78ac
81f9092
bf22a94
81f9092
c7a3196
4895777
 
f137ac4
 
6fe78ac
356440a
cb32d35
9538496
c72006e
 
356440a
 
bd2c7cd
 
 
 
 
 
 
 
356440a
d927f2d
bd2c7cd
 
81f9092
 
 
 
 
 
 
 
 
 
 
 
 
f137ac4
 
 
 
 
 
 
 
 
 
 
 
 
bd2c7cd
 
 
 
 
356440a
 
6fe78ac
 
 
356440a
81f9092
c7a3196
9538496
cb32d35
9538496
 
c7a3196
 
f137ac4
5567807
356440a
bd2c7cd
356440a
81f9092
 
 
356440a
bd2c7cd
 
 
 
 
 
 
33175c1
356440a
81f9092
3421e60
81f9092
 
356440a
81f9092
6fe78ac
 
 
 
 
bd2c7cd
 
c72006e
 
 
 
 
 
 
 
 
c7a3196
 
 
 
 
 
 
 
 
 
 
 
 
f137ac4
 
 
 
 
 
 
 
 
 
bf22a94
f137ac4
bf22a94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f137ac4
 
5567807
 
c72006e
 
e8598c4
c72006e
 
 
 
c7a3196
 
356440a
bd2c7cd
 
 
81f9092
 
 
 
bd2c7cd
6fe78ac
 
 
 
 
bd2c7cd
 
356440a
c7a3196
6fe78ac
 
356440a
 
bd2c7cd
356440a
81f9092
9538496
81f9092
356440a
81f9092
 
9538496
 
cb32d35
 
 
 
81f9092
 
 
 
 
 
 
c7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356440a
9538496
81f9092
9538496
 
 
356440a
 
 
 
81f9092
356440a
81f9092
356440a
81f9092
4c42592
356440a
81f9092
 
 
 
 
 
c7a3196
 
356440a
 
c7a3196
 
 
6fe78ac
 
 
 
 
 
c7a3196
356440a
 
 
c7a3196
6fe78ac
 
356440a
 
 
 
9538496
81f9092
bf22a94
 
 
 
 
356440a
81f9092
356440a
81f9092
 
 
c72006e
bf22a94
81f9092
 
c7a3196
 
f137ac4
4895777
 
 
 
 
f137ac4
 
 
 
 
 
 
 
 
 
81f9092
 
 
cb32d35
 
 
 
 
 
 
 
9538496
 
 
 
 
81f9092
 
 
5567807
 
 
 
 
 
 
 
 
 
 
 
 
6fe78ac
 
 
 
 
 
bf22a94
 
 
81f9092
 
 
 
 
356440a
bf22a94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356440a
 
 
bd2c7cd
 
356440a
 
bf22a94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356440a
bd2c7cd
 
 
 
 
356440a
bd2c7cd
 
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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
341
342
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
"""
Export a participant's NiceWebRL data into ONE combined CSV (long format), modelled on
the OG PsychoPy file: trial rows + quiz rows + rating rows + a summary row, sharing one
column set (cells empty where not applicable). Filter by `row_type`.

Outcomes are stored as +1 / 0 / -1 (`self_outcome`, `other_outcome`); the raw shown coin
value (+100 / 0 / -100) is kept alongside in `shown_self_outcome` / `shown_other_outcome`.

Usage:
  uv run python export_csv.py                 # all data/user_data_*.msgpack -> *_data.csv
  uv run python export_csv.py path/file.msgpack
"""
import csv
import glob
import json
import sys
from datetime import datetime, timedelta

from nicewebrl.utils import read_all_records_sync

import sprites
try:
    import orders
except Exception:
    orders = None

LETTERS = ["A", "B", "C", "D"]
PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
PAIR_STR = {i: LETTERS[a] + LETTERS[b] for i, (a, b) in enumerate(PAIRS)}
HOUSE_NAMES = ["castle", "cottage", "mansion", "treehouse", "tower", "barn", "windmill",
               "igloo", "tent", "pagoda", "lighthouse", "log cabin", "forest hut"]
M_CHOICE, M_OUTCOME, M_RATING = 1, 2, 3

COLUMNS = [
    "row_type", "pid", "gid", "role", "rando", "orderID", "practice",
    # ---- trial ---- (blockIndex = experienced block 0..11 = OG block order; physical_* = the
    #                  house it happened in; float_order = which avatar's coin animates first)
    "blockIndex", "trialIndex", "physical_place", "physical_house", "float_order",
    "option_pairs", "option_left", "option_right",
    "left_stim", "left_stim_desc", "right_stim", "right_stim_desc",
    "chosen_side", "chosen_key", "chosen_option", "chosen_stim", "chosen_stim_desc",
    "self_outcome", "other_outcome", "shown_self_outcome", "shown_other_outcome",
    "A_self", "A_other", "B_self", "B_other",
    "C_self", "C_other", "D_self", "D_other",
    "better_self_option", "chose_better_self",
    "better_other_option", "chose_better_other",
    "cumulPts_self", "cumulPts_other",
    "choice_rt_ms", "outcome_view_ms", "choice_time", "outcome_time",
    # The four PsychoPy trial landmarks. nicewebrl stamps image_seen_time and
    # action_taken_time on every record and this file used both only to subtract them,
    # so the onsets themselves were thrown away although they were always recorded.
    # pre_choice_ms and choice_to_outcome_ms stand in for the PsychoPy task's ITI_dur
    # and ISI_dur: there is no jitter here, so they are measured, not drawn.
    "stim_onset", "outcome_onset", "pre_choice_ms", "choice_to_outcome_ms",
    "house_type", "house_name", "displayedtarget",
    # ---- break / slide / click events ----
    "event_kind", "event_time", "break_start", "break_end", "break_ms",
    "slide_name", "slide_phase", "dwell_ms",
    # ---- per-screen timing (see screens.py) ----
    "screen_name", "screen_kind", "screen_index", "screen_enter", "screen_exit",
    "screen_dwell_ms", "screen_n_clicks", "screen_first_click_ms", "screen_action",
    "screen_keys", "screen_corr",
    "click_label", "click_tag", "click_x", "click_y",
    # ---- quiz ----
    "quizIndex", "quiz_position", "quiz_statement", "quiz_answer", "quiz_correct_answer",
    "quiz_is_correct", "quiz_attempt", "quiz_feedback",
    # ---- rating ----
    "rating_blockIndex", "rating_pair", "preferred_box_0to6", "rating_time", "rating_rt_ms",
    # ---- summary ----
    "started_at", "ended_at", "duration_min", "n_breaks", "total_break_ms",
    "game_version", "git_commit", "dev_mode", "prolific_pid", "study_id", "session_id",
    "nicewebrl_version", "framerate_fps", "browser", "os",
    "screen_w", "screen_h", "device_pixel_ratio", "viewport_w", "viewport_h",
    "language", "timezone", "cpu_cores", "user_agent",
    "partner_id", "partner_avatar_idx", "partner_avatar_gender", "partner_relation",
    "total_self", "total_partner", "money_self", "money_partner",
    "stim_by_block", "stim_desc_by_block",
    "house_by_block", "place_by_block", "house_by_place", "pos_by_place", "blocks_visited_order",
    # ---- post-game questionnaire (see questionnaires.py) ----
    "questionnaire_name", "measure", "responses_json",
]


def _ms(a, b):
    try:
        return round((datetime.fromisoformat(b) - datetime.fromisoformat(a)).total_seconds() * 1000)
    except Exception:
        return ""


def _money(pts):
    return round(max(0.0, min(6.0, (pts or 0) / 100.0)), 2)   # 10-coin scale -> $1 per 100 coins


def _sign(v):
    """+/-100/0 (or any magnitude) -> +1 / 0 / -1."""
    v = int(v)
    return (v > 0) - (v < 0)


def _desc(sid):
    try:
        return sprites.stim_describe(int(sid))
    except Exception:
        return ""


def _parse_ua(ua):
    """Rough browser/OS from a user-agent string (raw UA is kept too)."""
    ua = ua or ""
    browser = next((b for b in ("Edg", "OPR", "Chrome", "Firefox", "Safari")
                    if b in ua), "")
    browser = {"Edg": "Edge", "OPR": "Opera"}.get(browser, browser)
    os_name = next((name for key, name in (
        ("Windows", "Windows"), ("Mac OS", "macOS"), ("iPhone", "iOS"),
        ("iPad", "iPadOS"), ("Android", "Android"), ("Linux", "Linux"))
        if key in ua), "")
    return browser, os_name


def export(path):
    records = read_all_records_sync(path)
    if not records:
        print(f"  (no records in {path})")
        return
    rows = []
    pending_rt = None        # choice RT, captured at the directional keypress
    pending_stim_onset = None    # when the two chests appeared, off the choice record
    pending_pre_choice = None    # idle time before they did, the ITI analogue
    prev_action_end = None       # the previous record's action, to measure that idle time
    last_main_cum = (0, 0)
    first_ts, last_ts = None, None
    pending_choice_time = None
    visited = []             # physical places in entry order (= block order)
    block2stim = {}          # block -> (left_letter, left_stim, right_letter, right_stim), ground truth
    block2house = {}         # block -> physical house name
    block2place = {}         # block -> physical place index
    breaks = []              # (start_iso, end_iso, ms)
    break_open = None        # start time of a break awaiting its 'end'
    tech = {}                # device/browser/version info for the summary row
    partner = {}             # the partner this session was actually shown, if it recorded one
    base = dict.fromkeys(COLUMNS, "")

    def info(d):
        pid = str(d.get("pid", ""))
        return dict(pid=pid, gid=d.get("gid", ""),
                    orderID=orders.parse_pid(pid)[1] if orders and pid else pid[1:],
                    practice=int(d.get("practice", 0)))

    for rec in records:
        name = rec.get("name", "")
        meta = rec.get("metadata", {})
        d = rec.get("data", {})

        if meta.get("type") == "FeedbackStage" and name.lower().startswith("quiz"):
            for r in d.get("responses", []):
                rows.append({**base, "row_type": "quiz",
                             "quizIndex": r.get("quizIndex"),
                             "quiz_position": r.get("position", ""),
                             "quiz_statement": r.get("statement", ""),
                             "quiz_answer": r.get("answer"),
                             "quiz_correct_answer": r.get("correct_answer"),
                             "quiz_is_correct": r.get("is_correct"),
                             "quiz_attempt": r.get("attempt", ""),
                             # the text shown after answering. Held in the quiz table all
                             # along and never written down, so a transcript of what the
                             # participant was told could not be rebuilt.
                             "quiz_feedback": r.get("feedback", "")})
            continue

        if meta.get("type") == "FeedbackStage" and name.startswith("PostTask_"):
            # one row per post-game questionnaire battery (see questionnaires.py); the
            # individual slider/text answers are kept as a JSON blob rather than exploding
            # into dozens of one-off columns
            rows.append({**base, "row_type": "questionnaire",
                         "questionnaire_name": name, "measure": d.get("measure", ""),
                         "responses_json": json.dumps(d, default=str)})
            continue

        if meta.get("type") == "Event":
            kind = d.get("kind", "")
            if kind == "break":
                if d.get("phase") == "start":
                    break_open = d.get("t")
                elif d.get("phase") == "end":
                    ms = d.get("break_ms", "")
                    rows.append({**base, "row_type": "break", "event_kind": "break",
                                 "pid": d.get("pid", ""), "gid": d.get("gid", ""),
                                 "break_start": break_open or "", "break_end": d.get("t", ""),
                                 "break_ms": ms})
                    breaks.append((break_open, d.get("t"), ms))
                    break_open = None
            elif kind == "slide":
                rows.append({**base, "row_type": "slide", "event_kind": "slide",
                             "pid": d.get("pid", ""), "gid": d.get("gid", ""),
                             "slide_name": d.get("slide", ""), "slide_phase": d.get("phase", ""),
                             "dwell_ms": d.get("dwell_ms", ""), "event_time": d.get("t", "")})
            elif kind == "click":
                rows.append({**base, "row_type": "click", "event_kind": "click",
                             "pid": d.get("pid", ""), "gid": d.get("gid", ""),
                             "click_label": d.get("label", ""), "click_tag": d.get("tag", ""),
                             "click_x": d.get("x", ""), "click_y": d.get("y", ""),
                             "screen_name": d.get("screen", ""),
                             "event_time": d.get("t", "")})
            elif kind == "screen":
                rows.append({**base, "row_type": "screen", "event_kind": "screen",
                             "pid": d.get("pid", ""), "gid": d.get("gid", ""),
                             "screen_name": d.get("screen", ""),
                             "screen_kind": d.get("screen_kind", ""),
                             "screen_index": d.get("screen_index", ""),
                             "screen_enter": d.get("enter", ""),
                             "screen_exit": d.get("exit", ""),
                             "screen_dwell_ms": d.get("dwell_ms", ""),
                             "screen_n_clicks": d.get("n_clicks", ""),
                             "screen_first_click_ms": d.get("first_click_ms", ""),
                             "screen_action": d.get("action", ""),
                             "screen_keys": d.get("keys", ""),
                             "screen_corr": d.get("corr", ""),
                             "event_time": d.get("exit", "") or d.get("t", "")})
            elif kind == "tech":
                tech = d
            elif kind == "partner":
                partner = d
            elif kind == "error":
                # diagnostic side-channel for stuck-game reports (see experiment_structure.py
                # _log_glitch), reuses the click_label/click_tag columns for where/message
                rows.append({**base, "row_type": "error", "event_kind": "error",
                             "pid": d.get("pid", ""), "gid": d.get("gid", ""),
                             "click_label": d.get("where", ""), "click_tag": d.get("message", ""),
                             "event_time": d.get("t", "")})
            continue

        if meta.get("type") != "EnvStage":
            continue
        mode = d.get("mode")
        action = d.get("action_name")
        if d.get("image_seen_time"):
            first_ts = first_ts or d["image_seen_time"]
        if d.get("action_taken_time"):
            last_ts = d["action_taken_time"]
        rt = _ms(d.get("image_seen_time"), d.get("action_taken_time"))
        # Advance the previous-action clock here, unconditionally, keeping the old value
        # for the branch below. Doing it at the end of the loop body would skip whenever
        # a branch bails out early.
        prev_end_for_idle, prev_action_end = (
            prev_action_end, d.get("action_taken_time") or prev_action_end)

        if mode == M_CHOICE and action in ("left", "right"):
            pending_rt = rt
            pending_choice_time = d.get("action_taken_time", "")
            pending_stim_onset = d.get("image_seen_time", "")
            pending_pre_choice = _ms(prev_end_for_idle, pending_stim_onset)

        elif mode == M_OUTCOME and action == "continue":
            pc = int(d["pair_code"])
            ht = int(d.get("house_type", 0))
            practice = int(d.get("practice", 0))
            blk = int(d.get("block", d.get("place", 0)))
            if practice == 0:
                last_main_cum = (int(d["self_coins"]), int(d["other_coins"]))
                if int(d["place"]) not in visited:
                    visited.append(int(d["place"]))
                block2house[blk] = HOUSE_NAMES[ht] if ht < len(HOUSE_NAMES) else ht
                block2place[blk] = int(d["place"])
                # every one of the 24 chests is unique to its (block, letter) slot now, so this
                # must be recorded per BLOCK, not per letter (a letter's look varies block to block)
                block2stim[blk] = (int(d["left_letter"]), int(d.get("left_stim", -1)),
                                   int(d["right_letter"]), int(d.get("right_stim", -1)))
            # per-option outcomes this trial -> A_self ... D_other (only the 2 in this pair)
            per_opt = {}
            for k in (0, 1):
                lt = int(d.get(f"opt{k}_letter", -1))
                if 0 <= lt < 4:
                    per_opt[f"{LETTERS[lt]}_self"] = _sign(d.get(f"opt{k}_self", 0))
                    per_opt[f"{LETTERS[lt]}_other"] = _sign(d.get(f"opt{k}_other", 0))
            # which option is "better" by its underlying reward profile (not this trial's draw)
            ll, rl, cl = int(d["left_letter"]), int(d["right_letter"]), int(d.get("chosen_letter", -1))
            bs = bo = ""
            chose_bs = chose_bo = ""
            if orders:
                sg = orders.LETTER_SELF_GOOD
                og = orders.LETTER_OTHER_GOOD
                if sg[ll] != sg[rl]:
                    bs = LETTERS[ll] if sg[ll] > sg[rl] else LETTERS[rl]
                    chose_bs = int(0 <= cl < 4 and LETTERS[cl] == bs)
                else:
                    bs = "tie"
                if og[ll] != og[rl]:
                    bo = LETTERS[ll] if og[ll] > og[rl] else LETTERS[rl]
                    chose_bo = int(0 <= cl < 4 and LETTERS[cl] == bo)
                else:
                    bo = "tie"
            rows.append({**base, **info(d), "row_type": "trial",
                         "blockIndex": ("practice" if practice else blk),
                         "trialIndex": int(d["trial"]),
                         "physical_place": int(d["place"]),
                         "physical_house": HOUSE_NAMES[ht] if ht < len(HOUSE_NAMES) else ht,
                         "float_order": ("you-first" if int(d.get("float_order", 0)) == 0 else "partner-first"),
                         "option_pairs": PAIR_STR.get(pc, ""),
                         "option_left": LETTERS[int(d["left_letter"])],
                         "option_right": LETTERS[int(d["right_letter"])],
                         "left_stim": int(d.get("left_stim", -1)),
                         "left_stim_desc": _desc(d.get("left_stim", -1)),
                         "right_stim": int(d.get("right_stim", -1)),
                         "right_stim_desc": _desc(d.get("right_stim", -1)),
                         "chosen_side": ("left" if int(d["chosen_side"]) == 0 else "right"),
                         "chosen_key": ("ArrowLeft" if int(d["chosen_side"]) == 0 else "ArrowRight"),
                         "chosen_option": (LETTERS[cl] if 0 <= cl < 4 else ""),   # chosen letter A-D (for RL fitting)
                         "chosen_stim": int(d.get("chosen_stim", -1)),
                         "chosen_stim_desc": _desc(d.get("chosen_stim", -1)),
                         "self_outcome": _sign(d["self_outcome"]),
                         "other_outcome": _sign(d["other_outcome"]),
                         "shown_self_outcome": int(d["self_outcome"]),
                         "shown_other_outcome": int(d["other_outcome"]),
                         **per_opt,
                         "better_self_option": bs, "chose_better_self": chose_bs,
                         "better_other_option": bo, "chose_better_other": chose_bo,
                         "cumulPts_self": int(d["self_coins"]), "cumulPts_other": int(d["other_coins"]),
                         "choice_rt_ms": pending_rt if pending_rt is not None else "",
                         "outcome_view_ms": rt,
                         "choice_time": pending_choice_time or "",
                         "outcome_time": d.get("action_taken_time", ""),
                         "stim_onset": pending_stim_onset or "",
                         "outcome_onset": d.get("image_seen_time", ""),
                         "pre_choice_ms": (pending_pre_choice
                                           if pending_pre_choice is not None else ""),
                         "choice_to_outcome_ms": _ms(pending_choice_time,
                                                     d.get("image_seen_time")),
                         "house_type": ht,
                         "house_name": HOUSE_NAMES[ht] if ht < len(HOUSE_NAMES) else ht,
                         "displayedtarget": "both"})
            pending_rt = None
            pending_choice_time = None
            pending_stim_onset = None
            pending_pre_choice = None

        elif mode == M_RATING and action == "continue":
            pc = int(d["pair_code"])
            rows.append({**base, **info(d), "row_type": "rating",
                         "rating_blockIndex": ("practice" if int(d.get("practice", 0)) else int(d.get("block", d.get("place", 0)))),
                         "rating_pair": PAIR_STR.get(pc, ""),
                         "preferred_box_0to6": int(d["rating_cursor"]),
                         # The rating lives inside the env, so it has the same clock as a
                         # trial: when the screen was answered, and how long it was up.
                         "rating_time": d.get("action_taken_time", ""),
                         "rating_rt_ms": rt})

    # ---- summary row ----
    last = next((r for r in reversed(rows) if r["pid"]), {})
    pid = last.get("pid", "")
    summ = {**base, "row_type": "summary",
            "pid": pid, "gid": last.get("gid", ""), "orderID": last.get("orderID", ""),
            "role": tech.get("role", ""),
            "rando": tech.get("rando", ""),
            "started_at": first_ts or "", "ended_at": last_ts or "",
            "duration_min": _ms(first_ts, last_ts) / 60000.0 if first_ts and last_ts else "",
            "n_breaks": len(breaks),
            "total_break_ms": sum(int(b[2]) for b in breaks if str(b[2]).lstrip("-").isdigit()),
            "game_version": tech.get("game_version", ""),
            "git_commit": tech.get("git_commit", ""),
            "dev_mode": tech.get("dev_mode", ""),
            "prolific_pid": tech.get("prolific_pid", ""),
            "study_id": tech.get("study_id", ""),
            "session_id": tech.get("session_id", ""),
            "nicewebrl_version": tech.get("nicewebrl_version", ""),
            "framerate_fps": tech.get("framerate_fps", ""),
            "user_agent": tech.get("user_agent", ""),
            "browser": _parse_ua(tech.get("user_agent", ""))[0],
            "os": _parse_ua(tech.get("user_agent", ""))[1],
            "screen_w": tech.get("screen_w", ""), "screen_h": tech.get("screen_h", ""),
            "device_pixel_ratio": tech.get("device_pixel_ratio", ""),
            "viewport_w": tech.get("viewport_w", ""), "viewport_h": tech.get("viewport_h", ""),
            "language": tech.get("language", ""), "timezone": tech.get("timezone", ""),
            "cpu_cores": tech.get("cpu_cores", ""),
            "total_self": last_main_cum[0], "total_partner": last_main_cum[1],
            "money_self": _money(last_main_cum[0]), "money_partner": _money(last_main_cum[1]),
            "blocks_visited_order": "_".join(str(b) for b in visited)}
    # box assignment straight from what the participant actually saw (ground truth), one
    # entry per BLOCK since every chest look is unique to its (block, letter) slot
    summ["stim_by_block"] = "_".join(
        f"{b}:{LETTERS[ll]}{ls}-{LETTERS[rl]}{rs}"
        for b, (ll, ls, rl, rs) in sorted(block2stim.items()))
    summ["stim_desc_by_block"] = "_".join(
        f"{b}:{LETTERS[ll]}={_desc(ls)}|{LETTERS[rl]}={_desc(rs)}"
        for b, (ll, ls, rl, rs) in sorted(block2stim.items()))
    # which physical house each experienced BLOCK happened in
    summ["house_by_block"] = "_".join(f"{b}:{block2house[b]}" for b in sorted(block2house))
    summ["place_by_block"] = "_".join(f"{b}:{block2place[b]}" for b in sorted(block2place))
    summ["house_by_place"] = "_".join(
        f"{block2place[b]}:{block2house[b]}" for b in sorted(block2place))
    # house positions aren't logged per trial, so re-derive them from the PID (best effort)
    if orders and pid:
        try:
            # The partner the session recorded beats any re-derivation: since 2026-11-09
            # the number follows `rando` (orders.partner_id_for), so deriving it from the
            # pid alone would print a different stranger for the same session. A session
            # with no "partner" event predates that change and was seeded off the pid, so
            # the pid-only derivation is the right fallback for exactly those.
            if partner.get("partner_id"):
                summ["partner_id"] = partner["partner_id"]
                summ["partner_avatar_idx"] = partner.get("partner_avatar_idx", "")
                summ["partner_avatar_gender"] = partner.get("partner_avatar_gender", "")
            else:
                summ["partner_id"] = orders.partner_id_for(pid)
                summ["partner_avatar_idx"], summ["partner_avatar_gender"] = \
                    orders.partner_avatar_for(pid)
            # What the participant was told the partner is. Constant for now, as it was
            # in the PsychoPy task, and written down rather than assumed by a later reader:
            # the partner is an anonymous community-database member in every arm, including
            # the BEAR dyad arm, where the family member is the imagined player in the
            # questionnaire and never the partner.
            summ["partner_relation"] = "stranger"
            _rando = tech.get("rando") or None
            o = orders.make_order(pid, tech.get("role", ""),
                                  int(_rando) if _rando else None)
            summ["pos_by_place"] = "_".join(
                f"{i}:({r},{c})" for i, (r, c) in enumerate(o["house_pos"].tolist()))
        except Exception as e:
            print(f"  (could not attach positions for {pid}: {e})")
    rows.append(summ)

    # role on EVERY row, not just the summary. In a BEAR dyad a parent and their child share
    # one participant ID and one data folder, so the role is the only thing telling their
    # trials apart, and a reader who filters row_type=="trial" would otherwise lose it. It is
    # filled here rather than in `base` because `tech` only arrives partway through the
    # stream. Empty string outside dyad mode, exactly as before.
    # The houses and the rating screens are not wrapped in screens.watch: they run inside
    # the JAX env, where every timestep already carries its own clock. Their screen records
    # are built from those, so the timing file covers the whole session and not only the
    # parts made of widgets. Built here, before the pass below stamps every row.
    rows += _game_screens(rows, base)

    _role = tech.get("role", "")
    _rando_col = tech.get("rando", "")
    for _r in rows:
        _r["role"] = _role
        _r["rando"] = _rando_col

    out = path.rsplit(".", 1)[0] + "_data.csv"
    with open(out, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=COLUMNS)
        w.writeheader()
        w.writerows(rows)
    n_tr = sum(1 for r in rows if r["row_type"] == "trial")
    print(f"  wrote {out}  ({n_tr} trials, {len(rows)} rows)")

    timing = _write_timing(rows, path, tech)
    return out, timing


#: PsychoPy's expName, repeated on every row.
EXP_NAME = "Treasure Hunt for Two"

#: 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.
TIMING_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 _game_screens(rows, base):
    """Screen records for each house and each rating, from the env timesteps' own clocks."""
    out = []
    ident = next(({"pid": r.get("pid", ""), "gid": r.get("gid", "")}
                  for r in rows if r.get("pid")), {"pid": "", "gid": ""})
    base = {**base, **ident}
    by_block = {}
    for r in rows:
        if r["row_type"] != "trial" or not r.get("choice_time"):
            continue
        key = ("practice" if r.get("practice") in (1, "1") else r.get("blockIndex"))
        if key == "" or key is None:
            continue
        b = by_block.setdefault(key, {"first": r["choice_time"], "last": "", "n": 0,
                                      "house": r.get("house_name", "")})
        b["last"] = r.get("outcome_time") or b["last"]
        b["n"] += 1
    for i, (key, b) in enumerate(by_block.items()):
        out.append({**base, "row_type": "screen", "event_kind": "screen",
                    "screen_name": f"house_{b['house'] or key}", "screen_kind": "house",
                    "screen_index": key, "screen_enter": b["first"],
                    "screen_exit": b["last"], "screen_dwell_ms": _ms(b["first"], b["last"]),
                    "screen_n_clicks": "", "screen_first_click_ms": "",
                    "screen_action": f"{b['n']} trials", "event_time": b["last"]})
    for r in rows:
        if r["row_type"] != "rating" or not r.get("rating_time"):
            continue
        # The rating screen's own enter is not logged; its rt is the time it was up, so
        # back-date the exit by that to get a started the same shape as every other row.
        _rt = r.get("rating_rt_ms")
        _enter = ""
        if isinstance(_rt, (int, float)):
            _e = _iso(r["rating_time"])
            if _e is not None:
                _enter = (_e - timedelta(milliseconds=_rt)).isoformat(
                    timespec="milliseconds") + "Z"
        out.append({**base, "row_type": "screen", "event_kind": "screen",
                    "screen_name": f"rating_{r.get('rating_pair', '')}",
                    "screen_kind": "rating", "screen_index": r.get("rating_blockIndex", ""),
                    "screen_enter": _enter, "screen_exit": r["rating_time"],
                    "screen_dwell_ms": r.get("rating_rt_ms", ""),
                    "screen_n_clicks": "", "screen_first_click_ms": "",
                    "screen_action": "continue", "event_time": r["rating_time"]})
    return out


def _iso(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 = _iso(s)
    return "" if (x is None or t0 is None) else round((x - t0).total_seconds(), 4)


def _write_timing(rows, path, tech):
    """<base>_timing.csv: one row per component, in the order they were shown.

    The same records are in the main file as row_type == "screen". This is the same data
    with nothing else in the way, because the question it answers ("where did the 21
    minutes go") should not need a filter first. Columns match task_pe-cu-nicewebrl's file
    exactly, so the two tasks' timing can be stacked.
    """
    scr = [r for r in rows if r["row_type"] == "screen"]
    scr.sort(key=lambda r: (r.get("screen_exit") or r.get("event_time") or ""))
    stamps = []
    for r in rows:
        for k in ("screen_enter", "screen_exit", "event_time", "choice_time",
                  "outcome_time"):
            if r.get(k):
                stamps.append(r[k])
    t0 = min((x for x in (_iso(s) for s in stamps) if x), default=None)
    meta = {"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": str(tech.get("user_agent", ""))[:60],
            "frameRate": tech.get("framerate_fps", "")}
    out = path.rsplit(".", 1)[0] + "_timing.csv"
    with open(out, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=TIMING_COLUMNS)
        w.writeheader()
        for i, r in enumerate(scr):
            started = _secs(t0, r.get("screen_enter"))
            stopped = _secs(t0, r.get("screen_exit"))
            fc = r.get("screen_first_click_ms")
            w.writerow({**meta, "pid": r.get("pid", ""), "gid": r.get("gid", ""),
                        "component": r.get("screen_name", ""),
                        "component_kind": r.get("screen_kind", ""),
                        "component_index": r.get("screen_index", ""),
                        "thisN": i, "thisRepN": r.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": (r.get("screen_keys") or r.get("screen_action", "")),
                        "corr": r.get("screen_corr", ""),
                        "n_clicks": r.get("screen_n_clicks", ""),
                        "enter_iso": r.get("screen_enter", ""),
                        "exit_iso": r.get("screen_exit", "")})
    print(f"  wrote {out}  ({len(scr)} components)")
    return out


if __name__ == "__main__":
    paths = sys.argv[1:] or sorted(glob.glob("data/user_data_*.msgpack"))
    if not paths:
        print("No data files found (data/user_data_*.msgpack).")
    for p in paths:
        export(p)