File size: 29,957 Bytes
5fd2308
8d23ae4
5fd2308
 
e8598c4
5fd2308
 
 
 
 
cb32d35
 
 
 
 
3fecce7
 
 
 
 
e8598c4
3fecce7
 
cb32d35
e8598c4
cb32d35
 
 
e8598c4
5fd2308
cb32d35
5fd2308
 
ed546e6
 
 
 
 
 
 
 
5fd2308
6fe78ac
ed546e6
 
5fd2308
 
 
cb32d35
5fd2308
 
 
 
 
 
 
cb32d35
 
056d99b
5fd2308
cb32d35
a6f7c10
cb32d35
e80f5e1
a6f7c10
81f9092
a6f7c10
967c298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81f9092
3fecce7
 
 
 
 
 
 
 
cb32d35
 
 
3fecce7
 
 
 
 
 
 
 
 
a6f7c10
3fecce7
 
cb32d35
3fecce7
cb32d35
 
3fecce7
 
 
 
cb32d35
5fd2308
9538496
 
 
 
 
 
 
 
 
 
 
 
 
 
5fd2308
 
 
ed546e6
 
 
 
 
 
 
 
 
5fd2308
 
ed546e6
5fd2308
 
 
 
 
bf22a94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fd2308
bf22a94
 
 
 
 
 
 
 
 
 
 
 
 
5fd2308
 
 
6fe78ac
 
 
 
 
 
 
 
 
 
 
 
 
 
a6f7c10
 
 
 
6fe78ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5567807
 
 
 
 
 
 
 
 
 
 
 
 
 
a512d70
 
5567807
 
 
 
 
 
 
 
 
 
 
 
a512d70
6fe78ac
 
 
 
 
a512d70
 
 
5567807
a6f7c10
983eb92
 
 
5567807
 
 
 
983eb92
6fe78ac
983eb92
6fe78ac
 
 
 
 
 
983eb92
 
 
5fd2308
cb32d35
5fd2308
 
 
 
 
 
 
bf22a94
9538496
 
bf22a94
 
 
9538496
e8598c4
9538496
cb32d35
9538496
 
bf22a94
 
5fd2308
cb32d35
 
 
 
 
 
 
 
9538496
5fd2308
 
cb32d35
3fecce7
cb32d35
a6f7c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fd2308
9538496
5fd2308
9538496
5fd2308
9538496
 
 
 
 
 
 
5fd2308
9538496
 
 
 
ea29ada
967c298
 
 
 
 
5fd2308
bf22a94
 
cb32d35
 
 
5fd2308
9538496
 
cb32d35
9538496
967c298
5fd2308
 
 
3421e60
967c298
3421e60
a6f7c10
967c298
 
e8598c4
3421e60
a1250db
 
 
 
 
967c298
cb32d35
 
967c298
 
 
 
 
 
 
3421e60
a1250db
967c298
 
 
 
 
 
 
a1250db
 
 
c0b3484
 
 
 
 
bf22a94
a6f7c10
c0b3484
bf22a94
 
 
 
9538496
 
 
c0b3484
 
bf22a94
cb32d35
c0b3484
9538496
cb32d35
5567807
c0b3484
a512d70
bf22a94
5567807
983eb92
cb32d35
 
 
 
 
 
9538496
 
 
c0b3484
 
 
 
 
5fd2308
 
 
 
 
 
 
 
 
 
 
cb32d35
5fd2308
 
 
cb32d35
 
 
 
 
 
 
 
 
 
 
 
 
3fecce7
 
 
 
 
 
 
 
 
 
 
 
 
 
