Reproducing Saez et al. (2018) from CRCNS ofc-3ΒΆ

Paper. Saez I, Lin J, Stolk A, Chang E, Parvizi J, Schalk G, Knight RT, Hsu M (2018). Encoding of multiple reward-related computations in transient and sustained high-frequency activity in human OFC. Current Biology 28:2889-2899. doi:10.1016/j.cub.2018.07.045. The claims file (claims/saez-2018.yaml) was written from the version of record (main text, legends, STAR Methods, Supplemental Information).

Data set. CRCNS ofc-3, "High-frequency activity of human orbitofrontal sites during decision-making play", doi:10.6080/K0VM49GF, read from the public bucket crcnsarchive under ofc-3/live/. Version: unversioned. CRCNS does not version data sets, and the paper cites the data set by its DOI only, so the files as published under live/ (data description version 0.7 of Feb 19, 2019, which added ofc_behav_data.zip) are the only version that can be pinned. The MD5 sums of the files read, from the data set's checksums.md5, are printed below so that a later change is detectable (data.zip 3531c772af4e4eb0c4e5332e74f94c81, ofc_behav_data.zip c35393e7734d33dc52e2c62b1a806274). The folder ofc-3/orig/ holds only older descriptions (no data).

What the data set holds. For 10 patients: window-averaged and 1-kHz HFA epochs around game presentation and around a second event called "buttonpress" (the data show it is near the outcome reveal, see the data check), the behaviour of every round with event times, the game of each round, and the authors' regressors per HFA trial. It holds no broadband signal, no electrode locations and no data of the 10 healthy participants.

