File size: 3,874 Bytes
cb32d35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Materialize one order file per participant ID: writes orders/order_<pid>.csv, a complete,
human-readable, code-independent record of that participant's design (one row per
block x trial: which letter is on which side, its chest look, and its outcome).

Everything in orders.py is already deterministic from the ID, so these files don't change
what a participant sees -- they exist as a durable, frozen artifact: if orders.py is ever
edited later (it shouldn't be, once real data collection starts -- see PROJECT_LOG.md), these
files stay ground truth for what a given PID's design was AT THE TIME they were written, and
`--verify` catches any drift between the files and what the live code computes right now.

Usage:
  uv run python make_order_files.py            # write files for pids 1..N per group
  uv run python make_order_files.py --n 120     # a different N per group
  uv run python make_order_files.py --verify    # check existing files still match orders.py
"""
import argparse
import csv
import os

import orders

OUT_DIR = "orders"
N_PER_GROUP = 60          # target sample size per group; bump and re-run to add more


def _rows_for(pid):
    o = orders.make_order(pid)
    bp = o["block_pairs"].tolist()
    ss = o["side_schedule"].tolist()
    sm = o["stim_map"].tolist()
    oc = o["outcomes"].tolist()
    rows = []
    for b in range(orders.N_PLACES):
        l0, l1 = bp[b]
        for t in range(orders.N_TRIALS):
            left_is_opt0 = ss[b][t] == 0
            left_letter, right_letter = (l0, l1) if left_is_opt0 else (l1, l0)
            rows.append(dict(
                pid=pid, block=b, trial=t,
                pair=orders.LETTERS[l0] + orders.LETTERS[l1],
                left_letter=orders.LETTERS[left_letter], right_letter=orders.LETTERS[right_letter],
                left_stim=sm[b][left_letter], right_stim=sm[b][right_letter],
                opt0_self=oc[b][0][0][t], opt0_other=oc[b][0][1][t],
                opt1_self=oc[b][1][0][t], opt1_other=oc[b][1][1][t],
            ))
    return rows


def _path(pid):
    return os.path.join(OUT_DIR, f"order_{pid}.csv")


def write_order_file(pid):
    os.makedirs(OUT_DIR, exist_ok=True)
    rows = _rows_for(pid)
    path = _path(pid)
    with open(path, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)
    return path


def verify_order_file(pid):
    """Re-derive the order fresh from orders.py right now and diff against the file on disk."""
    path = _path(pid)
    if not os.path.exists(path):
        return False, "missing"
    with open(path) as f:
        on_disk = list(csv.DictReader(f))
    fresh = _rows_for(pid)
    if len(on_disk) != len(fresh):
        return False, f"row count mismatch: file={len(on_disk)} live={len(fresh)}"
    for i, (a, b) in enumerate(zip(on_disk, fresh)):
        for k, v in b.items():
            if str(a.get(k)) != str(v):
                return False, f"row {i} field {k}: file has {a.get(k)!r}, live computes {v!r}"
    return True, "ok"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--verify", action="store_true", help="check existing files instead of writing")
    ap.add_argument("--n", type=int, default=N_PER_GROUP)
    args = ap.parse_args()

    pids = [f"0{n:03d}" for n in range(1, args.n + 1)] + [f"1{n:03d}" for n in range(1, args.n + 1)]

    if args.verify:
        bad = 0
        for pid in pids:
            ok, msg = verify_order_file(pid)
            if not ok:
                bad += 1
                print(f"  MISMATCH {pid}: {msg}")
        print(f"\nVerified {len(pids)} order files; {bad} mismatch(es).")
        return

    for pid in pids:
        write_order_file(pid)
    print(f"Wrote {len(pids)} order files to {OUT_DIR}/ (N={args.n} per group).")


if __name__ == "__main__":
    main()