cb32d35
9538496
 
 
 
 
 
 
5fd2308
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
"""
Deterministic, counterbalanced order generation for TreasureHuntForTwo.

The participant ID *is* the order: parsing it gives the group and a number, and from
those we deterministically build that participant's whole session, reproducibly.

ID format: first digit = group (0 = control/healthy, 1 = CU), the rest = a number.
  e.g. "0042" -> group 0, number 42 ;  "1007" -> group 1, number 7.

Counterbalancing:
  * Chest APPEARANCE has no persistent identity: every one of the 24 chests seen in a
    session is used EXACTLY ONCE (one house entails 2 chests x 12 houses = 24), so a look
    never recurs and can't be used as a "always pick this one" shortcut. This matches the
    original PsychoPy task (fresh stimuli each block) and replaces an earlier NiceWebRL-port
    deviation (4 looks reused for the whole session) that pilot testers found exploitable
    ("I always pick red because it's the best").
  * Reward-profile <-> appearance is *systematically* counterbalanced, the same way as block
    order below: each letter (A-D) owns a fixed set of 6 "stim slots" out of 24, rotated by
    `number` rather than drawn independently per ID. Over any complete run of 24 consecutive
    participants (within a group), every one of the 24 chests lands under every letter exactly
    6 times, no color is ever systematically over/under-represented for any reward profile,
    for any completed prefix of the sample, not just in the limit (see `next_id.py`'s balance
    report, which now confirms this rather than merely hoping for it).
  * BLOCK ORDER (which pair-slot is entered 1st, 2nd, ... 12th) is a *cyclic Latin square*
    over `number`, systematically counterbalanced like `house_pos`'s layout rotation, NOT an
    independent random draw. This guarantees position balance holds for any completed prefix
    of the sample (robust to real-world quits/no-shows), which a pure per-ID shuffle can't.
  * Pair->house assignment, chest sides, and the exact outcome shuffles are
    *randomized but reproducible* per ID (a fixed seed from the ID), randomization
    decorrelates them from the pairs without needing a huge condition count.
Outcomes are EXACT per block per recipient: 12 good (+100), 2 bad (-100), 2 neutral (0).

Everything here is plain numpy and fully testable (run `python orders.py`).

A pid with NO digits at all (a typo, a stray browser-generated storage id, a non-numeric
pilot label) can't be parsed into a group/number, but it still needs *some* reproducible
seed. Group 9 is reserved for exactly this: never a real recruitment group, excluded from
next_id.py's per-group counting and from orders.py's within-group counterbalancing (both are
scoped to groups 0/1 only), so these sessions can't dilute real data. The number is a hash of
the original string rather than a fixed 0, so distinct bad pids land on distinct seeds instead
of all piling onto the same one.
"""
import functools
import zlib

import numpy as np

N_PLACES = 12
N_TRIALS = 16
LETTERS = ["A", "B", "C", "D"]
PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]   # AB AC AD BC BD CD
PLACE_PAIRS = PAIRS + PAIRS                                  # 12 places (each pair twice)
# fixed reward profiles per letter (self_good, other_good)
LETTER_SELF_GOOD = [1, 1, 0, 0]      # A,B good for self
LETTER_OTHER_GOOD = [1, 0, 1, 0]     # A,C good for partner

# exact outcome counts over 16 trials (75% good / 12.5% bad / 12.5% neutral)
N_PLUS, N_MINUS, N_ZERO = 12, 2, 2
COIN = 10                              # each coin outcome shown as +10 / -10 / 0

# 24 distinct box stimuli; one used per (house, chest-slot) = 12*2 = 24, so every look in a
# session is unique and never repeats. The look is an arbitrary, randomized label with no
# persistent tie to a reward profile.
N_STIM = 24
N_COLORS = 13          # must match len(sprites.STIM_PALETTE): stimulus color = sid % N_COLORS

# ---- PRACTICE: a fixed, guided 6-step tutorial (no randomization) ----------------------
# Four named practice chests (letters A,B,C,D -> these practice-only stimulus ids). The names
# come from sprites.PRACTICE_STIM_DESIGN; the narration lives in experiment_structure.
PRAC_STIMS = [24, 25, 26, 27]   # A brown woven, B blue striped, C green dotted, D dark stone
PRAC_TRIALS = 6
# Each step: (directed_letter, distractor_letter, self_coins, other_coins). The participant is
# TOLD which chest to open and only that one opens (enforced); the distractor is just shown.
PRACTICE_PLAN = [
    (0, 1, +COIN, +COIN),   # 1 mutual benefit    (brown woven)
    (0, 1, +COIN, +COIN),   # 2 consistency       (brown woven, again)
    (3, 2, -COIN, -COIN),   # 3 mutual loss       (dark stone)
    (1, 0, +COIN, -COIN),   # 4 instrumental harm (blue striped)
    (2, 3, -COIN, +COIN),   # 5 altruism          (green dotted)
    (0, 1,     0,     0),   # 6 zero              (brown woven)
]