claim tested here
methods-electrode-trial-counts tested
behavior-risk-neutral tested
fig1c-choice-win-probability tested
figs2a-choice-gamble-ev tested
fig1c-patients-like-controls blocked, data_missing (healthy participants not deposited)
figs2b-rt-conflict tested (patients only)
regressors-past-current-uncorrelated tested
figs6a-regressor-collinearity tested
fig3-present-encoding tested
fig3-latency-duration-similar tested
hfa-more-than-fp blocked, data_missing (no broadband signal)
figs4b-power-at-buttonpress blocked, data_missing (no broadband signal)
fig4-past-encoding tested
fig5-past-sustained tested
behavior-past-no-effect tested
fig6-past-short-lived tested
figs5d-sharp-boundary tested
mixed-effects-robust tested
figs6b-stepwise-similar tested
figs3a-risk-all-trials tested
figs3b-no-motor-encoding tested
anatomy-brodmann-counts blocked, data_missing (no electrode locations)
fig7-all-areas-similar blocked, data_missing
no-anatomical-gradient blocked, data_missing
tables2-patients-coverage tested
fig7f-multiplexing tested
figs7-present-past-overlap tested
fig2-example-electrodes tested
InΒ [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
import multiprocessing
import time
import warnings
from concurrent.futures import ProcessPoolExecutor

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats

import saez

pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
warnings.filterwarnings("ignore")
started = time.time()

print("checksums.md5:", saez.checksums())
beh = saez.load_behaviour()
H = {}
for s in saez.SUBJECTS:
    r = beh[s]["rounds"]
    idx = saez.align_trials(r, beh[s]["globals"])
    beh[s]["idx"] = idx
    H[s] = saez.load_hfa(s, rt_ms=np.round(r["rt"].values[idx] * 1000))
    print(s, "HFA trials x windows x electrodes:", H[s]["game"].shape, f"{time.time() - started:.0f} s")
checksums.md5: {'data.zip': '3531c772af4e4eb0c4e5332e74f94c81', 'docs/crcns_ofc-3_data_description.docx': 'f357eb8cb9997c95adb8d1ab0306f067', 'docs/crcns_ofc-3_data_description.pdf': '04f237a018b8ce1ca0e1045463653926', 'filelist.txt': '9e71d0641bdc9bf8de2b8ecf0baacac1', 'ofc_behav_data.zip': 'c35393e7734d33dc52e2c62b1a806274'}
s01 HFA trials x windows x electrodes: (180, 57, 5) 6 s
s02 HFA trials x windows x electrodes: (188, 57, 6) 11 s
s03 HFA trials x windows x electrodes: (194, 57, 59) 56 s
s04 HFA trials x windows x electrodes: (108, 57, 5) 59 s
s05 HFA trials x windows x electrodes: (179, 57, 61) 101 s
s06 HFA trials x windows x electrodes: (187, 57, 7) 106 s
s07 HFA trials x windows x electrodes: (181, 57, 11) 114 s
s08 HFA trials x windows x electrodes: (200, 57, 10) 122 s
s09 HFA trials x windows x electrodes: (200, 57, 19) 137 s
s10 HFA trials x windows x electrodes: (136, 57, 16) 145 s

Data checkΒΆ

InΒ [2]:
rows = []
for s in saez.SUBJECTS:
    r, g = beh[s]["rounds"], beh[s]["globals"]
    rows.append({"subject": s, "rounds": len(r), "timeouts": int(r.timeout.sum()),
                 "non_timeout": int((~r.timeout).sum()), "hfa_trials": H[s]["game"].shape[0],
                 "globals_rows": len(g), "electrodes": H[s]["game"].shape[2],
                 "gamble": int((r["choice.class"] == "Gamble").sum()),
                 "safebet": int((r["choice.class"] == "Safebet").sum())})
counts = pd.DataFrame(rows)
print(counts.to_string(index=False))
print("totals:", counts[["rounds", "timeouts", "non_timeout", "hfa_trials", "electrodes"]].sum().to_dict())
print("Description: 10 subjects, 200 rounds each, 192 electrodes; s10 has 138 rounds, and every subject",
      "but s08 and s09 has fewer HFA trials than non-timeout rounds.")
subject  rounds  timeouts  non_timeout  hfa_trials  globals_rows  electrodes  gamble  safebet
    s01     200         4          196         180           180           5     124       72
    s02     200         2          198         188           188           6     111       87
    s03     200         0          200         194           194          59      96      104
    s04     200        89          111         108           108           5      52       59
    s05     200         4          196         179           179          61     144       52
    s06     200         0          200         187           187           7     116       84
    s07     200         0          200         181           181          11      97      103
    s08     200         0          200         200           200          10     100      100
    s09     200         0          200         200           200          19      95      105
    s10     138         0          138         136           136          16      79       59
totals: {'rounds': 1938, 'timeouts': 99, 'non_timeout': 1839, 'hfa_trials': 1753, 'electrodes': 199}
Description: 10 subjects, 200 rounds each, 192 electrodes; s10 has 138 rounds, and every subject but s08 and s09 has fewer HFA trials than non-timeout rounds.

Each HFA trial is matched to a round (the files give no round number for HFA trials). The match uses the authors' regressors in sXX_behav_globals.mat (win probability, gamble, win, regret, previous win probability). The cell checks that every trial matched and that the other regressors agree with the values computed from the csv files (Table S1 definitions), including the t-1 values. It also matches the trials in reverse (each to the latest remaining round): where both matches give the same rounds, no other order-preserving match exists, so the t-2 to t-5, left/right and gamble-outcome values taken from the rounds are fixed by it.

InΒ [3]:
rows = []
for s in saez.SUBJECTS:
    r, g, idx = beh[s]["rounds"], beh[s]["globals"], beh[s]["idx"]
    p1 = saez.past_regressors(r, idx, 1)
    cur_mis = sum(int((~np.isclose(g[k].values, r[k].values[idx])).sum()) for k in saez.CURRENT)
    prev_mis = 0
    for k in saez.CURRENT:
        a, b = g["previous_" + k].values, p1[k].values
        prev_mis += int((~(np.isclose(a, b) | (np.isnan(a) & np.isnan(b)))).sum())
    dropped = sorted(set(np.where(~r.timeout.values)[0]) - set(idx))
    rev = saez.align_trials(r, g, reverse=True)
    p1r = saez.past_regressors(r, rev, 1)
    rev_mis = sum(int((~(np.isclose(g["previous_" + k].values, p1r[k].values) | (np.isnan(g["previous_" + k].values) & np.isnan(p1r[k].values)))).sum()) for k in saez.CURRENT)
    rows.append({"subject": s, "matched": len(idx), "mismatched current values": cur_mis,
                 "mismatched t-1 values": prev_mis, "rounds increasing": bool(np.all(np.diff(idx) > 0)),
                 "timeout rounds matched": int(r.timeout.values[idx].sum()),
                 "trials where the reverse match differs": ",".join(f"{t} (round {idx[t] + 1} or {rev[t] + 1})" for t in np.where(rev != idx)[0]),
                 "t-1 mismatches of the reverse match": rev_mis,
                 "non-timeout rounds without HFA": len(dropped),
                 "their round numbers": ",".join(str(d + 1) for d in dropped)})
print(pd.DataFrame(rows).to_string(index=False))
g = beh["s08"]["globals"]
print("\nValues of the authors' regressors (s08):")
for k in g.columns:
    print(f"  {k}: {np.unique(g[k].dropna()).round(3).tolist()[:12]}")
print("win probability = (10 - shown)/10 in every round:",
      all(np.allclose(beh[s]["rounds"].winprob, (10 - beh[s]["rounds"]["Risky.bet.shown.number"]) / 10) for s in saez.SUBJECTS))
print("risk = p(1-p) in the authors' file:", all(np.allclose(beh[s]["globals"].risk, beh[s]["globals"].winprob * (1 - beh[s]["globals"].winprob)) for s in saez.SUBJECTS))
subject  matched  mismatched current values  mismatched t-1 values  rounds increasing  timeout rounds matched trials where the reverse match differs  t-1 mismatches of the reverse match  non-timeout rounds without HFA                                                   their round numbers
    s01      180                          0                      0               True                       0                                                                           0                              16                11,13,14,37,40,74,75,84,85,105,114,115,116,120,173,181
    s02      188                          0                      0               True                       0                    88 (round 95 or 96)                                    2                              10                                       1,6,7,12,96,104,105,106,196,197
    s03      194                          0                      0               True                       0                                                                           0                               6                                                  16,20,51,152,199,200
    s04      108                          0                      0               True                       0                                                                           0                               3                                                              24,26,28
    s05      179                          0                      0               True                       0                                                                           0                              17               20,21,62,63,66,67,68,90,94,95,98,99,140,157,183,197,198
    s06      187                          0                      0               True                       0                                                                           0                              13                         13,14,34,40,41,42,130,131,132,133,171,172,173
    s07      181                          0                      0               True                       0                                                                           0                              19 39,40,41,78,79,80,105,106,107,125,126,127,139,166,167,193,194,195,196
    s08      200                          0                      0               True                       0                                                                           0                               0                                                                      
    s09      200                          0                      0               True                       0                                                                           0                               0                                                                      
    s10      136                          0                      0               True                       0                                                                           0                               2                                                               136,137

Values of the authors' regressors (s08):
  exputil: [0.0, 2.5, 3.0, 6.0, 7.5, 8.0, 9.0, 10.0, 10.5, 12.0, 12.5, 13.5]
  gamble_ind: [0.0, 1.0]
  loss_ind: [0.0, 1.0]
  previous_exputil: [0.0, 2.5, 3.0, 6.0, 7.5, 8.0, 9.0, 10.0, 10.5, 12.0, 12.5, 13.5]
  previous_gamble_ind: [0.0, 1.0]
  previous_loss_ind: [0.0, 1.0]
  previous_regret: [-20.0, -15.0, -10.0, -5.0, 0.0]
  previous_risk: [0.0, 0.09, 0.09, 0.16, 0.16, 0.21, 0.21, 0.24, 0.25]
  previous_rpe: [-21.0, -18.0, -17.5, -15.0, -14.0, -12.5, -12.0, -10.0, -9.0, -8.0, -7.5, -6.0]
  previous_win_ind: [0.0, 1.0]
  previous_winprob: [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
  regret: [-20.0, -15.0, -10.0, -5.0, 0.0]
  risk: [0.0, 0.09, 0.09, 0.16, 0.16, 0.21, 0.21, 0.24, 0.25]
  rpe: [-21.0, -18.0, -17.5, -15.0, -14.0, -12.5, -12.0, -10.0, -9.0, -8.0, -7.5, -6.0]
  win_ind: [0.0, 1.0]
  winprob: [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
win probability = (10 - shown)/10 in every round: True
risk = p(1-p) in the authors' file: True

The authors' regressor file settles three readings the claims file left open: win probability is (10 - shown number)/10 (Table S1's reading, so a shown 2 gives 0.8), risk is p(1 - p) (reading (b) of the claims file), and a t-1 regressor is the value of the previous round, with 0 for the choice and outcome regressors when that round was a timeout (reading (a) would drop those trials; the file keeps them with 0). The analysis uses the authors' values. The game is the same for every subject (gamble_choices.csv has one row per round), and the outcomes in every csv agree with it:

InΒ [4]:
for s in saez.SUBJECTS:
    r = beh[s]["rounds"]
    ok = ~r.timeout
    q = r.rt[ok].quantile([0.5, 1.0]).values
    lr = (r["reveal.time"] - r["buttonpress.time"])[ok]
    print(s, f"RT median {q[0]:.2f} s, max {q[1]:.2f} s, above 2 s: {int((r.rt[ok] > 2).sum())}",
          f"| reveal.time - buttonpress.time {lr.min():.3f} to {lr.max():.3f} s, median {lr.median():.3f}", end=" | ")
    won_csv = r["outcome"].isin(["Win", "WouldHaveWon"])
    side = (r["choice.location"] == r["Risky.Side"]) == (r["choice.class"] == "Gamble")
    print(s, "outcome agrees with hidden > shown:", f"{(won_csv == r.gamble_won)[ok].mean():.3f}",
          "| chosen side agrees with Risky.Side:", f"{side[ok].mean():.3f}",
          "| ties shown = hidden:", int((r['Risky.bet.hidden.number'] == r['Risky.bet.shown.number']).sum()))
gc = beh["s01"]["rounds"]
print("\nprize values:", sorted(gc["Risky.Bet.Amount"].unique()), "| shown numbers:", sorted(gc["Risky.bet.shown.number"].unique()))
rt = pd.concat([beh[s]["rounds"].loc[~beh[s]["rounds"].timeout, "rt"] for s in saez.SUBJECTS])
lag_game = pd.concat([beh[s]["rounds"]["choice.time"] - beh[s]["rounds"]["newround.time"] for s in saez.SUBJECTS])
lag_rev = pd.concat([beh[s]["rounds"]["reveal.time"] - beh[s]["rounds"]["buttonpress.time"] for s in saez.SUBJECTS])
print(f"choice.time - newround.time (s): {lag_game.min():.3f} to {lag_game.max():.3f} (game presentation at 0.75 s per the paper)")
print(f"reveal.time - buttonpress.time (s): {lag_rev.min():.3f} to {lag_rev.max():.3f} (the paper: 0.55 s);"
      f" quantiles 5, 25, 50, 75, 95%: {np.round(lag_rev.quantile([0.05, 0.25, 0.5, 0.75, 0.95]).values, 3)};"
      f" share of rounds within 0.031 to 0.047 s: {lag_rev.between(0.031, 0.047).mean():.3f} of {lag_rev.notna().sum()}")
print(f"reaction time buttonpress.time - choice.time (s), non-timeout: {rt.min():.3f} to {rt.max():.3f}, median {rt.median():.3f} (limit 2 s per the paper)")
print("non-timeout rounds with RT above 2 s:", int((rt > 2).sum()), "of", len(rt))
s01 RT median 1.17 s, max 1.94 s, above 2 s: 0 | reveal.time - buttonpress.time 0.531 to 0.547 s, median 0.532 | s01 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 1.000 | ties shown = hidden: 0
s02 RT median 1.01 s, max 1.96 s, above 2 s: 0 | reveal.time - buttonpress.time 0.544 to 0.548 s, median 0.546 | s02 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 1.000 | ties shown = hidden: 0
s03 RT median 0.84 s, max 1.45 s, above 2 s: 0 | reveal.time - buttonpress.time 0.531 to 0.547 s, median 0.531 | s03 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 1.000 | ties shown = hidden: 0
s04 RT median 1.30 s, max 1.98 s, above 2 s: 0 | reveal.time - buttonpress.time 0.531 to 0.547 s, median 0.532 | s04 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 1.000 | ties shown = hidden: 0
s05 RT median 0.83 s, max 1.97 s, above 2 s: 0 | reveal.time - buttonpress.time 0.531 to 0.593 s, median 0.532 | s05 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 1.000 | ties shown = hidden: 0
s06 RT median 0.97 s, max 2.27 s, above 2 s: 1 | reveal.time - buttonpress.time 0.031 to 0.047 s, median 0.047 | s06 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 1.000 | ties shown = hidden: 0
s07 RT median 1.12 s, max 2.50 s, above 2 s: 21 | reveal.time - buttonpress.time 0.031 to 0.047 s, median 0.047 | s07 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 0.975 | ties shown = hidden: 0
s08 RT median 1.72 s, max 2.50 s, above 2 s: 59 | reveal.time - buttonpress.time 0.031 to 0.047 s, median 0.047 | s08 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 0.925 | ties shown = hidden: 0
s09 RT median 1.28 s, max 2.00 s, above 2 s: 21 | reveal.time - buttonpress.time 0.042 to 0.045 s, median 0.043 | s09 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 0.945 | ties shown = hidden: 0
s10 RT median 4.35 s, max 80.50 s, above 2 s: 123 | reveal.time - buttonpress.time 0.031 to 0.235 s, median 0.047 | s10 outcome agrees with hidden > shown: 1.000 | chosen side agrees with Risky.Side: 0.870 | ties shown = hidden: 0

prize values: [np.int64(15), np.int64(20), np.int64(25), np.int64(30)] | shown numbers: [np.int64(0), np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(7), np.int64(8), np.int64(9), np.int64(10)]
choice.time - newround.time (s): 0.656 to 0.969 (game presentation at 0.75 s per the paper)
reveal.time - buttonpress.time (s): 0.031 to 0.593 (the paper: 0.55 s); quantiles 5, 25, 50, 75, 95%: [0.031 0.046 0.047 0.544 0.547]; share of rounds within 0.031 to 0.047 s: 0.310 of 1839
reaction time buttonpress.time - choice.time (s), non-timeout: 0.203 to 80.500, median 1.092 (limit 2 s per the paper)
non-timeout rounds with RT above 2 s: 225 of 1839

choice.time, a column the description does not list, is 0.66 to 0.97 s after the trial start: it is read as game presentation. reveal.time is 0.53 to 0.59 s after the button press in s01 to s05, near the 550 ms the paper and the description give, but 0.03 to 0.05 s in s06 to s10 (up to 0.24 s in s10). Reaction times stay under 2 s in s01 to s05, reach 2.5 s in s06 to s09, and in s10 have a median of 4.4 s and reach 80 s, with no timeouts: s10 does not follow the 2-s limit the paper states (and played 138 rounds). The chosen side agrees with Risky.Side in every round of s01 to s06 but in only 87 to 97.5% of rounds of s07 to s10. The gamble prizes are $15 to $30; the paper and the description say $10 to $30.

Next, the HFA arrays: window averages against the 1-kHz data, identical electrodes, value ranges.

InΒ [5]:
rows = []
for s in saez.SUBJECTS:
    h = H[s]
    rows.append({"subject": s, "electrodes": h["game"].shape[2],
                 "game raw range": tuple(round(v, 1) for v in h["game_raw_range"]),
                 "bp raw range": tuple(round(v, 1) for v in h["buttonpress_raw_range"]),
                 "NaN": h["game_nan"] + h["buttonpress_nan"],
                 "max |window - mean(raw)|": round(float(max(h["game_maxdiff"].max(), h["buttonpress_maxdiff"].max())), 4),
                 "electrodes whose windows differ": np.where((h["game_maxdiff"] > 1e-3) | (h["buttonpress_maxdiff"] > 1e-3))[0].tolist(),
                 "identical 1-kHz pairs": h["game_raw_identical"], "identical window pairs": h["game_win_identical"],
                 "window r > 0.95 pairs": h["game_high_corr"]})
chk = pd.DataFrame(rows)
print(chk.to_string(index=False))
print("same identical pairs in the buttonpress arrays:",
      all(H[s]["game_raw_identical"] == H[s]["buttonpress_raw_identical"] and H[s]["game_win_identical"] == H[s]["buttonpress_win_identical"] for s in saez.SUBJECTS))
print("\nvariables in sXX_ofc_hg_events.mat (s01):", H["s01"]["keys"])
print("same variable names in every subject:", all(set(H[s]["keys"]) == set(H["s01"]["keys"]) for s in saez.SUBJECTS))
subject  electrodes  game raw range   bp raw range  NaN  max |window - mean(raw)| electrodes whose windows differ                                                            identical 1-kHz pairs                                                           identical window pairs                                                                                                    window r > 0.95 pairs
    s01           5  (-79.5, 173.1) (-80.8, 199.8)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                                       []
    s02           6  (-25.5, 173.3) (-26.6, 178.2)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                                       []
    s03          59  (-43.7, 200.2) (-41.7, 173.9)    0                   33.6888                            [42] [(34, 42), (45, 52), (46, 53), (47, 54), (48, 55), (49, 56), (50, 57), (51, 58)] [(41, 42), (45, 52), (46, 53), (47, 54), (48, 55), (49, 56), (50, 57), (51, 58)] [(41, 42, 1.0), (45, 52, 1.0), (46, 53, 1.0), (47, 54, 1.0), (48, 55, 1.0), (49, 56, 1.0), (50, 57, 1.0), (51, 58, 1.0)]
    s04           5   (-17.6, 53.0)  (-16.0, 48.1)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                                       []
    s05          61 (-46.3, 1134.3) (-45.9, 909.7)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                       [(58, 60, 0.9959)]
    s06           7 (-97.7, 1566.3) (-59.9, 909.7)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                         [(4, 5, 0.9985)]
    s07          11  (-44.8, 261.2) (-41.6, 448.2)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                                       []
    s08          10   (-29.8, 94.2)  (-30.9, 88.0)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                                       []
    s09          19  (-44.6, 107.2) (-44.9, 113.8)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                                       []
    s10          16  (-31.8, 186.3) (-25.6, 159.6)    0                    0.0000                              []                                                                               []                                                                               []                                                                                                                       []
same identical pairs in the buttonpress arrays: True

variables in sXX_ofc_hg_events.mat (s01): {'buttonpress_events_hg': (180, 3001, 5), 'buttonpress_window_events_hg': (180, 57, 5), 'game_events_hg': (180, 3001, 5), 'game_window_events_hg': (180, 57, 5)}
same variable names in every subject: True

The window arrays are the mean of 201 samples (samples 50k to 50k + 200), so window k is centred at -900 + 50k ms. In s03, electrodes 52 to 58 are exact copies of electrodes 45 to 51 in both the 1-kHz and the window arrays; electrode 42's 1-kHz trace is a copy of electrode 34's and its window array a copy of electrode 41's (so its windows do not come from its own 1-kHz trace). With the seven copied electrodes removed, s03 holds 52 electrodes and the data set 192, the counts of Table S2. Electrode 42 holds no data of its own in either array. Following the protocol (each recording counted once), the analysis drops every electrode identical to an earlier one in either array: 8 in s03, leaving 191 electrodes. Pairs with r > 0.95 that are not identical (s05 58/60, s06 4/5) are kept.

InΒ [6]:
keep = {}
for s in saez.SUBJECTS:
    h = H[s]
    drop = sorted({j for i, j in h["game_raw_identical"] + h["game_win_identical"]})
    keep[s] = [e for e in range(h["game"].shape[2]) if e not in drop]
    for e in saez.EPOCHS:
        h[e] = h[e][:, :, keep[s]]
    h["offset_diff"] = h["offset_diff"][:, keep[s]]
    if drop:
        print(s, "dropped electrodes", drop)
N_ELEC = sum(len(v) for v in keep.values())
both = sum(H[s]["game"].shape[2] for s in saez.SUBJECTS)
print("electrodes analysed:", N_ELEC, {s: len(v) for s, v in keep.items()})
wall = np.concatenate([H[s]["game"].ravel() for s in saez.SUBJECTS])
print(f"window HFA, game epoch: range {wall.min():.1f} to {wall.max():.1f}, mean {wall.mean():.3f}, SD {wall.std():.2f} (units not stated)")
print("SD over trials of the first window [-1000, -800] ms (mean over electrodes), against the window centred 500 ms:")
for s in saez.SUBJECTS:
    g, b = H[s]["game"].astype(float), H[s]["buttonpress"].astype(float)
    print(f"  {s}: game first window {g[:, 0].std(0).mean():.3f}, game at 500 ms {g[:, 28].std(0).mean():.2f}; buttonpress first window {b[:, 0].std(0).mean():.2f}")
del wall
s03 dropped electrodes [42, 52, 53, 54, 55, 56, 57, 58]
electrodes analysed: 191 {'s01': 5, 's02': 6, 's03': 51, 's04': 5, 's05': 61, 's06': 7, 's07': 11, 's08': 10, 's09': 19, 's10': 16}
window HFA, game epoch: range -96.3 to 311.9, mean -0.133, SD 4.92 (units not stated)
SD over trials of the first window [-1000, -800] ms (mean over electrodes), against the window centred 500 ms:
  s01: game first window 0.000, game at 500 ms 5.10; buttonpress first window 5.34
  s02: game first window 0.000, game at 500 ms 5.05; buttonpress first window 4.85
  s03: game first window 0.000, game at 500 ms 4.52; buttonpress first window 4.34
  s04: game first window 0.000, game at 500 ms 3.86; buttonpress first window 3.93
  s05: game first window 0.000, game at 500 ms 4.45; buttonpress first window 4.20
  s06: game first window 0.000, game at 500 ms 6.03; buttonpress first window 5.89
  s07: game first window 0.000, game at 500 ms 4.77; buttonpress first window 4.67
  s08: game first window 0.000, game at 500 ms 5.17; buttonpress first window 4.96
  s09: game first window 0.000, game at 500 ms 5.89; buttonpress first window 5.68
  s10: game first window 0.000, game at 500 ms 4.45; buttonpress first window 4.01

The game epoch is baseline-corrected already: in every electrode its first window, [-1000, -800] ms, is the same in every trial (SD 0.000 over trials, against about 4 to 6 later on). This is consistent with the paper's 200-ms baseline having been subtracted before deposit, with the baseline before the fixation cross (game presentation is about 0.8 s after trial start). The buttonpress epoch is not corrected in its own first window (SD about 4 to 6). The analysis uses the deposited values, as the authors' own correction (an assumption, stated on the claims it changes). The claims file's baseline readings, (a) the 200 ms before each epoch's event and (b) the 200 ms before game presentation for both epochs, are applied on top of it in the section "Baseline readings" near the end, which repeats every test that rests on the encoding scans.

Clock. For every trial checked, the overlapping 1-kHz samples of the two epochs superimpose at one shift, with a small residual SD. The table gives that shift against the csv's reaction time (button press minus choice.time), over every HFA trial, and the mean difference between the two epochs at that shift, which shows whether the buttonpress epoch carries the same per-trial correction as the game epoch. A trial counts as matched when its shift minus the reaction time is within 25 ms of the subject's median (the median taken over trials whose residual SD is below 2); where the reaction time is long the epochs do not overlap and the shift cannot be found.

InΒ [7]:
off = pd.concat([H[s]["offsets"].assign(subject=s) for s in saez.SUBJECTS])
m = off[off.matched]
print("all HFA trials; matched = shift within 25 ms of the subject's median shift minus RT (taken over trials with residual SD < 2)")
print(off.groupby("subject").agg(trials=("trial", "size"), matched=("matched", "sum"), rt_ms_max=("rt_ms", "max")).join(
    m.groupby("subject").agg(offset_minus_rt_min=("offset_minus_rt", "min"), offset_minus_rt_median=("offset_minus_rt", "median"),
                             offset_minus_rt_max=("offset_minus_rt", "max"), sd_diff_median=("sd_diff", "median"),
                             sd_diff_max=("sd_diff", "max"), mean_diff_min=("mean_diff", "min"),
                             mean_diff_median=("mean_diff", "median"), mean_diff_max=("mean_diff", "max"))).to_string())
print("residual SD at the best shift, unmatched trials: median", round(float(off.sd_diff[~off.matched].median()), 2),
      "| unmatched trials with RT up to 2,100 ms (epochs overlap by 300 ms or more):", int((~off.matched & (off.rt_ms <= 2100)).sum()))
D = np.concatenate([H[s]["offset_diff"].ravel() for s in saez.SUBJECTS])
D = D[~np.isnan(D)]
print(f"level difference game - buttonpress, matched trials x electrodes: {np.percentile(D, [0, 5, 50, 95, 100]).round(2)} (min, 5%, median, 95%, max)")
print("trial-level HFA SD for comparison:", round(float(np.std(np.concatenate([H[s]['game'][:, 30].ravel() for s in saez.SUBJECTS]))), 2))
all HFA trials; matched = shift within 25 ms of the subject's median shift minus RT (taken over trials with residual SD < 2)
         trials  matched  rt_ms_max  offset_minus_rt_min  offset_minus_rt_median  offset_minus_rt_max  sd_diff_median  sd_diff_max  mean_diff_min  mean_diff_median  mean_diff_max
subject                                                                                                                                                                           
s01         180      180       1937                  564                   566.0                  567          0.4640        4.931         -2.463            0.0840          1.811
s02         188      188       1960                  564                   566.0                  569          0.8080        1.727         -0.676            0.8305          1.809
s03         194      194       1453                  534                   534.0                  535          0.3560        0.464         -0.672           -0.2435          0.121
s04         108      108       1985                  487                   487.0                  489          0.4360        1.034         -1.292            0.5335          1.453
s05         179      179       1968                  456                   472.0                  488          0.3480        0.869         -0.953           -0.5920          0.142
s06         187      185       2266                  564                   566.0                  582          0.6950        6.058         -2.372            0.0490          2.779
s07         181      167       2500                  595                   597.0                  598          0.3890        3.100         -4.857           -0.8540          3.275
s08         200      150       2500                  576                   597.0                  598          0.6115        5.672         -0.708            0.4830          1.427
s09         200      200       2003                  493                   494.0                  496          0.4010        0.955         -4.416           -3.2585         -0.057
s10         136       21      80500                  576                   592.0                  597          0.6110        1.997         -0.746            0.2700          1.226
residual SD at the best shift, unmatched trials: median 3.99 | unmatched trials with RT up to 2,100 ms (epochs overlap by 300 ms or more): 1
level difference game - buttonpress, matched trials x electrodes: [-36.48  -1.9   -0.36   0.84  16.98] (min, 5%, median, 95%, max)
trial-level HFA SD for comparison: 5.2

Per subject, the buttonpress epoch is centred a fixed 470 to 600 ms (the median per subject) after the csv's button press, measured from game presentation (choice.time). 1,572 of 1,753 trials are matched; of the 181 others, all but one have reaction times above 2.1 s, where the epochs overlap by less than 300 ms (s10 has 21 matched trials of 136, s08 150 of 200). That shift is near the outcome reveal as the paper times it (550 ms after the press). At that shift the two epochs differ by a per-trial constant whose median per subject runs from -3.26 to 0.83 (matched trials on the first electrode -4.86 to 3.28; over all electrodes 5 to 95% from -1.9 to 0.84, against a trial-level SD of 5.2), with median residual SDs of 0.35 to 0.81. So the buttonpress epoch is cut from the same HFA trace, with a per-trial offset close to the game epoch's correction but not equal to it; how it was set is not documented.

A contrast checks the alignment: the gamble outcome (hidden number above the shown one, defined whether or not the patient gambled) can be encoded only after the reveal. Below, the share of electrodes with p < 0.05 for that variable in each window, against the 5% expected by chance.

InΒ [8]:
won = {s: beh[s]["rounds"].gamble_won.values[beh[s]["idx"]].astype(float) for s in saez.SUBJECTS}
sc_won = saez.scan_all(H, won, 0, np.random.default_rng(0))
c = saez.WIN_CENTRES_MS
share_won = sc_won["sig"].mean(2) * 100
print("window centre (ms):      ", c[::2].tolist())
print("game epoch, % p<0.05:    ", share_won[0, ::2].round(1).tolist())
print("buttonpress epoch, %:    ", share_won[1, ::2].round(1).tolist())
for e, i in (("game", 0), ("buttonpress", 1)):
    pre, post = share_won[i, (c >= -900) & (c <= -100)].mean(), share_won[i, (c >= 100) & (c <= 900)].mean()
    print(f"{e}: mean share, centres -900 to -100 ms {pre:.1f}%, 100 to 900 ms {post:.1f}%; first window centre >= 0 above 10%: "
          f"{c[(c >= 0) & (share_won[i] > 10)].min() if ((c >= 0) & (share_won[i] > 10)).any() else None}")
window centre (ms):       [-900, -800, -700, -600, -500, -400, -300, -200, -100, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]
game epoch, % p<0.05:     [3.1, 5.2, 6.3, 7.3, 5.8, 4.7, 5.2, 4.7, 4.7, 6.3, 5.8, 3.1, 4.7, 1.6, 1.0, 4.2, 6.8, 7.3, 6.3, 6.3, 5.8, 5.8, 5.8, 7.3, 3.7, 3.1, 6.3, 5.8, 5.2]
buttonpress epoch, %:     [3.7, 4.2, 7.3, 4.7, 4.2, 9.4, 6.8, 4.2, 4.2, 6.3, 6.8, 8.9, 8.9, 14.1, 8.9, 8.4, 12.6, 9.9, 6.8, 7.3, 4.7, 5.8, 6.8, 6.3, 5.2, 6.8, 7.9, 5.8, 3.1]
game: mean share, centres -900 to -100 ms 5.5%, 100 to 900 ms 4.6%; first window centre >= 0 above 10%: None
buttonpress: mean share, centres -900 to -100 ms 5.8%, 100 to 900 ms 9.7%; first window centre >= 0 above 10%: 250

The gamble outcome is not encoded in the game epoch (near 5% throughout). In the buttonpress epoch the share rises above chance in windows centred 200 to 400 ms, too early for a reveal 550 ms after epoch time 0. The data are consistent with the "buttonpress" epoch being locked to the outcome reveal, as Figure 3C labels it ("time locked to gamble outcome (t = 0)"), and not to the button press as the data description says. This is consistent with the data, not shown: the true event times are not in the files. In what follows, time 0 of the buttonpress epoch is read as outcome reveal (the data's reading), and the claims file's reading (reveal at 550 ms) is shown alongside where timing matters.

methods-electrode-trial-countsΒΆ

Of 210 OFC electrodes recorded in 10 patients, 192 were artifact-free and included; each patient played 200 rounds, and timeouts, 9.98% of all trials, were excluded.

InΒ [9]:
table_s2_total = {"s01": 5, "s02": 6, "s03": 52, "s04": 5, "s05": 61, "s06": 7, "s07": 11, "s08": 10, "s09": 19, "s10": 16}  # paper, Table S2 last row
deposited = {s: len(keep[s]) + len({j for i, j in H[s]["game_raw_identical"] + H[s]["game_win_identical"]}) for s in saez.SUBJECTS}
copies_both = {s: len(set(H[s]["game_raw_identical"]) & set(H[s]["game_win_identical"])) for s in saez.SUBJECTS}   # same pair in both arrays
cmp = pd.DataFrame({"deposited": deposited, "without copies in both arrays": {s: deposited[s] - copies_both[s] for s in saez.SUBJECTS},
                    "unique recordings (analysed)": {s: len(keep[s]) for s in saez.SUBJECTS}, "Table S2": table_s2_total})
print(cmp.to_string()); print(cmp.sum().to_dict())
n_rounds, n_to = counts.rounds.sum(), counts.timeouts.sum()
print(f"patients: {len(saez.SUBJECTS)}")
print(f"rounds per patient: {counts.rounds.tolist()}")
print(f"timeouts {n_to} of {n_rounds} rounds = {100 * n_to / n_rounds:.2f}% (expected 9.98 +/- 0.998); of 2,000 = {100 * n_to / 2000:.2f}%")
missing = n_rounds - counts.hfa_trials.sum()
print(f"variant: rounds without an HFA trial (timeouts and other exclusions) {missing} of {n_rounds} = {100 * missing / n_rounds:.2f}%;"
      f" of 2,000 rounds {100 * (2000 - counts.hfa_trials.sum()) / 2000:.2f}%")
     deposited  without copies in both arrays  unique recordings (analysed)  Table S2
s01          5                              5                             5         5
s02          6                              6                             6         6
s03         59                             52                            51        52
s04          5                              5                             5         5
s05         61                             61                            61        61
s06          7                              7                             7         7
s07         11                             11                            11        11
s08         10                             10                            10        10
s09         19                             19                            19        19
s10         16                             16                            16        16
{'deposited': 199, 'without copies in both arrays': 192, 'unique recordings (analysed)': 191, 'Table S2': 192}
patients: 10
rounds per patient: [200, 200, 200, 200, 200, 200, 200, 200, 200, 138]
timeouts 99 of 1938 rounds = 5.11% (expected 9.98 +/- 0.998); of 2,000 = 4.95%
variant: rounds without an HFA trial (timeouts and other exclusions) 185 of 1938 = 9.55%; of 2,000 rounds 12.35%

Result: partially reproduced. There are 10 patients. With the seven electrodes of s03 that are copies of others in both arrays removed, the data set holds 192 electrodes, matching Table S2 patient by patient (199 as deposited; 191 unique recordings, as s03 electrode 42 has no data of its own). Timeouts are 99 of 1,938 rounds, 5.11%, outside 9.98 +/- 0.998, and s10 has 138 rounds, not 200. The share of rounds without an HFA trial (timeouts and other exclusions), 9.55%, would fall inside the tolerance, but the claims file defines the percentage on timeout trials.

behavior-risk-neutralΒΆ

Patients were approximately risk neutral, choosing the gamble only slightly more often than a risk-neutral baseline model, on 55.9% (plus or minus 8.5%) of trials.

InΒ [10]:
B = pd.concat([beh[s]["rounds"].assign(subject=s) for s in saez.SUBJECTS], ignore_index=True)
B["ev"] = B.winprob * B["Risky.Bet.Amount"]
B["rn"] = np.where(B.ev > 10, 1.0, np.where(B.ev == 10, 0.5, 0.0))
Bn = B[~B.timeout].copy()
per = Bn.groupby("subject").agg(gamble_pct=("gamble_ind", lambda v: 100 * v.mean()), risk_neutral_pct=("rn", lambda v: 100 * v.mean()), n=("gamble_ind", "size"))
print(per.round(1).to_string())
print(f"(a) mean over patients {per.gamble_pct.mean():.1f}% (SD {per.gamble_pct.std():.1f}, SEM {per.gamble_pct.sem():.1f}); risk-neutral model {per.risk_neutral_pct.mean():.1f}%")
print(f"(b) pooled {100 * Bn.gamble_ind.mean():.1f}%; risk-neutral model {100 * Bn.rn.mean():.1f}%")
print("expected 55.9 +/- 8.5 (47.4 to 64.4)")
         gamble_pct  risk_neutral_pct    n
subject                                   
s01            63.3              53.1  196
s02            56.1              53.0  198
s03            48.0              53.0  200
s04            46.8              51.4  111
s05            73.5              52.6  196
s06            58.0              53.0  200
s07            48.5              53.0  200
s08            50.0              53.0  200
s09            47.5              53.0  200
s10            57.2              54.7  138
(a) mean over patients 54.9% (SD 8.6, SEM 2.7); risk-neutral model 53.0%
(b) pooled 55.1%; risk-neutral model 53.0%
expected 55.9 +/- 8.5 (47.4 to 64.4)

Result: reproduced. Patients chose the gamble on 54.9% of non-timeout rounds averaged over patients (SD 8.6) and 55.1% pooled, within 55.9 +/- 8.5 under both readings; a risk-neutral chooser (gamble when p times prize exceeds $10) would gamble on 53.0%.

fig1c-choice-win-probabilityΒΆ

The proportion of risky choices increased with win probability, well captured by a logit model (p < 0.001, random effects logit analysis).

InΒ [11]:
print("proportion of gamble choices by win probability (mean over patients):")
print((Bn.groupby(["winprob", "subject"]).gamble_ind.mean().groupby("winprob").mean() * 100).round(1).to_string())
X = np.c_[np.ones(len(Bn)), Bn.winprob.values]
fit_a = saez.glmm_logit(Bn.gamble_ind.values, X, Bn.subject.values)
fit_b = saez.glmm_logit(Bn.gamble_ind.values, X, Bn.subject.values, random_slope_col=1)
for name, f in (("(a) random intercept", fit_a), ("(b) random intercept and slope", fit_b)):
    print(f"{name}: slope {f.estimate[1]:.2f} (SE {f.se[1]:.2f}), z {f.z[1]:.1f}, p {f.p[1]:.2e}; RE SD {np.round(f.attrs['re_sd'], 2).tolist()}, converged {f.attrs['converged']}")
print("per patient logit slopes (fixed-effect fits, for the breakdown):")
for s, d in Bn.groupby("subject"):
    f = saez.glmm_logit(d.gamble_ind.values, np.c_[np.ones(len(d)), d.winprob.values], np.zeros(len(d)))
    print(f"  {s}: slope {f.estimate[1]:.1f}, p {f.p[1]:.1e}")
proportion of gamble choices by win probability (mean over patients):
winprob
0.0    16.9
0.1    15.2
0.2    25.5
0.3    26.5
0.4    35.7
0.5    62.1
0.6    82.0
0.7    77.6
0.8    76.2
0.9    81.6
1.0    77.0
(a) random intercept: slope 4.79 (SE 0.24), z 19.7, p 1.52e-86; RE SD [0.43], converged True
(b) random intercept and slope: slope 5.75 (SE 0.33), z 17.7, p 6.04e-70; RE SD [1.39, 7.91], converged True
per patient logit slopes (fixed-effect fits, for the breakdown):
  s01: slope 6.1, p 8.1e-12
  s02: slope 18.0, p 9.7e-10
  s03: slope 3.1, p 1.5e-07
  s04: slope -0.6, p 3.7e-01
  s05: slope 2.0, p 1.1e-03
  s06: slope 12.9, p 1.0e-11
  s07: slope 12.6, p 5.4e-12
  s08: slope 4.0, p 8.2e-10
  s09: slope 10.0, p 3.0e-13
  s10: slope 0.7, p 3.0e-01

Result: reproduced. The slope of gamble choice on win probability is positive with p < 1e-60 under both random-effects readings (4.79 and 5.75 per unit probability). Per patient the slope is positive and significant in 8 of 10; s04 (slope -0.6) and s10 (0.7) show no significant effect.

figs2a-choice-gamble-evΒΆ

Patients' choices were sensitive to the expected value of the gamble (prize times win probability), with gamble choices more frequent at higher gamble expected value.

InΒ [12]:
print("proportion of gamble choices by gamble expected value (mean over patients, % ; n rounds):")
tab = Bn.groupby(["ev", "subject"]).gamble_ind.mean().groupby("ev").mean() * 100
print(pd.DataFrame({"gamble %": tab.round(1), "rounds": Bn.groupby("ev").size()}).T.to_string())
X = np.c_[np.ones(len(Bn)), Bn.ev.values]
for name, f in (("(a) random intercept", saez.glmm_logit(Bn.gamble_ind.values, X, Bn.subject.values)),
                ("(b) random intercept and slope", saez.glmm_logit(Bn.gamble_ind.values, X, Bn.subject.values, random_slope_col=1))):
    print(f"{name}: slope per $ {f.estimate[1]:.3f} (SE {f.se[1]:.3f}), p {f.p[1]:.2e}")
proportion of gamble choices by gamble expected value (mean over patients, % ; n rounds):
ev        0.0   1.5   2.0   2.5   3.0   4.0   4.5   5.0    6.0   7.5   8.0    9.0    10.0  10.5   12.0  12.5  13.5  14.0  15.0  16.0  17.5   18.0   20.0  21.0  22.5  24.0  25.0  27.0  30.0
gamble %  16.9  10.0   0.0  24.0  27.7  19.3  22.5  26.0   33.3  47.5  39.5   51.8   52.1  80.0   66.2  60.3  78.3  76.5  77.7  78.3  70.0   86.9   74.6  80.1  83.3  68.3  73.3  77.8  75.0
rounds    90.0  19.0   9.0  47.0  82.0  81.0  47.0  46.0  100.0  84.0  69.0  117.0  147.0  19.0  158.0  47.0  52.0  48.0  91.0  27.0  19.0  102.0  106.0  66.0  26.0  29.0  26.0  65.0  20.0
(a) random intercept: slope per $ 0.163 (SE 0.009), p 1.95e-69
(b) random intercept and slope: slope per $ 0.161 (SE 0.011), p 3.67e-45

Result: reproduced. Gamble choices rise from 16.9% at an expected value of $0 to 68 to 87% above $15, and the random-effects logit slope is positive (0.16 per $) with p < 1e-40 under both readings.

figs2b-rt-conflictΒΆ

Reaction times were longer in high-conflict trials (win probability 40 to 60%) than in low-conflict trials (below 30% or above 70%), in patients and in healthy subjects (both p < 0.001, t test), with comparable effect sizes.

RT is buttonpress.time minus choice.time (game presentation, see the data check). Only the patients are in the data set.

InΒ [13]:
Bn["conflict"] = np.where(Bn.winprob.between(0.4, 0.6), "high", np.where((Bn.winprob < 0.3) | (Bn.winprob > 0.7), "low", "mid"))
print(Bn.groupby("conflict").rt.agg(["size", "mean", "std"]).round(3).to_string())
hi, lo = Bn.rt[Bn.conflict == "high"], Bn.rt[Bn.conflict == "low"]
t_a = stats.ttest_ind(hi, lo)
d_a = (hi.mean() - lo.mean()) / np.sqrt(((len(hi) - 1) * hi.var() + (len(lo) - 1) * lo.var()) / (len(hi) + len(lo) - 2))
m = Bn[Bn.conflict != "mid"].groupby(["subject", "conflict"]).rt.mean().unstack()
t_b = stats.ttest_rel(m["high"], m["low"])
diff = m["high"] - m["low"]
print(f"(a) pooled trials: high {hi.mean():.3f} s vs low {lo.mean():.3f} s, t = {t_a.statistic:.2f}, p = {t_a.pvalue:.2e}, Cohen's d = {d_a:.2f}")
print(f"(b) paired over patients: mean difference {diff.mean() * 1000:.0f} ms, t = {t_b.statistic:.2f}, p = {t_b.pvalue:.2e}, d_z = {diff.mean() / diff.std():.2f}")
print("per patient high - low (ms):", (diff * 1000).round(0).to_dict())
v = Bn[(Bn.subject != "s10") & (Bn.conflict != "mid")]
tv = stats.ttest_ind(v.rt[v.conflict == "high"], v.rt[v.conflict == "low"])
mv = m.drop("s10")
print(f"variant without s10 (RTs not bounded, see the data check): pooled t = {tv.statistic:.2f}, p = {tv.pvalue:.2e};"
      f" paired over 9 patients p = {stats.ttest_rel(mv['high'], mv['low']).pvalue:.2e}")
          size   mean    std
conflict                    
high       669  1.691  2.949
low        843  1.476  3.014
mid        327  1.567  2.894
(a) pooled trials: high 1.691 s vs low 1.476 s, t = 1.39, p = 1.65e-01, Cohen's d = 0.07
(b) paired over patients: mean difference 179 ms, t = 1.81, p = 1.04e-01, d_z = 0.57
per patient high - low (ms): {'s01': 38.0, 's02': 142.0, 's03': -28.0, 's04': -200.0, 's05': 33.0, 's06': 84.0, 's07': 300.0, 's08': 77.0, 's09': 411.0, 's10': 932.0}
variant without s10 (RTs not bounded, see the data check): pooled t = 4.75, p = 2.20e-06; paired over 9 patients p = 1.47e-01

Result: not reproduced. High-conflict RTs are longer on average (1.691 against 1.476 s pooled; 179 ms per patient), but neither reading reaches p < 0.001: p = 0.165 over pooled trials (Cohen's d 0.07) and p = 0.104 over the 10 patients. s10's unbounded RTs (up to 80 s) dominate the pooled test; without s10 the pooled test gives p = 2.2e-06 and the paired one p = 0.147. The healthy subjects' part cannot be tested. RT is taken as buttonpress.time minus choice.time, an inference from the data (the description lists neither column's meaning); leaving s10 out is not a reading the claims file allows and is shown only for sensitivity.

Regressors per HFA trialΒΆ

Current and t-1 regressors are the authors' (sXX_behav_globals.mat); t-2 to t-5 are built from the rounds with the same convention (helper, past_regressors).

InΒ [14]:
LAGS = range(6)
REG = {}   # (regressor, lag) -> subject -> values per HFA trial
for s in saez.SUBJECTS:
    g, r, idx = beh[s]["globals"], beh[s]["rounds"], beh[s]["idx"]
    for k in saez.CURRENT:
        REG.setdefault((k, 0), {})[s] = g[k].values
        REG.setdefault((k, 1), {})[s] = g["previous_" + k].values
    for lag in range(2, 6):
        p = saez.past_regressors(r, idx, lag)
        for k in saez.CURRENT:
            REG.setdefault((k, lag), {})[s] = p[k].values
    REG.setdefault(("left", 0), {})[s] = r["left"].values[idx]
    REG.setdefault(("risk_gamble_only", 0), {})[s] = np.where(g.gamble_ind.values == 1, g.risk.values, np.nan)
print(len(REG), "regressors;", "NaN trials per lag (all subjects):",
      {lag: int(sum(np.isnan(REG[("winprob", lag)][s]).sum() for s in saez.SUBJECTS)) for lag in LAGS})
50 regressors; NaN trials per lag (all subjects): {0: 0, 1: 7, 2: 16, 3: 25, 4: 34, 5: 44}

regressors-past-current-uncorrelatedΒΆ

Past and current regressors were nearly uncorrelated (mean R2 2.1%, maximum R2 3.7%).

InΒ [15]:
def r2_pairs(pairs, reg=None):
    """R2 per pair: mean over patients of within-patient R2, and R2 on pooled trials."""
    reg = REG if reg is None else reg
    per_pat, pooled = [], []
    for a, b in pairs:
        vals = []
        xa, xb = [], []
        for s in saez.SUBJECTS:
            u, v = reg[a][s], reg[b][s]
            ok = ~np.isnan(u) & ~np.isnan(v)
            if u[ok].std() > 0 and v[ok].std() > 0:
                vals.append(np.corrcoef(u[ok], v[ok])[0, 1] ** 2)
            xa.append(u[ok]); xb.append(v[ok])
        per_pat.append(np.mean(vals))
        pooled.append(np.corrcoef(np.concatenate(xa), np.concatenate(xb))[0, 1] ** 2)
    return np.array(per_pat) * 100, np.array(pooled) * 100

readings = {"(a) own t-1 (8 pairs)": [((k, 0), (k, 1)) for k in saez.CURRENT],
            "(b) all current x t-1 (64)": [((k, 0), (j, 1)) for k in saez.CURRENT for j in saez.CURRENT],
            "(c) all current x t-1..t-5 (320)": [((k, 0), (j, lag)) for k in saez.CURRENT for j in saez.CURRENT for lag in range(1, 6)]}
for name, pairs in readings.items():
    pp, pl = r2_pairs(pairs)
    print(f"{name}: averaged over patients mean {pp.mean():.2f}% max {pp.max():.2f}% | pooled trials mean {pl.mean():.2f}% max {pl.max():.2f}%")
print("expected mean 2.1 +/- 0.21, max 3.7 +/- 0.37")

# variant: the same regressors over all 1,839 non-timeout rounds (the criterion's trials), built from the rounds
REG_NT = {}
for s in saez.SUBJECTS:
    r = beh[s]["rounds"]
    nt = np.where(~r.timeout.values)[0]
    for lag in range(6):
        p = saez.past_regressors(r, nt, lag)
        for k in saez.CURRENT:
            REG_NT.setdefault((k, lag), {})[s] = p[k].values
print("variant, non-timeout rounds:", sum(len(REG_NT[("risk", 0)][s]) for s in saez.SUBJECTS))
for name, pairs in readings.items():
    pp, pl = r2_pairs(pairs, REG_NT)
    print(f"  {name}: averaged over patients mean {pp.mean():.2f}% max {pp.max():.2f}% | pooled trials mean {pl.mean():.2f}% max {pl.max():.2f}%")
(a) own t-1 (8 pairs): averaged over patients mean 0.37% max 0.70% | pooled trials mean 0.25% max 0.64%
(b) all current x t-1 (64): averaged over patients mean 0.53% max 1.73% | pooled trials mean 0.23% max 1.20%
(c) all current x t-1..t-5 (320): averaged over patients mean 0.59% max 2.29% | pooled trials mean 0.21% max 1.71%
expected mean 2.1 +/- 0.21, max 3.7 +/- 0.37
variant, non-timeout rounds: 1839
  (a) own t-1 (8 pairs): averaged over patients mean 0.35% max 0.64% | pooled trials mean 0.26% max 0.66%
  (b) all current x t-1 (64): averaged over patients mean 0.50% max 1.73% | pooled trials mean 0.23% max 1.21%
  (c) all current x t-1..t-5 (320): averaged over patients mean 0.56% max 1.87% | pooled trials mean 0.21% max 1.61%

Result: not reproduced. Past and current regressors are even less correlated than the paper reports: the mean R2 is 0.21 to 0.59% and the maximum 0.64 to 2.29% across the readings, so no reading is within 2.1 +/- 0.21% and 3.7 +/- 0.37%. The finding that they are nearly uncorrelated holds. Over the 1,839 non-timeout rounds that the criterion names (variant, regressors built from the rounds), the mean R2 is 0.21 to 0.56% and the maximum 0.64 to 1.87%, also outside the tolerance.

figs6a-regressor-collinearityΒΆ

Regressors were weakly correlated between and within categories (mean R2 0.15, all R2 below 0.6).

InΒ [16]:
cur = [(k, 0) for k in saez.CURRENT]
both16 = cur + [(k, 1) for k in saez.CURRENT]
for name, regs in (("(a) 8 current", cur), ("(b) 8 current + 8 t-1", both16)):
    pairs = [(regs[i], regs[j]) for i in range(len(regs)) for j in range(i + 1, len(regs))]
    pp, pl = r2_pairs(pairs)
    print(f"{name}, {len(pairs)} pairs: averaged over patients mean {pp.mean() / 100:.4f} max {pp.max() / 100:.3f} | pooled mean {pl.mean() / 100:.4f} max {pl.max() / 100:.3f}")
    top = sorted(zip(pl / 100, pairs), reverse=True)[:4]
    print("   largest pooled R2:", [(round(float(v), 2), a[0], a[1], b[0], b[1]) for v, (a, b) in top])
    top = sorted(zip(pp / 100, pairs), reverse=True)[:4]
    print("   largest R2 averaged over patients:", [(round(float(v), 2), a[0], a[1], b[0], b[1]) for v, (a, b) in top])
print("expected mean 0.15 +/- 0.015, all below 0.6")
(a) 8 current, 28 pairs: averaged over patients mean 0.1648 max 0.570 | pooled mean 0.1551 max 0.549
   largest pooled R2: [(0.55, 'loss_ind', 0, 'rpe', 0), (0.49, 'gamble_ind', 0, 'win_ind', 0), (0.46, 'winprob', 0, 'exputil', 0), (0.42, 'win_ind', 0, 'rpe', 0)]
   largest R2 averaged over patients: [(0.57, 'loss_ind', 0, 'rpe', 0), (0.48, 'gamble_ind', 0, 'win_ind', 0), (0.46, 'winprob', 0, 'exputil', 0), (0.42, 'win_ind', 0, 'rpe', 0)]
(b) 8 current + 8 t-1, 120 pairs: averaged over patients mean 0.0790 max 0.570 | pooled mean 0.0723 max 0.549
   largest pooled R2: [(0.55, 'loss_ind', 0, 'rpe', 0), (0.55, 'loss_ind', 1, 'rpe', 1), (0.5, 'gamble_ind', 1, 'win_ind', 1), (0.49, 'gamble_ind', 0, 'win_ind', 0)]
   largest R2 averaged over patients: [(0.57, 'loss_ind', 0, 'rpe', 0), (0.57, 'loss_ind', 1, 'rpe', 1), (0.49, 'gamble_ind', 1, 'win_ind', 1), (0.48, 'gamble_ind', 0, 'win_ind', 0)]
expected mean 0.15 +/- 0.015, all below 0.6

Result: reproduced. For the 8 current regressors (reading (a)) the mean R2 over the 28 pairs is 0.155 on pooled trials and 0.165 averaged over patients, both within 0.15 +/- 0.015, and no pair reaches 0.6 (largest 0.55 pooled and 0.57 averaged over patients, both loss index with RPE). With the t-1 regressors added (reading (b)) the mean falls to 0.07 to 0.08, outside the tolerance.

Encoding scansΒΆ

For each regressor, lag and electrode: a linear regression of window HFA on the regressor in each of the 57 windows of both epochs; an electrode encodes the regressor when p < 0.05 in 5 or more consecutive windows of either epoch. Chance: 1,000 shuffles of the regressor across trials (the same shuffle for both epochs), each pooled over subjects.

InΒ [17]:
t0 = time.time()
SC = {}
for i, key in enumerate(REG):
    SC[key] = saez.scan_all(H, REG[key], 1000, np.random.default_rng(1000 + i))
print(f"{len(SC)} scans in {time.time() - t0:.0f} s")
SUBJ = SC[("risk", 0)]["subject"]

def summary(key):
    sc = SC[key]
    return {"regressor": saez.LABELS.get(key[0], key[0]), "lag": key[1], "encoding": int(sc["encoding"].sum()),
            "percent": round(100 * sc["encoding"].mean(), 1), "chance mean": round(sc["perm_count"].mean(), 1),
            "chance 95th": float(np.percentile(sc["perm_count"], 95)), "patients": len(set(SUBJ[sc["encoding"]]))}
50 scans in 10 s

fig3-present-encodingΒΆ

OFC HFA encodes the choice regressors (risk, gamble choice, offer value, chosen value), time locked to game presentation, and the outcome regressors (gamble win, gamble loss, RPE, regret), time locked to outcome reveal, with average %EV above chance and a rise in the number of encoding electrodes.

InΒ [18]:
expected_cur = {"risk": 50, "gamble_ind": 34, "winprob": 31, "exputil": 26, "win_ind": 45, "loss_ind": 33, "rpe": 28, "regret": 35}
t3 = pd.DataFrame([summary((k, 0)) for k in saez.CURRENT])
t3["expected"] = [expected_cur[k] for k in saez.CURRENT]
t3["within 10%"] = (t3.encoding - t3.expected).abs() <= 0.1 * t3.expected
t3["above chance 95th"] = t3.encoding > t3["chance 95th"]
t3["own-null variant"] = [int((SC[(k, 0)]["encoding"] & (SC[(k, 0)]["run"].max(0) > SC[(k, 0)]["run95"])).sum()) for k in saez.CURRENT]
print(t3.to_string(index=False))
print(f"false-positive rate of the selection under shuffles: {np.mean([SC[(k, 0)]['perm_count'].mean() for k in saez.CURRENT]) / N_ELEC * 100:.1f}% of electrodes")
print("\nper patient (data / Table S2):")
table_s2 = {"risk": [1, 1, 25, 0, 14, 0, 0, 3, 4, 2], "gamble_ind": [2, 1, 7, 0, 14, 0, 1, 4, 3, 2], "winprob": [0, 0, 6, 1, 9, 0, 1, 6, 7, 1],
            "exputil": [0, 0, 5, 2, 8, 0, 3, 1, 6, 1], "win_ind": [0, 1, 7, 0, 16, 0, 0, 5, 13, 3], "loss_ind": [3, 1, 2, 0, 14, 0, 3, 1, 8, 1],
            "rpe": [0, 1, 2, 0, 10, 0, 2, 1, 11, 1], "regret": [0, 3, 4, 1, 14, 0, 1, 2, 6, 4]}   # paper, Table S2
for k in saez.CURRENT:
    e = SC[(k, 0)]["encoding"]
    print(f"  {saez.LABELS[k]:24s}", " ".join(f"{int(e[SUBJ == s].sum()):2d}/{table_s2[k][i]:<2d}" for i, s in enumerate(saez.SUBJECTS)))


def profile(keys, epoch):
    """Mean %EV over each regressor's encoding electrodes, averaged over the regressors; chance profile."""
    ei = saez.EPOCHS.index(epoch)
    prof = np.mean([SC[k]["r2"][ei][:, SC[k]["encoding"]].mean(1) * 100 for k in keys], 0)
    ch = np.mean([SC[k]["perm_r2_enc"][:, ei].sum(0) / SC[k]["perm_count"].sum() * 100 for k in keys], 0)
    return prof, ch


def share(keys, epoch, among_encoding):
    ei = saez.EPOCHS.index(epoch)
    if among_encoding:
        return np.mean([SC[k]["sig"][ei][:, SC[k]["encoding"]].mean(1) * 100 for k in keys], 0)
    return np.mean([SC[k]["sig"][ei].mean(1) * 100 for k in keys], 0)


c = saez.WIN_CENTRES_MS
fig, axes = plt.subplots(1, 2, figsize=(11, 3.2))
for ax, (name, keys, epoch, onset) in zip(axes, (("choice", [(k, 0) for k in saez.CHOICE], "game", 0),
                                                ("outcome", [(k, 0) for k in saez.OUTCOME], "buttonpress", 0))):
    prof, ch = profile(keys, epoch)
    sa, sb = share(keys, epoch, True), share(keys, epoch, False)
    pk = c[prof.argmax()]
    print(f"\n{name} regressors, {epoch} epoch: peak mean %EV {prof.max():.2f} at window centre {pk} ms (chance profile {ch.min():.2f} to {ch.max():.2f});"
          f" windows above chance: {int((prof > ch).sum())} of 57")
    print(f"   share among encoding electrodes (a) peaks at {c[sa.argmax()]} ms ({sa.max():.1f}%); share of all electrodes (b) peaks at {c[sb.argmax()]} ms ({sb.max():.1f}%)")
    if name == "outcome":
        print(f"   reveal at epoch time 0 (data): peak {pk} ms after reveal; reveal at +550 ms (claims file): peak {pk - 550} ms after reveal")
    ax.plot(c, prof, label="mean %EV"); ax.plot(c, ch, "k:", label="chance")
    ax2 = ax.twinx(); ax2.bar(c, sb, width=40, alpha=0.3, color="gray"); ax2.set_ylabel("% electrodes p<0.05")
    ax.set_title(f"{name}, {epoch} epoch"); ax.set_xlabel("window centre (ms)"); ax.set_ylabel("%EV"); ax.legend(fontsize=7)
plt.tight_layout(); plt.show()
              regressor  lag  encoding  percent  chance mean  chance 95th  patients  expected  within 10%  above chance 95th  own-null variant
                   risk    0        84     44.0         34.7         48.0         9        50       False               True                41
                 gamble    0        71     37.2         34.2         48.0         8        34       False               True                31
offer value (win prob.)    0        61     31.9         35.0         49.0         8        31       False               True                21
           chosen value    0        41     21.5         34.6         50.0         8        26       False              False                12
              win index    0        59     30.9         35.0         49.0         7        45       False               True                24
             loss index    0        54     28.3         35.1         49.0         8        33       False               True                15
                    RPE    0        52     27.2         35.4         49.0         9        28       False               True                15
                 regret    0        64     33.5         34.9         49.0        10        35       False               True                17
false-positive rate of the selection under shuffles: 18.2% of electrodes

per patient (data / Table S2):
  risk                      1/1   1/1  33/25  0/0  29/14  4/0   2/0   3/3   6/4   5/2 
  gamble                    3/2   1/1  14/7   0/0  24/14  0/0   5/1   5/4  13/3   6/2 
  offer value (win prob.)   0/0   2/0   9/6   2/1  25/9   0/0   4/1   7/6   9/7   3/1 
  chosen value              0/0   1/0   8/5   2/2  14/8   0/0   4/3   2/1   7/6   3/1 
  win index                 0/0   1/1  11/7   0/0  19/16  0/0   4/0   5/5  14/13  5/3 
  loss index                4/3   1/1  11/2   0/0  20/14  0/0   5/3   1/1  10/8   2/1 
  RPE                       0/0   1/1   5/2   3/0  22/10  1/0   6/2   2/1  11/11  1/1 
  regret                    1/0   4/3  13/4   1/1  24/14  2/0   2/1   4/2   7/6   6/4 

choice regressors, game epoch: peak mean %EV 1.82 at window centre 750 ms (chance profile 0.57 to 1.25); windows above chance: 14 of 57
   share among encoding electrodes (a) peaks at 850 ms (34.1%); share of all electrodes (b) peaks at 850 ms (13.9%)

outcome regressors, buttonpress epoch: peak mean %EV 2.10 at window centre 800 ms (chance profile 1.12 to 1.26); windows above chance: 21 of 57
   share among encoding electrodes (a) peaks at 650 ms (43.3%); share of all electrodes (b) peaks at 850 ms (16.1%)
   reveal at epoch time 0 (data): peak 800 ms after reveal; reveal at +550 ms (claims file): peak 250 ms after reveal
No description has been provided for this image

Result: not reproduced. The timing holds: the mean %EV of the choice regressors peaks 750 ms after game presentation and that of the outcome regressors 800 ms after time 0 of the buttonpress epoch (250 ms after a reveal at +550 ms, the claims file's timing), with the per-window share of encoding electrodes peaking in the same post-event period (850 ms under both readings, and 650 ms for outcome under reading (a)). The counts do not: none of the eight is within 10% of Table S2 (41 to 84 against 26 to 50), and chosen value (41 electrodes) does not exceed the 95th percentile of its shuffles (50). The selection rule itself classifies 18.2% of electrodes as encoding under shuffled labels (about 35 of 191), more than Table S2 reports for chosen value (26). If an electrode is also required to beat the 95th percentile of its own shuffled run lengths (a variant, not the claims file's reading), the counts are 12 to 41, all eight below Table S2. Per patient, s03 and s05 hold most encoding electrodes in both the data and Table S2. The claims file's baseline readings do not change the outcome (section "Baseline readings").

fig3-latency-duration-similarΒΆ

The delays of choice encoding after game presentation and of outcome encoding after outcome reveal did not differ (512.5 plus or minus 59 ms against 287 plus or minus 114.33 ms, p = 0.14, t test), nor did their transient durations (612.15 plus or minus 132.9 ms against 712.5 plus or minus 112.5 ms, p = 0.58).

InΒ [19]:
def run_around(mask, k):
    """Length of the run of True in mask that contains index k."""
    if not mask[k]:
        return 0
    a = k
    while a > 0 and mask[a - 1]:
        a -= 1
    b = k
    while b < len(mask) - 1 and mask[b + 1]:
        b += 1
    return b - a + 1


def latency_table(reveal_ms):
    rows = []
    for k in saez.CURRENT:
        epoch, event = ("game", 0) if k in saez.CHOICE else ("buttonpress", reveal_ms)
        ei = saez.EPOCHS.index(epoch)
        sc = SC[(k, 0)]
        prof = sc["r2"][ei][:, sc["encoding"]].mean(1) * 100
        ch = sc["perm_r2_enc"][:, ei].sum(0) / sc["perm_count"].sum() * 100
        after = c - 100 >= event            # windows that start at or after the event
        kpk = np.where(after)[0][prof[after].argmax()]
        dur = run_around(prof > ch, kpk) * 50
        shr = sc["sig"][ei].mean(1)
        thr = np.percentile(sc["perm_sig_count"][:, ei] / N_ELEC, 95, axis=0)
        above = np.where(after & (shr > thr))[0]
        rows.append({"regressor": saez.LABELS[k], "group": "choice" if k in saez.CHOICE else "outcome",
                     "(a) delay": c[kpk] - event, "(a,b) duration": dur,
                     "(b) delay": (c[above[0]] - event) if len(above) else np.nan})
    return pd.DataFrame(rows)


def per_electrode(reveal_ms):
    rows = []
    for k in saez.CURRENT:
        epoch, event = ("game", 0) if k in saez.CHOICE else ("buttonpress", reveal_ms)
        ei = saez.EPOCHS.index(epoch)
        sc = SC[(k, 0)]
        for e in np.where(sc["run"][ei] >= saez.MIN_RUN)[0]:
            st, ln = saez.run_bounds(sc["sig"][ei][:, e])
            rows.append({"group": "choice" if k in saez.CHOICE else "outcome", "delay": c[st] - event, "duration": ln * 50})
    return pd.DataFrame(rows)


def ttest_line(a, b, label):
    t = stats.ttest_ind(a, b, nan_policy="omit")
    return (f"{label}: choice {np.nanmean(a):.1f} +/- {stats.sem(a, nan_policy='omit'):.1f} vs outcome {np.nanmean(b):.1f} +/- "
            f"{stats.sem(b, nan_policy='omit'):.1f} ms, t = {t.statistic:.2f}, p = {t.pvalue:.3f}")


for reveal, name in ((0, "reveal at buttonpress-epoch 0 (data)"), (550, "reveal at +550 ms (claims file)")):
    lt = latency_table(reveal)
    print(f"\n{name}\n", lt.to_string(index=False))
    ch, oc = lt[lt.group == "choice"], lt[lt.group == "outcome"]
    print(ttest_line(ch["(a) delay"], oc["(a) delay"], "(a) delay"))
    print(ttest_line(ch["(a,b) duration"], oc["(a,b) duration"], "(a,b) duration"))
    print(ttest_line(ch["(b) delay"], oc["(b) delay"], "(b) delay"))
    pe = per_electrode(reveal)
    print(ttest_line(pe.delay[pe.group == "choice"], pe.delay[pe.group == "outcome"], f"(c) delay, {len(pe)} electrode-regressor pairs"))
    print(ttest_line(pe.duration[pe.group == "choice"], pe.duration[pe.group == "outcome"], "(c) duration"))
print("expected: delay 512.5 +/- 59 vs 287 +/- 114.33 ms (p = 0.14); duration 612.15 +/- 132.9 vs 712.5 +/- 112.5 ms (p = 0.58)")
reveal at buttonpress-epoch 0 (data)
               regressor   group  (a) delay  (a,b) duration  (b) delay
                   risk  choice       1000            1100        400
                 gamble  choice        650             750        300
offer value (win prob.)  choice        750             450        600
           chosen value  choice        800             450        750
              win index outcome        500            1400        100
             loss index outcome        800             700        600
                    RPE outcome        500            1100        100
                 regret outcome        800             800        500
(a) delay: choice 800.0 +/- 73.6 vs outcome 650.0 +/- 86.6 ms, t = 1.32, p = 0.235
(a,b) duration: choice 687.5 +/- 154.6 vs outcome 1000.0 +/- 158.1 ms, t = -1.41, p = 0.207
(b) delay: choice 512.5 +/- 100.8 vs outcome 325.0 +/- 131.5 ms, t = 1.13, p = 0.301
(c) delay, 370 electrode-regressor pairs: choice 413.3 +/- 48.8 vs outcome 268.5 +/- 43.0 ms, t = 2.24, p = 0.026
(c) duration: choice 463.6 +/- 18.7 vs outcome 444.9 +/- 17.1 ms, t = 0.74, p = 0.462

reveal at +550 ms (claims file)
               regressor   group  (a) delay  (a,b) duration  (b) delay
                   risk  choice       1000            1100        400
                 gamble  choice        650             750        300
offer value (win prob.)  choice        750             450        600
           chosen value  choice        800             450        750
              win index outcome        150            1400        100
             loss index outcome        250             700        100
                    RPE outcome        250            1100        100
                 regret outcome        250             800        100
(a) delay: choice 800.0 +/- 73.6 vs outcome 225.0 +/- 25.0 ms, t = 7.40, p = 0.000
(a,b) duration: choice 687.5 +/- 154.6 vs outcome 1000.0 +/- 158.1 ms, t = -1.41, p = 0.207
(b) delay: choice 512.5 +/- 100.8 vs outcome 100.0 +/- 0.0 ms, t = 4.09, p = 0.006
(c) delay, 370 electrode-regressor pairs: choice 413.3 +/- 48.8 vs outcome -281.5 +/- 43.0 ms, t = 10.73, p = 0.000
(c) duration: choice 463.6 +/- 18.7 vs outcome 444.9 +/- 17.1 ms, t = 0.74, p = 0.462
expected: delay 512.5 +/- 59 vs 287 +/- 114.33 ms (p = 0.14); duration 612.15 +/- 132.9 vs 712.5 +/- 112.5 ms (p = 0.58)

Result: reproduced, resting on the reading of the buttonpress epoch as locked to the outcome reveal. With the reveal at time 0 of the buttonpress epoch (the data's reading), the choice and outcome delays do not differ under reading (a) (800 +/- 74 against 650 +/- 87 ms, p = 0.235) or reading (b) (512.5 +/- 101 against 325 +/- 132 ms, p = 0.301), nor do the durations (687.5 +/- 155 against 1,000 +/- 158 ms, p = 0.207). Under reading (b) both delays are within the paper's values (512.5 +/- 59 and 287 +/- 114.33 ms) and the choice duration is within 612.15 +/- 132.9 ms; the outcome duration is not (1,000 against 712.5 +/- 112.5). With the reveal at +550 ms (the claims file's timing) outcome encoding starts earlier than choice encoding (p = 0.006 under (b)), and the per-electrode reading (c), less supported, gives p = 0.026 for the delays under the data's timing. Under the claims file's baseline readings, reading (a) of the delays (p = 0.224 and 0.200) and the durations (p = 0.118 and 1.000) still give p > 0.05 (section "Baseline readings"); reading (b) of the delays gives p = 0.034 under baseline (a) and 0.052 under baseline (b). The outcome holds as reading (a) holds under every baseline.

fig4-past-encodingΒΆ

HFA encodes characteristics of the preceding trial; past choice and outcome features are widely represented across OFC except past risk, dissociable from current signals.

InΒ [20]:
expected_past = {"risk": 17, "gamble_ind": 43, "winprob": 46, "exputil": 35, "win_ind": 49, "loss_ind": 56, "rpe": 50, "regret": 64}
t4 = pd.DataFrame([summary((k, 1)) for k in saez.CURRENT])
t4["expected"] = [expected_past[k] for k in saez.CURRENT]
t4["within 10%"] = (t4.encoding - t4.expected).abs() <= 0.1 * t4.expected
t4["above chance 95th"] = t4.encoding > t4["chance 95th"]
t4["own-null variant"] = [int((SC[(k, 1)]["encoding"] & (SC[(k, 1)]["run"].max(0) > SC[(k, 1)]["run95"])).sum()) for k in saez.CURRENT]
print(t4.to_string(index=False))
print(f"mean proportion of encoding electrodes over the 16 current and t-1 regressors: {(t3.percent.sum() + t4.percent.sum()) / 16:.1f}% (paper, HFA: 20.9%)")
print("past risk has the lowest count:", t4.encoding.iloc[0] == t4.encoding.min(), "| rank of past risk (1 = lowest):", int(t4.encoding.rank(method="min").iloc[0]))
for ep in saez.EPOCHS:
    prof, ch = profile([(k, 1) for k in saez.CURRENT], ep)
    print(f"t-1 regressors, {ep} epoch: peak mean %EV {prof.max():.2f} at {c[prof.argmax()]} ms; windows above chance {int((prof > ch).sum())} of 57")
              regressor  lag  encoding  percent  chance mean  chance 95th  patients  expected  within 10%  above chance 95th  own-null variant
                   risk    1        40     20.9         35.1        49.00         6        17       False              False                 9
                 gamble    1        64     33.5         34.6        48.05        10        43       False               True                33
offer value (win prob.)    1        59     30.9         34.4        48.00         9        46       False               True                27
           chosen value    1        53     27.7         35.1        49.00         9        35       False               True                22
              win index    1        67     35.1         34.2        48.00         9        49       False               True                35
             loss index    1        79     41.4         35.1        48.00        10        56       False               True                37
                    RPE    1        76     39.8         34.9        50.00         9        50       False               True                28
                 regret    1        95     49.7         35.0        49.00         9        64       False               True                40
mean proportion of encoding electrodes over the 16 current and t-1 regressors: 33.3% (paper, HFA: 20.9%)
past risk has the lowest count: True | rank of past risk (1 = lowest): 1
t-1 regressors, game epoch: peak mean %EV 2.38 at 1000 ms; windows above chance 56 of 57
t-1 regressors, buttonpress epoch: peak mean %EV 2.23 at 1500 ms; windows above chance 57 of 57

Result: partially reproduced. Past features are encoded: the seven t-1 regressors other than risk each exceed the 95th percentile of their shuffles (53 to 95 electrodes against 48 to 50), and past risk has the lowest count (40, below its 95th percentile of 49). None of the eight counts is within 10% of Table S2 (40 to 95 against 17 to 64). The mean %EV of the t-1 regressors is above its chance profile in 56 of 57 game-epoch windows and all 57 buttonpress-epoch windows. This rests on the deposited baseline: under the claims file's baseline readings fewer than seven of the past regressors other than risk exceed their shuffles (section "Baseline readings").

fig5-past-sustainedΒΆ

Past-trial signals were sustained; the longest continuous stretch of significant encoding was longer for past outcome (1,341.37 plus or minus 49.63 ms) and past choice (1,169.15 plus or minus 61.2 ms) than for current choice (799.6 plus or minus 36.94 ms) and current outcome (706.9 plus or minus 30.56 ms), all p < 10^-6, t test.

InΒ [21]:
GROUPS = {"choice": [(k, 0) for k in saez.CHOICE], "outcome": [(k, 0) for k in saez.OUTCOME],
          "past choice": [(k, 1) for k in saez.CHOICE], "past outcome": [(k, 1) for k in saez.OUTCOME]}
exp5 = {"past outcome": 1341.37, "past choice": 1169.15, "choice": 799.6, "outcome": 706.9}
sem5 = {"past outcome": 49.63, "past choice": 61.2, "choice": 36.94, "outcome": 30.56}


def durations(epoch_reading):
    out = {}
    for gname, keys in GROUPS.items():
        vals = []
        for k in keys:
            sc = SC[k]
            if epoch_reading == "a":
                n = sc["run"].max(0)
            else:
                n = sc["run"][1 if gname == "outcome" else 0]
            vals.append(n[n >= saez.MIN_RUN])
        out[gname] = np.concatenate(vals).astype(float)
    return out


for er, ename in (("a", "longest over both epochs"), ("b", "choice and past in game epoch, outcome in buttonpress epoch")):
    d = durations(er)
    for lr, f in (("(a) windows x 50 ms", lambda n: n * 50), ("(b)/(c) windows x 50 + 150 ms", lambda n: n * 50 + 150)):
        print(f"\nepoch reading ({er}) {ename}; length {lr}")
        for gname in GROUPS:
            v = f(d[gname])
            print(f"   {gname:13s} n = {len(v):3d}  mean {v.mean():7.1f} +/- {stats.sem(v):5.1f} ms  (expected {exp5[gname]} +/- {sem5[gname]};"
                  f" within SEM {abs(v.mean() - exp5[gname]) <= sem5[gname]}, within 10% {abs(v.mean() - exp5[gname]) <= 0.1 * exp5[gname]})")
        for p in ("past outcome", "past choice"):
            for q in ("choice", "outcome"):
                t = stats.ttest_ind(f(d[p]), f(d[q]))
                print(f"   {p} vs {q}: t = {t.statistic:.2f}, p = {t.pvalue:.1e}")
epoch reading (a) longest over both epochs; length (a) windows x 50 ms
   choice        n = 257  mean   534.2 +/-  24.0 ms  (expected 799.6 +/- 36.94; within SEM False, within 10% False)
   outcome       n = 229  mean   462.0 +/-  17.6 ms  (expected 706.9 +/- 30.56; within SEM False, within 10% False)
   past choice   n = 216  mean   650.7 +/-  39.0 ms  (expected 1169.15 +/- 61.2; within SEM False, within 10% False)
   past outcome  n = 317  mean   669.9 +/-  33.0 ms  (expected 1341.37 +/- 49.63; within SEM False, within 10% False)
   past outcome vs choice: t = 3.19, p = 1.5e-03
   past outcome vs outcome: t = 4.99, p = 8.0e-07
   past choice vs choice: t = 2.63, p = 8.8e-03
   past choice vs outcome: t = 4.50, p = 8.9e-06

epoch reading (a) longest over both epochs; length (b)/(c) windows x 50 + 150 ms
   choice        n = 257  mean   684.2 +/-  24.0 ms  (expected 799.6 +/- 36.94; within SEM False, within 10% False)
   outcome       n = 229  mean   612.0 +/-  17.6 ms  (expected 706.9 +/- 30.56; within SEM False, within 10% False)
   past choice   n = 216  mean   800.7 +/-  39.0 ms  (expected 1169.15 +/- 61.2; within SEM False, within 10% False)
   past outcome  n = 317  mean   819.9 +/-  33.0 ms  (expected 1341.37 +/- 49.63; within SEM False, within 10% False)
   past outcome vs choice: t = 3.19, p = 1.5e-03
   past outcome vs outcome: t = 4.99, p = 8.0e-07
   past choice vs choice: t = 2.63, p = 8.8e-03
   past choice vs outcome: t = 4.50, p = 8.9e-06

epoch reading (b) choice and past in game epoch, outcome in buttonpress epoch; length (a) windows x 50 ms
   choice        n = 173  mean   463.6 +/-  18.7 ms  (expected 799.6 +/- 36.94; within SEM False, within 10% False)
   outcome       n = 197  mean   444.9 +/-  17.1 ms  (expected 706.9 +/- 30.56; within SEM False, within 10% False)
   past choice   n = 159  mean   567.6 +/-  37.5 ms  (expected 1169.15 +/- 61.2; within SEM False, within 10% False)
   past outcome  n = 225  mean   621.8 +/-  31.7 ms  (expected 1341.37 +/- 49.63; within SEM False, within 10% False)
   past outcome vs choice: t = 3.99, p = 8.0e-05
   past outcome vs outcome: t = 4.72, p = 3.2e-06
   past choice vs choice: t = 2.54, p = 1.1e-02
   past choice vs outcome: t = 3.17, p = 1.6e-03

epoch reading (b) choice and past in game epoch, outcome in buttonpress epoch; length (b)/(c) windows x 50 + 150 ms
   choice        n = 173  mean   613.6 +/-  18.7 ms  (expected 799.6 +/- 36.94; within SEM False, within 10% False)
   outcome       n = 197  mean   594.9 +/-  17.1 ms  (expected 706.9 +/- 30.56; within SEM False, within 10% False)
   past choice   n = 159  mean   717.6 +/-  37.5 ms  (expected 1169.15 +/- 61.2; within SEM False, within 10% False)
   past outcome  n = 225  mean   771.8 +/-  31.7 ms  (expected 1341.37 +/- 49.63; within SEM False, within 10% False)
   past outcome vs choice: t = 3.99, p = 8.0e-05
   past outcome vs outcome: t = 4.72, p = 3.2e-06
   past choice vs choice: t = 2.54, p = 1.1e-02
   past choice vs outcome: t = 3.17, p = 1.6e-03

Result: partially reproduced. Past signals last longer: under epoch reading (a) both past groups have longer stretches than both current groups in all four comparisons with p < 0.01 (p = 8.0e-07 to 8.8e-03), but only past outcome against current outcome reaches p < 10^-6. Under epoch reading (b) past choice against current choice gives p = 0.011. The durations are much shorter than the paper's under every reading (for example 820 and 801 ms for past outcome and past choice against 1,341 and 1,169, and 684 and 612 ms for current choice and outcome against 800 and 707, with the 150 ms of the window added). This rests on the deposited baseline: under the claims file's baseline readings the four comparisons are not all at p < 0.01 (section "Baseline readings").

fig6-past-short-livedΒΆ

Encoding of past information was limited to the immediately preceding trial; the proportion of electrodes encoding choices and outcomes 2 to 5 trials back was significantly lower than for the current and previous trials (p < 0.01, t test), with no evidence of encoding from earlier rounds.

InΒ [22]:
prop = pd.DataFrame({lag: {saez.LABELS[k]: 100 * SC[(k, lag)]["encoding"].mean() for k in saez.CURRENT} for lag in LAGS})
prop.columns = [f"t-{lag}" if lag else "t" for lag in LAGS]
print("percent of electrodes encoding, per regressor and lag:\n", prop.round(1).to_string())
chance = {lag: np.mean([SC[(k, lag)]["perm_count"] for k in saez.CURRENT], 0) / N_ELEC * 100 for lag in LAGS}
lagmean = prop.mean()
print("\nmean over regressors per lag:", lagmean.round(1).to_dict())
print("chance (mean over regressors) per lag, mean and 95th percentile:",
      {f"t-{lag}": (round(chance[lag].mean(), 1), round(np.percentile(chance[lag], 95), 1)) for lag in LAGS})
far = prop[[f"t-{lag}" for lag in range(2, 6)]].values.ravel()
ta, tb = stats.ttest_ind(far, prop["t"]), stats.ttest_ind(far, prop["t-1"])
print(f"(a) per-regressor proportions, t-2..t-5 pooled (mean {far.mean():.1f}%) vs t ({prop['t'].mean():.1f}%): t = {ta.statistic:.2f}, p = {ta.pvalue:.2e};"
      f" vs t-1 ({prop['t-1'].mean():.1f}%): t = {tb.statistic:.2f}, p = {tb.pvalue:.2e}")
lm = lagmean.values[2:]
ra, rb = stats.ttest_1samp(lm, lagmean["t"]), stats.ttest_1samp(lm, lagmean["t-1"])
print(f"(b) per-lag means t-2..t-5 {lm.round(1).tolist()} vs t {lagmean['t']:.1f}: p = {ra.pvalue:.2e}; vs t-1 {lagmean['t-1']:.1f}: p = {rb.pvalue:.2e}")
print("lags t-2..t-5 whose mean proportion exceeds the 95th percentile of chance:",
      [f"t-{lag}" for lag in range(2, 6) if lagmean.iloc[lag] > np.percentile(chance[lag], 95)])
above = {f"t-{lag}": [saez.LABELS[k] for k in saez.CURRENT if SC[(k, lag)]["encoding"].sum() > np.percentile(SC[(k, lag)]["perm_count"], 95)] for lag in range(2, 6)}
print("regressors above their own 95th percentile at t-2..t-5:", above)
percent of electrodes encoding, per regressor and lag:
                             t   t-1   t-2   t-3   t-4   t-5
risk                     44.0  20.9  13.1  18.8  15.7  17.3
gamble                   37.2  33.5  14.1  18.3  16.2  18.3
offer value (win prob.)  31.9  30.9  15.2  16.2  20.4  20.4
chosen value             21.5  27.7  11.0  14.1  16.8  15.7
win index                30.9  35.1  20.4  15.2  16.8  20.4
loss index               28.3  41.4  17.8  27.7  16.8  18.3
RPE                      27.2  39.8  18.8  18.8  18.3  24.1
regret                   33.5  49.7  22.0  12.6  14.1  20.4

mean over regressors per lag: {'t': 31.8, 't-1': 34.9, 't-2': 16.6, 't-3': 17.7, 't-4': 16.9, 't-5': 19.4}
chance (mean over regressors) per lag, mean and 95th percentile: {'t-0': (np.float64(18.2), np.float64(20.7)), 't-1': (np.float64(18.2), np.float64(20.6)), 't-2': (np.float64(18.3), np.float64(20.7)), 't-3': (np.float64(18.2), np.float64(20.6)), 't-4': (np.float64(18.3), np.float64(20.7)), 't-5': (np.float64(18.3), np.float64(20.5))}
(a) per-regressor proportions, t-2..t-5 pooled (mean 17.6%) vs t (31.8%): t = -8.46, p = 2.87e-10; vs t-1 (34.9%): t = -8.91, p = 7.60e-11
(b) per-lag means t-2..t-5 [16.6, 17.7, 16.9, 19.4] vs t 31.8: p = 1.92e-04; vs t-1 34.9: p = 1.07e-04
lags t-2..t-5 whose mean proportion exceeds the 95th percentile of chance: []
regressors above their own 95th percentile at t-2..t-5: {'t-2': [], 't-3': ['loss index'], 't-4': [], 't-5': []}

Result: reproduced. The proportion of encoding electrodes falls from 31.8% (t) and 34.9% (t-1) to 16.6 to 19.4% at t-2 to t-5 (p = 2.9e-10 and 7.6e-11 under reading (a); 1.9e-04 and 1.1e-04 under reading (b)). At no lag from t-2 to t-5 does the mean proportion exceed the 95th percentile of chance (20.5 to 20.7%); only loss index at t-3 exceeds its own 95th percentile. The claims file's baseline readings give the same outcome (section "Baseline readings").

figs5d-sharp-boundaryΒΆ

The distribution of encoding significance at the peak %EV shows a sharp boundary between t-1 and t-2 but not between t and t-1 (one-sided Kolmogorov-Smirnov tests).

Per electrode, the window with the highest %EV over both epochs, and -log10 p of the regression there. "t-1>t" is tested as the ECDF of t-1 lying above that of t (ks_2samp(t-1, t, alternative="greater")), and "t-2>t-1" likewise.

InΒ [23]:
def peak_logp(key):
    sc = SC[key]
    r2 = sc["r2"].reshape(-1, sc["r2"].shape[2])
    best = r2.max(0)
    n = np.array([sc["n"][s] for s in SUBJ])
    t = np.sqrt(best * (n - 2) / np.maximum(1 - best, 1e-12))
    return -np.log10(2 * stats.t.sf(t, n - 2))


rows = []
pooled = {lag: [] for lag in LAGS}
for k in saez.CURRENT:
    lp = {lag: peak_logp((k, lag)) for lag in LAGS}
    for lag in LAGS:
        pooled[lag].append(lp[lag])
    a = stats.ks_2samp(lp[1], lp[0], alternative="greater")
    b = stats.ks_2samp(lp[2], lp[1], alternative="greater")
    rows.append({"regressor": saez.LABELS[k], "median -log10p t": np.median(lp[0]), "t-1": np.median(lp[1]), "t-2": np.median(lp[2]),
                 "KS t-1>t p": a.pvalue, "KS t-2>t-1 p": b.pvalue})
ks = pd.DataFrame(rows)
print(ks.round(4).to_string(index=False))
P = {lag: np.concatenate(pooled[lag]) for lag in LAGS}
a, b = stats.ks_2samp(P[1], P[0], alternative="greater"), stats.ks_2samp(P[2], P[1], alternative="greater")
print(f"pooled: t-1>t D = {a.statistic:.3f}, p = {a.pvalue:.3g}; t-2>t-1 D = {b.statistic:.3f}, p = {b.pvalue:.3g}")
n_ok = int(((ks["KS t-2>t-1 p"] < 0.05) & (ks["KS t-1>t p"] >= 0.05)).sum())
print(f"regressors with t-2>t-1 significant and t-1>t not: {n_ok} of 8")
print("pooled medians of -log10 p by lag:", {lag: round(float(np.median(P[lag])), 3) for lag in LAGS})
              regressor  median -log10p t    t-1    t-2  KS t-1>t p  KS t-2>t-1 p
                   risk            1.9499 1.6219 1.4459      0.0002        0.0219
                 gamble            1.8841 1.8036 1.4367      0.2623        0.0000
offer value (win prob.)            1.7034 1.6988 1.4950      0.1837        0.0033
           chosen value            1.6478 1.6582 1.4283      0.5314        0.0003
              win index            1.6545 1.8447 1.4752      0.9793        0.0000
             loss index            1.7192 1.8524 1.5663      0.8286        0.0000
                    RPE            1.5573 1.8490 1.4836      1.0000        0.0000
                 regret            1.7425 2.0469 1.5853      0.9793        0.0000
pooled: t-1>t D = 0.005, p = 0.968; t-2>t-1 D = 0.207, p = 2.64e-29
regressors with t-2>t-1 significant and t-1>t not: 7 of 8
pooled medians of -log10 p by lag: {0: 1.731, 1: 1.775, 2: 1.494, 3: 1.466, 4: 1.469, 5: 1.515}

Result: reproduced. The t-2 distribution lies above the t-1 distribution (weaker encoding) with p < 0.05 for all 8 regressors (pooled D = 0.207, p = 2.6e-29), while t-1 does not lie above t for 7 of 8 (risk is the exception, p = 0.0002; pooled p = 0.968). This rests on the deposited baseline: under the claims file's baseline readings t-1 also lies above t in the pooled test (section "Baseline readings").

figs3a-risk-all-trialsΒΆ

The risk regressor over all trials explains slightly more HFA variance than risk restricted to gamble trials, so risk is encoded whatever the subsequent choice.

InΒ [24]:
e_risk = SC[("risk", 0)]["encoding"]
all_prof = SC[("risk", 0)]["r2"][0][:, e_risk].mean(1) * 100
g_prof = SC[("risk_gamble_only", 0)]["r2"][0][:, e_risk].mean(1) * 100
print(f"risk-encoding electrodes (all-trial selection): {int(e_risk.sum())}")
print(f"game epoch peak mean %EV: all trials {all_prof.max():.2f} at {c[all_prof.argmax()]} ms; gamble trials only {g_prof.max():.2f} at {c[g_prof.argmax()]} ms")
post = c >= 100
print(f"mean over windows centred >= 100 ms: all {all_prof[post].mean():.2f}, gamble only {g_prof[post].mean():.2f}")
e2 = SC[("risk_gamble_only", 0)]["encoding"]
print(f"variant, electrodes selected on gamble trials ({int(e2.sum())}): peak gamble-only {SC[('risk_gamble_only', 0)]['r2'][0][:, e2].mean(1).max() * 100:.2f},"
      f" all-trial on the same electrodes {SC[('risk', 0)]['r2'][0][:, e2].mean(1).max() * 100:.2f}")
print("gamble-only trials have fewer trials, so the chance %EV is higher there: chance peak, all",
      f"{(SC[('risk', 0)]['perm_r2_enc'][:, 0].sum(0) / SC[('risk', 0)]['perm_count'].sum()).max() * 100:.2f},",
      f"gamble only {(SC[('risk_gamble_only', 0)]['perm_r2_enc'][:, 0].sum(0) / SC[('risk_gamble_only', 0)]['perm_count'].sum()).max() * 100:.2f}")
risk-encoding electrodes (all-trial selection): 84
game epoch peak mean %EV: all trials 2.32 at 1000 ms; gamble trials only 3.12 at 1000 ms
mean over windows centred >= 100 ms: all 1.48, gamble only 1.80
variant, electrodes selected on gamble trials (64): peak gamble-only 3.51, all-trial on the same electrodes 1.99
gamble-only trials have fewer trials, so the chance %EV is higher there: chance peak, all 1.25, gamble only 2.30

Result: not reproduced. Over the 84 risk-encoding electrodes the gamble-only regressor gives the higher peak mean %EV (3.12 against 2.32 for all trials). Gamble trials are fewer, and the chance peak is higher for them too (2.30 against 1.25), so the comparison of raw %EV favours the smaller set. With each chance peak subtracted, all trials come out higher (2.32 - 1.25 = 1.07 against 3.12 - 2.30 = 0.82); the criterion compares raw %EV, so the outcome follows it, but the comparison is confounded by the number of trials.

figs3b-no-motor-encodingΒΆ

The direction of the response (left or right option) is not reflected in OFC HFA.

InΒ [25]:
s3b = summary(("left", 0))
print(s3b)
for ep in saez.EPOCHS:
    prof, ch = profile([("left", 0)], ep)
    print(f"{ep}: peak mean %EV {prof.max():.2f} at {c[prof.argmax()]} ms (chance profile max {ch.max():.2f})")
print("encoding > 95th percentile of chance:", s3b["encoding"] > s3b["chance 95th"],
      f"| percentile of the observed count among shuffles: {stats.percentileofscore(SC[('left', 0)]['perm_count'], s3b['encoding']):.1f}")
{'regressor': 'left', 'lag': 0, 'encoding': 31, 'percent': np.float64(16.2), 'chance mean': np.float64(34.7), 'chance 95th': 49.0, 'patients': 7}
game: peak mean %EV 1.61 at 1200 ms (chance profile max 1.25)
buttonpress: peak mean %EV 2.00 at -550 ms (chance profile max 1.26)
encoding > 95th percentile of chance: False | percentile of the observed count among shuffles: 34.5

Result: reproduced. 31 electrodes (16.2%) meet the encoding rule for the left/right response, below the mean of its shuffles (34.7) and the 95th percentile (49); the observed count is at the 34.5th percentile of the shuffled counts.

tables2-patients-coverageΒΆ

All signals were present in at least 6 of the 10 patients (mean 7.41 plus or minus 0.4).

InΒ [26]:
cov = pd.DataFrame([summary((k, lag)) for lag in (0, 1) for k in saez.CURRENT])[["regressor", "lag", "encoding", "patients"]]
print(cov.to_string(index=False))
grp_pat = {}
for gname, keys in GROUPS.items():
    any_enc = np.any([SC[k]["encoding"] for k in keys], 0)
    grp_pat[gname] = len(set(SUBJ[any_enc]))
ra = cov.patients.values
rb = cov[~((cov.regressor == "risk") & (cov.lag == 1))].patients.values
rc = np.array(list(grp_pat.values()))
for name, v in (("(a) 16 regressors", ra), ("(b) 15 without past risk", rb), ("(c) 4 groups", rc)):
    print(f"{name}: mean {v.mean():.2f} (SEM {stats.sem(v):.2f}), min {v.min()}, all >= 6: {bool((v >= 6).all())}")
print("groups:", grp_pat)
print("expected 7.41 +/- 0.4 (7.01 to 7.81), all >= 6")
              regressor  lag  encoding  patients
                   risk    0        84         9
                 gamble    0        71         8
offer value (win prob.)    0        61         8
           chosen value    0        41         8
              win index    0        59         7
             loss index    0        54         8
                    RPE    0        52         9
                 regret    0        64        10
                   risk    1        40         6
                 gamble    1        64        10
offer value (win prob.)    1        59         9
           chosen value    1        53         9
              win index    1        67         9
             loss index    1        79        10
                    RPE    1        76         9
                 regret    1        95         9
(a) 16 regressors: mean 8.62 (SEM 0.27), min 6, all >= 6: True
(b) 15 without past risk: mean 8.80 (SEM 0.22), min 7, all >= 6: True
(c) 4 groups: mean 10.00 (SEM 0.00), min 10, all >= 6: True
groups: {'choice': 10, 'outcome': 10, 'past choice': 10, 'past outcome': 10}
expected 7.41 +/- 0.4 (7.01 to 7.81), all >= 6

Result: not reproduced. Every regressor is present in at least 6 patients (past risk in 6, the others in 7 to 10), but the mean is 8.62 patients over the 16 regressors, 8.80 without past risk and 10 over the four groups, all above 7.41 +/- 0.4 and above the 7.75 that Table S2 gives counted the same way.

fig2-example-electrodesΒΆ

Example electrodes show risk encoding with an inverted U relation between win probability and HFA at peak encoding, and regret encoding with a linear drop of HFA with regret.

InΒ [27]:
def at_peak(key, e_global):
    """HFA at the electrode's peak %EV window (over both epochs) for all its trials."""
    sc = SC[key]
    s = SUBJ[e_global]
    e_local = int(e_global - np.where(SUBJ == s)[0][0])
    ei, wi = np.unravel_index(sc["r2"][:, :, e_global].argmax(), (2, saez.N_WIN))
    return s, H[s][saez.EPOCHS[ei]][:, wi, e_local].astype(float)


quad, lin, quad_neg_any = [], [], []
for e in np.where(SC[("risk", 0)]["encoding"])[0]:
    s, y = at_peak(("risk", 0), e)
    p = REG[("winprob", 0)][s]
    X = np.c_[np.ones(len(p)), p, p ** 2]
    beta, *_ = np.linalg.lstsq(X, y, rcond=None)
    res = y - X @ beta
    se = np.sqrt(np.diag(np.linalg.inv(X.T @ X)) * (res @ res) / (len(y) - 3))
    tq = beta[2] / se[2]
    quad.append((beta[2], 2 * stats.t.sf(abs(tq), len(y) - 3)))
for e in np.where(SC[("regret", 0)]["encoding"])[0]:
    s, y = at_peak(("regret", 0), e)
    lr = stats.linregress(REG[("regret", 0)][s], y)
    lin.append((lr.slope, lr.pvalue))
quad, lin = np.array(quad), np.array(lin)
print(f"risk-encoding electrodes {len(quad)}: negative quadratic term with p < 0.05 in {int(((quad[:, 0] < 0) & (quad[:, 1] < 0.05)).sum())},"
      f" positive with p < 0.05 in {int(((quad[:, 0] > 0) & (quad[:, 1] < 0.05)).sum())}")
print(f"regret-encoding electrodes {len(lin)}: significant linear slope in {int((lin[:, 1] < 0.05).sum())}"
      f" ({int(((lin[:, 0] > 0) & (lin[:, 1] < 0.05)).sum())} with HFA rising with regret, i.e. falling as regret becomes more negative;"
      f" {int(((lin[:, 0] < 0) & (lin[:, 1] < 0.05)).sum())} the other way)")
risk-encoding electrodes 84: negative quadratic term with p < 0.05 in 44, positive with p < 0.05 in 40
regret-encoding electrodes 64: significant linear slope in 64 (38 with HFA rising with regret, i.e. falling as regret becomes more negative; 26 the other way)

Result: reproduced. Of the 84 risk-encoding electrodes, 44 show a significant negative quadratic term in win probability at their peak window (an inverted U) and 40 a significant positive one. All 64 regret-encoding electrodes show a significant linear slope at their peak window, 38 with HFA rising with regret (falling as regret becomes more negative) and 26 the other way. The regret half holds by construction: an electrode selected for encoding regret has a significant slope at its peak window. For risk, upright and inverted U shapes are about as common (40 and 44).

behavior-past-no-effectΒΆ

None of the past trial characteristics significantly affected risk taking (all p > 0.15, random effects logistic regression).

All non-timeout rounds after the first; t-1 regressors from the rounds with the authors' convention (0 for choice and outcome regressors after a timeout).

InΒ [28]:
rows = []
for s in saez.SUBJECTS:
    r = beh[s]["rounds"]
    idx = np.where(~r.timeout.values)[0]
    p1 = saez.past_regressors(r, idx, 1)
    d = pd.DataFrame({"subject": s, "gamble": r.gamble_ind.values[idx], "winprob": r.winprob.values[idx]})
    rows.append(pd.concat([d, p1.add_prefix("prev_")], axis=1))
BP = pd.concat(rows, ignore_index=True).dropna()
print("rounds used:", len(BP))
out = []
for k in saez.CURRENT:
    xk = BP["prev_" + k].values
    fa = saez.glmm_logit(BP.gamble.values, np.c_[np.ones(len(BP)), BP.winprob.values, xk], BP.subject.values)
    fb = saez.glmm_logit(BP.gamble.values, np.c_[np.ones(len(BP)), xk], BP.subject.values)
    out.append({"past regressor": saez.LABELS[k], "(a) beta": fa.estimate[2], "(a) p": fa.p[2], "(b) beta": fb.estimate[1], "(b) p": fb.p[1],
                "beta per SD (a)": fa.estimate[2] * xk.std()})
bpe = pd.DataFrame(out)
print(bpe.round(4).to_string(index=False))
print("reading (a): any p < 0.05:", bool((bpe["(a) p"] < 0.05).any()), "| min p", round(bpe["(a) p"].min(), 4),
      "| all p > 0.15:", bool((bpe["(a) p"] > 0.15).all()))
print("reading (b): any p < 0.05:", bool((bpe["(b) p"] < 0.05).any()), "| min p", round(bpe["(b) p"].min(), 4))
rounds used: 1831
         past regressor  (a) beta  (a) p  (b) beta  (b) p  beta per SD (a)
                   risk    1.7442 0.0154    2.1206 0.0005           0.1371
                 gamble    0.1085 0.3421    0.1068 0.2722           0.0541
offer value (win prob.)   -0.0418 0.8327   -0.0870 0.6088          -0.0117
           chosen value   -0.0207 0.0390   -0.0184 0.0343          -0.1181
              win index    0.1468 0.2160    0.0148 0.8821           0.0708
             loss index   -0.0499 0.7434    0.1631 0.2081          -0.0188
                    RPE    0.0167 0.0473    0.0022 0.7594           0.1112
                 regret    0.0002 0.9790    0.0019 0.8163           0.0015
reading (a): any p < 0.05: True | min p 0.0154 | all p > 0.15: False
reading (b): any p < 0.05: True | min p 0.0005

Result: not reproduced. With current win probability as a covariate (reading (a)), past risk (p = 0.015) and past chosen value (p = 0.039) affect gamble choice at p < 0.05; RPE is at p = 0.047. Alone (reading (b)), past risk (p = 0.0005) and past chosen value (p = 0.034) are significant. The effects are small (about 0.1 log-odds per SD).

figs6b-stepwise-similarΒΆ

Stepwise regression with model selection gave proportions of encoding electrodes per regressor similar to those of the 5-consecutive-window selection.

STAR Methods, Stepwise regression: per electrode and regressor, the sum of F over the longest stretch of consecutive windows with p < 0.05; 10,000 label shuffles give a permutation p, Bonferroni corrected over the electrodes ("across n = 192 electrodes"; the 191 analysed here are used); surviving regressors enter forward selection by ANOVA at p < 0.05, starting from the one with the highest peak %EV, adding the regressor with the largest residual improvement. Two details are open and are assumptions: the stretch is taken in each epoch and the larger sum used; the model comparison is made on the HFA of the window where the base regressor has its peak %EV (reading (a)). Reading (b) shows the proportions after the permutation step alone, before model selection.

InΒ [29]:
# check of the procedure on a synthetic electrode that encodes x strongly, and one that does not
rng = np.random.default_rng(4999)
xs = rng.normal(size=150)
fake = {e: rng.normal(size=(150, saez.N_WIN, 2)).astype(np.float32) for e in saez.EPOCHS}
fake["game"][:, 25:40, 0] += xs[:, None]
print("synthetic check, permutation p (encoding, null electrode):", saez.stepwise_sumF(fake, xs, 2000, rng)[1].round(4))
KEYS16 = [(k, 0) for k in saez.CURRENT] + [(k, 1) for k in saez.CURRENT]


def stepwise_selection():
    """Permutation step (10,000 shuffles, Bonferroni over the electrodes) and forward selection."""
    perm_p = {}
    for i, key in enumerate(KEYS16):
        rng = np.random.default_rng(5000 + i)
        perm_p[key] = np.concatenate([saez.stepwise_sumF(H[s], np.asarray(REG[key][s], float), 10000, rng)[1] for s in saez.SUBJECTS])
    bonf = saez.ALPHA / N_ELEC
    survive = {k: perm_p[k] < bonf for k in KEYS16}
    selected = {k: np.zeros(N_ELEC, bool) for k in KEYS16}
    offset = 0
    for s in saez.SUBJECTS:
        ne = H[s]["game"].shape[2]
        for e in range(ne):
            eg = offset + e
            cands = [k for k in KEYS16 if survive[k][eg]]
            if not cands:
                continue
            peak = {k: SC[k]["r2"][:, :, eg].max() for k in cands}
            base = max(cands, key=peak.get)
            ei, wi = np.unravel_index(SC[base]["r2"][:, :, eg].argmax(), (2, saez.N_WIN))
            y = H[s][saez.EPOCHS[ei]][:, wi, e].astype(float)
            Xd = pd.DataFrame({f"{k[0]}|{k[1]}": REG[k][s] for k in cands})
            ok = ~Xd.isna().any(axis=1).values
            chosen = saez.forward_select(y[ok], Xd[ok].reset_index(drop=True), f"{base[0]}|{base[1]}")
            for name in chosen:
                k0, l0 = name.split("|")
                selected[(k0, int(l0))][eg] = True
        offset += ne
    return survive, selected


t0 = time.time()
survive, selected = stepwise_selection()
print(f"permutations and selection done in {time.time() - t0:.0f} s")
sw = pd.DataFrame({"regressor": [saez.LABELS[k[0]] for k in KEYS16], "lag": [k[1] for k in KEYS16],
                   "5-window %": [100 * SC[k]["encoding"].mean() for k in KEYS16],
                   "stepwise %": [100 * selected[k].mean() for k in KEYS16],
                   "permutation step only %": [100 * survive[k].mean() for k in KEYS16]})
sw["difference"] = sw["stepwise %"] - sw["5-window %"]
print(sw.round(1).to_string(index=False))
for col in ("stepwise %", "permutation step only %"):
    rho = stats.spearmanr(sw["5-window %"], sw[col])
    print(f"{col}: (a) Spearman rho {rho.statistic:.2f}, p {rho.pvalue:.3f}; (b) max |difference| {np.abs(sw[col] - sw['5-window %']).max():.1f} points")
print("electrodes with any regressor after stepwise:", int(np.any(list(selected.values()), 0).sum()), "of", N_ELEC)
synthetic check, permutation p (encoding, null electrode): [0.0005 0.2934]
permutations and selection done in 32 s
              regressor  lag  5-window %  stepwise %  permutation step only %  difference
                   risk    0        44.0         0.5                      0.5       -43.5
                 gamble    0        37.2         0.5                      0.5       -36.6
offer value (win prob.)    0        31.9         0.0                      0.0       -31.9
           chosen value    0        21.5         0.0                      0.0       -21.5
              win index    0        30.9         0.0                      0.0       -30.9
             loss index    0        28.3         0.0                      0.0       -28.3
                    RPE    0        27.2         0.0                      0.0       -27.2
                 regret    0        33.5         0.0                      0.0       -33.5
                   risk    1        20.9         0.0                      0.0       -20.9
                 gamble    1        33.5         2.1                      2.6       -31.4
offer value (win prob.)    1        30.9         0.0                      1.6       -30.9
           chosen value    1        27.7         0.0                      0.5       -27.7
              win index    1        35.1         1.6                      2.6       -33.5
             loss index    1        41.4         1.6                      2.1       -39.8
                    RPE    1        39.8         1.0                      2.1       -38.7
                 regret    1        49.7         1.6                      2.1       -48.2
stepwise %: (a) Spearman rho 0.77, p 0.000; (b) max |difference| 48.2 points
permutation step only %: (a) Spearman rho 0.65, p 0.006; (b) max |difference| 47.6 points
electrodes with any regressor after stepwise: 16 of 191

Result: partially reproduced, resting on assumptions about the stepwise procedure. The procedure behaves as intended on a synthetic electrode (p = 0.0005, the smallest possible with 2,000 shuffles). On the data, few electrodes survive the Bonferroni step: 16 of 191 keep any regressor, and the stepwise proportions are 0 to 2.1% against 20.9 to 49.7% for the 5-window selection. They are ranked alike (Spearman rho 0.77, p < 0.001, reading (a) holds) but differ by up to 48.2 points (reading (b) fails). Reading (a) passes only formally: the stepwise proportions are 0 for 9 of 16 regressors, and in substance the two selections are not similar. Under the claims file's baseline readings neither reading holds (section "Baseline readings").

fig7f-multiplexingΒΆ

Most electrodes (132 of 192, 68.7%) encoded at least two of the four signal types (choice, outcome, past choice, past outcome) and 30 of 192 (15.6%) encoded all four.

InΒ [30]:
def group_sets(sel):
    return {g: np.any([sel[k] for k in keys], 0) for g, keys in GROUPS.items()}


for name, sel in (("stepwise", selected), ("5-window (variant)", {k: SC[k]["encoding"] for k in KEYS16})):
    gs = group_sets(sel)
    ntypes = np.sum(list(gs.values()), 0)
    print(f"{name}: per group {dict((g, int(v.sum())) for g, v in gs.items())}; >= 2 types {int((ntypes >= 2).sum())} ({100 * (ntypes >= 2).mean():.1f}%),"
          f" all 4 {int((ntypes == 4).sum())} ({100 * (ntypes == 4).mean():.1f}%), any {int((ntypes >= 1).sum())} of {N_ELEC}")
print("expected: >= 2 types 132 +/- 13.2, all four 30 +/- 3")
stepwise: per group {'choice': 2, 'outcome': 0, 'past choice': 4, 'past outcome': 10}; >= 2 types 0 (0.0%), all 4 0 (0.0%), any 16 of 191
5-window (variant): per group {'choice': 147, 'outcome': 124, 'past choice': 125, 'past outcome': 142}; >= 2 types 166 (86.9%), all 4 65 (34.0%), any 184 of 191
expected: >= 2 types 132 +/- 13.2, all four 30 +/- 3

Result: not reproduced. The stepwise selection rests on assumptions, but the 5-window selection fails as well, so the outcome does not depend on them. Under the stepwise selection no electrode encodes two or more types (16 encode one). Under the 5-window selection (variant) 166 electrodes (86.9%) encode two or more and 65 (34.0%) all four, both above 132 +/- 13.2 and 30 +/- 3.

figs7-present-past-overlapΒΆ

Electrodes encoding both present and t-1 information were overrepresented, for choice (39 of 120, 32.5%, against an expected 31, p < 0.05) and for outcome (43 of 120, 35.8%, against an expected 34, p < 0.01), chi-square tests; many electrodes still encoded only present or only past information.

InΒ [31]:
def overlap(sets, base_mask, label):
    for cls in ("choice", "outcome"):
        a, b = sets[cls][base_mask], sets["past " + cls][base_mask]
        tab = np.array([[np.sum(a & b), np.sum(a & ~b)], [np.sum(~a & b), np.sum(~a & ~b)]])
        n = tab.sum()
        exp = a.sum() * b.sum() / n
        if (tab.sum(0) == 0).any() or (tab.sum(1) == 0).any():
            print(f"  {label} {cls}: N {n}, both {tab[0, 0]}, expected {exp:.1f}; a row or column is empty, no test")
            continue
        chi = stats.chi2_contingency(tab, correction=False)
        chiy = stats.chi2_contingency(tab, correction=True)
        print(f"  {label} {cls}: N {n}, both {tab[0, 0]} ({100 * tab[0, 0] / n:.1f}%), expected {exp:.1f}; present only {tab[0, 1]}, past only {tab[1, 0]};"
              f" chi2 {chi.statistic:.2f} p {chi.pvalue:.3g} (Yates p {chiy.pvalue:.3g}); overrepresented {tab[0, 0] > exp}")


gs_sw, gs_5 = group_sets(selected), group_sets({k: SC[k]["encoding"] for k in KEYS16})
any_sw = np.any(list(gs_sw.values()), 0)
any_5 = np.any(list(gs_5.values()), 0)
overlap(gs_sw, any_sw, "(a) stepwise, electrodes encoding any group")
overlap(gs_5, any_5, "(b) 5-window, electrodes encoding any group")
overlap(gs_sw, np.ones(N_ELEC, bool), "(c) stepwise, all electrodes")
overlap(gs_5, np.ones(N_ELEC, bool), "(c) 5-window, all electrodes")
print("expected: choice both 39 +/- 3.9 (p < 0.05), outcome both 43 +/- 4.3 (p < 0.01), each above the count expected under independence")
  (a) stepwise, electrodes encoding any group choice: N 16, both 0 (0.0%), expected 0.5; present only 2, past only 4; chi2 0.76 p 0.383 (Yates p 1); overrepresented False
  (a) stepwise, electrodes encoding any group outcome: N 16, both 0, expected 0.0; a row or column is empty, no test
  (b) 5-window, electrodes encoding any group choice: N 184, both 99 (53.8%), expected 99.9; present only 48, past only 26; chi2 0.12 p 0.733 (Yates p 0.886); overrepresented False
  (b) 5-window, electrodes encoding any group outcome: N 184, both 101 (54.9%), expected 95.7; present only 23, past only 41; chi2 3.95 p 0.0469 (Yates p 0.0718); overrepresented True
  (c) stepwise, all electrodes choice: N 191, both 0 (0.0%), expected 0.0; present only 2, past only 4; chi2 0.04 p 0.835 (Yates p 1); overrepresented False
  (c) stepwise, all electrodes outcome: N 191, both 0, expected 0.0; a row or column is empty, no test
  (c) 5-window, all electrodes choice: N 191, both 99 (51.8%), expected 96.2; present only 48, past only 26; chi2 1.02 p 0.312 (Yates p 0.407); overrepresented True
  (c) 5-window, all electrodes outcome: N 191, both 101 (52.9%), expected 92.2; present only 23, past only 41; chi2 9.36 p 0.00222 (Yates p 0.00391); overrepresented True
expected: choice both 39 +/- 3.9 (p < 0.05), outcome both 43 +/- 4.3 (p < 0.01), each above the count expected under independence

Result: not reproduced. The stepwise selection rests on assumptions, but readings (b) and (c) fail as well, so the outcome does not depend on them. Under the stepwise selection the sets are too small to test (both counts 0). Under the 5-window selection the counts of electrodes encoding both present and past information are 99 (choice) and 101 (outcome) of 184, against 39 and 43 of 120; outcome is overrepresented (101 against 95.7 expected, p = 0.047; 101 against 92.2 over all 191, p = 0.002) but choice is not (99 against 99.9 expected, p = 0.73).

mixed-effects-robustΒΆ

In nested mixed-effects models with patient and electrode as random effects, all regressors were significant (all p < 10^-4, Bonferroni corrected).

Every model has patient and electrode within patient as random intercepts, fitted by REML. The helper (nested_lmm) fits it in closed form, as every electrode of a patient shares the trials and the regressors; the first cell checks it against statsmodels MixedLM on three fits. Readings of the claims file: time point (a) one model per window (both epochs, 114 windows; Bonferroni over 16 regressors and 114 windows) and (b) HFA averaged over the windows that start at or after the event (centres 100 to 1,900 ms) in each epoch (Bonferroni over 16 regressors and 2 epochs); regressors (a) one per model and (b) all together; electrodes (a) all and (b) encoding only (those encoding the regressor, or for the joint model those encoding any of the 16). A regressor counts when its corrected p is below 10^-4 in some window or epoch. Gamble choice is the sum of the win and loss indices (at t and at t-1), so the 16 cannot be estimated together: the joint model leaves out the two gamble regressors (14 estimated), and under reading (b) of the regressors the gamble regressors are not tested.

InΒ [32]:
POST = c >= 100
names = [f"{k[0]}_{k[1]}" for k in KEYS16]
K14 = [k for k in KEYS16 if k[0] != "gamble_ind"]
print("gamble = win index + loss index in every trial:",
      all(np.nanmax(np.abs(REG[("gamble_ind", lag)][s] - REG[("win_ind", lag)][s] - REG[("loss_ind", lag)][s])) == 0 for lag in (0, 1) for s in saez.SUBJECTS))
ENC_ANY = np.any([SC[k]["encoding"] for k in KEYS16], 0)


def me_blocks(epoch, keys, win, electrodes=None):
    """Per patient (HFA trials x electrodes, [1, regressors]) for nested_lmm; NaN trials dropped."""
    out, off = [], 0
    for s in saez.SUBJECTS:
        h = H[s][epoch]
        ne = h.shape[2]
        m = np.ones(ne, bool) if electrodes is None else electrodes[off:off + ne]
        off += ne
        if not m.any():
            continue
        y = h[:, win, :].mean(1) if np.ndim(win) else h[:, win, :]
        X = np.c_[np.ones(len(y)), np.column_stack([REG[k][s] for k in keys])]
        ok = ~np.isnan(X).any(1)
        out.append((y[ok][:, m].astype(float), X[ok]))
    return out


def me_fits(win):
    """p of each regressor under the four regressor x electrode readings, both epochs, at win.

    Windows whose HFA does not vary over trials (the baseline window) are skipped."""
    rows = []
    for epoch in saez.EPOCHS:
        if not np.ndim(win) and max(H[s][epoch][:, win, :].std(0).max() for s in saez.SUBJECTS) < 1e-3:
            continue            # a window constant over trials (a baseline window, SD at most 1e-5) has nothing to fit
        for k, nm in zip(KEYS16, names):
            for model, el in (("one, all", None), ("one, encoding", SC[k]["encoding"])):
                f = saez.nested_lmm(me_blocks(epoch, [k], win, el))
                rows.append({"model": model, "epoch": epoch, "regressor": nm, "beta": f["beta"][1], "p": f["p"][1], "converged": f["converged"]})
        for model, el in (("together, all", None), ("together, encoding", ENC_ANY)):
            f = saez.nested_lmm(me_blocks(epoch, K14, win, el))
            for j, k in enumerate(K14):
                rows.append({"model": model, "epoch": epoch, "regressor": f"{k[0]}_{k[1]}", "beta": f["beta"][j + 1], "p": f["p"][j + 1], "converged": f["converged"]})
    return rows


def me_count(df, n_tests):
    df = df.assign(p_bonf=np.minimum(df.p * n_tests, 1))
    best = df.groupby(["model", "regressor"]).p_bonf.min().unstack(0).reindex(names)
    return best, {m: int((best[m] < 1e-4).sum()) for m in best.columns}


# check of nested_lmm against statsmodels MixedLM (patient random intercept, electrode variance component)
for key, epoch, win in ((("regret", 1), "game", POST), (("risk", 0), "buttonpress", POST), (("rpe", 0), "game", 30)):
    f = saez.nested_lmm(me_blocks(epoch, [key], win))
    rows = []
    for s in saez.SUBJECTS:
        h = H[s][epoch]
        y = h[:, win, :].mean(1) if np.ndim(win) else h[:, win, :]
        for e in range(h.shape[2]):
            rows.append(pd.DataFrame({"y": y[:, e].astype(float), "subj": s, "elec": f"{s}_{e}", "x": REG[key][s]}))
    m = smf.mixedlm("y ~ x", pd.concat(rows, ignore_index=True).dropna(), groups="subj", re_formula="1",
                    vc_formula={"elec": "0+C(elec)"}).fit(reml=True)
    print(f"{key[0]}_{key[1]} {epoch}: closed form beta {f['beta'][1]:.6f} SE {f['se'][1]:.6f} p {f['p'][1]:.3e};"
          f" statsmodels beta {m.params['x']:.6f} SE {m.bse['x']:.6f} p {m.pvalues['x']:.3e}")

t0 = time.time()
mm = pd.DataFrame(me_fits(POST))
best_b, n_b = me_count(mm, 32)
print(f"\ntime point (b), HFA averaged after the event: {len(mm)} estimates in {time.time() - t0:.0f} s; all converged: {bool(mm.converged.all())}")
print("corrected p (smaller of the two epochs):")
print(best_b.map(lambda v: "" if np.isnan(v) else f"{v:.1e}").to_string())
print("regressors with corrected p < 1e-4:", n_b, "(of 16; the joint models estimate 14)")
sign = mm[mm.model == "one, all"].pivot(index="regressor", columns="epoch", values="beta")
print("fixed-effect slopes, one regressor, all electrodes:\n", sign.round(3).to_string())
gamble = win index + loss index in every trial: True
regret_1 game: closed form beta -0.031642 SE 0.003467 p 7.145e-20; statsmodels beta -0.031642 SE 0.003468 p 7.271e-20
risk_0 buttonpress: closed form beta 0.468905 SE 0.271477 p 8.413e-02; statsmodels beta 0.468908 SE 0.271480 p 8.413e-02
rpe_0 game: closed form beta -0.002138 SE 0.004080 p 6.002e-01; statsmodels beta -0.002138 SE 0.004080 p 6.002e-01
time point (b), HFA averaged after the event: 120 estimates in 1 s; all converged: True
corrected p (smaller of the two epochs):
model        one, all one, encoding together, all together, encoding
regressor                                                           
risk_0        1.0e+00       3.4e-01       2.4e-01            2.7e-01
gamble_ind_0  8.1e-05       2.5e-09                                 
winprob_0     1.6e-03       2.4e-03       5.8e-01            7.3e-01
exputil_0     1.0e+00       1.0e+00       6.6e-01            4.8e-01
win_ind_0     4.9e-05       3.5e-08       2.2e-01            3.6e-01
loss_ind_0    1.6e-01       2.8e-01       1.0e+00            1.0e+00
rpe_0         3.8e-04       1.6e-07       1.0e+00            1.0e+00
regret_0      1.0e+00       9.9e-01       1.0e+00            1.0e+00
risk_1        1.0e+00       1.0e+00       1.5e-02            1.7e-02
gamble_ind_1  2.7e-04       3.1e-08                                 
winprob_1     7.5e-01       1.0e+00       2.2e-02            1.2e-02
exputil_1     6.8e-02       1.9e-01       3.0e-03            1.0e-02
win_ind_1     4.3e-02       1.1e-02       1.5e-03            2.0e-03
loss_ind_1    2.3e-11       3.0e-24       3.6e-18            1.7e-17
rpe_1         4.3e-03       8.9e-03       3.0e-16            2.6e-15
regret_1      1.0e-23       4.8e-37       8.0e-11            2.2e-10
regressors with corrected p < 1e-4: {'one, all': 4, 'one, encoding': 6, 'together, all': 3, 'together, encoding': 3} (of 16; the joint models estimate 14)
fixed-effect slopes, one regressor, all electrodes:
 epoch         buttonpress   game
regressor                       
exputil_0          -0.003 -0.004
exputil_1          -0.012  0.001
gamble_ind_0       -0.210 -0.110
gamble_ind_1        0.116  0.195
loss_ind_0         -0.018  0.151
loss_ind_1          0.396  0.347
regret_0            0.005 -0.006
regret_1           -0.037 -0.032
risk_0              0.469  0.432
risk_1             -0.273 -0.272
rpe_0              -0.006 -0.014
rpe_1              -0.012 -0.004
win_ind_0          -0.198 -0.212
win_ind_1          -0.144 -0.031
winprob_0          -0.310 -0.053
winprob_1           0.094  0.171

Reading (a) of the time point: one model per window (both epochs, 114 windows), under the four regressor and electrode readings; Bonferroni over 16 regressors and 114 windows.

InΒ [33]:
t0 = time.time()
pw = pd.DataFrame([dict(row, window=w) for w in range(saez.N_WIN) for row in me_fits(w)])
best_a, n_a = me_count(pw, 16 * 114)
print(f"per-window estimates: {len(pw)} in {time.time() - t0:.0f} s; all converged: {bool(pw.converged.all())}")
print("smallest corrected p over windows and epochs:")
print(best_a.map(lambda v: "" if np.isnan(v) else f"{v:.1e}").to_string())
print("regressors with corrected p < 1e-4 in some window:", n_a, "(of 16; the joint models estimate 14)")
print("windows fitted per epoch:", pw.groupby("epoch").window.nunique().to_dict())
lo = pw.loc[pw[pw.model == "one, all"].groupby("regressor").p.idxmin()]
print("one regressor, all electrodes, window of the smallest p:\n", lo.assign(centre=c[lo.window.values])[["regressor", "epoch", "centre", "beta", "p"]].to_string(index=False))
per-window estimates: 6780 in 58 s; all converged: True
smallest corrected p over windows and epochs:
model        one, all one, encoding together, all together, encoding
regressor                                                           
risk_0        1.5e-14       8.7e-11       3.4e-09            2.4e-08
gamble_ind_0  9.2e-12       1.3e-15                                 
winprob_0     3.9e-07       2.3e-06       3.4e-06            7.0e-06
exputil_0     1.7e-05       2.3e-02       3.3e-03            2.2e-03
win_ind_0     4.3e-22       1.3e-20       7.8e-04            1.4e-03
loss_ind_0    7.0e-09       4.0e-05       1.4e-03            1.4e-03
rpe_0         1.7e-08       2.1e-12       2.2e-09            8.6e-10
regret_0      6.7e-05       3.4e-03       8.5e-08            1.3e-07
risk_1        3.0e-03       8.6e-02       2.2e-12            5.1e-12
gamble_ind_1  4.0e-08       1.1e-06                                 
winprob_1     1.4e-05       4.7e-03       3.4e-05            2.5e-05
exputil_1     1.7e-03       1.6e-01       3.5e-08            1.5e-07
win_ind_1     8.5e-07       5.4e-07       1.0e-05            2.0e-05
loss_ind_1    2.6e-31       1.8e-42       2.4e-28            1.4e-27
rpe_1         8.4e-10       1.5e-08       6.6e-23            3.5e-21
regret_1      4.3e-23       1.7e-32       1.9e-14            1.2e-13
regressors with corrected p < 1e-4 in some window: {'one, all': 14, 'one, encoding': 11, 'together, all': 11, 'together, encoding': 11} (of 16; the joint models estimate 14)
windows fitted per epoch: {'buttonpress': 57, 'game': 56}
one regressor, all electrodes, window of the smallest p:
    regressor       epoch  centre      beta            p
   exputil_0        game       0 -0.029907 9.086307e-09
   exputil_1 buttonpress     150 -0.023626 9.576457e-07
gamble_ind_0 buttonpress     300 -0.427690 5.032506e-15
gamble_ind_1        game    1150  0.386039 2.202994e-11
  loss_ind_0 buttonpress    -900  0.441255 3.819547e-12
  loss_ind_1        game    1150  0.876731 1.406249e-34
    regret_0 buttonpress     900  0.024571 3.698186e-08
    regret_1 buttonpress      50 -0.046557 2.349708e-26
      risk_0 buttonpress    -900  2.710466 8.435784e-18
      risk_1 buttonpress    1650 -1.710583 1.653648e-06
       rpe_0        game    1100 -0.027976 9.586609e-12
       rpe_1 buttonpress    1900 -0.030960 4.606931e-13
   win_ind_0 buttonpress     250 -0.567929 2.379575e-25
   win_ind_1 buttonpress    -200 -0.347446 4.673519e-10
   winprob_0        game    -550 -0.541403 2.131151e-10
   winprob_1        game     300  0.579727 7.925207e-09

Result: reproduced, resting on baseline reading (a) and one model per window. With the nested model (patient, and electrode within patient) fitted by the closed-form REML, which agrees with statsmodels on three fits (slopes and SEs to four or more significant digits, p within 2%), no combination of readings on the deposited HFA makes every regressor significant at corrected p < 10^-4. The best is one model per window with one regressor and all electrodes: 14 of 16, with past chosen value (corrected p = 1.7e-03) and past risk (3.0e-03) short of it. On encoding electrodes only, 11 of 16 reach it. The joint models cannot estimate the gamble regressors (gamble is the sum of the win and loss indices) and 11 of the 14 others reach it. With HFA averaged after the event, 4 of 16 (all electrodes) and 6 of 16 (encoding electrodes) reach it, and 3 of 14 in the joint models. Under the claims file's baseline reading (a), the per-window model with one regressor and all electrodes makes all 16 significant (section "Baseline readings"; the largest corrected p is 3.3e-05, past gamble). The criterion passes when one reading meets it, and baseline (a) is a reading the claims file names, so the claim is reproduced. The pass is the best of the 24 combinations of readings run and rests on baseline (a) and the per-window reading (assumed). The verifier agreed in round 3.

Baseline readingsΒΆ

The claims file names two baseline readings: (a) subtract, per trial and electrode, the mean of the 200 ms before each epoch's event, and (b) subtract the mean of the 200 ms before game presentation from both epochs. The analysis above uses the HFA as deposited (game epoch corrected over [-1000, -800] ms, buttonpress epoch with an offset close to it, see the data check). The window centred at -100 ms is the mean of [-200, 0] ms, so (a) subtracts that window of each epoch from the epoch, and (b) subtracts that window of the game epoch from both, after putting the buttonpress epoch on the game epoch's level with its own per-trial, per-electrode offset (data check). Where the two epochs do not overlap (181 of 1,753 trials, 115 of them in s10) the offset is not known and the electrode's median over the subject's matched trials is used. Every encoding scan, the stepwise selection and the per-window mixed models are run again under each reading, with the same seeds, and the numbers each criterion rests on are printed side by side. "deposited" repeats the results above.

InΒ [34]:
BW = int(np.where(c == -100)[0][0])
H_DEP, SC_DEP = H, SC
H_BL = {"(a) own event": {}, "(b) game presentation": {}}
for s in saez.SUBJECTS:
    g, b = H_DEP[s]["game"].astype(np.float32), H_DEP[s]["buttonpress"].astype(np.float32)
    # (b): the buttonpress epoch is put on the game epoch's level with its per-trial, per-electrode offset
    # (data check), then the game epoch's 200 ms before game presentation is subtracted. Where the two
    # epochs do not overlap the offset is unknown and the electrode's median over the subject's matched
    # trials is used.
    dlev = H_DEP[s]["offset_diff"]
    dlev = np.where(np.isnan(dlev), np.nanmedian(dlev, 0), dlev).astype(np.float32)
    H_BL["(a) own event"][s] = {"game": g - g[:, BW:BW + 1], "buttonpress": b - b[:, BW:BW + 1]}
    H_BL["(b) game presentation"][s] = {"game": g - g[:, BW:BW + 1], "buttonpress": b + dlev[:, None, :] - g[:, BW:BW + 1]}
nm = {s: int(H_DEP[s]["offsets"].matched.sum()) for s in saez.SUBJECTS}
print("reading (b): trials with the buttonpress offset measured, per subject (others take the electrode's median):",
      {s: f"{nm[s]} of {len(H_DEP[s]['offsets'])}" for s in saez.SUBJECTS}, f"total {sum(nm.values())} of {sum(len(H_DEP[s]['offsets']) for s in saez.SUBJECTS)}")


def fmt(v):
    return " ".join(str(int(x)) for x in v)


def claim_numbers():
    """The numbers each encoding criterion rests on, from the current H and SC."""
    out = {}
    cur, past = [summary((k, 0)) for k in saez.CURRENT], [summary((k, 1)) for k in saez.CURRENT]
    ec, ep = [expected_cur[k] for k in saez.CURRENT], [expected_past[k] for k in saez.CURRENT]
    out["fig3: counts"] = fmt(d["encoding"] for d in cur)
    out["fig3: counts within 10% (of 8)"] = sum(abs(d["encoding"] - e) <= 0.1 * e for d, e in zip(cur, ec))
    out["fig3: counts above chance 95th (of 8)"] = sum(d["encoding"] > d["chance 95th"] for d in cur)
    out["fig3: chance 95th percentiles"] = fmt(d["chance 95th"] for d in cur)
    out["fig3: choice peak, game epoch (ms)"] = int(c[profile([(k, 0) for k in saez.CHOICE], "game")[0].argmax()])
    out["fig3: outcome peak, buttonpress epoch (ms)"] = int(c[profile([(k, 0) for k in saez.OUTCOME], "buttonpress")[0].argmax()])
    lt = latency_table(0)
    ch, oc = lt[lt.group == "choice"], lt[lt.group == "outcome"]
    for col in ("(a) delay", "(b) delay", "(a,b) duration"):
        out[f"latency: {col} choice / outcome (ms), p"] = (f"{ch[col].mean():.1f} / {oc[col].mean():.1f}, "
                                                           f"p = {stats.ttest_ind(ch[col], oc[col], nan_policy='omit').pvalue:.3f}")
    out["fig4: counts"] = fmt(d["encoding"] for d in past)
    out["fig4: counts within 10% (of 8)"] = sum(abs(d["encoding"] - e) <= 0.1 * e for d, e in zip(past, ep))
    out["fig4: past risk lowest"] = past[0]["encoding"] == min(d["encoding"] for d in past)
    out["fig4: other 7 above chance 95th"] = sum(d["encoding"] > d["chance 95th"] for d in past[1:])
    out["hfa-more-than-fp: mean % encoding, 16 regressors"] = round(np.mean([d["percent"] for d in cur + past]), 1)
    du = durations("a")
    out["fig5: mean ms, past outcome / past choice / choice / outcome"] = " / ".join(f"{(du[g] * 50).mean():.0f}" for g in ("past outcome", "past choice", "choice", "outcome"))
    ps = [stats.ttest_ind(du[p], du[q]).pvalue for p in ("past outcome", "past choice") for q in ("choice", "outcome")]
    out["fig5: four p, past longer (all < 0.01; < 1e-6)"] = f"{' '.join(f'{v:.1e}' for v in ps)} ({sum(v < 0.01 for v in ps)}; {sum(v < 1e-6 for v in ps)})"
    db = durations("b")
    ps = [stats.ttest_ind(db[p], db[q]).pvalue for p in ("past outcome", "past choice") for q in ("choice", "outcome")]
    out["fig5: epoch reading (b), four p (all < 0.01; past means longer)"] = (f"{' '.join(f'{v:.1e}' for v in ps)} ({sum(v < 0.01 for v in ps)}; "
                                                                             f"{min(db[p].mean() for p in ('past outcome', 'past choice')) > max(db[q].mean() for q in ('choice', 'outcome'))})")
    pr = pd.DataFrame({lag: [100 * SC[(k, lag)]["encoding"].mean() for k in saez.CURRENT] for lag in LAGS})
    far = pr[[2, 3, 4, 5]].values.ravel()
    ch6 = {lag: np.percentile(np.mean([SC[(k, lag)]["perm_count"] for k in saez.CURRENT], 0) / N_ELEC * 100, 95) for lag in LAGS}
    out["fig6: mean % by lag t..t-5"] = " ".join(f"{v:.1f}" for v in pr.mean())
    out["fig6: (a) p vs t, vs t-1"] = f"{stats.ttest_ind(far, pr[0]).pvalue:.1e}, {stats.ttest_ind(far, pr[1]).pvalue:.1e}"
    out["fig6: lags t-2..t-5 above chance 95th"] = sum(pr[lag].mean() > ch6[lag] for lag in range(2, 6))
    P5 = {lag: np.concatenate([peak_logp((k, lag)) for k in saez.CURRENT]) for lag in (0, 1, 2)}
    n_ok = sum((stats.ks_2samp(peak_logp((k, 2)), peak_logp((k, 1)), alternative="greater").pvalue < 0.05)
               and (stats.ks_2samp(peak_logp((k, 1)), peak_logp((k, 0)), alternative="greater").pvalue >= 0.05) for k in saez.CURRENT)
    out["figs5d: pooled KS p, t-1>t / t-2>t-1; regressors with the pattern"] = (
        f"{stats.ks_2samp(P5[1], P5[0], alternative='greater').pvalue:.2g} / {stats.ks_2samp(P5[2], P5[1], alternative='greater').pvalue:.2g}; {n_ok}")
    er = SC[("risk", 0)]["encoding"]
    out["figs3a: peak %EV all trials / gamble only"] = (f"{SC[('risk', 0)]['r2'][0][:, er].mean(1).max() * 100:.2f} / "
                                                         f"{SC[('risk_gamble_only', 0)]['r2'][0][:, er].mean(1).max() * 100:.2f}")
    sl = summary(("left", 0))
    out["figs3b: left/right count, chance 95th"] = f"{sl['encoding']}, {sl['chance 95th']:.0f}"
    pats = np.array([d["patients"] for d in cur + past])
    out["tables2: mean patients (a), min"] = f"{pats.mean():.2f}, {pats.min()}"
    q = []
    for e in np.where(er)[0]:
        s, y = at_peak(("risk", 0), e)
        p = REG[("winprob", 0)][s]
        X = np.c_[np.ones(len(p)), p, p ** 2]
        beta, *_ = np.linalg.lstsq(X, y, rcond=None)
        res = y - X @ beta
        se = np.sqrt(np.diag(np.linalg.inv(X.T @ X)) * (res @ res) / (len(y) - 3))
        q.append(beta[2] < 0 and 2 * stats.t.sf(abs(beta[2] / se[2]), len(y) - 3) < 0.05)
    out["fig2: risk electrodes with inverted U / all"] = f"{sum(q)} / {len(q)}"
    lr = [stats.linregress(REG[("regret", 0)][at_peak(("regret", 0), e)[0]], at_peak(("regret", 0), e)[1]).pvalue < 0.05
          for e in np.where(SC[("regret", 0)]["encoding"])[0]]
    out["fig2: regret electrodes with a linear slope / all"] = f"{sum(lr)} / {len(lr)}"
    sv, sel = stepwise_selection()
    swp = np.array([100 * sel[k].mean() for k in KEYS16])
    fivep = np.array([100 * SC[k]["encoding"].mean() for k in KEYS16])
    out["figs6b: Spearman rho (p); max difference (points)"] = (f"{stats.spearmanr(fivep, swp).statistic:.2f} ({stats.spearmanr(fivep, swp).pvalue:.3f}); "
                                                                f"{np.abs(swp - fivep).max():.1f}")
    out["figs6b: electrodes kept by stepwise"] = int(np.any(list(sel.values()), 0).sum())
    for name, sets in (("stepwise", group_sets(sel)), ("5-window", group_sets({k: SC[k]["encoding"] for k in KEYS16}))):
        nt = np.sum(list(sets.values()), 0)
        out[f"fig7f: {name}, >= 2 types / all 4"] = f"{int((nt >= 2).sum())} / {int((nt == 4).sum())}"
        base = nt >= 1
        vals = []
        for cls in ("choice", "outcome"):
            a, b = sets[cls][base], sets["past " + cls][base]
            tab = np.array([[np.sum(a & b), np.sum(a & ~b)], [np.sum(~a & b), np.sum(~a & ~b)]])
            ok = not ((tab.sum(0) == 0).any() or (tab.sum(1) == 0).any())
            pv = stats.chi2_contingency(tab, correction=False).pvalue if ok else np.nan
            vals.append(f"{tab[0, 0]} (exp {a.sum() * b.sum() / max(tab.sum(), 1):.1f}, p {pv:.2g})")
        out[f"figs7: {name}, both choice / both outcome"] = " / ".join(vals)
    pwb = pd.DataFrame([dict(row, window=w) for w in range(saez.N_WIN) for row in me_fits(w)])
    bb, nb_ = me_count(pwb, 16 * 114)
    out["mixed effects, per window: regressors at corrected p < 1e-4"] = ", ".join(f"{m} {v}" for m, v in nb_.items())
    out["mixed effects, per window, one regressor, all electrodes: corrected p >= 1e-4"] = (
        ", ".join(f"{r} {v:.1e}" for r, v in bb["one, all"].items() if v >= 1e-4) or "none")
    out["mixed effects, per window, one regressor, all electrodes: largest corrected p of the 16"] = (
        f"{bb['one, all'].max():.1e} ({bb['one, all'].idxmax()})")
    return out


t0 = time.time()
BL = {"deposited": claim_numbers()}
for name, hb in H_BL.items():
    H = hb
    ENC_ANY_DEP = ENC_ANY
    SC = {key: saez.scan_all(H, REG[key], 1000, np.random.default_rng(1000 + i)) for i, key in enumerate(REG)}
    ENC_ANY = np.any([SC[k]["encoding"] for k in KEYS16], 0)
    BL[name] = claim_numbers()
    ENC_ANY = ENC_ANY_DEP
H, SC = H_DEP, SC_DEP
print(f"baseline readings in {time.time() - t0:.0f} s")
print(pd.DataFrame(BL).to_string())
print("expected: fig3 counts 50 34 31 26 45 33 28 35; fig4 counts 17 43 46 35 49 56 50 64; hfa 20.9%; fig5 1341 / 1169 / 800 / 707;"
      " latency delays 512.5 / 287, durations 612 / 712.5; tables2 7.41 +/- 0.4; fig7f 132 / 30; figs7 39 / 43")
reading (b): trials with the buttonpress offset measured, per subject (others take the electrode's median): {'s01': '180 of 180', 's02': '188 of 188', 's03': '194 of 194', 's04': '108 of 108', 's05': '179 of 179', 's06': '185 of 187', 's07': '167 of 181', 's08': '150 of 200', 's09': '200 of 200', 's10': '21 of 136'} total 1572 of 1753
baseline readings in 283 s
                                                                                                                                                      deposited                                                         (a) own event                                                   (b) game presentation
fig3: counts                                                                                                                            84 71 61 41 59 54 52 64                                               75 82 54 51 74 51 64 63                                                 66 74 56 37 68 41 50 45
fig3: counts within 10% (of 8)                                                                                                                                0                                                                     0                                                                       0
fig3: counts above chance 95th (of 8)                                                                                                                         7                                                                     5                                                                       5
fig3: chance 95th percentiles                                                                                                           48 48 49 50 49 49 49 49                                               55 53 56 55 55 55 57 56                                                 48 47 48 47 48 47 47 47
fig3: choice peak, game epoch (ms)                                                                                                                          750                                                                   800                                                                     800
fig3: outcome peak, buttonpress epoch (ms)                                                                                                                  800                                                                   700                                                                     800
latency: (a) delay choice / outcome (ms), p                                                                                            800.0 / 650.0, p = 0.235                                             1050.0 / 662.5, p = 0.224                                               1075.0 / 662.5, p = 0.200
latency: (b) delay choice / outcome (ms), p                                                                                            512.5 / 325.0, p = 0.301                                              625.0 / 325.0, p = 0.034                                                625.0 / 300.0, p = 0.052
latency: (a,b) duration choice / outcome (ms), p                                                                                      687.5 / 1000.0, p = 0.207                                             725.0 / 1100.0, p = 0.118                                                700.0 / 700.0, p = 1.000
fig4: counts                                                                                                                            40 64 59 53 67 79 76 95                                               42 66 55 50 48 74 55 47                                                 43 57 39 47 39 48 33 45
fig4: counts within 10% (of 8)                                                                                                                                0                                                                     2                                                                       0
fig4: past risk lowest                                                                                                                                     True                                                                  True                                                                   False
fig4: other 7 above chance 95th                                                                                                                               7                                                                     2                                                                       1
hfa-more-than-fp: mean % encoding, 16 regressors                                                                                                           33.3                                                                  31.1                                                                    25.8
fig5: mean ms, past outcome / past choice / choice / outcome                                                                              670 / 651 / 534 / 462                                                 462 / 445 / 486 / 432                                                   452 / 515 / 529 / 440
fig5: four p, past longer (all < 0.01; < 1e-6)                                                                           1.5e-03 8.0e-07 8.8e-03 8.9e-06 (4; 1)                                3.4e-01 2.0e-01 9.8e-02 5.5e-01 (0; 0)                                  2.4e-02 6.4e-01 7.3e-01 2.2e-02 (0; 0)
fig5: epoch reading (b), four p (all < 0.01; past means longer)                                                       8.0e-05 3.2e-06 1.1e-02 1.6e-03 (3; True)                            1.2e-01 7.3e-01 9.7e-01 2.2e-01 (0; False)                              1.2e-01 6.1e-01 9.7e-01 2.4e-01 (0; False)
fig6: mean % by lag t..t-5                                                                                                        31.8 34.9 16.6 17.7 16.9 19.4                                         33.6 28.6 22.3 22.3 20.7 19.0                                           28.6 23.0 17.2 18.7 17.6 16.8
fig6: (a) p vs t, vs t-1                                                                                                                       2.9e-10, 7.6e-11                                                      3.3e-09, 2.6e-05                                                        5.9e-07, 1.1e-03
fig6: lags t-2..t-5 above chance 95th                                                                                                                         0                                                                     0                                                                       0
figs5d: pooled KS p, t-1>t / t-2>t-1; regressors with the pattern                                                                             0.97 / 2.6e-29; 7                                                     3e-05 / 0.0044; 3                                                     0.0014 / 0.00048; 4
figs3a: peak %EV all trials / gamble only                                                                                                           2.32 / 3.12                                                           2.00 / 2.68                                                             2.54 / 2.88
figs3b: left/right count, chance 95th                                                                                                                    31, 49                                                                35, 55                                                                  28, 47
tables2: mean patients (a), min                                                                                                                         8.62, 6                                                               8.94, 8                                                                 8.06, 6
fig2: risk electrodes with inverted U / all                                                                                                             44 / 84                                                               32 / 75                                                                 18 / 66
fig2: regret electrodes with a linear slope / all                                                                                                       64 / 64                                                               63 / 63                                                                 45 / 45
figs6b: Spearman rho (p); max difference (points)                                                                                            0.77 (0.000); 48.2                                                    0.43 (0.101); 42.9                                                     -0.25 (0.349); 38.7
figs6b: electrodes kept by stepwise                                                                                                                          16                                                                     5                                                                       4
fig7f: stepwise, >= 2 types / all 4                                                                                                                       0 / 0                                                                 0 / 0                                                                   0 / 0
figs7: stepwise, both choice / both outcome                                                                            0 (exp 0.5, p 0.38) / 0 (exp 0.0, p nan)                             0 (exp 0.2, p 0.58) / 0 (exp 0.4, p 0.36)                                 0 (exp 0.2, p 0.5) / 0 (exp 0.0, p nan)
fig7f: 5-window, >= 2 types / all 4                                                                                                                    166 / 65                                                              168 / 63                                                                147 / 47
figs7: 5-window, both choice / both outcome                                                                     99 (exp 99.9, p 0.73) / 101 (exp 95.7, p 0.047)                        108 (exp 105.5, p 0.3) / 89 (exp 86.3, p 0.35)                           98 (exp 94.4, p 0.17) / 65 (exp 63.0, p 0.54)
mixed effects, per window: regressors at corrected p < 1e-4                              one, all 14, one, encoding 11, together, all 11, together, encoding 11  one, all 16, one, encoding 10, together, all 9, together, encoding 8  one, all 15, one, encoding 10, together, all 10, together, encoding 10
mixed effects, per window, one regressor, all electrodes: corrected p >= 1e-4                                                 risk_1 3.0e-03, exputil_1 1.7e-03                                                                  none                                                          risk_1 2.9e-02
mixed effects, per window, one regressor, all electrodes: largest corrected p of the 16                                                        3.0e-03 (risk_1)                                                3.3e-05 (gamble_ind_1)                                                        2.9e-02 (risk_1)
expected: fig3 counts 50 34 31 26 45 33 28 35; fig4 counts 17 43 46 35 49 56 50 64; hfa 20.9%; fig5 1341 / 1169 / 800 / 707; latency delays 512.5 / 287, durations 612 / 712.5; tables2 7.41 +/- 0.4; fig7f 132 / 30; figs7 39 / 43

Result of the baseline readings. The table repeats the deposited results in its first column. Outcomes that hold under all three: fig3-present-encoding, tables2-patients-coverage, figs3a-risk-all-trials, fig7f-multiplexing and figs7-present-past-overlap are not reproduced (for example chosen value has 41, 51 and 37 encoding electrodes against chance 95th percentiles of 50, 55 and 47, and the mean number of patients is 8.62, 8.94 and 8.06); fig6-past-short-lived, figs3b-no-motor-encoding and fig2-example-electrodes are reproduced; fig3-latency-duration-similar is reproduced under its reading (a) (delay p = 0.235, 0.224 and 0.200; duration p = 0.207, 0.118 and 1.000). Outcomes that change with the baseline: fig4-past-encoding (7, 2 and 1 of the seven past regressors other than risk above their shuffles; past risk is not the lowest under (b)), fig5-past-sustained (4, 0 and 0 of the four comparisons at p < 0.01 under epoch reading (a), 3, 0 and 0 under (b)), figs5d-sharp-boundary (pooled t-1 against t p = 0.97, 3e-05 and 0.0014; 7, 3 and 4 regressors with the pattern), figs6b-stepwise-similar (Spearman rho 0.77, 0.43 and -0.25, p < 0.001, 0.101 and 0.349) and mixed-effects-robust (per window, one regressor, all electrodes: 14, 16 and 15 of 16; the largest corrected p is 3.0e-03, 3.3e-05 and 2.9e-02). For the first four the outcome rests on the deposited HFA, the authors' own baseline correction (an assumption). For mixed-effects-robust the deposited baseline does not meet the criterion and baseline (a) does, so it is reproduced, resting on baseline (a) (section mixed-effects-robust). The HFA side of hfa-more-than-fp is 33.3, 31.1 and 25.8%, outside 20.9 +/- 2.09 under all three.

SummaryΒΆ

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

claim outcome
methods-electrode-trial-counts partially reproduced
behavior-risk-neutral reproduced
fig1c-choice-win-probability reproduced
figs2a-choice-gamble-ev reproduced
fig1c-patients-like-controls blocked, data_missing
figs2b-rt-conflict not reproduced
regressors-past-current-uncorrelated not reproduced
figs6a-regressor-collinearity reproduced
fig3-present-encoding not reproduced
fig3-latency-duration-similar reproduced (assumption)
hfa-more-than-fp blocked, data_missing
figs4b-power-at-buttonpress blocked, data_missing
fig4-past-encoding partially reproduced (assumption)
fig5-past-sustained partially reproduced (assumption)
behavior-past-no-effect not reproduced
fig6-past-short-lived reproduced
figs5d-sharp-boundary reproduced (assumption)
mixed-effects-robust reproduced (assumption)
figs6b-stepwise-similar partially reproduced (assumption)
figs3a-risk-all-trials not reproduced
figs3b-no-motor-encoding reproduced
anatomy-brodmann-counts blocked, data_missing
fig7f-multiplexing not reproduced
figs7-present-past-overlap not reproduced
fig7-all-areas-similar blocked, data_missing
no-anatomical-gradient blocked, data_missing
tables2-patients-coverage not reproduced
fig2-example-electrodes reproduced

How the analysis differs from the paper's. The deposited HFA is used as it is: already window-averaged and, in the game epoch, baseline-corrected; the buttonpress epoch carries a per-trial offset close to the game epoch's. This is taken as the authors' baseline (an assumption). The claims file's two baseline readings, applied on top of it, change the outcomes of fig4-past-encoding, fig5-past-sustained, figs5d-sharp-boundary and figs6b-stepwise-similar, which are marked as resting on the assumption; under reading (a) mixed-effects-robust passes, and its outcome rests on that reading. Eight electrodes of s03 that copy others are dropped (191 analysed against the paper's 192). The buttonpress epoch is read as locked to the outcome reveal, as the data indicate. The regressors are the authors' own file; t-2 to t-5 follow its convention. Random-effects logits are fitted by maximum likelihood with Gauss-Hermite quadrature. The stepwise procedure takes the longest stretch in each epoch and compares models at the base regressor's peak window (assumptions). The nested mixed models are fitted by a closed-form REML in the helper, checked against statsmodels.

What was found about the data set. The files hold 199 electrodes, of which seven in s03 are exact copies of others and one (s03 electrode 42) holds copies of two different electrodes in its 1-kHz and window arrays; without the seven, the per-patient counts match Table S2. The "buttonpress" epoch is centred 470 to 600 ms after the csv's button press, and the gamble outcome is encoded from about 200 ms after its time 0: it behaves as locked to the outcome reveal, not the button press. reveal.time is 0.53 to 0.59 s after the button press in s01 to s05 but 0.03 to 0.05 s in s06 to s10 (up to 0.24 s in s10), where the description gives 550 ms. HFA trials carry no round number and are fewer than the non-timeout rounds (1,753 against 1,839), without documentation of the exclusions; they can be matched to rounds through the authors' regressor file. s10 played 138 rounds with reaction times up to 80 s and no timeouts; timeouts are 5.1% of rounds, not 9.98%. The column choice.time, the HFA units and the baseline subtraction are not described. The data set holds no broadband signal, no electrode locations and no data from the healthy participants.