File size: 11,910 Bytes
a05d415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcb0147
a05d415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcb0147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a05d415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcb0147
 
a05d415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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 sys
from datetime import datetime

from nicewebrl.utils import read_all_records_sync

import effort_design as D
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", "orderID", "practice",
    # ---- trial ----
    "blockIndex", "trialIndex", "option_pairs", "option_left", "option_right",
    "left_stim", "left_stim_desc", "right_stim", "right_stim_desc",
    "chosen_side", "chosen_key", "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",
    "house_type", "house_name", "displayedtarget",
    # ---- quiz ----
    "quizIndex", "quiz_position", "quiz_statement", "quiz_answer", "quiz_correct_answer",
    "quiz_is_correct", "quiz_attempt",
    # ---- rating ----
    "rating_blockIndex", "rating_pair", "preferred_box_0to6",
    # ---- summary ----
    "started_at", "ended_at", "duration_min",
    "total_self", "total_partner", "money_self", "money_partner",
    "stim_A", "stim_B", "stim_C", "stim_D",
    "stim_A_desc", "stim_B_desc", "stim_C_desc", "stim_D_desc",
    "house_by_place", "pos_by_place", "blocks_visited_order",
]


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


def _self_money(pts):
    """Dollars in the participant's purse. Reads effort_design, which is the
    only place the rate and the caps are written down.

    This held its own `/ 1000.0` divisor, inherited from sl-cu's `/100` with an
    extra zero when the task was forked. The screens were corrected on
    2026-08-25 and this copy was not, so every exported `money_self` and
    `money_partner` since then is 40x short of what the participant was shown
    and 20x short of what they are owed. Re-export any CSV built before
    2026-10-21 before paying from it."""
    return round(D.self_money(pts), 2)


def _partner_money(pts):
    return round(D.partner_money(pts), 2)


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 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
    last_main_cum = (0, 0)
    first_ts, last_ts = None, None
    visited = []             # order of main blocks (places) the participant entered
    letter2stim = {}         # observed reward-profile -> box stimulus id (ground truth)
    place2house = {}         # observed place index -> house name
    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", "")})
            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"))

        if mode == M_CHOICE and action in ("left", "right"):
            pending_rt = rt

        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))
            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"]))
                place2house[int(d["place"])] = HOUSE_NAMES[ht] if ht < len(HOUSE_NAMES) else ht
                letter2stim[LETTERS[int(d["left_letter"])]] = int(d.get("left_stim", -1))
                letter2stim[LETTERS[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 int(d["place"])),
                         "trialIndex": int(d["trial"]),
                         "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_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, "house_type": ht,
                         "house_name": HOUSE_NAMES[ht] if ht < len(HOUSE_NAMES) else ht,
                         "displayedtarget": "both"})
            pending_rt = 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["place"])),
                         "rating_pair": PAIR_STR.get(pc, ""),
                         "preferred_box_0to6": int(d["rating_cursor"])})

    # ---- 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", ""),
            "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 "",
            "total_self": last_main_cum[0], "total_partner": last_main_cum[1],
            "money_self": _self_money(last_main_cum[0]),
            "money_partner": _partner_money(last_main_cum[1]),
            "blocks_visited_order": "_".join(str(b) for b in visited)}
    # box & house assignment straight from what the participant actually saw (ground truth)
    for letter in LETTERS:
        sid = letter2stim.get(letter)
        if sid is not None:
            summ[f"stim_{letter}"] = sid
            summ[f"stim_{letter}_desc"] = _desc(sid)
    summ["house_by_place"] = "_".join(f"{p}:{place2house[p]}" for p in sorted(place2house))
    # house positions aren't logged per trial, so re-derive them from the PID (best effort)
    if orders and pid:
        try:
            o = orders.make_order(pid)
            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)

    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)")
    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)