# Fixed (session-invariant) baseline: for each letter, the 6 canonical PLACE_PAIRS indices
# (0..11) where it appears, in list order -> a rank 0..5. Every letter gets a fixed block of
# 6 "stim slots" out of 24 (A: 0-5, B: 6-11, C: 12-17, D: 18-23) -- see _place_stim_map.
_LETTER_OCCURRENCES = [[i for i in range(N_PLACES) if letter in PLACE_PAIRS[i]] for letter in range(4)]
_OCC_RANK = [{idx: rank for rank, idx in enumerate(occ)} for occ in _LETTER_OCCURRENCES]


def _place_stim_map(number, block_order):
    """Assign all 24 chest stimuli, one each, across the 12 blocks' 2 letters (never reused).

    Returns a (12,4) array: `stim_map[block, letter]` is the stimulus id for that letter AT
    that block (only the 2 letters present at that block are ever populated; the other 2
    entries per row are -1 and never looked up).

    Systematically counterbalanced, like block order and house layout, rather than an
    independent random draw: each letter owns a fixed baseline of 6 stimulus "slots" out of
    24, and the id in each slot is `(slot + number) % 24` -- a single rotation shared by every
    slot. Rotating a permutation by a constant is still a permutation, so every one of the 24
    ids is still used exactly once per session; but because the SAME rotation amount is used
    for every slot, over any complete run of 24 consecutive participants (within a group) each
    of the 24 ids lands under each letter exactly 6 times -- no color is ever systematically
    over/under-represented for any reward profile, for any completed prefix of the sample, not
    just in the limit. See RANDOMIZATION.md.
    """
    shift = number % N_STIM
    stim_map = np.full((N_PLACES, 4), -1, dtype=np.int32)
    for b in range(N_PLACES):
        canonical_idx = int(block_order[b])
        for letter in PLACE_PAIRS[canonical_idx]:
            baseline = letter * 6 + _OCC_RANK[letter][canonical_idx]
            stim_map[b, letter] = (baseline + shift) % N_STIM
    return stim_map

# 5 FIXED house-location layouts on the 25x25 world (avoid the start tile [12,12]). The
# participant's layout = number % N_LAYOUTS (counterbalanced). Locations are decoupled from
# the block order: WHERE a house sits is just one of these 5 maps; WHICH condition (pair) it
# holds is set by the order the participant enters houses (see make_order).
N_LAYOUTS = 5
_GRIDS = [
    ([3, 8, 16, 21], [4, 12, 20]),
    ([4, 9, 15, 22], [6, 13, 21]),
    ([2, 9, 16, 23], [3, 11, 19]),
    ([5, 10, 17, 22], [5, 13, 21]),
    ([3, 10, 16, 21], [4, 14, 22]),
]
LOCATION_LAYOUTS = np.array(
    [[[r, c] for r in rows for c in cols] for rows, cols in _GRIDS], dtype=np.int32)   # (5,12,2)


def parse_pid(pid):
    """'0042' -> (group=0, number=42).  Robust to stray characters.

    A pid with no digits at all (e.g. 'BEAR_BehavPilot', a browser-generated hex storage id)
    can't be read as <group><number> -- rather than collapsing every such pid onto the same
    (0, 0) slot (where they'd pile up on top of each other AND on top of a real group-0
    participant), it falls to group 9 (reserved, never a real recruitment group -- see the
    module docstring) with a number hashed from the original string, so distinct bad pids
    land on distinct, reproducible seeds instead of colliding.
    """
    s = "".join(ch for ch in str(pid).strip() if ch.isdigit())
    if not s:
        return 9, zlib.crc32(str(pid).encode()) % 999_999
    group = int(s[0])
    number = int(s[1:]) if len(s) > 1 else 0
    return group, number


