File size: 4,224 Bytes
1f942d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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))