Spaces:
Sleeping

File size: 7,038 Bytes
f6ae054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""msgpack -> one long-format CSV per participant.

Long format with a `row_type` column, matching ../task_sl-cu-nicewebrl so
existing analysis scripts work unchanged. Filter by `row_type` to get trials,
quiz answers, ratings, and so on.

Every trial row is re-derived from its own inputs by the Python reference
functions in maze_design before it is written. If the browser ever disagrees
with the Python reference, the mismatch lands in the `integrity` column and is
counted in the run summary rather than disappearing.

    uv run python export_csv.py                      # every data/*.msgpack
    uv run python export_csv.py path/to/file.msgpack
"""

import csv
import glob
import sys
from pathlib import Path

from nicewebrl.utils import read_all_records_sync

import maze_design as D
import maze_world as W

#: Trial-row columns, in output order. Every one is documented in CODEBOOK.md,
#: which tests/test_export.py enforces.
TRIAL_COLUMNS = (
    "row_type",
    "pid",
    "prolific_pid",
    "session_id",
    "git_commit",
    "dev_mode",
    "t",
    "leg",
    "run_idx",
    "trial_idx",
    "is_practice",
    "provocation_level",
    "interference_level",
    "freeze_s",
    "provocation_freeze_s",
    "rt_ms",
    "timed_out",
    "sp_pts_before",
    "sp_pts_after",
    "pp_pts_before",
    "pp_pts_after",
    "pp_earned_this_trial",
    "elapsed_ms_session",
    "integrity",
)

#: Non-trial rows (quiz, ratings, slides, summary) are written with
#: these columns plus a free-form `payload` holding the stage's own dict.
META_COLUMNS = ("row_type", "pid", "prolific_pid", "session_id", "t", "payload")

ALL_COLUMNS = tuple(dict.fromkeys(TRIAL_COLUMNS + META_COLUMNS))


def _integrity(data: dict) -> str:
    """Recompute this trial from its inputs; describe any disagreement.

    Returns "ok", "unverifiable" (the record lacks a field we need), or a
    semicolon-joined list of mismatches.
    """
    needed = ("leg", "interference_level", "sp_pts_before", "run_idx", "trial_idx", "is_practice")
    if any(data.get(k) is None for k in needed):
        return "unverifiable"
    try:
        leg = data["leg"]
        level = int(data["interference_level"])
        sp_before = int(data["sp_pts_before"])
        trial_idx = int(data["trial_idx"])
        run_idx = int(data["run_idx"])
        is_practice = bool(data["is_practice"])
        seg_lens = W.sp_segment_lengths(run_idx, is_practice)
        if leg == "proactive":
            # A pinned constant, not this run's maze geometry — must match
            # maze_grid.sp_checkpoint_cost_tiles's live behavior. See
            # maze_design.CONFIG["sp_nav_tiles_per_trial"].
            tiles = float(D.CONFIG["sp_nav_tiles_per_trial"])
        else:
            tiles = seg_lens[trial_idx - 1] if 1 <= trial_idx <= len(seg_lens) else seg_lens[-1]
        problems = []

        if leg == "proactive":
            r = D.resolve_proactive_trial(level, sp_before, tiles)
            if data.get("freeze_s") is not None and int(data["freeze_s"]) != r["freeze_s"]:
                problems.append(f"freeze_s: got {data['freeze_s']} expected {r['freeze_s']}")
            if (data.get("pp_earned_this_trial") is not None
                    and int(data["pp_earned_this_trial"]) != r["pp_earned_this_trial"]):
                problems.append(
                    f"pp_earned_this_trial: got {data['pp_earned_this_trial']}"
                    f" expected {r['pp_earned_this_trial']}"
                )
        else:
            prov = data.get("provocation_level")
            pp_before = data.get("pp_pts_before")
            pp_after = data.get("pp_pts_after")
            if prov is None or pp_before is None or pp_after is None:
                return "unverifiable"
            r = D.resolve_reactive_trial(
                level, int(prov), int(pp_before), int(pp_after), sp_before, tiles
            )
            if data.get("freeze_s") is not None and int(data["freeze_s"]) != r["freeze_s"]:
                problems.append(f"freeze_s: got {data['freeze_s']} expected {r['freeze_s']}")
            if (data.get("sp_pts_after") is not None
                    and int(data["sp_pts_after"]) != r["sp_pts_after"]):
                problems.append(
                    f"sp_pts_after: got {data['sp_pts_after']}"
                    f" expected {r['sp_pts_after']}"
                )
    except Exception as exc:
        return f"error: {exc}"
    return "ok" if not problems else "; ".join(problems)


def _rows(records):
    """Flatten msgpack records into long-format rows."""
    for rec in records:
        data = rec.get("data") if isinstance(rec, dict) else None
        if not isinstance(data, dict):
            continue
        row_type = data.get("row_type")
        if row_type is None:
            continue

        if row_type == "trial":
            out = {c: data.get(c) for c in TRIAL_COLUMNS}
            out["row_type"] = "trial"
            out["integrity"] = _integrity(data)
        else:
            out = {c: data.get(c) for c in META_COLUMNS}
            out["row_type"] = row_type
            # Anything not already a named column travels in `payload`, so a new
            # stage field is never silently dropped on the way to the CSV.
            extra = {k: v for k, v in data.items() if k not in META_COLUMNS}
            out["payload"] = repr(extra) if extra else ""
        yield out


def export(msgpack_path, out_csv) -> int:
    """Write the long-format CSV. Returns the number of rows written."""
    msgpack_path, out_csv = Path(msgpack_path), Path(out_csv)
    rows = list(_rows(read_all_records_sync(str(msgpack_path))))

    out_csv.parent.mkdir(parents=True, exist_ok=True)
    with out_csv.open("w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(ALL_COLUMNS), extrasaction="ignore")
        w.writeheader()
        for row in rows:
            w.writerow(row)

    bad = [
        r
        for r in rows
        if r.get("row_type") == "trial" and r.get("integrity") not in ("ok", None)
    ]
    if bad:
        # Loud on purpose. This means the browser and the Python reference
        # disagree, which is a bug in the reactive-leg client-side JS in
        # maze_stages.py, not a data quirk.
        print(
            f"  !! {len(bad)} trial row(s) failed the integrity check in {msgpack_path.name}",
            file=sys.stderr,
        )
        for r in bad[:5]:
            print(
                f"     trial {r.get('trial_idx')}: {r.get('integrity')}",
                file=sys.stderr,
            )

    return len(rows)


def main(argv=None) -> int:
    argv = list(sys.argv[1:] if argv is None else argv)
    paths = argv or sorted(glob.glob("data/*.msgpack"))
    if not paths:
        print("No data files found (data/*.msgpack).")
        return 1
    for p in paths:
        p = Path(p)
        out = p.with_name(p.stem + "_data.csv")
        n = export(p, out)
        print(f"{out}  ({n} rows)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())