#: Added to a PARENT's number so a parent and their child, who share one participant ID,
#: do not receive the same design. Without it `make_order` is a function of the pid alone,
#: so a dyad sees the same 24 chests in the same 12 houses in the same order, and a parent
#: who plays first can hand their child advice that transfers exactly ("the left one in the
#: castle"). An OFFSET rather than a hash of the role: the block order, chest-slot and
#: layout rotations are all cyclic in `number`, so shifting by a constant leaves the parent
#: sample as systematically counterbalanced as the child sample, where a hash would reduce
#: both to balanced-in-expectation. The value has to be coprime to all three cycle
#: lengths or it moves the parent on some and not others: 500 leaves layout alone, because
#: 500 % 5 == 0. 503 shifts the block order by 11, the chest slots by 23 and the layout by
#: 3, and keeps a 100-dyad study's parents (504-603) clear of its children (1-100).
#:
#: Set to 0 to give a dyad the identical design, which makes the within-dyad comparison a
#: matched one. Estimated from the SONA sessions, that matching is worth at most about a
#: 10% narrower standard error on the parent-child difference, and only if the design
#: explains a fifth of the between-session variance, which those sessions cannot show.
PARENT_SEED_OFFSET = 503

#: Seed space for a design drawn from a PREDETERMINED POOL (see randos.py) instead of from
#: the participant ID. A pool entry is identified by a `rando` id, and the design is then a
#: function of that id alone: the pid can be any label the study likes, in any order, with
#: any gaps, and two people who share a pid still get two designs because they hold two
#: pool entries. The base keeps a pool design's shuffles clear of every pid-derived seed,
#: so the pool is reproducible on its own and no collected session changes.
POOL_SEED_BASE = 20_000_003


def _group_number(pid, role="", rando=None):
    """(group, number) for the rotations. `role` is "" outside a dyad.

    With a `rando` from the pool, THAT is the number and the role shift does not apply:
    a parent and child already hold two different pool entries, so shifting again would
    move the parent off the entry the pool assigned them.

    Without one, every rotation in `make_order` is cyclic in `number`, so the one role
    shift moves a parent off their child's design on all of them at once.
    """
    group, number = parse_pid(pid)
    if rando is not None:
        return group, int(rando)
    if role == "p":
        number += PARENT_SEED_OFFSET
    return group, number


def _seed(pid, role="", rando=None):
    """Seed for this participant. Every pid that reached this function before `role` and
    `rando` existed, SONA and lab alike, still gets exactly its old seed."""
    group, number = _group_number(pid, role, rando)
    if rando is not None:
        return POOL_SEED_BASE + int(rando)
    return group * 1_000_003 + number + 1


#: The partner code and look for every pool entry, built once and indexed by `rando`.
#:
#: Drawing them independently per session is exactly what make_order's three rotations
#: avoid: over the 206 pool entries it gave avatar counts of 58/51/49/48 and handed two
#: entries the same code. Dealt from the pool instead, each entry gets its own code and
#: each of the four looks is used 51 or 52 times. Four looks is the intended number, so
#: two people in one household can still draw the same face; the share is now the honest
#: 1-in-4 rather than whatever an independent draw happened to produce.
#:
#: A `rando` outside 1..POOL_SIZE is not something allocate() hands out. It falls through
#: to the per-entry draw below rather than resizing these sequences, because resizing them
#: would move every other participant's partner.
_PARTNER_XOR, _AVATAR_XOR = 0x50A2748, 0x3C7B91

#: Its own stream for the within-block side counterbalance, for the reason given where it
#: is used: the shared rng's draw order is load-bearing for everything after it.
_SIDE_XOR = 0x51DE9A1


@functools.lru_cache(maxsize=4)
def _pool_partners(size):
    """([code per entry], [avatar index per entry]), both indexed from rando 1."""
    from sprites import PARTNER_AVATAR_GENDERS
    codes = np.random.default_rng(POOL_SEED_BASE ^ _PARTNER_XOR).choice(
        np.arange(2000, 9900), size=size, replace=False)
    looks = np.arange(size) % len(PARTNER_AVATAR_GENDERS)
    np.random.default_rng(POOL_SEED_BASE ^ _AVATAR_XOR).shuffle(looks)
    return codes.tolist(), looks.tolist()


def _pool_entry(rando):
    """The pool index for `rando`, or None when it is not a pool entry."""
    import randos
    if rando is None:
        return None
    r = int(rando)
    return r - 1 if 1 <= r <= randos.POOL_SIZE else None


