"""Look up a participant's condition assignment at run time. The problem this solves is the one the Pavlovia shelf solved in the PsychoPy tasks: a participant who reloads, refreshes, or restarts must land on the SAME condition, or the counterbalancing is quietly destroyed. The shelf did it with a persistent `orderMap` dictionary keyed by subject id -- look the subject up, and only assign a new order if they are not already in it. Here the same guarantee comes from DETERMINISM instead of shared state, which removes the failure modes the shelf has to work around: assignment = f(participant id) Same id in, same arm out -- on the first visit, on a reload, after the server restarts, forever, with no counter to increment and no state to lose. There is no window in which two simultaneous arrivals can claim the same slot, because nothing is claimed. It is also why effort_design._seed_from_pid had to move off Python's hash(): a per-process salt made f() unstable and the trial order changed under exactly these conditions. Two sources, in order: 1. allocation.csv -- the pre-registered table for the planned study. Assignment is EXACTLY balanced there (25 per cell per group) because it was dealt out in advance rather than sampled per arrival. 2. a hash of the id -- for ids that were never in the table, i.e. SONA, where participants bring their own identifiers. Balance is then approximate, the way any per-arrival randomisation is. Repeat starts are safe under both. """ import csv import os import zlib import effort_design as D HERE = os.path.dirname(os.path.abspath(__file__)) TABLE = os.path.join(HERE, "allocation.csv") #: Must match make_allocation.ARMS. Kept as a plain list so a hashed assignment #: draws from exactly the same set of arms as the pre-registered table. ARMS = [ ("", ""), ("1", ""), ("2", ""), ("both", "12"), ("both", "21"), ] _table = None def _load(path=TABLE): global _table if _table is None: _table = {} try: with open(path, newline="", encoding="utf-8") as f: for row in csv.DictReader(f): _table[str(row["pid"]).strip()] = row except FileNotFoundError: pass # hashed assignment still works without the table return _table def group_of(pid): """Recruited group from the first digit of the pid, per next_id.py. Returns "" for ids that do not follow that convention -- a SONA id is not a group 0 participant just because it happens to start with a zero, so this only claims a group when the table says so. """ row = _load().get(str(pid).strip()) if row: return row.get("group", "") return "" def assign(pid): """This participant's arm: {'night', 'night_order', 'group', 'source'}. Deterministic in both branches, so calling it again for the same pid always returns the same arm. """ key = str(pid or "").strip() row = _load().get(key) if row: return { "night": row.get("night", ""), "night_order": row.get("night_order", "") or "12", "group": row.get("group", ""), "source": "table", } # Not pre-allocated (a SONA id). Derive the arm from the id itself. The salt # keeps this independent of the trial-order seed, so the arm and the order # are not two views of the same number. n = zlib.crc32(f"arm|{key}".encode()) % len(ARMS) night, order = ARMS[n] return { "night": night, "night_order": order or "12", "group": "", "source": "hash", } def night_list(night): """'both' / '1' / '2' / '' -> the list effort_stages.night_conditions wants.""" if night == "both": return [1, 2] if night in ("1", "2"): return [int(night)] return [] def describe(pid): a = assign(pid) return (f"pid={pid} group={a['group'] or '-'} night={a['night'] or 'none'} " f"order={a['night_order']} seed={D._seed_from_pid(pid)} ({a['source']})") if __name__ == "__main__": import sys for p in sys.argv[1:] or ["0001", "1001", "SONA12345", "SONA12345"]: print(" ", describe(p))