HarvestForTwo / experiment_structure.py
princessamygdala's picture
Scaffold task_pe-cu-nicewebrl: fork SL-task infra for prosocial effort task
a05d415
Raw History Blame Contribute Delete
35.6 kB
"""
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 one
of four kinds (A/B/C/D). Opening a chest gives an outcome for BOTH you and a real
anonymous 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.10
Both 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) and
which 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 asyncio
import random
from typing import Optional
import jax
import jax.numpy as jnp
import jax.tree_util as jtu
import numpy as np
from flax import struct
from nicegui import app, ui
import sprites
import orders
import nicewebrl
from nicewebrl import JaxWebEnv, TimeStep, TimestepWrapper
from nicewebrl import Stage, EnvStage, FeedbackStage
from nicewebrl import get_logger
from nicewebrl.experiment import SimpleExperiment
logger = get_logger(__name__)
# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------
N_TRIALS = 20
PRAC_TRIALS = 5
N_PLACES = 12
WORLD = 25
M_OVERWORLD, M_CHOICE, M_OUTCOME, M_RATING = 0, 1, 2, 3
A_UP, A_DOWN, A_LEFT, A_RIGHT, A_SPACE = 0, 1, 2, 3, 4
action_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 self
LETTER_OTHER_GOOD = jnp.array([1, 0, 1, 0], dtype=jnp.int32) # A,C good for partner
LETTER_NAMES = ["A", "B", "C", "D"]
LETTER_COLOR = {0: (46, 204, 113), 1: (52, 152, 219), 2: (230, 126, 34), 3: (155, 89, 182)}
COLOR_NAMES = {0: "green", 1: "blue", 2: "orange", 3: "purple"}
P_PLUS_GOOD, P_MINUS_GOOD = 0.75, 0.15
P_PLUS_BAD, P_MINUS_BAD = 0.15, 0.75
COIN = 100 # each coin outcome is +100 / -100 / 0
PRAC_HOUSE_TYPE = 6 # "forest hut" (not used in main trials)
PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] # AB AC AD BC BD CD
PLACE_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 these
CANDIDATE_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 practice
RATING_MAX = 6 # 7-point scale 0..6
# ----------------------------------------------------------------------------
# Env structs
# ----------------------------------------------------------------------------
@struct.dataclass
class EnvParams:
house_pos: jax.Array # (12,2)
place_pairs: jax.Array # (12,2) letters per place (in block order)
pair_code: jax.Array # (12,)
house_type: jax.Array # (12,) 0..12
stim_map: jax.Array # (4,) letter -> stimulus id (0..23)
side_schedule: jax.Array # (12,N_TRIALS)
outcomes: jax.Array # (12,2,2,N_TRIALS) [place, option, recipient, trial]
n_trials: jax.Array
active_mask: jax.Array # (12,)
practice: jax.Array
@struct.dataclass
class EnvState:
mode: jax.Array
agent_pos: jax.Array
partner_pos: jax.Array
facing: jax.Array
walk_frame: jax.Array
consumed: jax.Array # (12,) bool
current_place: jax.Array
trial: jax.Array
n_trials: jax.Array
practice: jax.Array
self_coins: jax.Array
other_coins: jax.Array
left_letter: jax.Array
right_letter: jax.Array
chosen_side: jax.Array
chosen_letter: jax.Array
last_self_outcome: jax.Array
last_other_outcome: jax.Array
rating_cursor: jax.Array
ratings: jax.Array # (12,) -1 unrated else 0..6
house_pos: jax.Array # (12,2) positions this session
house_active: jax.Array # (12,) bool
place_pairs: jax.Array # (12,2) letters
pair_code: jax.Array # (12,) 0..5 (option-pair identity, for data)
house_type: jax.Array # (12,) 0..12 (which distinct house / room theme)
stim_map: jax.Array # (4,) letter -> stimulus id
side_schedule: jax.Array # (12, N_TRIALS) 0/1
outcomes: jax.Array # (12,2,2,N_TRIALS) pre-baked exact outcomes
def _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, right
def _select(cond, a, b):
return 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):
# the whole order is precomputed (per participant) and just copied into state
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,
current_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=params.house_pos.astype(jnp.int32),
house_active=active,
place_pairs=params.place_pairs.astype(jnp.int32),
pair_code=params.pair_code.astype(jnp.int32),
house_type=params.house_type.astype(jnp.int32),
stim_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), s
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 - 1
tr = 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)
# which option of this place's pair (0 or 1), then look up the pre-baked outcome
opt_idx = jnp.where(chosen_letter == s.place_pairs[s.current_place, 0],
jnp.int32(0), jnp.int32(1))
self_out = s.outcomes[s.current_place, opt_idx, 0, s.trial]
other_out = s.outcomes[s.current_place, opt_idx, 1, s.trial]
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) # Space closes the chosen chest -> next round
next_trial = s.trial + 1
place_done = next_trial >= s.n_trials
nt = 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_LEFT
is_right = action == A_RIGHT
is_confirm = (action == A_SPACE)
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, done
def 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_done
made_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)
def build_env_params(order, n_trials, active_mask, practice):
"""Turn an `orders.make_order(...)` dict into EnvParams (jnp arrays)."""
return EnvParams(
house_pos=jnp.asarray(order["house_pos"], jnp.int32),
place_pairs=jnp.asarray(order["place_pairs"], jnp.int32),
pair_code=jnp.asarray(order["pair_code"], jnp.int32),
house_type=jnp.asarray(order["house_type"], jnp.int32),
stim_map=jnp.asarray(order["stim_map"], jnp.int32),
side_schedule=jnp.asarray(order["side_schedule"], jnp.int32),
outcomes=jnp.asarray(order["outcomes"], jnp.int32),
n_trials=jnp.int32(n_trials),
active_mask=jnp.asarray(active_mask, jnp.int32),
practice=jnp.int32(practice),
)
_MAIN_ACTIVE = np.ones(N_PLACES, np.int32)
_PRAC_ACTIVE = np.zeros(N_PLACES, np.int32); _PRAC_ACTIVE[0] = 1
def main_params_for(pid):
return build_env_params(orders.make_order(pid), N_TRIALS, _MAIN_ACTIVE, 0)
def practice_params(pid="practice"):
return build_env_params(orders.make_practice_order(pid), PRAC_TRIALS, _PRAC_ACTIVE, 1)
# default params for module-load compilation (overridden per participant at runtime)
main_params = main_params_for("0001")
practice_params_default = practice_params()
# ----------------------------------------------------------------------------
# Rendering
# ----------------------------------------------------------------------------
W, H = 720, 560
TILE = 48
VIEW_W, VIEW_H = 13, 9
BOARD_W, BOARD_H = VIEW_W * TILE, VIEW_H * TILE
OX, OY = (W - BOARD_W) // 2, 104
def _i(x):
return int(np.asarray(x))
def _player_pal():
"""The avatar the participant chose (falls back to avatar 0)."""
try:
return sprites.AVATARS[int(app.storage.user.get("avatar", 0)) % len(sprites.AVATARS)]
except Exception:
return sprites.AVATARS[0]
from PIL import Image, ImageDraw
T = sprites.text # T(d, x, y, s, size=, bold=, fill=, center=, outline=)
def _hud(d, s_coins, o_coins):
T(d, 16, 12, f"YOU: {s_coins} PARTNER: {o_coins}", size=17, bold=True,
fill=(245, 245, 245), outline=True)
def _clip(v, lo, hi):
return max(lo, min(hi, v))
def _render_overworld(s):
consumed = np.asarray(s.consumed)
active = np.asarray(s.house_active)
hpos = np.asarray(s.house_pos)
htype = np.asarray(s.house_type)
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)
def screen(wr, wc):
return OX + (wc - cam_left) * TILE, OY + (wr - cam_top) * TILE
house_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 + vc
sprites.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(htype[a]), completed=bool(consumed[a]))
else:
wr = int(round(key - (0.6 if b == "player" else 0.5)))
sx, sy = screen(wr, a)
cxx, cyy = sx + TILE // 2, sy + TILE - 6
if b == "player":
sprites.draw_character(d, cxx, cyy, facing, frame, **_player_pal())
else:
sprites.draw_character(d, cxx, cyy, facing, frame, **sprites.PARTNER_PAL)
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)
label = "PRACTICE" if practice else f"Houses cleared: {explored}/{n_active}"
T(d, 16, 14, label, size=17, bold=True, fill=(245, 230, 150) if practice else (235, 235, 240),
outline=True)
T(d, 16, 40, "Walk with the arrow keys and step onto a house to go inside.",
size=15, fill=(205, 210, 220), outline=True)
d.rectangle([OX - 2, OY - 2, OX + BOARD_W + 1, OY + BOARD_H + 1], outline=(20, 24, 32), width=2)
T(d, OX, OY + BOARD_H + 8, "the figure beside you is your partner, who walks with you",
size=14, fill=(205, 210, 220))
return img
def _amt(v):
return f"+{v}" if v > 0 else (str(v) if v < 0 else "0")
def _earn(v, who):
if v > 0:
return f"You earned {v} points for {who}"
if v < 0:
return f"You lost {abs(v)} points for {who}"
return f"0 points for {who}"
# rotating teaching tips shown during the practice house (cycle one per try)
PRACTICE_TIPS = [
"Each try always wins OR loses coins for both you and your partner.",
"Your partner does not play - they only get coins from your choices.",
"Where a chest sits does not matter - only what is inside it does.",
"These coins become REAL bonus money at the end, for both of you.",
"The chests in a house are not equal - some give coins more often.",
]
def _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)
stim_map = np.asarray(s.stim_map)
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)
htype = int(np.asarray(s.house_type)[place_id])
house_name = sprites.HOUSE_NAMES[htype]
accent = (255, 90, 90) if practice else (255, 230, 120) # practice = red, main = gold
floor_y, table_top = 372, 338
cw, ch = 170, 116
y0 = table_top - ch
lx, rx = 130, W - 130 - cw
img = Image.new("RGB", (W, H), (0, 0, 0))
d = ImageDraw.Draw(img)
sprites.draw_room(d, W, H, floor_y, 80, W - 80, table_top, theme=sprites.ROOM_THEMES[htype])
T(d, 16, 58, f"Inside the {house_name} - Try {min(trial + 1, n_trials)} / {n_trials}",
size=15, bold=True, fill=(245, 245, 245), outline=True)
for x, letter, side in ((lx, left_letter, 0), (rx, right_letter, 1)):
chosen = (mode == M_OUTCOME) and (chosen_side == side)
stim = int(stim_map[letter])
sprites.draw_stim_chest(d, x, y0, cw, ch, stim, is_open=chosen, highlight=chosen)
sprites.draw_key(d, x + cw // 2 - 12, table_top + 4,
sprites.stim_color(stim))
# ---- top-center prompt / verbose feedback ----
if mode == M_CHOICE:
T(d, W // 2, 12, "Pick a chest to open: press <- or ->", size=22, bold=True,
fill=accent, center=True, outline=True)
else:
cx = (lx if chosen_side == 0 else rx) + cw // 2
sprites.draw_coin(d, cx - 32, y0 - 42, s_out)
sprites.draw_coin(d, cx + 32, y0 - 42, o_out)
T(d, cx - 32, y0 - 74, "YOU", size=14, bold=True, fill=(255, 255, 255), center=True, outline=True)
T(d, cx + 32, y0 - 74, "PARTNER", size=14, bold=True, fill=(255, 255, 255), center=True, outline=True)
T(d, W // 2, 8, _earn(s_out, "YOURSELF"), size=18, bold=True, fill=accent, center=True, outline=True)
T(d, W // 2, 34, _earn(o_out, "your PARTNER"), size=18, bold=True, fill=accent, center=True, outline=True)
T(d, W // 2, H - 30, "Press SPACE to continue", size=16, bold=True,
fill=(255, 255, 255), center=True, outline=True)
# ---- practice: a rotating teaching tip, centred on the floor below the table ----
if practice:
tip = PRACTICE_TIPS[trial % len(PRACTICE_TIPS)]
T(d, W // 2, floor_y + 18, tip, size=15, bold=True, fill=(255, 120, 120),
center=True, outline=True)
# ---- you + partner at the bottom; show only THIS try's outcome (never a running score) ----
sprites.draw_character(d, 120, H - 12, 1, 0, **_player_pal())
sprites.draw_character(d, W - 120, H - 12, 1, 0, **sprites.PARTNER_PAL)
T(d, 120, H - 98, "YOU", size=15, bold=True, fill=(255, 255, 255), center=True, outline=True)
T(d, W - 120, H - 98, "PARTNER", size=15, bold=True, fill=(255, 255, 255), center=True, outline=True)
if mode == M_OUTCOME:
T(d, 120, H - 78, _amt(s_out), size=26, bold=True, fill=(255, 235, 140), center=True, outline=True)
T(d, W - 120, H - 78, _amt(o_out), size=26, bold=True, fill=(255, 235, 140), center=True, outline=True)
return img
def _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]
stim_map = np.asarray(s.stim_map)
stim_l, stim_r = int(stim_map[int(opt[0])]), int(stim_map[int(opt[1])])
img = Image.new("RGB", (W, H), (40, 44, 60))
d = ImageDraw.Draw(img)
T(d, W // 2, 56, "You're done at this house!", size=22, bold=True,
fill=(255, 230, 120), center=True, outline=True)
T(d, W // 2, 96, "Which box did you prefer?", size=20, bold=True,
fill=(255, 255, 255), center=True, outline=True)
sprites.draw_stim_chest(d, 70, 200, 120, 96, stim_l, is_open=False)
sprites.draw_stim_chest(d, W - 70 - 120, 200, 120, 96, stim_r, is_open=False)
n = RATING_MAX + 1
x0, x1, y = 250, W - 250, 250
for i in range(n):
cx = x0 + (x1 - x0) * i // (n - 1)
r = 17 if i == cursor else 11
fill = (241, 196, 15) if i == cursor else (95, 100, 124)
d.ellipse([cx - r, y - r, cx + r, y + r], fill=fill, outline=(20, 24, 32), width=2)
T(d, 130, 322, "strongly prefer", size=14, fill=(220, 220, 228), center=True, outline=True)
T(d, 130, 340, "this box", size=16, bold=True,
fill=sprites.stim_color(stim_l), center=True, outline=True)
T(d, W - 130, 322, "strongly prefer", size=14, fill=(220, 220, 228), center=True, outline=True)
T(d, W - 130, 340, "this box", size=16, bold=True,
fill=sprites.stim_color(stim_r), center=True, outline=True)
T(d, W // 2, 322, "no preference", size=14, fill=(220, 220, 228), center=True, outline=True)
T(d, W // 2, H - 70, "Move with <- / ->, then press SPACE to confirm", size=18, bold=True,
fill=(255, 255, 255), center=True, outline=True)
return img
def render_state(timestep):
s = timestep.state
mode = _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.state
cp = jnp.clip(s.current_place, 0, N_PLACES - 1)
cl = jnp.clip(s.chosen_letter, 0, 3)
ct = jnp.clip(s.trial, 0, N_TRIALS - 1)
pid, gid = "", -1
# stash latest non-practice totals so the final screen can show points -> money
try:
pid = app.storage.user.get("pid", "")
gid = orders.parse_pid(pid)[0]
if int(s.practice) == 0:
app.storage.user["self_points"] = int(s.self_coins)
app.storage.user["partner_points"] = int(s.other_coins)
except Exception:
pass
return dict(
pid=pid, gid=gid,
mode=s.mode, place=s.current_place, trial=s.trial, n_trials=s.n_trials,
practice=s.practice, pair_code=s.pair_code[cp], house_type=s.house_type[cp],
left_letter=s.left_letter, right_letter=s.right_letter,
left_stim=s.stim_map[s.left_letter], right_stim=s.stim_map[s.right_letter],
chosen_side=s.chosen_side, chosen_letter=s.chosen_letter,
chosen_stim=s.stim_map[cl],
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,
# per-option outcomes THIS trial (for A_self/A_other ... columns), as shown (+/-100/0)
opt0_letter=s.place_pairs[cp, 0], opt1_letter=s.place_pairs[cp, 1],
opt0_self=s.outcomes[cp, 0, 0, ct], opt0_other=s.outcomes[cp, 0, 1, ct],
opt1_self=s.outcomes[cp, 1, 0, ct], opt1_other=s.outcomes[cp, 1, 1, ct],
)
# ----------------------------------------------------------------------------
# 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()
class OrderedEnvStage(EnvStage):
"""Rebuilds env_params for THIS participant (from their PID) just before the reset.
Safe under concurrency: env_params is only used by reset(), which runs synchronously
at the very start of activate() with no await in between; step() ignores params.
"""
async def activate(self, container):
task = self.metadata.get("task", "main")
try:
if task == "practice":
self.env_params = practice_params(app.storage.user.get("pid", "practice"))
else:
self.env_params = main_params_for(app.storage.user.get("pid", "0001"))
except Exception as e:
logger.warning(f"order build failed, using default: {e}")
await super().activate(container)
def make_env_stage(name, params, metadata):
return OrderedEnvStage(
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)
# ----------------------------------------------------------------------------
# Instruction text (shown by the web_app intro flow with Back/Next, mouse-only)
# ----------------------------------------------------------------------------
COVER_STORY = """
You are an adventurer exploring a world to make some money. Inside each house are two
treasure chests β€” open one with its key and you'll find coins.
Here's the twist: you've been matched with a **partner** β€” **another person your age** from
our community database, who is **not** taking part in this study. Every chest you open
affects the coins for **both you and your partner** at once. Your partner does **not** play β€”
they only earn or lose money from **your** choices.
- Some chests are more likely to give coins to **you** but not your **partner**.
- Some are more likely to give coins to your **partner** but not **you**.
- Some are more likely to give coins to **both** of you, some to **neither** of you.
Coins become real money at the end (**about $1 per 1000 coins, up to $6**), paid to both
**you** and the **other person** as a bonus pocket-money payment.
**Your job: open chests and learn which ones are worth opening.**
"""
HOW_TO_PLAY = """
- **Walk** with the **arrow keys**, and step onto a house to go inside.
- Inside are **two unique chests**. Press the **left** or **right** **arrow key** on your
keyboard to open that chest.
- Each **unique chest** brings a certain amount of coins β€” that's what matters. Watch out:
the chests can **swap sides**, so don't click too fast!
- You'll see what you and your partner got, then press **Space**.
- Each house gives you **20 tries** β€” choose carefully, and finish all 20 before leaving
each house.
- Then you'll **rate which unique chest you preferred**, and head to the next house.
Let's start with a quick **practice**!
"""
# ----------------------------------------------------------------------------
# Quiz (after the practice round). Wrong answers lock the buttons and just advance.
# ----------------------------------------------------------------------------
QUIZ = [
("On each round you open ONE of two unique treasure chests, and your choice affects the "
"coins for BOTH you and your partner.",
True, "Correct β€” each choice affects both you and your partner."),
("Your partner is another participant who also plays this game on your behalf.",
False, "Not quite β€” your partner is another person your age that we randomly picked from "
"our community database. They only earn or lose money based on YOUR choices."),
("After each choice you see what you got AND what your partner got.",
True, "Correct β€” every choice shows a result for both of you, so make sure you use this "
"feedback throughout the game!"),
("All chests are equally likely to give coins.",
False, "Not quite β€” some unique chests are more likely to give coins than others."),
("Coins turn into real money at the end (about $1 per 1000 coins, up to $6), for both you "
"and your partner.",
True, "Correct β€” both you and your partner get a bonus payment based on the coins."),
("Each unique chest keeps its meaning no matter where it appears on the screen.",
True, "Correct β€” each unique chest tells you what it tends to give, wherever it shows up."),
("Once you enter a house, you must finish all 20 choices before leaving.",
True, "Correct β€” you make 20 choices in each house, then move on."),
]
async def _ask_one(container, header, statement, correct, feedback):
nicewebrl.clear_element(container)
answer = {"val": None}
done = asyncio.Event()
with container.style("align-items:center; max-width:720px;"):
ui.markdown(f"### {header}")
ui.markdown(statement) # plain weight (not all-bold)
fb = ui.markdown("")
cont = ui.button("Continue", on_click=lambda: done.set())
cont.set_visibility(False)
with ui.row():
btn_t = ui.button("TRUE")
btn_f = ui.button("FALSE")
def choose(val):
answer["val"] = val
ok = (val == correct)
fb.set_content(("βœ… **Correct!** " if ok else "❌ **Incorrect.** ") + feedback)
btn_t.disable()
btn_f.disable() # once answered, can't choose again
cont.set_visibility(True)
btn_t.on("click", lambda: choose(True))
btn_f.on("click", lambda: choose(False))
await done.wait()
return answer["val"]
async def quiz_display(stage, container):
"""Ask each item once; lock the buttons after answering; no re-asking."""
nicewebrl.clear_element(container)
ev = asyncio.Event()
with container.style("align-items:center; max-width:720px;"):
ui.markdown("## Quiz β€” let's see if everything's clear!")
ui.markdown("A few quick true/false questions. You'll get feedback after each one.")
ui.button("Start quiz", on_click=lambda: ev.set())
await ev.wait()
responses = []
order = list(range(len(QUIZ)))
random.shuffle(order) # randomise question order per participant
for pos, i in enumerate(order):
st, co, fb = QUIZ[i]
ans = await _ask_one(container, f"Quiz β€” question {pos + 1} of {len(QUIZ)}", st, co, fb)
responses.append(dict(quizIndex=i, position=pos, statement=st,
answer=("TRUE" if ans else "FALSE"),
correct_answer=("TRUE" if co else "FALSE"),
is_correct=bool(ans == co), attempt=1))
# re-ask the missed ones at the end, until all are answered correctly
wrong = [r["quizIndex"] for r in responses if not r["is_correct"]]
if wrong:
nicewebrl.clear_element(container)
okev = asyncio.Event()
with container.style("align-items:center; max-width:720px;"):
ui.markdown("### Let's revisit the questions you missed")
ui.markdown("Please answer these again before continuing.")
ui.button("OK", on_click=lambda: okev.set())
await okev.wait()
attempt = 2
while wrong:
i = wrong[0]
st, co, fb = QUIZ[i]
ans = await _ask_one(container, "Try again", st, co, fb)
responses.append(dict(quizIndex=i, position=-1, statement=st,
answer=("TRUE" if ans else "FALSE"),
correct_answer=("TRUE" if co else "FALSE"),
is_correct=bool(ans == co), attempt=attempt))
if ans == co:
wrong.pop(0)
attempt += 1
nicewebrl.clear_element(container)
ev2 = asyncio.Event()
with container.style("align-items:center; max-width:720px;"):
ui.markdown("## You're all set!")
ui.markdown("The real adventure begins now β€” **12 houses** to explore. "
"Click below, then use the **arrow keys** to play.")
ui.button("Start the adventure", on_click=lambda: ev2.set())
await ev2.wait()
return dict(responses=responses)
async def _ignore_keys(e, container):
return # quiz is mouse-only; ignore stray key presses
# ----------------------------------------------------------------------------
# Assemble experiment (intro: welcome/instructions/explorer live in web_app.py)
# ----------------------------------------------------------------------------
all_stages = [
make_env_stage("Practice", practice_params_default, dict(task="practice")),
FeedbackStage(name="Quiz", display_fn=quiz_display, custom_key_press_fn=_ignore_keys),
make_env_stage("Explore", main_params, dict(task="main")),
]
experiment = SimpleExperiment(stages=all_stages, name="Duo Treasure Hunt")