def partner_seed_args(storage):
    """(pid, role, rando) for partner_id_for and partner_avatar_for, off a session store.

    Takes a plain mapping so this stays importable without nicegui; callers pass
    app.storage.user. `rando` arrives from the URL as a string and is absent outside
    the dyad pool, where None keeps the pid-only seed every earlier participant got.
    """
    rando = storage.get("rando")
    return (storage.get("pid", "") or "0001",
            storage.get("role", "") or "",
            int(rando) if str(rando if rando is not None else "").strip() else None)


def partner_id_for(pid, role="", rando=None):
    """A deterministic, anonymous 'community-database' member code for the matched partner.

    The partner does not play: the coins are earned on their behalf and a real stranger
    is paid them at the end. The code makes the match concrete in the instructions, and is
    reproducible (stable across reloads) and recorded. A 4-digit code, kept clear of the
    0xxx/1xxx participant IDs.

    `role` and `rando` have to be passed or the number is a function of the pid alone,
    which was the bug found in the first BEAR family on 2026-11-09: a parent plays under
    their first child's pid so the family keeps one row in the link sheet, so parent and
    child were handed the SAME stranger, #4846, with the same face, an hour apart in the
    same house. `rando` is unique per session, so it separates them. A session with no
    rando still gets its old pid-seeded number, which is every session collected before
    that date (see test_partner_identity.py).
    """
    import randos
    i = _pool_entry(rando)
    if i is not None:
        return int(_pool_partners(randos.POOL_SIZE)[0][i])
    rng = np.random.default_rng(_seed(pid, role, rando) ^ _PARTNER_XOR)
    return int(rng.integers(2000, 9900))


def partner_avatar_for(pid, role="", rando=None):
    """A deterministic, randomized-per-participant look for the matched partner (one of the
    4 sprites.PARTNER_AVATARS), used consistently at the matching reveal and everywhere the
    partner appears in-game. Independent RNG stream (own XOR constant), same pattern as
    partner_id_for, so it doesn't disturb make_order's stream and is reproducible on its own.

    Takes `role` and `rando` for the reason partner_id_for does. Four looks means two
    people in one household still draw the same face about a quarter of the time, the
    rate any two unrelated participants draw it; their partner numbers differ.
    """
    import randos
    from sprites import PARTNER_AVATAR_GENDERS
    i = _pool_entry(rando)
    if i is not None:
        idx = int(_pool_partners(randos.POOL_SIZE)[1][i])
    else:
        rng = np.random.default_rng(_seed(pid, role, rando) ^ _AVATAR_XOR)
        idx = int(rng.integers(0, len(PARTNER_AVATAR_GENDERS)))
    return idx, PARTNER_AVATAR_GENDERS[idx]


def _exact_sequence(good, rng):
    """A length-16 sequence with exactly 12/2/2, signed by good vs bad profile."""
    plus, minus = (COIN, -COIN) if good else (-COIN, COIN)
    seq = [plus] * N_PLUS + [minus] * N_MINUS + [0] * N_ZERO
    seq = np.array(seq, dtype=np.int32)
    rng.shuffle(seq)
    return seq


