File size: 7,391 Bytes
63879a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Simulate ONE full playthrough of the ReactorRoom task headlessly and write a msgpack
data file in the SAME length-prefixed format the live nicewebrl app produces, so
export_csv.py can be validated with no browser.

Run:
  python3 make_demo_data.py            # -> data/user_data_<PID>.msgpack
  python3 export_csv.py data/user_data_1007.msgpack
"""
import os
import sys
from datetime import datetime, timedelta

import msgpack
import numpy as np

import ole_design as D
import questionnaires as Q

PID = sys.argv[1] if len(sys.argv) > 1 else "1007"
os.makedirs("data", exist_ok=True)
PATH = f"data/user_data_{PID}.msgpack"
BASE = datetime(2026, 1, 1, 12, 0, 0)


def write_record(f, payload, name, rtype="FeedbackStage"):
    """Wrap a payload dict as a nicewebrl record and write it length-prefixed."""
    rec = dict(name=name, body="", stage_idx=0, session_id="demo",
               user_data=dict(user_id=PID, age=27, sex="Female"),
               metadata=dict(type=rtype), data=payload)
    packed = msgpack.packb(rec)
    f.write(len(packed).to_bytes(4, "big"))
    f.write(packed)


def _self_rating(rng, severity, intensity):
    """Plausible 0-100 self feeling rating: high for painful, low for non-painful."""
    if severity == "pain":
        val = 40 + intensity * 45 + rng.normal(0, 6)
    else:
        val = 10 + intensity * 20 + rng.normal(0, 5)
    return int(max(0, min(100, round(val))))


def main():
    rng = np.random.default_rng(int("".join(c for c in PID if c.isdigit()) or "0") + 7)
    sched = D.make_schedule(PID)
    group = sched["group"]
    t = 0.0  # seconds elapsed (fabricated clock)

    def ts():
        nonlocal t
        t += 6.0
        return (BASE + timedelta(seconds=t)).isoformat()

    with open(PATH, "wb") as f:
        # ---- pre-task surveys -------------------------------------------------
        # comprehension: all correct first try (round 1)
        responses = [dict(key=it["key"], qid=it["qid"], round=1, choice=it["correct"],
                          export_text=it["options"][it["correct"]][1],
                          correct=it["correct"], is_correct=True)
                     for it in Q.COMP_ITEMS]
        write_record(f, dict(row_type="survey", measure="comprehension", pid=PID,
                             group=group, n_items=len(responses),
                             n_correct_first_try=len(responses), responses=responses,
                             ts=ts()), "Comprehension")

        # IRI battery (1-5)
        iri = {k: int(rng.integers(1, 6)) for k, _ in Q.IRI_ITEMS}
        write_record(f, dict(row_type="survey", measure="IRI", pid=PID, group=group,
                             reverse_keyed=sorted(Q.IRI_REVERSE), ts=ts(), **iri), "IRI")

        names = [c["name"] for c in sched["coviewers"]]
        # impression pre (1-9 per co-viewer)
        pre = {nm: int(rng.integers(1, 10)) for nm in names}
        write_record(f, dict(row_type="survey", measure="impression", when="pre", pid=PID,
                             group=group, coviewer_names=names, ratings=pre, ts=ts()),
                     "Impression_pre")
        # willingness pre (0-60)
        write_record(f, dict(row_type="survey", measure="willingness", when="pre", pid=PID,
                             group=group, willingness_minutes=int(rng.integers(0, 61)),
                             ts=ts()), "Willingness_pre")

        # ---- BASELINE block (self-only) --------------------------------------
        pain_self = []
        for clip in sched["baseline"]:
            sr = _self_rating(rng, clip["severity"], clip["intensity"])
            if clip["severity"] == "pain":
                pain_self.append(sr)
            write_record(f, dict(row_type="trial", phase="baseline", pid=PID, group=group,
                                 clip_id=clip["clip_id"], recipient=clip["recipient"],
                                 severity=clip["severity"], mishap=clip["mishap"],
                                 intensity=round(clip["intensity"], 3),
                                 self_rating=sr, rt_self_ms=int(rng.integers(700, 2500)),
                                 ts=ts()), "Baseline")
        baseline_mean = float(np.mean(pain_self)) if pain_self else 55.0

        # ---- attention check (inside learning phase) -------------------------
        write_record(f, dict(row_type="survey", measure="attention_check", pid=PID,
                             group=group, target=7, answer=7, is_correct=True, ts=ts()),
                     "AttentionCheck")

        # ---- LEARNING blocks (with co-viewer) --------------------------------
        for clip in sched["learning"]:
            demo = D.demonstrator_rating(baseline_mean, clip["severity"], group,
                                         clip["demo_noise"])
            # participant's prediction: noisy estimate of the demo rating
            predicted = int(max(0, min(100, round(demo + rng.normal(0, 10)))))
            sr = _self_rating(rng, clip["severity"], clip["intensity"])
            write_record(f, dict(row_type="trial", phase="learning", pid=PID, group=group,
                                 block=clip["block"], trial=clip["trial"],
                                 clip_id=clip["clip_id"], recipient=clip["recipient"],
                                 severity=clip["severity"], mishap=clip["mishap"],
                                 intensity=round(clip["intensity"], 3),
                                 coviewer=clip["coviewer"], coviewer_level=clip["coviewer_level"],
                                 predicted_demo=predicted, demo_rating=demo,
                                 prediction_error=demo - predicted,
                                 self_rating=sr,
                                 rt_predict_ms=int(rng.integers(800, 3000)),
                                 rt_self_ms=int(rng.integers(700, 2500)),
                                 ts=ts()), "Learning")

        # ---- GENERALIZATION block (self-only, new recipient) -----------------
        for clip in sched["generalization"]:
            sr = _self_rating(rng, clip["severity"], clip["intensity"])
            write_record(f, dict(row_type="trial", phase="generalization", pid=PID,
                                 group=group, clip_id=clip["clip_id"],
                                 recipient=clip["recipient"], severity=clip["severity"],
                                 mishap=clip["mishap"], intensity=round(clip["intensity"], 3),
                                 self_rating=sr, rt_self_ms=int(rng.integers(700, 2500)),
                                 ts=ts()), "Generalization")

        # ---- post-task surveys -----------------------------------------------
        post = {nm: int(rng.integers(1, 10)) for nm in names}
        write_record(f, dict(row_type="survey", measure="impression", when="post", pid=PID,
                             group=group, coviewer_names=names, ratings=post, ts=ts()),
                     "Impression_post")
        write_record(f, dict(row_type="survey", measure="willingness", when="post", pid=PID,
                             group=group, willingness_minutes=int(rng.integers(0, 61)),
                             ts=ts()), "Willingness_post")

    print(f"wrote {PATH}  (baseline_mean={baseline_mean:.1f}, group={group}, "
          f"counts={sched['counts']})")
    return PATH


if __name__ == "__main__":
    main()