Commit ·
bd2c7cd
1
Parent(s): 8c72a82
Full experiment: cover story + quiz + practice, simultaneous self/partner outcomes, per-session randomized houses + counterbalancing, end-of-house rating, OG-style CSV export
Browse filesFiles changed (5)
- README.md+29
- experiment_structure.py+411-248
- export_csv.pyAdded+128
- make_demo_data.pyAdded+99
- smoke_test.py+68-62
53 unmodified lines54555657585953 unmodified lines- Data is written locally under `data/` (msgpack). Google Cloud upload is a no-opunless you add `google-cloud-key.json` + `BUCKET_NAME`.## Design knobs (things you'll likely want to tune)First-pass decisions baked in — all easy to change in `experiment_structure.py`:53 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878853 unmodified lines- Data is written locally under `data/` (msgpack). Google Cloud upload is a no-opunless you add `google-cloud-key.json` + `BUCKET_NAME`.## Flow & featuresStages (in order): **Cover story → How to play → 6-item comprehension quiz → Practice(1 house, 5 rounds, with tips) → Practice done → Main task (12 houses, 20 rounds each)**.- **Cover story**: you're an adventurer making money; a real anonymous partner earns fromyour choices (they don't play).- **Simultaneous outcomes**: each chest = an option A/B/C/D; opening it shows **both** yourcoin and your partner's coin, and both update.- **Per-session randomization**: house **positions** (drawn from a candidate pool) and the**chest-pair assigned to each house** (counterbalanced) are reshuffled every session.- **End-of-house rating**: after clearing a house you rate which chest you preferred on a7-point scale (←/→ then Space).- **Quiz**: 6 true/false comprehension items with feedback (ported from the original).## Data export (OG-style CSVs)The app logs msgpack per keypress to `data/user_data_<seed>.msgpack`. Convert to tidy CSVs:```bashuv run python export_csv.py # -> *_trials.csv, *_ratings.csv, *_quiz.csv````*_trials.csv` has one row per round with the meaningful OG columns: `blockIndex, pair,trialIndex, option_left, option_right, chosen_side, chosen_option, self_outcome,other_outcome, cum_self, cum_other, rt_ms` (+ subject/age/sex/practice). It's a clean longformat with the same *variables* as the original — not the 80-column PsychoPy dump.`make_demo_data.py` simulates a playthrough to test the exporter without a browser.## Design knobs (things you'll likely want to tune)First-pass decisions baked in — all easy to change in `experiment_structure.py`:
1234567891011121314151617181920212223242526272 unmodified lines3031323334353637383940413 unmodified lines454647484950515253545556575859606162632 unmodified lines666768697071727374757677787980818283841 unmodified line86878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221233 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661675 unmodified lines1731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982992 unmodified lines3023033043053063073083093103113123133143153163173183193203213223233243253263273281 unmodified line330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505"""Social-learning ("Minecraft") task for NiceWebRL.A walkable top-down OVERWORLD: you move an avatar around a grid with the arrow keys,find 12 "places" (houses) scattered on the map, and walk onto one to enter it. Inside aplace you face two doors and play 20 rounds of a social choice; then the place is"consumed" and you explore for the next one. A partner ("lil guy") trails behind you.Options A/B/C/D have hidden reward profiles for SELF and PARTNER:A good/good B good/bad C bad/good D bad/bad"good" => P(+1)=0.75, P(-1)=0.15, P(0)=0.10 ; "bad" => P(+1)=0.15, P(-1)=0.75, P(0)=0.10The 6 pairs AB AC AD BC BD CD each appear twice -> 12 places. Per place, 10 rounds showthe SELF outcome and 10 show the PARTNER outcome.Controls--------Overworld : Arrow keys move. Walk onto a house to enter it.Inside : Left / Right arrow = choose that door. Space (or Up) = continue.Implementation: one gymnax-style JAX env (a small state machine over modesOVERWORLD/CHOICE/OUTCOME), wrapped by TimestepWrapper -> JaxWebEnv, rendered with PIL.The whole experiment is a single EnvStage; it ends when all 12 places are consumed."""from typing import Optionalimport jax2 unmodified linesimport numpy as npfrom flax import structfrom nicegui import uifrom PIL import Image, ImageDrawimport spritesimport nicewebrlfrom nicewebrl import JaxWebEnv, TimeStep, TimestepWrapperfrom nicewebrl import Stage, EnvStagefrom nicewebrl import get_loggerfrom nicewebrl.experiment import SimpleExperiment3 unmodified lines# Constants# ----------------------------------------------------------------------------N_TRIALS = 20N_PLACES = 12WORLD = 25 # world is 25x25 tiles; only a viewport follows the player# ModesM_OVERWORLD, M_CHOICE, M_OUTCOME = 0, 1, 2# ActionsA_UP, A_DOWN, A_LEFT, A_RIGHT, A_SPACE = 0, 1, 2, 3, 4action_keys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", " "]action_to_name = ["up", "down", "left", "right", "continue"]action_array = jnp.arange(len(action_keys))# OptionsLETTER_SELF_GOOD = jnp.array([1, 1, 0, 0], dtype=jnp.int32) # A,B good for selfLETTER_OTHER_GOOD = jnp.array([1, 0, 1, 0], dtype=jnp.int32) # A,C good for partnerLETTER_NAMES = ["A", "B", "C", "D"]2 unmodified linesP_PLUS_GOOD, P_MINUS_GOOD = 0.75, 0.15P_PLUS_BAD, P_MINUS_BAD = 0.15, 0.75PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] # AB AC AD BC BD CDPLACE_PAIRS = PAIRS + PAIRS # 12 places# 12 house positions (row, col) spread across the 25x25 world so you must explore# to find them. House index i has type i % 6 -> two of each of the 6 house types,# which mirrors the 6 option-pairs (PLACE_PAIRS) appearing twice.HOUSE_POS = np.array([[3, 4], [2, 15], [5, 9], [4, 21], [9, 2], [8, 18], # types 0..5[10, 12], [11, 23], [16, 6], [17, 16], [21, 3], [20, 20], # types 0..5 again], dtype=np.int32)START_POS = np.array([12, 12], dtype=np.int32)PARTNER_START = np.array([12, 13], dtype=np.int32)HOUSE_DICT = {(int(r), int(c)): i for i, (r, c) in enumerate(HOUSE_POS)}# ----------------------------------------------------------------------------1 unmodified line# ----------------------------------------------------------------------------@struct.dataclassclass EnvParams:house_pos: jax.Array # (12, 2)place_pairs: jax.Array # (12, 2) letter indicesn_trials: jax.Arraygrid: jax.Array@struct.dataclassclass EnvState:mode: jax.Array # 0 overworld, 1 choice, 2 outcomeagent_pos: jax.Array # (2,)partner_pos: jax.Array # (2,)facing: jax.Array # 0 down, 1 up, 2 left, 3 rightwalk_frame: jax.Array # 0/1 step toggle for the walk cycleconsumed: jax.Array # (12,) boolcurrent_place: jax.Array # -1 or 0..11trial: jax.Arrayself_coins: jax.Arrayother_coins: jax.Array# active-place door layoutleft_letter: jax.Arrayright_letter: jax.Arraycur_target: jax.Array # 0 self / 1 partnerchosen_side: jax.Array # -1 / 0 / 1last_outcome: jax.Array # -1 / 0 / +1last_target: jax.Array# schedules for all placestarget_schedule: jax.Array # (12, N_TRIALS) 0/1side_schedule: jax.Array # (12, N_TRIALS) 0/1def _layout(opt_letters, side_bit):"""side_bit 0 => opt0 on left."""left = jnp.where(side_bit == 0, opt_letters[0], opt_letters[1])right = jnp.where(side_bit == 0, opt_letters[1], opt_letters[0])return left, right3 unmodified linesreturn jtu.tree_map(lambda x, y: jnp.where(cond, x, y), a, b)class OverworldSocialEnv:def _obs(self, s: EnvState) -> jax.Array:return jnp.array([s.mode, s.agent_pos[0], s.agent_pos[1], s.trial,s.self_coins, s.other_coins, s.current_place, jnp.sum(s.consumed)],dtype=jnp.float32,)def reset(self, key, params: EnvParams):k_t, k_s = jax.random.split(key)base = jnp.concatenate([jnp.zeros(N_TRIALS // 2, jnp.int32), jnp.ones(N_TRIALS // 2, jnp.int32)])t_keys = jax.random.split(k_t, N_PLACES)target_schedule = jax.vmap(lambda k: jax.random.permutation(k, base))(t_keys)side_schedule = jax.random.bernoulli(k_s, 0.5, (N_PLACES, N_TRIALS)).astype(jnp.int32)s = EnvState(mode=jnp.int32(M_OVERWORLD),agent_pos=jnp.asarray(START_POS, jnp.int32),partner_pos=jnp.asarray(PARTNER_START, jnp.int32),facing=jnp.int32(0),walk_frame=jnp.int32(0),consumed=jnp.zeros(N_PLACES, bool),current_place=jnp.int32(-1),trial=jnp.int32(0),self_coins=jnp.int32(0),other_coins=jnp.int32(0),left_letter=jnp.int32(0),right_letter=jnp.int32(0),cur_target=jnp.int32(0),chosen_side=jnp.int32(-1),last_outcome=jnp.int32(0),last_target=jnp.int32(0),target_schedule=target_schedule,side_schedule=side_schedule,)return self._obs(s), s5 unmodified linesreturn jnp.where(u < p_plus, jnp.int32(1),jnp.where(u < p_plus + p_minus, jnp.int32(-1), jnp.int32(0)))# -- overworld movement / entering a place --def _overworld(self, key, s: EnvState, action, params: EnvParams):drow = jnp.where(action == A_UP, -1, jnp.where(action == A_DOWN, 1, 0))dcol = jnp.where(action == A_LEFT, -1, jnp.where(action == A_RIGHT, 1, 0))gr = params.grid - 1tr = jnp.clip(s.agent_pos[0] + drow, 0, gr)tc = jnp.clip(s.agent_pos[1] + dcol, 0, gr)target = jnp.array([tr, tc])moved = jnp.any(target != s.agent_pos)new_partner = jnp.where(moved, s.agent_pos, s.partner_pos)# face the direction pressed (default keep facing if it was a no-op key)facing = jnp.where(action == A_UP, 1,jnp.where(action == A_DOWN, 0,jnp.where(action == A_LEFT, 2,jnp.where(action == A_RIGHT, 3, s.facing))))new_walk = jnp.where(moved, 1 - s.walk_frame, s.walk_frame)# did we step onto an unconsumed house?matches = (jnp.all(params.house_pos == target, axis=1)) & (~s.consumed) # (12,)entering = jnp.any(matches)place_idx = jnp.argmax(matches)opt = params.place_pairs[place_idx]left, right = _layout(opt, s.side_schedule[place_idx, 0])moved_state = s.replace(agent_pos=target, partner_pos=new_partner,facing=facing, walk_frame=new_walk)enter_state = moved_state.replace(mode=jnp.int32(M_CHOICE),current_place=place_idx,trial=jnp.int32(0),left_letter=left,right_letter=right,cur_target=s.target_schedule[place_idx, 0],chosen_side=jnp.int32(-1),)return _select(entering, enter_state, moved_state)# -- inside a place: choose a door --def _choice(self, key, s: EnvState, action, params: EnvParams):is_choice = (action == A_LEFT) | (action == A_RIGHT)chosen_side = jnp.where(action == A_LEFT, jnp.int32(0), jnp.int32(1))chosen_letter = jnp.where(chosen_side == 0, s.left_letter, s.right_letter)good = jnp.where(s.cur_target == 0,LETTER_SELF_GOOD[chosen_letter], LETTER_OTHER_GOOD[chosen_letter])outcome = self._draw(key, good)resolved = s.replace(mode=jnp.int32(M_OUTCOME),chosen_side=chosen_side,last_outcome=outcome,last_target=s.cur_target,self_coins=s.self_coins + jnp.where(s.cur_target == 0, outcome, 0),other_coins=s.other_coins + jnp.where(s.cur_target == 1, outcome, 0),)return _select(is_choice, resolved, s)# -- inside a place: continue past the outcome --def _outcome(self, key, s: EnvState, action, params: EnvParams):is_continue = (action == A_SPACE) | (action == A_UP)next_trial = s.trial + 1place_done = next_trial >= params.n_trialsnt = jnp.clip(next_trial, 0, N_TRIALS - 1)opt = params.place_pairs[s.current_place]n_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,cur_target=s.target_schedule[s.current_place, nt],chosen_side=jnp.int32(-1),)new_consumed = s.consumed.at[s.current_place].set(True)exit_place = s.replace(mode=jnp.int32(M_OVERWORLD),consumed=new_consumed,current_place=jnp.int32(-1),chosen_side=jnp.int32(-1),)advanced = _select(place_done, exit_place, next_round)new_state = _select(is_continue, advanced, s)done = is_continue & place_done & jnp.all(new_consumed)return new_state, donedef step(self, key, s: EnvState, action, params: EnvParams):action = jnp.asarray(action, jnp.int32)ow = self._overworld(key, s, action, params)ch = self._choice(key, s, action, params)oc, oc_done = self._outcome(key, s, action, params)new_state = _select(s.mode == M_OVERWORLD, ow,_select(s.mode == M_CHOICE, ch, oc))done = jnp.where(s.mode == M_OUTCOME, oc_done, False)# reward = coin shown this step (only on a door choice)made_choice = (s.mode == M_CHOICE) & ((action == A_LEFT) | (action == A_RIGHT))reward = jnp.where(made_choice, new_state.last_outcome, 0).astype(jnp.float32)return self._obs(new_state), new_state, reward, done, {}# ----------------------------------------------------------------------------# Build env + params (single env for the whole experiment)# ----------------------------------------------------------------------------raw_env = OverworldSocialEnv()wrapped_env = TimestepWrapper(raw_env, autoreset=True)jax_web_env = JaxWebEnv(env=wrapped_env, actions=action_array)env_params = EnvParams(house_pos=jnp.asarray(HOUSE_POS, jnp.int32),place_pairs=jnp.asarray(np.array(PLACE_PAIRS, dtype=np.int32)),n_trials=jnp.int32(N_TRIALS),grid=jnp.int32(WORLD),)# ----------------------------------------------------------------------------# Rendering (fixed-size canvas; overworld uses a viewport that follows the player)# ----------------------------------------------------------------------------W, H = 720, 560TILE = 48VIEW_W, VIEW_H = 13, 9 # visible tilesBOARD_W, BOARD_H = VIEW_W * TILE, VIEW_H * TILEOX, OY = (W - BOARD_W) // 2, 1042 unmodified linesreturn int(np.asarray(x))def _hud(d, self_coins, other_coins):d.text((20, 16), f"Coins -- YOU: {self_coins} PARTNER: {other_coins}", fill=(245, 245, 245))def _clip(v, lo, hi):return max(lo, min(hi, v))def _render_overworld(s) -> Image.Image:consumed = np.asarray(s.consumed)ar, ac = _i(s.agent_pos[0]), _i(s.agent_pos[1])pr, pc = _i(s.partner_pos[0]), _i(s.partner_pos[1])facing, frame = _i(s.facing), _i(s.walk_frame)self_coins, other_coins = _i(s.self_coins), _i(s.other_coins)img = Image.new("RGB", (W, H), (30, 38, 50))d = ImageDraw.Draw(img)_hud(d, self_coins, other_coins)d.text((20, 40), f"Places explored: {int(consumed.sum())}/{N_PLACES}", fill=(245, 245, 245))d.text((20, 62), "Arrow keys to walk. Explore to find houses, then walk onto one.",fill=(200, 205, 215))cam_top = _clip(ar - VIEW_H // 2, 0, WORLD - VIEW_H)cam_left = _clip(ac - VIEW_W // 2, 0, WORLD - VIEW_W)1 unmodified linedef screen(wr, wc):return OX + (wc - cam_left) * TILE, OY + (wr - cam_top) * TILE# pass 1: ground + decorationsfor vr in range(VIEW_H):for vc in range(VIEW_W):wr, wc = cam_top + vr, cam_left + vcsprites.draw_grass_tile(d, OX + vc * TILE, OY + vr * TILE, TILE, wr, wc)# pass 2: depth-sorted entities (houses + characters), lower rows drawn on topents = []for vr in range(VIEW_H):for vc in range(VIEW_W):wr, wc = cam_top + vr, cam_left + vcidx = HOUSE_DICT.get((wr, wc))if idx is not None:ents.append((wr, "house", idx, wc))ents.append((pr + 0.5, "char", pc, "partner"))ents.append((ar + 0.6, "char", ac, "player"))for key, kind, a, b in sorted(ents, key=lambda e: e[0]):if kind == "house":idx, wc = a, bsx, sy = screen(int(key), wc)sprites.draw_house(d, sx, sy, TILE, idx % 6, completed=bool(consumed[idx]))else:wr = int(round(key - (0.6 if b == "player" else 0.5)))sx, sy = screen(wr, a)feet = (sx + TILE // 2, sy + TILE - 6)if b == "player":sprites.draw_character(d, feet[0], feet[1], facing, frame, **sprites.PLAYER_PAL)else:sprites.draw_character(d, feet[0], feet[1], facing, frame, **sprites.PARTNER_PAL)# mask anything that bled outside the viewport (houses/characters at edges),# then redraw the HUD, frame and legend cleanly on top.bg = (30, 38, 50)d.rectangle([0, 0, W, OY - 3], fill=bg)d.rectangle([0, OY + BOARD_H + 2, W, H], fill=bg)d.rectangle([0, 0, OX - 3, H], fill=bg)d.rectangle([OX + BOARD_W + 2, 0, W, H], fill=bg)_hud(d, self_coins, other_coins)d.text((20, 40), f"Places explored: {int(consumed.sum())}/{N_PLACES}", fill=(245, 245, 245))d.text((20, 62), "Arrow keys to walk. Explore to find houses, then walk onto one.",fill=(200, 205, 215))d.rectangle([OX - 2, OY - 2, OX + BOARD_W + 1, OY + BOARD_H + 1], outline=(20, 24, 32), width=2)d.text((OX, OY + BOARD_H + 8), "Blue hat = you Green = your partner", fill=(200, 205, 215))return imgdef _render_place(s) -> Image.Image:place_id = _i(s.current_place)trial = _i(s.trial)mode = _i(s.mode)left_letter, right_letter = _i(s.left_letter), _i(s.right_letter)self_coins, other_coins = _i(s.self_coins), _i(s.other_coins)last_outcome, last_target = _i(s.last_outcome), _i(s.last_target)chosen_side = _i(s.chosen_side)house_name = sprites.HOUSE_NAMES[place_id % 6]img = Image.new("RGB", (W, H), (44, 38, 58))d = ImageDraw.Draw(img)_hud(d, self_coins, other_coins)d.text((20, 40), f"Inside the {house_name} -- Place {place_id + 1}/{N_PLACES} "f"Round {min(trial + 1, N_TRIALS)}/{N_TRIALS}", fill=(245, 245, 245))cw, ch, y0 = 170, 120, 200lx, rx = 120, W - 120 - cwfor x, letter, side in ((lx, left_letter, 0), (rx, right_letter, 1)):chosen = (mode == M_OUTCOME) and (chosen_side == side)is_open = chosensprites.draw_chest(d, x, y0, cw, ch, LETTER_COLOR[letter], is_open=is_open, highlight=chosen)sprites.draw_key(d, x + cw // 2 - 12, y0 + ch + 18, LETTER_COLOR[letter])if mode == M_OUTCOME and chosen:sprites.draw_coin(d, x + cw // 2, y0 - 34, last_outcome)d.text((lx + cw // 2 - 36, y0 + ch + 36), "<- this key", fill=(215, 215, 225))d.text((rx + cw // 2 - 36, y0 + ch + 36), "that key ->", fill=(215, 215, 225))if mode == M_CHOICE:d.text((W // 2 - 180, 96), "Pick a chest to open: press <- or ->", fill=(255, 255, 255))else:word = {1: "a gold coin (+1)", 0: "nothing (0)", -1: "lost a coin (-1)"}[last_outcome]who = "YOU" if last_target == 0 else "PARTNER"col = (241, 196, 15) if last_outcome > 0 else (231, 76, 60) if last_outcome < 0 else (180, 180, 180)d.text((W // 2 - 170, 96), f"{who} got {word}", fill=col)d.text((W // 2 - 165, H - 70), "Press SPACE (or Up arrow) to continue", fill=(255, 255, 255))# you + partner watching at the bottomsprites.draw_character(d, 250, H - 18, 1, 0, **sprites.PLAYER_PAL)sprites.draw_character(d, W - 250, H - 18, 1, 0, **sprites.PARTNER_PAL)d.text((232, H - 16), "you", fill=(200, 205, 215))d.text((W - 280, H - 16), "partner", fill=(200, 205, 215))return imgdef render_state(timestep: TimeStep) -> np.ndarray:s = timestep.stateimg = _render_overworld(s) if _i(s.mode) == M_OVERWORLD else _render_place(s)return np.asarray(img, dtype=np.uint8)def vmap_render_fn(batched_timesteps) -> np.ndarray:n = int(np.asarray(batched_timesteps.reward).shape[0])imgs = [render_state(jtu.tree_map(lambda x: x[i], batched_timesteps)) for i in range(n)]return np.stack(imgs)# ----------------------------------------------------------------------------# Stages# ----------------------------------------------------------------------------def _img_html(src):# NOTE: the id="stateImage" is REQUIRED -- nicewebrl's basics.js swaps this# element's src on each keypress for instant client-side updates. Without it# the screen never visually advances even though keys register.return ('<div id="stateImageContainer" style="display:flex;justify-content:center;align-items:center;">'f'<img id="stateImage" src="{src}" style="width:100%;height:100%;object-fit:contain;"></div>')async def env_stage_display_fn(stage: EnvStage, container: ui.element, timestep: TimeStep):image = nicewebrl.base64_npimage(stage.render_fn(timestep))with container.style("align-items: center;"):nicewebrl.clear_element(container)ui.html(_img_html(image))def never_success(timestep: TimeStep, params: Optional[struct.PyTreeNode] = None):return jnp.int32(0)def all_places_done(timestep: TimeStep):return timestep.last()async def instruction_display_fn(stage, container):with container.style("align-items: center;"):nicewebrl.clear_element(container)ui.markdown("## Welcome — explore the world!")ui.markdown("""You'll walk around a map and find **12 places** (houses). Walk onto a house to go inside.**Inside a place** there are two doors and **20 rounds**:- Press **Left / Right arrow** to choose that door.- You'll see who got a coin (**YOU** or your **PARTNER**); press **Space** (or **Up arrow**) to continue.Some doors are more likely to give coins to *you*, some to your *partner*, some to *both*,some to *neither*. After 20 rounds the place is done and you head back out to find the next one.**Click "Next page" below to start. Then use the arrow keys.**""")main_stage = EnvStage(name="Explore",web_env=jax_web_env,action_keys=action_keys,action_to_name=action_to_name,env_params=env_params,render_fn=render_state,vmap_render_fn=vmap_render_fn,precompile=False,display_fn=env_stage_display_fn,evaluate_success_fn=never_success,check_finished=all_places_done,min_success=10_000,max_episodes=1,notify_success=False,metadata=dict(task="overworld_social_learning"),)all_stages = [Stage(name="Instructions", display_fn=instruction_display_fn),main_stage,]experiment = SimpleExperiment(stages=all_stages, name="Social Learning CU")1234567891011121314151617181920212223242526272 unmodified lines30313233343536373839403 unmodified lines444546474849505152535455565758592 unmodified lines626364656667686970717273747576777879808182831 unmodified line8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251263 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841855 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043052 unmodified lines3083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393401 unmodified line342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668"""Social-learning treasure-hunt task for NiceWebRL (cover story: explorers/adventurers).You are a treasure hunter exploring a world to make some money. You travel a grid,discover houses, and inside each house you find two treasure chests. Each chest is oneof four kinds (A/B/C/D). Opening a chest gives an outcome for BOTH you and a realanonymous PARTNER who earns money from your choices (the partner does NOT play).Each chest kind has hidden coin-odds for self and partner:A good/good B good/bad C bad/good D bad/bad"good" => P(+1 coin)=0.75, P(-1)=0.15, P(0)=0.10 ; "bad" => P(+1)=0.15, P(-1)=0.75, P(0)=0.10Both self and partner outcomes are drawn and shown SIMULTANEOUSLY every round.The 6 chest-pairs AB AC AD BC BD CD each appear twice -> 12 houses, 20 rounds each.After clearing a house you rate which of its two chests you preferred.Per session everything is randomized: house POSITIONS (drawn from a candidate pool) andwhich chest-pair each house holds (counterbalanced order).Modes (one EnvStage state machine): OVERWORLD -> CHOICE -> OUTCOME -> (loop) -> RATING -> OVERWORLD.A separate practice EnvStage uses one house and a few rounds with extra explanations."""import asynciofrom typing import Optionalimport jax2 unmodified linesimport numpy as npfrom flax import structfrom nicegui import uiimport spritesimport nicewebrlfrom nicewebrl import JaxWebEnv, TimeStep, TimestepWrapperfrom nicewebrl import Stage, EnvStage, FeedbackStagefrom nicewebrl import get_loggerfrom nicewebrl.experiment import SimpleExperiment3 unmodified lines# Constants# ----------------------------------------------------------------------------N_TRIALS = 20PRAC_TRIALS = 5N_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, 4action_keys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", " "]action_to_name = ["up", "down", "left", "right", "continue"]action_array = jnp.arange(len(action_keys))LETTER_SELF_GOOD = jnp.array([1, 1, 0, 0], dtype=jnp.int32) # A,B good for selfLETTER_OTHER_GOOD = jnp.array([1, 0, 1, 0], dtype=jnp.int32) # A,C good for partnerLETTER_NAMES = ["A", "B", "C", "D"]2 unmodified linesP_PLUS_GOOD, P_MINUS_GOOD = 0.75, 0.15P_PLUS_BAD, P_MINUS_BAD = 0.15, 0.75PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] # AB AC AD BC BD CDPLACE_PAIRS_ARR = np.array(PAIRS + PAIRS, dtype=np.int32) # (12,2)BASE_PAIRCODE = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5], dtype=np.int32)# candidate house positions (spread); per session we pick & shuffle 12 of theseCANDIDATE_POS = np.array([[3, 4], [2, 15], [5, 9], [4, 21], [9, 2], [8, 18],[6, 12], [11, 23], [16, 6], [17, 16], [21, 3], [20, 20],[13, 5], [7, 22], [22, 12], [3, 20], [19, 9], [14, 18],], dtype=np.int32)N_CAND = CANDIDATE_POS.shape[0]START_POS = np.array([12, 12], dtype=np.int32)PARTNER_START = np.array([12, 13], dtype=np.int32)PRAC_HOUSE = np.array([12, 16], dtype=np.int32) # one nearby house for practiceRATING_MAX = 6 # 7-point scale 0..6# ----------------------------------------------------------------------------1 unmodified line# ----------------------------------------------------------------------------@struct.dataclassclass EnvParams:candidate_pos: jax.Array # (N_CAND, 2)n_trials: jax.Array # scalaractive_mask: jax.Array # (12,) 1 = this house is used this runpractice: jax.Array # scalar 0/1@struct.dataclassclass EnvState:mode: jax.Arrayagent_pos: jax.Arraypartner_pos: jax.Arrayfacing: jax.Arraywalk_frame: jax.Arrayconsumed: jax.Array # (12,) boolcurrent_place: jax.Arraytrial: jax.Arrayn_trials: jax.Arraypractice: jax.Arrayself_coins: jax.Arrayother_coins: jax.Arrayleft_letter: jax.Arrayright_letter: jax.Arraychosen_side: jax.Arraychosen_letter: jax.Arraylast_self_outcome: jax.Arraylast_other_outcome: jax.Arrayrating_cursor: jax.Arrayratings: jax.Array # (12,) -1 unrated else 0..6house_pos: jax.Array # (12,2) positions this sessionhouse_active: jax.Array # (12,) boolplace_pairs: jax.Array # (12,2) letterspair_code: jax.Array # (12,) 0..5side_schedule: jax.Array # (12, N_TRIALS) 0/1def _layout(opt_letters, side_bit):left = jnp.where(side_bit == 0, opt_letters[0], opt_letters[1])right = jnp.where(side_bit == 0, opt_letters[1], opt_letters[0])return left, right3 unmodified linesreturn jtu.tree_map(lambda x, y: jnp.where(cond, x, y), a, b)class TreasureEnv:def _obs(self, s):return jnp.array([s.mode, s.agent_pos[0], s.agent_pos[1], s.trial,s.self_coins, s.other_coins, s.current_place,jnp.sum(s.consumed)], dtype=jnp.float32)def reset(self, key, params: EnvParams):k_pos, k_pair, k_side = jax.random.split(key, 3)cand = params.candidate_pos# main: shuffle positions + counterbalance pair assignmentpos_perm = jax.random.permutation(k_pos, N_CAND)[:N_PLACES]main_house = cand[pos_perm]pair_perm = jax.random.permutation(k_pair, N_PLACES)main_pairs = jnp.asarray(PLACE_PAIRS_ARR)[pair_perm]main_code = jnp.asarray(BASE_PAIRCODE)[pair_perm]# practice: one fixed nearby house, pair ABprac_house = cand[:N_PLACES].at[0].set(jnp.asarray(PRAC_HOUSE))prac_pairs = jnp.asarray(PLACE_PAIRS_ARR)prac_code = jnp.asarray(BASE_PAIRCODE)pr = params.practicehouse_pos = jnp.where(pr == 1, prac_house, main_house)place_pairs = jnp.where(pr == 1, prac_pairs, main_pairs)pair_code = jnp.where(pr == 1, prac_code, main_code)side_schedule = jax.random.bernoulli(k_side, 0.5, (N_PLACES, N_TRIALS)).astype(jnp.int32)active = params.active_mask.astype(bool)s = EnvState(mode=jnp.int32(M_OVERWORLD),agent_pos=jnp.asarray(START_POS, jnp.int32),partner_pos=jnp.asarray(PARTNER_START, jnp.int32),facing=jnp.int32(0), walk_frame=jnp.int32(0),consumed=~active, # inactive houses count as donecurrent_place=jnp.int32(-1),trial=jnp.int32(0),n_trials=params.n_trials,practice=params.practice,self_coins=jnp.int32(0), other_coins=jnp.int32(0),left_letter=jnp.int32(0), right_letter=jnp.int32(0),chosen_side=jnp.int32(-1), chosen_letter=jnp.int32(-1),last_self_outcome=jnp.int32(0), last_other_outcome=jnp.int32(0),rating_cursor=jnp.int32(RATING_MAX // 2),ratings=jnp.full(N_PLACES, -1, jnp.int32),house_pos=house_pos.astype(jnp.int32),house_active=active,place_pairs=place_pairs.astype(jnp.int32),pair_code=pair_code.astype(jnp.int32),side_schedule=side_schedule,)return self._obs(s), s5 unmodified linesreturn jnp.where(u < p_plus, jnp.int32(1),jnp.where(u < p_plus + p_minus, jnp.int32(-1), jnp.int32(0)))def _overworld(self, key, s, action, params):drow = jnp.where(action == A_UP, -1, jnp.where(action == A_DOWN, 1, 0))dcol = jnp.where(action == A_LEFT, -1, jnp.where(action == A_RIGHT, 1, 0))gr = WORLD - 1tr = jnp.clip(s.agent_pos[0] + drow, 0, gr)tc = jnp.clip(s.agent_pos[1] + dcol, 0, gr)target = jnp.array([tr, tc])moved = jnp.any(target != s.agent_pos)new_partner = jnp.where(moved, s.agent_pos, s.partner_pos)facing = jnp.where(action == A_UP, 1, jnp.where(action == A_DOWN, 0,jnp.where(action == A_LEFT, 2, jnp.where(action == A_RIGHT, 3, s.facing))))new_walk = jnp.where(moved, 1 - s.walk_frame, s.walk_frame)matches = jnp.all(s.house_pos == target, axis=1) & s.house_active & (~s.consumed)entering = jnp.any(matches)place_idx = jnp.argmax(matches)opt = s.place_pairs[place_idx]left, right = _layout(opt, s.side_schedule[place_idx, 0])moved_state = s.replace(agent_pos=target, partner_pos=new_partner,facing=facing, walk_frame=new_walk)enter_state = moved_state.replace(mode=jnp.int32(M_CHOICE), current_place=place_idx, trial=jnp.int32(0),left_letter=left, right_letter=right, chosen_side=jnp.int32(-1))return _select(entering, enter_state, moved_state)def _choice(self, key, s, action, params):is_choice = (action == A_LEFT) | (action == A_RIGHT)chosen_side = jnp.where(action == A_LEFT, jnp.int32(0), jnp.int32(1))chosen_letter = jnp.where(chosen_side == 0, s.left_letter, s.right_letter)k1, k2 = jax.random.split(key)self_out = self._draw(k1, LETTER_SELF_GOOD[chosen_letter]) # simultaneousother_out = self._draw(k2, LETTER_OTHER_GOOD[chosen_letter])resolved = s.replace(mode=jnp.int32(M_OUTCOME), chosen_side=chosen_side, chosen_letter=chosen_letter,last_self_outcome=self_out, last_other_outcome=other_out,self_coins=s.self_coins + self_out, other_coins=s.other_coins + other_out)return _select(is_choice, resolved, s)def _outcome(self, key, s, action, params):is_continue = (action == A_SPACE) | (action == A_UP)next_trial = s.trial + 1place_done = next_trial >= s.n_trialsnt = jnp.clip(next_trial, 0, N_TRIALS - 1)opt = s.place_pairs[s.current_place]n_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_RIGHTis_confirm = (action == A_SPACE) | (action == A_UP)cursor = jnp.clip(s.rating_cursor + is_right.astype(jnp.int32) - is_left.astype(jnp.int32),0, RATING_MAX)moved = s.replace(rating_cursor=cursor)new_consumed = s.consumed.at[s.current_place].set(True)new_ratings = s.ratings.at[s.current_place].set(s.rating_cursor)confirmed = s.replace(mode=jnp.int32(M_OVERWORLD), consumed=new_consumed,ratings=new_ratings, current_place=jnp.int32(-1))new_state = _select(is_confirm, confirmed, moved)done = is_confirm & jnp.all(new_consumed)return new_state, donedef step(self, key, s, action, params):action = jnp.asarray(action, jnp.int32)ow = 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)return self._obs(new_state), new_state, reward, done, {}# ----------------------------------------------------------------------------# Build env + params (main + practice share the JaxWebEnv)# ----------------------------------------------------------------------------raw_env = TreasureEnv()wrapped_env = TimestepWrapper(raw_env, autoreset=True)jax_web_env = JaxWebEnv(env=wrapped_env, actions=action_array)main_params = EnvParams(candidate_pos=jnp.asarray(CANDIDATE_POS, jnp.int32),n_trials=jnp.int32(N_TRIALS),active_mask=jnp.ones(N_PLACES, jnp.int32),practice=jnp.int32(0),)practice_params = EnvParams(candidate_pos=jnp.asarray(CANDIDATE_POS, jnp.int32),n_trials=jnp.int32(PRAC_TRIALS),active_mask=jnp.zeros(N_PLACES, jnp.int32).at[0].set(1),practice=jnp.int32(1),)# ----------------------------------------------------------------------------# Rendering# ----------------------------------------------------------------------------W, H = 720, 560TILE = 48VIEW_W, VIEW_H = 13, 9BOARD_W, BOARD_H = VIEW_W * TILE, VIEW_H * TILEOX, OY = (W - BOARD_W) // 2, 1042 unmodified linesreturn int(np.asarray(x))def _hud(d, s_coins, o_coins):d.text((20, 16), f"Coins -- YOU: {s_coins} PARTNER: {o_coins}", fill=(245, 245, 245))def _clip(v, lo, hi):return max(lo, min(hi, v))from PIL import Image, ImageDrawdef _render_overworld(s):consumed = np.asarray(s.consumed)active = np.asarray(s.house_active)hpos = np.asarray(s.house_pos)pcode = np.asarray(s.pair_code)ar, ac = _i(s.agent_pos[0]), _i(s.agent_pos[1])pr, pc = _i(s.partner_pos[0]), _i(s.partner_pos[1])facing, frame = _i(s.facing), _i(s.walk_frame)sc, oc = _i(s.self_coins), _i(s.other_coins)practice = _i(s.practice)n_active = int(active.sum())explored = int((consumed & active).sum())img = Image.new("RGB", (W, H), (30, 38, 50))d = ImageDraw.Draw(img)cam_top = _clip(ar - VIEW_H // 2, 0, WORLD - VIEW_H)cam_left = _clip(ac - VIEW_W // 2, 0, WORLD - VIEW_W)1 unmodified linedef screen(wr, wc):return OX + (wc - cam_left) * TILE, OY + (wr - cam_top) * TILEhouse_at = {(int(hpos[i][0]), int(hpos[i][1])): i for i in range(N_PLACES) if active[i]}for vr in range(VIEW_H):for vc in range(VIEW_W):wr, wc = cam_top + vr, cam_left + vcsprites.draw_grass_tile(d, OX + vc * TILE, OY + vr * TILE, TILE, wr, wc)ents = []for (wr, wc), idx in house_at.items():if cam_top <= wr < cam_top + VIEW_H and cam_left <= wc < cam_left + VIEW_W:ents.append((wr, "house", idx, wc))ents.append((pr + 0.5, "char", pc, "partner"))ents.append((ar + 0.6, "char", ac, "player"))for key, kind, a, b in sorted(ents, key=lambda e: e[0]):if kind == "house":sx, sy = screen(int(key), b)sprites.draw_house(d, sx, sy, TILE, int(pcode[a]), completed=bool(consumed[a]))else:wr = int(round(key - (0.6 if b == "player" else 0.5)))sx, sy = screen(wr, a)pal = sprites.PLAYER_PAL if b == "player" else sprites.PARTNER_PALsprites.draw_character(d, sx + TILE // 2, sy + TILE - 6, facing, frame, **pal)# mask bleed, then HUD + framebg = (30, 38, 50)d.rectangle([0, 0, W, OY - 3], fill=bg)d.rectangle([0, OY + BOARD_H + 2, W, H], fill=bg)d.rectangle([0, 0, OX - 3, H], fill=bg)d.rectangle([OX + BOARD_W + 2, 0, W, H], fill=bg)_hud(d, sc, oc)label = "PRACTICE" if practice else f"Houses cleared: {explored}/{n_active}"d.text((20, 40), label, fill=(245, 230, 150) if practice else (245, 245, 245))d.text((20, 62), "Arrow keys to walk. Explore to find a house, then walk onto it.",fill=(200, 205, 215))d.rectangle([OX - 2, OY - 2, OX + BOARD_W + 1, OY + BOARD_H + 1], outline=(20, 24, 32), width=2)d.text((OX, OY + BOARD_H + 8), "Blue = you Green = your partner", fill=(200, 205, 215))return imgdef _chest_positions():cw, ch, y0 = 170, 120, 200lx, rx = 120, W - 120 - cwreturn cw, ch, y0, lx, rxdef _render_place(s):place_id = _i(s.current_place)trial, mode = _i(s.trial), _i(s.mode)n_trials = _i(s.n_trials)left_letter, right_letter = _i(s.left_letter), _i(s.right_letter)sc, oc = _i(s.self_coins), _i(s.other_coins)s_out, o_out = _i(s.last_self_outcome), _i(s.last_other_outcome)chosen_side = _i(s.chosen_side)practice = _i(s.practice)house_name = sprites.HOUSE_NAMES[int(np.asarray(s.pair_code)[place_id]) % 6]img = Image.new("RGB", (W, H), (44, 38, 58))d = ImageDraw.Draw(img)_hud(d, sc, oc)tag = "PRACTICE -- " if practice else ""d.text((20, 40), f"{tag}Inside the {house_name} Round {min(trial + 1, n_trials)}/{n_trials}",fill=(245, 230, 150) if practice else (245, 245, 245))cw, ch, y0, lx, rx = _chest_positions()for x, letter, side in ((lx, left_letter, 0), (rx, right_letter, 1)):chosen = (mode == M_OUTCOME) and (chosen_side == side)sprites.draw_chest(d, x, y0, cw, ch, LETTER_COLOR[letter], is_open=chosen, highlight=chosen)sprites.draw_key(d, x + cw // 2 - 12, y0 + ch + 18, LETTER_COLOR[letter])if mode == M_CHOICE:d.text((W // 2 - 200, 92), "Pick a chest to open: press <- or ->", fill=(255, 255, 255))if practice:d.text((W // 2 - 250, H - 92),"Tip: each chest gives a coin result for BOTH you and your partner.",fill=(220, 220, 150))else:# show BOTH outcomes floating from the opened chest (you + partner)cx = (lx if chosen_side == 0 else rx) + cw // 2sprites.draw_coin(d, cx - 26, y0 - 36, s_out)sprites.draw_coin(d, cx + 26, y0 - 36, o_out)d.text((cx - 44, y0 - 64), "YOU", fill=(210, 210, 220))d.text((cx + 12, y0 - 64), "PARTNER", fill=(210, 210, 220))def word(v):return "+1" if v > 0 else ("-1" if v < 0 else "0")d.text((W // 2 - 210, 92),f"You {word(s_out)} coin Partner {word(o_out)} coin", fill=(255, 255, 255))d.text((W // 2 - 165, H - 60), "Press SPACE (or Up arrow) to continue", fill=(255, 255, 255))sprites.draw_character(d, 250, H - 18, 1, 0, **sprites.PLAYER_PAL)sprites.draw_character(d, W - 250, H - 18, 1, 0, **sprites.PARTNER_PAL)d.text((232, H - 16), "you", fill=(200, 205, 215))d.text((W - 285, H - 16), "partner", fill=(200, 205, 215))return imgdef _render_rating(s):place_id = _i(s.current_place)cursor = _i(s.rating_cursor)sc, oc = _i(s.self_coins), _i(s.other_coins)opt = np.asarray(s.place_pairs)[place_id]left_col, right_col = LETTER_COLOR[int(opt[0])], LETTER_COLOR[int(opt[1])]img = Image.new("RGB", (W, H), (40, 44, 60))d = ImageDraw.Draw(img)_hud(d, sc, oc)d.text((W // 2 - 220, 70), "You've cleared this house and taken all you can get!",fill=(245, 230, 150))d.text((W // 2 - 175, 100), "Which treasure chest did you prefer?", fill=(255, 255, 255))# the two chests at the endssprites.draw_chest(d, 70, 200, 120, 90, left_col, is_open=False)sprites.draw_chest(d, W - 70 - 120, 200, 120, 90, right_col, is_open=False)# 7-point scalen = RATING_MAX + 1x0, x1, y = 230, W - 230, 250for i in range(n):cx = x0 + (x1 - x0) * i // (n - 1)r = 16 if i == cursor else 11fill = (241, 196, 15) if i == cursor else (90, 96, 120)d.ellipse([cx - r, y - r, cx + r, y + r], fill=fill, outline=(20, 24, 32), width=2)d.text((205, 300), "strongly prefer", fill=(210, 210, 220))d.text((215, 314), "LEFT chest", fill=left_col)d.text((W - 300, 300), "strongly prefer", fill=(210, 210, 220))d.text((W - 290, 314), "RIGHT chest", fill=right_col)d.text((W // 2 - 30, 300), "no pref.", fill=(210, 210, 220))d.text((W // 2 - 230, H - 80),"Move with <- / -> then press SPACE (or Up) to confirm", fill=(255, 255, 255))return imgdef render_state(timestep):s = timestep.statemode = _i(s.mode)if mode == M_OVERWORLD:img = _render_overworld(s)elif mode == M_RATING:img = _render_rating(s)else:img = _render_place(s)return np.asarray(img, dtype=np.uint8)def vmap_render_fn(batched_timesteps):n = int(np.asarray(batched_timesteps.reward).shape[0])imgs = [render_state(jtu.tree_map(lambda x: x[i], batched_timesteps)) for i in range(n)]return np.stack(imgs)# ----------------------------------------------------------------------------# Logging: rich per-step data so we can export an OG-style trial CSV# ----------------------------------------------------------------------------def custom_data_fn(timestep):s = timestep.statecp = jnp.clip(s.current_place, 0, N_PLACES - 1)return dict(mode=s.mode, place=s.current_place, trial=s.trial, n_trials=s.n_trials,practice=s.practice, pair_code=s.pair_code[cp],left_letter=s.left_letter, right_letter=s.right_letter,chosen_side=s.chosen_side, chosen_letter=s.chosen_letter,self_outcome=s.last_self_outcome, other_outcome=s.last_other_outcome,self_coins=s.self_coins, other_coins=s.other_coins,rating=s.ratings[cp], rating_cursor=s.rating_cursor,)# ----------------------------------------------------------------------------# Stage callbacks# ----------------------------------------------------------------------------def _img_html(src):return ('<div id="stateImageContainer" style="display:flex;justify-content:center;align-items:center;">'f'<img id="stateImage" src="{src}" style="width:100%;height:100%;object-fit:contain;"></div>')async def env_stage_display_fn(stage, container, timestep):image = nicewebrl.base64_npimage(stage.render_fn(timestep))with container.style("align-items: center;"):nicewebrl.clear_element(container)ui.html(_img_html(image))def never_success(timestep, params=None):return jnp.int32(0)def all_done(timestep):return timestep.last()def make_env_stage(name, params, metadata):return EnvStage(name=name, web_env=jax_web_env, action_keys=action_keys, action_to_name=action_to_name,env_params=params, render_fn=render_state, vmap_render_fn=vmap_render_fn, precompile=False,display_fn=env_stage_display_fn, evaluate_success_fn=never_success, check_finished=all_done,min_success=10_000, max_episodes=1, notify_success=False,custom_data_fn=custom_data_fn, metadata=metadata)# ---------------- instructions (cover story) ----------------async def _markdown_stage(stage, container, md):with container.style("align-items: center;"):nicewebrl.clear_element(container)ui.markdown(md)COVER_STORY = """## Treasure Hunt!You are an **adventurer** exploring a world to make some money. As you travel, you'lldiscover **houses** — and inside each house are **two treasure chests**.Open a chest with its **key** and you'll find coins. But here's the twist: you have beenmatched with a **real, anonymous partner**. Every chest you open affects the coins for**both you and your partner**. Your partner does **not** play — they simply earn (or lose)money based on *your* choices.- Some chests are more likely to give coins to **you**.- Some are more likely to give coins to your **partner**.- Some help **both** of you, some help **neither**.- Coins are converted to real money at the end (about **$1 per 1000 points, up to $6**)and paid to **both** you and your partner.Your job: explore, open chests, and learn which chests are worth your while."""HOW_TO_PLAY = """## How to play- **Walk** around the world with the **arrow keys** and step onto a house to go inside.- Inside, **press Left / Right arrow** to open the left or right chest.- You'll see what **you** got and what your **partner** got — then press **Space** (or Up)to continue.- Each house has several rounds. When you've taken all you can, you'll **rate which chestyou preferred**, then head out to find the next house.Each chest **color/kind keeps its meaning** wherever it appears — so you can learn whateach one tends to do. Let's start with a quick **practice** house!"""PRACTICE_DONE = """## Nicely done!That was just practice. Now the **real adventure** begins — there are **12 houses** hiddenacross the world. Explore to find them all, and choose wisely for you *and* your partner.Press **Next page**, then use the arrow keys to start exploring."""# ---------------- quiz ----------------QUIZ = [("As an adventurer, on each round you open ONE of two treasure chests, and each chest ""affects the coins for BOTH you and a real, anonymous partner you've been matched with.",True,"Correct: you choose one of two chests that affect outcomes for you and a real, ""anonymous partner you've been matched with."),("Your anonymous partner will also play this treasure hunt on your behalf.",False,"Correct answer: FALSE. The other person will NOT play this game on your behalf."),("Every chest you open always gives an outcome for BOTH you and your partner, which you ""see right after each choice.",True,"Correct: every choice gives an outcome for both you and the other person, shown after ""each choice."),("Each chest kind has its own meaning, regardless of which side of the screen it appears on.",True,"Correct: each chest has its own meaning regardless of how or where it appears."),("Coins gained or lost across your choices are converted into money at the end and added ""to BOTH your compensation and your partner's.",True,"Correct: points convert to money at the end (about $1 per 1000 points, up to $6) for ""both you and the other person."),("All chests basically give the same coins.",False,"Correct answer: FALSE. The chests are not the same — some are more likely to give coins ""than others."),]def make_quiz_stage(idx, statement, correct, feedback):async def quiz_display(stage, container):nicewebrl.clear_element(container)answer = {"val": None}done = asyncio.Event()with container.style("align-items:center; max-width:680px;"):ui.markdown(f"### Comprehension check ({idx + 1}/{len(QUIZ)})")ui.markdown(f"**{statement}**")fb = ui.markdown("")cont = ui.button("Continue")cont.set_visibility(False)def choose(val):answer["val"] = valis_correct = (val == correct)fb.set_content(("✅ " if is_correct else "❌ ") + feedback)cont.set_visibility(True)with ui.row():ui.button("TRUE", on_click=lambda: choose(True))ui.button("FALSE", on_click=lambda: choose(False))cont.on("click", lambda: done.set())await done.wait()return dict(quizIndex=idx, statement=statement,answer=answer["val"], correct_answer=correct,is_correct=bool(answer["val"] == correct))return FeedbackStage(name=f"Quiz {idx + 1}", display_fn=quiz_display)# ----------------------------------------------------------------------------# Assemble experiment# ----------------------------------------------------------------------------all_stages = [Stage(name="Cover Story", display_fn=lambda stage, container: _markdown_stage(stage, container, COVER_STORY)),Stage(name="How To Play", display_fn=lambda stage, container: _markdown_stage(stage, container, HOW_TO_PLAY)),]all_stages += [make_quiz_stage(i, st, co, fb) for i, (st, co, fb) in enumerate(QUIZ)]all_stages += [make_env_stage("Practice", practice_params, dict(task="practice")),Stage(name="Practice Done", display_fn=lambda stage, container: _markdown_stage(stage, container, PRACTICE_DONE)),make_env_stage("Explore", main_params, dict(task="main")),]experiment = SimpleExperiment(stages=all_stages, name="Social Learning CU")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Export a participant's NiceWebRL data into clean, OG-style CSV files.
NiceWebRL logs one length-prefixed msgpack record per keypress to`data/user_data_<seed>.msgpack`. This script reconstructs, per session: * <stem>_trials.csv -- one row per round (the columns that matter in the OG task) * <stem>_ratings.csv -- the end-of-house chest-preference rating per house * <stem>_quiz.csv -- comprehension-quiz responses
Usage: uv run python export_csv.py # process all data/user_data_*.msgpack uv run python export_csv.py path/to/file.msgpack"""import csvimport globimport sysfrom datetime import datetime
from nicewebrl.utils import read_all_records_sync
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)}M_CHOICE, M_OUTCOME, M_RATING = 1, 2, 3
def _ms(a, b): try: return round((datetime.fromisoformat(b) - datetime.fromisoformat(a)).total_seconds() * 1000) except Exception: return ""
def _is_env(rec): return rec.get("metadata", {}).get("type") == "EnvStage"
def export(path): records = read_all_records_sync(path) if not records: print(f" (no records in {path})") return uid = records[0].get("user_data", {}) subject = uid.get("user_id", "") age, sex = uid.get("age", ""), uid.get("sex", "") stem = path.rsplit(".", 1)[0]
trials, ratings, quiz = [], [], [] seen_trial = set() pending_choice = None # (rt_ms, seen_time) from the choice keypress
for rec in records: name = rec.get("name", "") meta = rec.get("metadata", {}) d = rec.get("data", {})
# ---- quiz (FeedbackStage) ---- if meta.get("type") == "FeedbackStage" and name.lower().startswith("quiz"): quiz.append(dict(subject=subject, quizIndex=d.get("quizIndex"), answer=d.get("answer"), correct_answer=d.get("correct_answer"), is_correct=d.get("is_correct"))) continue
if not _is_env(rec): continue mode = d.get("mode") action = d.get("action_name") rt = _ms(d.get("image_seen_time"), d.get("action_taken_time"))
# a directional press on the choice screen IS the choice -> stash its RT if mode == M_CHOICE and action in ("left", "right"): pending_choice = rt
# the resulting outcome state holds the trial result (once per place/trial) if mode == M_OUTCOME: key = (int(d.get("practice", 0)), int(d["place"]), int(d["trial"])) if key not in seen_trial: seen_trial.add(key) pc = int(d["pair_code"]) ll, rl = int(d["left_letter"]), int(d["right_letter"]) trials.append(dict( subject=subject, age=age, sex=sex, practice=int(d.get("practice", 0)), blockIndex=int(d["place"]), pair=PAIR_STR.get(pc, ""), trialIndex=int(d["trial"]), option_left=LETTERS[ll], option_right=LETTERS[rl], chosen_side=("left" if int(d["chosen_side"]) == 0 else "right"), chosen_option=LETTERS[int(d["chosen_letter"])], self_outcome=int(d["self_outcome"]), other_outcome=int(d["other_outcome"]), cum_self=int(d["self_coins"]), cum_other=int(d["other_coins"]), rt_ms=pending_choice if pending_choice is not None else "", )) pending_choice = None
# the confirm press on the rating screen carries the chosen rating if mode == M_RATING and action == "continue": pc = int(d["pair_code"]) ll, rl = int(d["left_letter"]), int(d["right_letter"]) opt = PAIRS[pc] ratings.append(dict( subject=subject, practice=int(d.get("practice", 0)), blockIndex=int(d["place"]), pair=PAIR_STR.get(pc, ""), left_option=LETTERS[opt[0]], right_option=LETTERS[opt[1]], rating_0to6=int(d["rating_cursor"]), ))
_write(f"{stem}_trials.csv", trials) _write(f"{stem}_ratings.csv", ratings) _write(f"{stem}_quiz.csv", quiz) print(f" {path}: {len(trials)} trials, {len(ratings)} ratings, {len(quiz)} quiz rows")
def _write(path, rows): if not rows: return with open(path, "w", newline="") as f: w = csv.DictWriter(f, fieldnames=list(rows[0].keys())) w.writeheader() w.writerows(rows) print(f" wrote {path}")
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). Play the task first.") for p in paths: export(p)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Simulate a full playthrough and write a msgpack data file in the SAME format thelive app produces, so we can validate export_csv.py without a browser."""import osfrom datetime import datetime, timedelta
import msgpackimport numpy as npimport jaximport jax.tree_util as jtu
import experiment_structure as Eimport nicewebrl
os.makedirs("data", exist_ok=True)SEED = 999999PATH = f"data/user_data_{SEED}.msgpack"BASE = datetime(2026, 1, 1, 12, 0, 0)
def write_record(f, rec): packed = msgpack.packb(rec) f.write(len(packed).to_bytes(4, "big")) f.write(packed)
def env_record(name, timestep, action_idx, t): d = nicewebrl.make_serializable(E.custom_data_fn(timestep)) d.update( image_seen_time=(BASE + timedelta(seconds=t)).isoformat(), action_taken_time=(BASE + timedelta(seconds=t, milliseconds=450)).isoformat(), computer_interaction=E.action_keys[action_idx], action_name=E.action_to_name[action_idx], action_idx=action_idx, ) return dict(name=name, body="", stage_idx=0, session_id="demo", user_data=dict(user_id=SEED, age=27, sex="Female"), metadata=dict(type="EnvStage", task=name.lower()), data=d)
def drive(f, params, name, t0): p = params ts = E.jax_web_env.reset(jax.random.PRNGKey(7), p) t = t0
def step(ts, a, sd): nxt = E.jax_web_env.next_steps(jax.random.PRNGKey(sd), ts, p) return jtu.tree_map(lambda x: x[a], nxt)
def nearest(s): ar, ac = int(s.agent_pos[0]), int(s.agent_pos[1]) hp, act, co = np.asarray(s.house_pos), np.asarray(s.house_active), np.asarray(s.consumed) best, bd = None, 1e9 for i in range(E.N_PLACES): if act[i] and not co[i]: dd = abs(hp[i][0] - ar) + abs(hp[i][1] - ac) if dd < bd: best, bd = (int(hp[i][0]), int(hp[i][1])), dd return best
rating_target = 0 for stp in range(40000): if bool(ts.last()): break s = ts.state m = int(s.mode) if m == E.M_OVERWORLD: tgt = nearest(s) if tgt is None: break ar, ac = int(s.agent_pos[0]), int(s.agent_pos[1]) tr, tc = tgt a = (E.A_UP if tr < ar else E.A_DOWN) if ar != tr else (E.A_LEFT if tc < ac else E.A_RIGHT) elif m == E.M_CHOICE: a = E.A_LEFT if (stp % 2 == 0) else E.A_RIGHT # vary choices elif m == E.M_OUTCOME: a = E.A_SPACE else: # rating: nudge cursor then confirm cur = int(s.rating_cursor) a = E.A_RIGHT if cur < (1 + (int(s.current_place) % 5)) else E.A_SPACE write_record(f, env_record(name, ts, a, t)) ts = step(ts, a, stp + 1) t += 2 return t
with open(PATH, "wb") as f: # quiz records for i, (st, co, fb) in enumerate(E.QUIZ): ans = co if i != 1 else (not co) # get one wrong on purpose f_rec = dict(name=f"Quiz {i + 1}", body="", stage_idx=0, session_id="demo", user_data=dict(user_id=SEED, age=27, sex="Female"), metadata=dict(type="FeedbackStage"), data=dict(quizIndex=i, statement=st, answer=ans, correct_answer=co, is_correct=bool(ans == co))) write_record(f, f_rec) t = drive(f, E.practice_params, "Practice", 100) drive(f, E.main_params, "Explore", t + 10)
print(f"wrote {PATH}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Headless smoke test: drive the overworld env to completion (no web server)."""import numpy as npimport jaximport jax.tree_util as jtuimport experiment_structure as Ep = E.env_paramsdef step(ts, action, seed):nxt = E.jax_web_env.next_steps(jax.random.PRNGKey(seed), ts, p)return jtu.tree_map(lambda x: x[action], nxt)def nearest_unconsumed(ar, ac, consumed):best, bestd = None, 1e9for idx, (hr, hc) in enumerate(E.HOUSE_POS):if consumed[idx]:continuedist = abs(hr - ar) + abs(hc - ac)if dist < bestd:best, bestd = (int(hr), int(hc)), distreturn bestrng = jax.random.PRNGKey(0)ts = E.jax_web_env.reset(rng, p)assert bool(ts.first())# render sanity: all 5 action previews must be the same fixed canvas sizenxt = E.jax_web_env.next_steps(rng, ts, p)imgs = E.vmap_render_fn(nxt)assert imgs.shape == (5, E.H, E.W, 3), imgs.shapeplaces_completed = 0seen_target_counts = []cur_place_targets = {0: 0, 1: 0}prev_mode = 0steps = 0while not bool(ts.last()) and steps < 20000:s = ts.statemode = int(s.mode)if mode == E.M_OVERWORLD:ar, ac = int(s.agent_pos[0]), int(s.agent_pos[1])tgt = nearest_unconsumed(ar, ac, np.asarray(s.consumed))if tgt is None:breaktr, tc = tgtif ar != tr:action = E.A_UP if tr < ar else E.A_DOWNelse:action = E.A_LEFT if tc < ac else E.A_RIGHTelif mode == E.M_CHOICE:# count which recipient is shown this roundcur_place_targets[int(s.cur_target)] += 1action = E.A_LEFTelse: # M_OUTCOMEaction = E.A_SPACE# detect a place just finished (outcome->overworld transition)ts = step(ts, action, seed=steps + 1)if prev_mode == E.M_OUTCOME and int(ts.state.mode) == E.M_OVERWORLD:places_completed += 1seen_target_counts.append((cur_place_targets[0], cur_place_targets[1]))cur_place_targets = {0: 0, 1: 0}prev_mode = int(ts.state.mode)steps += 1s = ts.stateprint(f"steps={steps} done={bool(ts.last())} consumed={int(np.asarray(s.consumed).sum())}/12")print(f"final coins -> YOU={int(s.self_coins):+d} PARTNER={int(s.other_coins):+d}")print("per-place (self_shown, partner_shown):", seen_target_counts)assert bool(ts.last()), "experiment should finish when all places consumed"assert int(np.asarray(s.consumed).sum()) == 12# completed places includes the last one (which ends the experiment); allow 11 recordedassert places_completed >= 11assert all(a == 10 and b == 10 for a, b in seen_target_counts), "each place: 10 self / 10 partner"print("\nALL SMOKE TESTS PASSED")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Headless smoke test: drive the treasure env to completion (main + practice)."""import numpy as npimport jaximport jax.tree_util as jtuimport experiment_structure as Edef run(params, label):p = paramsrng = jax.random.PRNGKey(0)ts = E.jax_web_env.reset(rng, p)assert bool(ts.first())# all 5 action previews must be one fixed canvas sizenxt = E.jax_web_env.next_steps(rng, ts, p)imgs = E.vmap_render_fn(nxt)assert imgs.shape == (5, E.H, E.W, 3), imgs.shapedef step(ts, action, seed):nxt = E.jax_web_env.next_steps(jax.random.PRNGKey(seed), ts, p)return jtu.tree_map(lambda x: x[action], nxt)def nearest(s):ar, ac = int(s.agent_pos[0]), int(s.agent_pos[1])hpos, act, cons = np.asarray(s.house_pos), np.asarray(s.house_active), np.asarray(s.consumed)best, bd = None, 1e9for i in range(E.N_PLACES):if act[i] and not cons[i]:dist = abs(hpos[i][0] - ar) + abs(hpos[i][1] - ac)if dist < bd:best, bd = (int(hpos[i][0]), int(hpos[i][1])), distreturn beststeps, trials_per_house, cur_trials = 0, [], 0prev_mode = E.M_OVERWORLDwhile not bool(ts.last()) and steps < 40000:s = ts.statem = int(s.mode)if m == E.M_OVERWORLD:tgt = nearest(s)if tgt is None:breakar, ac = int(s.agent_pos[0]), int(s.agent_pos[1])tr, tc = tgtaction = (E.A_UP if tr < ar else E.A_DOWN) if ar != tr else (E.A_LEFT if tc < ac else E.A_RIGHT)elif m == E.M_CHOICE:cur_trials += 1action = E.A_LEFTelif m == E.M_OUTCOME:action = E.A_SPACEelse: # ratingaction = E.A_SPACEts = step(ts, action, steps + 1)if prev_mode == E.M_RATING and int(ts.state.mode) == E.M_OVERWORLD:trials_per_house.append(cur_trials)cur_trials = 0prev_mode = int(ts.state.mode)steps += 1s = ts.staten_active = int(np.asarray(s.house_active).sum())nt = int(np.asarray(s.n_trials))print(f"[{label}] steps={steps} done={bool(ts.last())} "f"cleared={int((np.asarray(s.consumed) & np.asarray(s.house_active)).sum())}/{n_active} "f"coins YOU={int(s.self_coins):+d} PARTNER={int(s.other_coins):+d}")print(f"[{label}] trials/house={trials_per_house} ratings={[int(r) for r in np.asarray(s.ratings)]}")assert bool(ts.last())assert int((np.asarray(s.consumed) & np.asarray(s.house_active)).sum()) == n_activeassert all(t == nt for t in trials_per_house), f"each house should have {nt} rounds"# houses should be at distinct positionsused = [tuple(np.asarray(s.house_pos)[i]) for i in range(E.N_PLACES) if np.asarray(s.house_active)[i]]assert len(set(used)) == len(used), "house positions must be distinct"# per-session randomization: positions differ across seedsdef positions(seed):ts = E.jax_web_env.reset(jax.random.PRNGKey(seed), E.main_params)return [tuple(int(v) for v in np.asarray(ts.state.house_pos)[i]) for i in range(E.N_PLACES)]run(E.main_params, "MAIN")run(E.practice_params, "PRACTICE")assert positions(1) != positions(2), "house layout should differ across sessions"print("\nALL SMOKE TESTS PASSED")
README.md+29
experiment_structure.py+411-248
export_csv.pyAdded+128
make_demo_data.pyAdded+99
smoke_test.py+68-62