def make_order(pid, role="", rando=None):
    """Build the full, deterministic order for one participant ID.

    `rando` is a pool entry id (see randos.py). When given, the design is a function of it
    alone and the pid contributes nothing but the group label and the folder name.

    Like the ORIGINAL task: the BLOCK ORDER (sequence of the 12 option-pairs) is fixed per
    ID, and the Nth house the participant *enters* receives the Nth pair, independent of
    where the houses sit (that's set by one of 5 fixed location layouts). So `block_pairs`,
    `pair_code`, `side_schedule`, `outcomes`, `float_order` are all
    indexed by BLOCK (0..11 = entry order); `house_type` and `house_pos` are physical.
    """
    group, number = _group_number(pid, role, rando)
    rng = np.random.default_rng(_seed(pid, role, rando))

    # BLOCK ORDER: a cyclic Latin square over the 12 canonical pair-slots (systematically
    # counterbalanced, like the house_pos layout rotation below) instead of an independent
    # random permutation per ID. Over any complete run of 12 consecutive participants (within
    # a group), each pair-slot appears at each entry-position exactly once; a genuine i.i.d.
    # shuffle only balances position asymptotically, which breaks down under real-world
    # attrition (no-shows / quits) -- a participant who quits partway just leaves a gap, but
    # doesn't skew the position balance of whoever HAS completed so far.
    block_order = np.array([(i + number) % N_PLACES for i in range(N_PLACES)], dtype=np.int64)
    block_pairs = np.array([PLACE_PAIRS[i] for i in block_order], dtype=np.int32)        # (12,2)
    pair_code = np.array([PAIRS.index(tuple(PLACE_PAIRS[i])) for i in block_order], dtype=np.int32)

    # all 24 chests, one per (block, letter) slot -- never reused across the session
    stim_map = _place_stim_map(number, block_order)          # (12,4): [block, letter] -> stim id

    # which option is on the LEFT each trial, per block (0 => block_pairs[:,0] on left).
    #
    # Counterbalanced within a block, not drawn per trial: exactly half the trials put the
    # pair's first letter on the left and half its second, in shuffled order. That is what
    # the 20-trial PsychoPy task did through its targetIndex column, where 480 blocks over
    # 40 order files are every one of them exactly 10 and 10, across 432 distinct
    # sequences. This was `rng.integers(0, 2, size=...)` until 2026-11-09, which over 132
    # blocks of real sessions gave a median 9 of 16 on the commoner side, a worst block of
    # 13 of 16, and exact balance in 16% of blocks. It was the only part of the design
    # drawn that way: `outcomes` below is built by _exact_sequence and `float_order` is
    # counterbalanced 6 and 6.
    #
    # Its OWN rng, not the shared one. Every quantity after this point is drawn from `rng`
    # in order, so consuming a different number of values here would move the outcomes,
    # the float order, the house types and the house positions for every participant.
    # export_csv re-derives house positions from make_order for sessions already
    # collected, so that would make a re-export disagree with what was played.
    # The old per-trial draw still runs and its result is thrown away, purely to leave
    # `rng` at the position everything below expects. Deleting the call instead moved the
    # outcomes and house positions of every participant, which the fingerprints in
    # test_side_balance.py catch.
    rng.integers(0, 2, size=(N_PLACES, N_TRIALS))
    side_rng = np.random.default_rng(_seed(pid, role, rando) ^ _SIDE_XOR)
    half = np.array([0] * (N_TRIALS // 2) + [1] * (N_TRIALS // 2), dtype=np.int32)
    side_schedule = np.stack([side_rng.permutation(half) for _ in range(N_PLACES)])

    # exact outcomes per block: [block, option(0/1), recipient(0 self/1 partner), trial]
    outcomes = np.zeros((N_PLACES, 2, 2, N_TRIALS), dtype=np.int32)
    for b in range(N_PLACES):
        for o in range(2):
            letter = int(block_pairs[b, o])
            outcomes[b, o, 0] = _exact_sequence(LETTER_SELF_GOOD[letter], rng)
            outcomes[b, o, 1] = _exact_sequence(LETTER_OTHER_GOOD[letter], rng)

    # coin-float order per block: 6 you-first (0) + 6 partner-first (1), counterbalanced
    float_order = np.array([0] * (N_PLACES // 2) + [1] * (N_PLACES // 2), dtype=np.int32)
    rng.shuffle(float_order)

    # PHYSICAL houses: appearance (random per participant) + 1 of 5 fixed location layouts
    house_type = rng.permutation(N_PLACES).astype(np.int32)          # (12,) appearance per place
    layout_id = int(number % N_LAYOUTS)
    house_pos = LOCATION_LAYOUTS[layout_id].astype(np.int32)         # (12,2) positions per place

    # per-trial pair + directed option. In the MAIN task the pair is the same every trial of a
    # block and the choice is free (-1); the PRACTICE order overrides block 0 with the tutorial.
    trial_pairs = np.repeat(block_pairs[:, None, :], N_TRIALS, axis=1).astype(np.int32)  # (12,N_TRIALS,2)
    directed = np.full((N_PLACES, N_TRIALS), -1, dtype=np.int32)                         # -1 = free

    return dict(
        pid=str(pid), group=group, number=number, orderID=number,
        rando=(None if rando is None else int(rando)), stim_map=stim_map,
        # unused in the main task (only PRACTICE reads this); a fixed placeholder keeps every
        # EnvParams/EnvState instance the same shape for JAX (see make_practice_order).
        prac_stim_map=np.array(PRAC_STIMS, dtype=np.int32),
        block_order=block_order.tolist(),
        block_pairs_str="_".join(LETTERS[a] + LETTERS[b] for a, b in block_pairs.tolist()),
        block_pairs=block_pairs, pair_code=pair_code, side_schedule=side_schedule,
        outcomes=outcomes, float_order=float_order,
        house_type=house_type, house_pos=house_pos, layout_id=layout_id,
        trial_pairs=trial_pairs, directed=directed,
    )


def make_practice_order(pid="practice"):
    """Practice order: one nearby 'forest hut', a FIXED 6-step guided tutorial (PRACTICE_PLAN).

    The tutorial is the same for every participant (no randomization): each step shows two of
    the four named practice chests, TELLS the player which one to open (enforced via `directed`,
    so only that chest opens), and reveals a hand-set outcome covering all the social outcome
    types, mutual benefit, consistency, mutual loss, instrumental harm, altruism, and zero.
    """
    o = make_order("90000")
    o["house_pos"] = o["house_pos"].copy()
    o["house_pos"][0] = [12, 16]                      # near the start tile
    o["house_type"] = o["house_type"].copy()
    o["house_type"][0] = 12                           # practice-only forest hut
    # the four named practice chests: A brown woven, B blue striped, C green dotted, D dark stone
    # (o["stim_map"] is left as-is from make_order and unused during practice: rendering always
    # reads o["prac_stim_map"], already set to PRAC_STIMS by make_order, when practice=1)
    # block 0 = the AB pair label (used only by the end-of-practice rating screen)
    o["block_pairs"] = o["block_pairs"].copy(); o["block_pairs"][0] = [0, 1]
    o["pair_code"] = o["pair_code"].copy();     o["pair_code"][0] = 0

    # build the scripted block-0 schedule from PRACTICE_PLAN (trials 0..PRAC_TRIALS-1)
    o["trial_pairs"] = o["trial_pairs"].copy()
    o["directed"] = o["directed"].copy()
    o["side_schedule"] = o["side_schedule"].copy()
    o["outcomes"] = o["outcomes"].copy()
    o["outcomes"][0] = 0
    for t, (d_letter, x_letter, s_coin, o_coin) in enumerate(PRACTICE_PLAN):
        o["trial_pairs"][0, t] = [d_letter, x_letter]   # directed chest is option 0 of the pair
        o["directed"][0, t] = 0                          # enforce: only option 0 opens
        o["side_schedule"][0, t] = t % 2                 # alternate which side the directed chest is on
        o["outcomes"][0, 0, 0, t] = s_coin               # what the directed chest gives (self)
        o["outcomes"][0, 0, 1, t] = o_coin               # ... and partner
    return o


HOUSE_NAMES = ["castle", "cottage", "mansion", "treehouse", "tower", "barn", "windmill",
               "igloo", "tent", "pagoda", "lighthouse", "log cabin", "forest hut"]
GROUP_LABELS = {0: "control", 1: "CU"}


def manifest_row(pid, role="", rando=None):
    """One flat, self-describing row summarizing a participant's randomization.

    `role` and `rando` have to be passed in or the row describes the design the pid alone
    would have produced, which is the CHILD's design for a parent and the wrong pool entry
    for anyone drawing from randos.py.

    `block_order` is the fixed sequence of pairs the participant experiences (block 0,1,2,…),
    matching the original task: the Nth house entered = the Nth pair here. House appearance
    and position are physical (by place slot), set by the `layout_id` location layout.
    """
    import sprites  # lazy: only needed when actually logging
    o = make_order(pid, role, rando)
    sm = o["stim_map"].tolist()                       # (12,4): [block][letter] -> stim id (-1 unused)
    ht = o["house_type"].tolist()
    pairs = o["block_pairs_str"].split("_")          # pair for each BLOCK (entry order)
    bp = o["block_pairs"].tolist()
    partner_avatar_idx, partner_avatar_gender = partner_avatar_for(pid, role, rando)
    row = dict(pid=o["pid"], gid=o["group"],
               group=GROUP_LABELS.get(o["group"], o["group"]), orderID=o["orderID"],
               role=role, rando=("" if rando is None else int(rando)),
               partner_id=partner_id_for(pid, role, rando), layout_id=o["layout_id"],
               partner_avatar_idx=partner_avatar_idx, partner_avatar_gender=partner_avatar_gender)
    # every one of the 24 chests, one per (block, letter) slot, never reused in the session
    row["stim_by_block"] = "_".join(
        f"{b}:{LETTERS[l0]}{sm[b][l0]}-{LETTERS[l1]}{sm[b][l1]}" for b, (l0, l1) in enumerate(bp))
    row["stim_desc_by_block"] = "_".join(
        f"{b}:{LETTERS[l0]}={sprites.stim_describe(sm[b][l0])}|"
        f"{LETTERS[l1]}={sprites.stim_describe(sm[b][l1])}" for b, (l0, l1) in enumerate(bp))
    row["block_order"] = "_".join(f"{i}:{p}" for i, p in enumerate(pairs))
    row["float_order"] = "_".join(
        f"{i}:{'you' if f == 0 else 'partner'}-first" for i, f in enumerate(o["float_order"].tolist()))
    row["house_by_place"] = "_".join(
        f"{i}:{HOUSE_NAMES[h] if h < len(HOUSE_NAMES) else h}" for i, h in enumerate(ht))
    row["pos_by_place"] = "_".join(
        f"{i}:({r},{c})" for i, (r, c) in enumerate(o["house_pos"].tolist()))
    return row


if __name__ == "__main__":
    # --- self-tests ---
    o = make_order("0042")
    assert o["group"] == 0 and o["number"] == 42
    # exact counts hold for every place/option/recipient
    for p in range(N_PLACES):
        for opt in range(2):
            for r in range(2):
                seq = o["outcomes"][p, opt, r]
                assert (seq == COIN).sum() + (seq == -COIN).sum() == 14
                assert (seq == 0).sum() == 2
    # reproducible
    assert np.array_equal(make_order("0042")["outcomes"], o["outcomes"])
    # all 24 chest stimuli are used, each exactly once, across the session's 12 blocks x 2 letters
    bp = o["block_pairs"]
    used = [int(o["stim_map"][b, l]) for b in range(N_PLACES) for l in bp[b].tolist()]
    assert sorted(used) == list(range(N_STIM)), "every one of the 24 chests must appear exactly once"
    # the 2 unused letter-slots per block stay at the -1 sentinel
    for b in range(N_PLACES):
        unused_letters = [l for l in range(4) if l not in bp[b].tolist()]
        assert all(o["stim_map"][b, l] == -1 for l in unused_letters)
    # block order is a cyclic Latin square over `number`: any 12 consecutive numbers give each
    # of the 12 pair-slots at every entry-position exactly once
    for pos in range(N_PLACES):
        seen = {int(make_order(f"0{n:03d}")["block_order"][pos]) for n in range(1, N_PLACES + 1)}
        assert seen == set(range(N_PLACES)), f"position {pos} isn't balanced across a full cycle"
    # chest stim assignment is likewise a cyclic rotation over `number`: any 24 consecutive
    # numbers give each of the 24 chests under each letter exactly 6 times (never skewed
    # toward any one reward profile)
    from collections import Counter
    letter_counts = {letter: Counter() for letter in range(4)}
    for n in range(1, N_STIM + 1):
        oo = make_order(f"0{n:03d}")
        bp = oo["block_pairs"].tolist()
        for b in range(N_PLACES):
            for letter in bp[b]:
                letter_counts[letter][int(oo["stim_map"][b, letter])] += 1
    for letter in range(4):
        assert set(letter_counts[letter].values()) == {6}, \
            f"letter {letter} isn't balanced across a full 24-participant cycle"
    # block-order scheme: 6/6 float order, valid layout, distinct positions
    assert o["float_order"].sum() == 6 and len(o["float_order"]) == N_PLACES
    assert 0 <= o["layout_id"] < N_LAYOUTS
    assert len({tuple(p) for p in o["house_pos"].tolist()}) == N_PLACES
    # the 5 layouts are distinct and avoid the start tile
    seen = [tuple(map(tuple, L.tolist())) for L in LOCATION_LAYOUTS]
    assert len(set(seen)) == N_LAYOUTS
    assert all([12, 12] not in L.tolist() for L in LOCATION_LAYOUTS)
    print("orders.py self-tests passed.\n")
    print("Sample manifest rows:")
    for pid in ["0001", "0002", "0003", "0004", "1001", "1002"]:
        print(" ", manifest_row(pid))