Commit ·
ea29ada
1
Parent(s): b2c2e8b
Attention check (21st trial in 2 random houses) + post-hoc quality flags
Browse files- new M_ATTENTION env mode: after the 20 trials, 2 deterministically-chosen houses show
'Press the LEFT arrow key to show you're paying attention'; any key advances (no trap),
the key + RT are recorded
- orders: 2 random attention houses per pid (none in practice)
- export: 'attention' rows (block, key, correct, rt) + summary attention_passed/total
- quality_flags.py: flags incomplete / fast-RT / side-bias / failed-attention participants
(surfaces for review, does not auto-exclude)
- CODEBOOK documents the attention rows + summary fields
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Files changed (7)
- CODEBOOK.md+18
- experiment_structure.py+39-3
- export_csv.py+16-1
- make_demo_data.py+2
- orders.py+7
- quality_flags.csvAdded+3
- quality_flags.pyAdded+87
7 unmodified lines891011121379 unmodified lines93949596979833 unmodified lines1321331341351361377 unmodified lines|------------|--------------|----------------------------|| `trial` | chest opening (a choice + its outcome) | 5 practice + 240 main = 245 || `rating` | end-of-house preference rating | 1 practice + 12 main = 13 || `quiz` | quiz answer (incl. re-asks of missed items) | 7+ || `slide` | intro-slide enter/exit | 8 (4 slides × enter/exit) || `click` | a button/mouse click | many |79 unmodified lines---## `slide` rows — intro screen timing| Column | Values | Meaning |33 unmodified lines| `started_at` / `ended_at` | First / last gameplay action (ISO). || `duration_min` | Minutes between them (includes breaks). || `n_breaks` / `total_break_ms` | Number of breaks and total break time (subtract for time-on-task). |**Outcome & payment**7 unmodified lines89101112131479 unmodified lines94959697989910010110210310410510610710810911011111211311411533 unmodified lines1491501511521531541557 unmodified lines|------------|--------------|----------------------------|| `trial` | chest opening (a choice + its outcome) | 5 practice + 240 main = 245 || `rating` | end-of-house preference rating | 1 practice + 12 main = 13 || `attention` | an in-game attention check (21st trial in 2 random houses) | 2 || `quiz` | quiz answer (incl. re-asks of missed items) | 7+ || `slide` | intro-slide enter/exit | 8 (4 slides × enter/exit) || `click` | a button/mouse click | many |79 unmodified lines---## `attention` rows — in-game attention checkTwo randomly chosen houses get a **21st trial** that just says *"Press the LEFT arrow key toshow you're still paying attention."* Any key advances (so nobody gets stuck); the key theypressed is recorded.| Column | Values | Meaning ||--------|--------|---------|| `attention_blockIndex` | `0`–`11` | Which house the check appeared in. || `attention_key` | `left`/`right`/`up`/`down`/`continue` | The key the participant pressed. || `attention_correct` | `1`/`0` | `1` if they pressed **left** (the instructed key). || `attention_rt_ms` | int (ms) | Time from the check appearing to their keypress. |Session totals are in the `summary` row: `attention_passed` / `attention_total`. Thehelper `quality_flags.py` uses these (plus RTs and side-bias) to flag participants for review.## `slide` rows — intro screen timing| Column | Values | Meaning |33 unmodified lines| `started_at` / `ended_at` | First / last gameplay action (ISO). || `duration_min` | Minutes between them (includes breaks). || `n_breaks` / `total_break_ms` | Number of breaks and total break time (subtract for time-on-task). || `attention_passed` / `attention_total` | Attention checks passed (pressed LEFT) out of those shown (usually 2). |**Outcome & payment**
49 unmodified lines5051525354555644 unmodified lines10110210310410510626 unmodified lines13313413513613713839 unmodified lines17817918018118218347 unmodified lines23123223323423523623723823924014 unmodified lines25525625725825926026126226326421 unmodified lines286287288289290291236 unmodified lines5285295305315325331 unmodified line53553653753853954049 unmodified linesN_PLACES = 12WORLD = 25M_OVERWORLD, M_CHOICE, M_OUTCOME, M_RATING = 0, 1, 2, 3A_UP, A_DOWN, A_LEFT, A_RIGHT, A_SPACE = 0, 1, 2, 3, 4OUTCOME_HOLD_MS = 2000 # the open chest stays visible this long, then closes automaticallyaction_keys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", " "]44 unmodified linesn_trials: jax.Arrayactive_mask: jax.Array # (12,)practice: jax.Array@struct.dataclass26 unmodified linesstim_map: jax.Array # (4,) letter -> stimulus idside_schedule: jax.Array # (12, N_TRIALS) 0/1outcomes: jax.Array # (12,2,2,N_TRIALS) pre-baked exact outcomesdef _layout(opt_letters, side_bit):39 unmodified linesstim_map=params.stim_map.astype(jnp.int32),side_schedule=params.side_schedule.astype(jnp.int32),outcomes=params.outcomes.astype(jnp.int32),)return self._obs(s), s47 unmodified linesn_left, n_right = _layout(opt, s.side_schedule[s.current_place, nt])next_round = s.replace(mode=jnp.int32(M_CHOICE), trial=next_trial,left_letter=n_left, right_letter=n_right, chosen_side=jnp.int32(-1))to_rating = s.replace(mode=jnp.int32(M_RATING), rating_cursor=jnp.int32(RATING_MAX // 2))advanced = _select(place_done, to_rating, next_round)return _select(is_continue, advanced, s)def _rating(self, key, s, action, params):is_left = action == A_LEFTis_right = action == A_RIGHT14 unmodified linesow = self._overworld(key, s, action, params)ch = self._choice(key, s, action, params)oc = self._outcome(key, s, action, params)rt, rt_done = self._rating(key, s, action, params)new_state = _select(s.mode == M_OVERWORLD, ow,_select(s.mode == M_CHOICE, ch,_select(s.mode == M_OUTCOME, oc, rt)))done = (s.mode == M_RATING) & rt_donemade_choice = (s.mode == M_CHOICE) & ((action == A_LEFT) | (action == A_RIGHT))reward = jnp.where(made_choice, new_state.last_self_outcome, 0).astype(jnp.float32)21 unmodified linesn_trials=jnp.int32(n_trials),active_mask=jnp.asarray(active_mask, jnp.int32),practice=jnp.int32(practice),)236 unmodified linesreturn imgdef render_state(timestep):s = timestep.statemode = _i(s.mode)1 unmodified lineimg = _render_overworld(s)elif mode == M_RATING:img = _render_rating(s)else:img = _render_place(s)return np.asarray(img, dtype=np.uint8)49 unmodified lines5051525354555644 unmodified lines10110210310410510610726 unmodified lines13413513613713813914039 unmodified lines18018118218318418518647 unmodified lines23423523623723823924024124224324424524624724824925025125225325414 unmodified lines26927027127227327427527627727827928021 unmodified lines302303304305306307308236 unmodified lines5455465475485495505515525535545555565575585595605615625635645655665671 unmodified line56957057157257357457557649 unmodified linesN_PLACES = 12WORLD = 25M_OVERWORLD, M_CHOICE, M_OUTCOME, M_RATING, M_ATTENTION = 0, 1, 2, 3, 4A_UP, A_DOWN, A_LEFT, A_RIGHT, A_SPACE = 0, 1, 2, 3, 4OUTCOME_HOLD_MS = 2000 # the open chest stays visible this long, then closes automaticallyaction_keys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", " "]44 unmodified linesn_trials: jax.Arrayactive_mask: jax.Array # (12,)practice: jax.Arrayattention_places: jax.Array # (12,) 1 = this house gets a 21st 'attention check' trial@struct.dataclass26 unmodified linesstim_map: jax.Array # (4,) letter -> stimulus idside_schedule: jax.Array # (12, N_TRIALS) 0/1outcomes: jax.Array # (12,2,2,N_TRIALS) pre-baked exact outcomesattention_places: jax.Array # (12,) 1 = house with a 21st attention-check trialdef _layout(opt_letters, side_bit):39 unmodified linesstim_map=params.stim_map.astype(jnp.int32),side_schedule=params.side_schedule.astype(jnp.int32),outcomes=params.outcomes.astype(jnp.int32),attention_places=params.attention_places.astype(jnp.int32),)return self._obs(s), s47 unmodified linesn_left, n_right = _layout(opt, s.side_schedule[s.current_place, nt])next_round = s.replace(mode=jnp.int32(M_CHOICE), trial=next_trial,left_letter=n_left, right_letter=n_right, chosen_side=jnp.int32(-1))# after the 20 trials: an attention-check house gets a 21st check; others -> ratingis_att = s.attention_places[s.current_place] > 0to_attention = s.replace(mode=jnp.int32(M_ATTENTION))to_rating = s.replace(mode=jnp.int32(M_RATING), rating_cursor=jnp.int32(RATING_MAX // 2))place_end = _select(is_att, to_attention, to_rating)advanced = _select(place_done, place_end, next_round)return _select(is_continue, advanced, s)def _attention(self, key, s, action, params):# any arrow / space advances to the rating; the key pressed (LEFT = correct) is# captured in the data record's action_name.is_key = action >= 0to_rating = s.replace(mode=jnp.int32(M_RATING), rating_cursor=jnp.int32(RATING_MAX // 2))return _select(is_key, to_rating, s)def _rating(self, key, s, action, params):is_left = action == A_LEFTis_right = action == A_RIGHT14 unmodified linesow = self._overworld(key, s, action, params)ch = self._choice(key, s, action, params)oc = self._outcome(key, s, action, params)at = self._attention(key, s, action, params)rt, rt_done = self._rating(key, s, action, params)new_state = _select(s.mode == M_OVERWORLD, ow,_select(s.mode == M_CHOICE, ch,_select(s.mode == M_OUTCOME, oc,_select(s.mode == M_ATTENTION, at, rt))))done = (s.mode == M_RATING) & rt_donemade_choice = (s.mode == M_CHOICE) & ((action == A_LEFT) | (action == A_RIGHT))reward = jnp.where(made_choice, new_state.last_self_outcome, 0).astype(jnp.float32)21 unmodified linesn_trials=jnp.int32(n_trials),active_mask=jnp.asarray(active_mask, jnp.int32),practice=jnp.int32(practice),attention_places=jnp.asarray(order["attention_places"], jnp.int32),)236 unmodified linesreturn imgdef _render_attention(s):img = Image.new("RGB", (W, H), (38, 42, 58))d = ImageDraw.Draw(img)T(d, W // 2, 120, "Quick attention check!", size=30, bold=True,fill=(255, 230, 120), center=True, outline=True)T(d, W // 2, 210, "Press the LEFT arrow key", size=27, bold=True,fill=(255, 255, 255), center=True, outline=True)T(d, W // 2, 256, "to show you're still paying attention.", size=20,fill=(220, 220, 230), center=True, outline=True)# a big left-pointing arrowcx, cy = W // 2, 380d.polygon([(cx - 70, cy), (cx - 22, cy - 36), (cx - 22, cy - 14), (cx + 70, cy - 14),(cx + 70, cy + 14), (cx - 22, cy + 14), (cx - 22, cy + 36)],fill=(120, 200, 255), outline=(18, 22, 32))return np.asarray(img, dtype=np.uint8)def render_state(timestep):s = timestep.statemode = _i(s.mode)1 unmodified lineimg = _render_overworld(s)elif mode == M_RATING:img = _render_rating(s)elif mode == M_ATTENTION:img = _render_attention(s)else:img = _render_place(s)return np.asarray(img, dtype=np.uint8)
27 unmodified lines2829303132333418 unmodified lines535455565758596057 unmodified lines118119120121122123129 unmodified lines25325425525625725810 unmodified lines26927027127227327427 unmodified linesPAIR_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, 3COLUMNS = ["row_type", "pid", "gid", "orderID", "practice",18 unmodified lines"quiz_is_correct", "quiz_attempt",# ---- rating ----"rating_blockIndex", "rating_pair", "preferred_box_0to6",# ---- summary ----"started_at", "ended_at", "duration_min", "n_breaks", "total_break_ms","game_version", "nicewebrl_version", "framerate_fps", "browser", "os","screen_w", "screen_h", "device_pixel_ratio", "viewport_w", "viewport_h","language", "timezone", "cpu_cores", "user_agent",57 unmodified linesplace2house = {} # observed place index -> house namebreaks = [] # (start_iso, end_iso, ms)break_open = None # start time of a break awaiting its 'end'tech = {} # device/browser/version info for the summary rowbase = dict.fromkeys(COLUMNS, "")129 unmodified linespending_rt = Nonepending_choice_time = Noneelif mode == M_RATING and action == "continue":pc = int(d["pair_code"])rows.append({**base, **info(d), "row_type": "rating",10 unmodified lines"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", ""),"nicewebrl_version": tech.get("nicewebrl_version", ""),"framerate_fps": tech.get("framerate_fps", ""),27 unmodified lines2829303132333418 unmodified lines535455565758596061626357 unmodified lines121122123124125126127129 unmodified lines25725825926026126226326426526626726826927027127210 unmodified lines28328428528628728828927 unmodified linesPAIR_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, M_ATTENTION = 1, 2, 3, 4COLUMNS = ["row_type", "pid", "gid", "orderID", "practice",18 unmodified lines"quiz_is_correct", "quiz_attempt",# ---- rating ----"rating_blockIndex", "rating_pair", "preferred_box_0to6",# ---- attention check ----"attention_blockIndex", "attention_key", "attention_correct", "attention_rt_ms",# ---- summary ----"started_at", "ended_at", "duration_min", "n_breaks", "total_break_ms","attention_passed", "attention_total","game_version", "nicewebrl_version", "framerate_fps", "browser", "os","screen_w", "screen_h", "device_pixel_ratio", "viewport_w", "viewport_h","language", "timezone", "cpu_cores", "user_agent",57 unmodified linesplace2house = {} # observed place index -> house namebreaks = [] # (start_iso, end_iso, ms)break_open = None # start time of a break awaiting its 'end'att_total = att_passed = 0tech = {} # device/browser/version info for the summary rowbase = dict.fromkeys(COLUMNS, "")129 unmodified linespending_rt = Nonepending_choice_time = Noneelif mode == M_ATTENTION:ok = int(action == "left")att_total += 1att_passed += okrows.append({**base, **info(d), "row_type": "attention","attention_blockIndex": int(d["place"]),"attention_key": action,"attention_correct": ok,"attention_rt_ms": rt})elif mode == M_RATING and action == "continue":pc = int(d["pair_code"])rows.append({**base, **info(d), "row_type": "rating",10 unmodified lines"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()),"attention_passed": att_passed, "attention_total": att_total,"game_version": tech.get("game_version", ""),"nicewebrl_version": tech.get("nicewebrl_version", ""),"framerate_fps": tech.get("framerate_fps", ""),
75 unmodified lines76777879808175 unmodified linesa = E.A_LEFT if (stp % 2 == 0) else E.A_RIGHT # vary choiceselif m == E.M_OUTCOME:a = E.A_SPACEelse: # rating: nudge cursor then confirmcur = int(s.rating_cursor)a = E.A_RIGHT if cur < (1 + (int(s.current_place) % 5)) else E.A_SPACE75 unmodified lines767778798081828375 unmodified linesa = E.A_LEFT if (stp % 2 == 0) else E.A_RIGHT # vary choiceselif m == E.M_OUTCOME:a = E.A_SPACEelif m == E.M_ATTENTION:a = E.A_LEFT # the correct attention responseelse: # rating: nudge cursor then confirmcur = int(s.rating_cursor)a = E.A_RIGHT if cur < (1 + (int(s.current_place) % 5)) else E.A_SPACE
122 unmodified lines1231241251261271281 unmodified line13013113213313413516 unmodified lines152153154155156157122 unmodified linesoutcomes[p, o, 0] = _exact_sequence(LETTER_SELF_GOOD[letter], rng)outcomes[p, o, 1] = _exact_sequence(LETTER_OTHER_GOOD[letter], rng)return dict(pid=str(pid), group=group, number=number,orderID=number, stim_map=stim_map,1 unmodified lineblock_pairs_str="_".join(LETTERS[a] + LETTERS[b] for a, b in place_pairs.tolist()),place_pairs=place_pairs, pair_code=pair_code, house_type=house_type,house_pos=house_pos, side_schedule=side_schedule, outcomes=outcomes,)16 unmodified lineso["house_type"][0] = 12 # practice-only forest huto["stim_map"] = o["stim_map"].copy()o["stim_map"][0], o["stim_map"][1] = 24, 25 # practice-only boxes (not in main pool)o["side_schedule"] = o["side_schedule"].copy()o["side_schedule"][0] = rng.integers(0, 2, size=N_TRIALS).astype(np.int32) # randomise sideso["outcomes"] = o["outcomes"].copy()122 unmodified lines1231241251261271281291301311321331 unmodified line13513613713813914014116 unmodified lines158159160161162163164122 unmodified linesoutcomes[p, o, 0] = _exact_sequence(LETTER_SELF_GOOD[letter], rng)outcomes[p, o, 1] = _exact_sequence(LETTER_OTHER_GOOD[letter], rng)# 2 random houses get a 21st 'attention check' trial (drawn last, so it doesn't shift# the outcome stream above)attention_places = np.zeros(N_PLACES, dtype=np.int32)attention_places[rng.choice(N_PLACES, size=2, replace=False)] = 1return dict(pid=str(pid), group=group, number=number,orderID=number, stim_map=stim_map,1 unmodified lineblock_pairs_str="_".join(LETTERS[a] + LETTERS[b] for a, b in place_pairs.tolist()),place_pairs=place_pairs, pair_code=pair_code, house_type=house_type,house_pos=house_pos, side_schedule=side_schedule, outcomes=outcomes,attention_places=attention_places,)16 unmodified lineso["house_type"][0] = 12 # practice-only forest huto["stim_map"] = o["stim_map"].copy()o["stim_map"][0], o["stim_map"][1] = 24, 25 # practice-only boxes (not in main pool)o["attention_places"] = np.zeros(N_PLACES, dtype=np.int32) # no attention check in practiceo["side_schedule"] = o["side_schedule"].copy()o["side_schedule"][0] = rng.integers(0, 2, size=N_TRIALS).astype(np.int32) # randomise sideso["outcomes"] = o["outcomes"].copy()
123pid,gid,houses,med_rt,pct_fast,side_bias,attn,dur_min,flags
006,0,1,658,40,0.71,0/0,283.3,incomplete(1/12)
0007,0,12,450,0,0.58,2/2,20.3,ok123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""Post-hoc data-quality flags for Treasure Hunt for Two. Reads exported *_data.csv files andsurfaces participants worth a closer look — it does NOT auto-exclude anyone, it just flags.
Flags (all heuristic — tune the thresholds to your study): incomplete < 12 main houses finished fast_rt median choice RT < 350 ms many_fast > 40% of choices faster than 250 ms side_bias chose the same side (left/right) on > 90% of trials attn_fail missed one or more attention checks
uv run python quality_flags.py [folder ...] # default: downloaded_data + dataWrites quality_flags.csv."""import csvimport globimport osimport statisticsimport sys
FAST_MS, MANY_FAST_PCT, SIDE_BIAS = 350, 40, 0.90
def _int(x): return int(x) if str(x).lstrip("-").isdigit() else None
def analyze(path): rows = list(csv.DictReader(open(path))) trials = [r for r in rows if r["row_type"] == "trial" and r["blockIndex"] != "practice"] if not trials: return None summ = next((r for r in rows if r["row_type"] == "summary"), {}) att = [r for r in rows if r["row_type"] == "attention"] rts = [v for r in trials if (v := _int(r["choice_rt_ms"])) is not None] sides = [r["chosen_side"] for r in trials] n_house = len(set(r["blockIndex"] for r in trials)) med_rt = round(statistics.median(rts)) if rts else 0 pct_fast = round(100 * sum(1 for x in rts if x < 250) / len(rts)) if rts else 0 side_bias = round(max(sides.count("left"), sides.count("right")) / len(sides), 2) if sides else 0 att_total = _int(summ.get("attention_total")) or len(att) att_pass = _int(summ.get("attention_passed")) if att_pass is None: att_pass = sum(1 for r in att if r.get("attention_correct") == "1") dur = float(summ.get("duration_min") or 0)
flags = [] if n_house < 12: flags.append(f"incomplete({n_house}/12)") if med_rt and med_rt < FAST_MS: flags.append(f"fast_rt({med_rt}ms)") if pct_fast > MANY_FAST_PCT: flags.append(f"many_fast({pct_fast}%)") if side_bias > SIDE_BIAS: flags.append(f"side_bias({int(side_bias*100)}%)") if att_total and att_pass < att_total: flags.append(f"attn_fail({att_pass}/{att_total})") return dict(pid=summ.get("pid") or trials[0]["pid"], gid=summ.get("gid", ""), houses=n_house, med_rt=med_rt, pct_fast=pct_fast, side_bias=side_bias, attn=f"{att_pass}/{att_total}", dur_min=round(dur, 1), flags=";".join(flags) or "ok")
def main(folders): paths = [] for fo in folders: paths += glob.glob(os.path.join(fo, "**", "*_data.csv"), recursive=True) paths = sorted(set(paths)) if not paths: print("No *_data.csv files found in:", folders) return results = [r for r in (analyze(p) for p in paths) if r] print(f"{'pid':7}{'gid':4}{'houses':>7}{'medRT':>7}{'%fast':>6}{'sideB':>7}{'attn':>6}{'min':>6} flags") for r in results: print(f"{r['pid']:7}{str(r['gid']):4}{r['houses']:>7}{r['med_rt']:>7}{r['pct_fast']:>6}" f"{r['side_bias']:>7}{r['attn']:>6}{r['dur_min']:>6} {r['flags']}") flagged = [r for r in results if r["flags"] != "ok"] print(f"\n{len(flagged)}/{len(results)} participant(s) flagged for review (not auto-excluded).") with open("quality_flags.csv", "w", newline="") as f: wr = csv.DictWriter(f, fieldnames=list(results[0].keys())) wr.writeheader() wr.writerows(results) print("wrote quality_flags.csv")
if __name__ == "__main__": main(sys.argv[1:] or ["downloaded_data", "data"])CODEBOOK.md+18
experiment_structure.py+39-3
export_csv.py+16-1
make_demo_data.py+2
orders.py+7
quality_flags.csvAdded+3
quality_flags.pyAdded+87