Reproducing Hunt, Malalasekera et al. (2018) from CRCNS pfc-7¶

Paper: Hunt, Malalasekera, de Berker, Miranda, Farmer, Behrens & Kennerley (2018), "Triple dissociation of attention and decision computations across prefrontal cortex", Nature Neuroscience 21, 1471-1481, doi:10.1038/s41593-018-0239-5.

Data: CRCNS data set pfc-7 (doi:10.6080/K0PZ5712), read anonymously from the public S3 bucket crcnsarchive under pfc-7/live/. CRCNS data sets are not versioned, so the version is recorded as unversioned; the only published copy is the one under live/ (data description version 0.5, September 6, 2018), and it is the one pinned here. The MD5 sums of the files read, from the data set's checksums.md5, are printed below, so that a later change is detectable.

Claims: claims/hunt-2018.yaml, written from the version of record (PMC6331040) with its supplement. The paper's MATLAB scripts are files of the data set (scripts.zip); where the claims file leaves a detail open and a script settles it, the script is cited (see pfc7.py).

All 40 claims of the claims file are tested; none is blocked. Outcomes are in the summary at the end.

Claim Tested Claim Tested
sessions-and-trials yes fig5c-attribute-cue2-vs-cue1 yes
neuron-counts yes fig5de-option-cue3-vs-stored yes
choice-accuracy-ev yes fig5f-option-stored-combined yes
chose-on-partial-information yes fig5gj-cross-correlation-dynamics yes
choice-accuracy-observed yes fig5k-ofc-comparison-unique yes
figs1ab-cue-weights yes figs67-no-comparison-acc-dlpfc yes
figs1cd-fewer-cues-more-accurate yes fig6a-acc-belief-subspace yes
fig2a-sample-the-favourite yes fig6b-acc-belief-stronger yes
fig2b-positive-evidence yes fig6c-belief-subspace-rt yes
fig4d-spatial-attention yes fig6d-belief-ramp-to-choice yes
fig4e-ofc-stimulus-identity yes fig6e-action-subspace-ramp yes
fig4f-ofc-attended-value yes fig7a-ofc-value-difference-neurons yes
fig4g-left-right-value yes fig7b-ofc-value-difference-any yes
fig4h-acc-accept-reject yes fig7c-acc-belief-neurons yes
figs2-consistent-across-subjects yes fig8-cue1-value-all-regions yes
figs4-dlpfc-top-bottom yes fig8-action-value-acc-dlpfc yes
fig4-t75-latencies yes fig8-spatial-value-dlpfc yes
figs5c-latency-order yes fig8-attribute-value-ofc yes
fig5a-ofc-value-cpd yes figs9-ev16-correlation yes
fig5b-stable-attended-value-subspace yes figs11-alternative-value-template yes
In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import resource
import time
import zlib

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

import pfc7

T0 = time.time()
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)


def section_rng(name):
    """One generator per claim section, seeded from its name (a standard choice)."""
    return np.random.default_rng(zlib.crc32(name.encode()))

Loading¶

The file listing and checksums, the units table, the two behavioural files (one at a time, in memory), and the preprocessed units of ACC, DLPFC and OFC (reduced as they load).

In [2]:
listing = pfc7.listing()
md5 = pfc7.checksums()
READ = ["behavioural_data/Miles_InfoGathering_All_Data.mat",
        "behavioural_data/Frank_InfoGathering_All_Data.mat",
        "neuronal_data/LTH_processed_data.zip", "other_data/all_units_info.mat",
        "neuronal_regression_results/info_gathering_cue123_alltrials_attentional_final.mat",
        "scripts.zip"]
print(f"{len(listing)} keys under pfc-7/, {listing['size'].sum() / 1e9:.1f} GB")
for f in READ:
    print(f"{md5[f]}  {f}")
info = pfc7.units_info()
beh = pd.concat([pfc7.load_behaviour("M"), pfc7.load_behaviour("F")], ignore_index=True)
print(f"behaviour loaded, {time.time() - T0:.0f} s")
U = pfc7.load_units(info, areas=(1, 2, 3), long_areas=(1,))
print(f"{len(U)} units loaded, {time.time() - T0:.0f} s, peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
83 keys under pfc-7/, 70.7 GB
b821300630d337838de951dd3a19fa5b  behavioural_data/Miles_InfoGathering_All_Data.mat
fb7545f884e5789c70196ec360e18f65  behavioural_data/Frank_InfoGathering_All_Data.mat
1d9e29eccbcdb2a8610f9268f4150c18  neuronal_data/LTH_processed_data.zip
99d5b71e652d9d70108890bcb335622a  other_data/all_units_info.mat
386cf609f60e8dfc0aa3cfa46c85496e  neuronal_regression_results/info_gathering_cue123_alltrials_attentional_final.mat
dbf1eabfa9abc27f982c1b501b64d875  scripts.zip
behaviour loaded, 142 s
549 units loaded, 196 s, peak memory 3.9 GB

Data check¶

In [3]:
zips = listing[listing.key.str.match(r"pfc-7/live/neuronal_data/[FM]\d{3}\.zip")]
zip_sessions = zips.key.str.extract(r"/([FM])(\d{3})\.zip")
print("raw recording sessions (zip files):", zip_sessions[0].value_counts().to_dict())
print("behavioural sessions:", beh.groupby("subject").session.nunique().to_dict(),
      " trials:", beh.groupby("subject").size().to_dict())
print("trial errors in the behavioural files:", beh.trial_error.value_counts().to_dict(),
      " conditions:", beh.condition.value_counts().to_dict())
print("units in all_units_info.mat by area:", info.area_name.value_counts().to_dict())
print("subject by session counts of units (all areas):",
      info.groupby("subject").session.nunique().to_dict())
# the unit files agree with all_units_info.mat on subject, session, channel and area
mism = [u for u, d in U.items() if (d["sb"], int(d["snum"]), int(d["chnum"]), int(d["brain_region"]))
        != (info.loc[u, "subject"], info.loc[u, "session"], info.loc[u, "channel"], info.loc[u, "area"])]
print("units whose file disagrees with all_units_info.mat on subject, session, channel or area:", mism)
print("subject letter as stored in the unit files:", pd.Series([d["sb_raw"] for d in U.values()]).value_counts().to_dict(),
      "; lower case in units", [u for u, d in U.items() if d["sb_raw"].islower()][:3], "...",
      [u for u, d in U.items() if d["sb_raw"].islower()][-1:], "; their sessions:",
      sorted({(d["sb"], int(d["snum"])) for d in U.values() if d["sb_raw"].islower()}))
# value ranges
print("probabilities:", sorted(np.round(pd.unique(beh[["LP", "RP"]].values.ravel()), 3)))
print("magnitudes:", sorted(np.round(pd.unique(beh[["LM", "RM"]].values.ravel()), 3)))
print("pictures viewed (eye codes):", beh.npv.value_counts().sort_index().to_dict())
print("joystick movement time found on", beh.move_time.notna().sum(), "of", len(beh), "trials")
rt = beh.response - beh.cue1_on
print(f"response time from cue 1, ms: median {rt.median():.0f}, range {rt.min():.0f} to {rt.max():.0f}")
u0 = U[1]
print("rasters: Cue1_MatrixRaw holds 0/1 per ms (spikes, not the 1000 per spike of neuron_matrix.m);"
      f" GLM bins {u0['X1'].shape[1]} centred {pfc7.TIMEBINS[0]} to {pfc7.TIMEBINS[-1]} ms")
rates = pd.DataFrame({u: dict(area=AREA, session_rate=d["rate_session"], trial_rate=d["rate_trials"],
                              men=d["men"], info_rate=info.loc[u, "info_rate"])
                      for u, d in U.items() for AREA in [pfc7.AREAS[int(d["brain_region"])]]}).T
print("mean rate (Hz) per unit, medians by area:")
print(rates.groupby("area")[["session_rate", "trial_rate", "men", "info_rate"]].median().round(2))
print("whole-session rate from OverallSpikeCodes against the stored men: max |diff| "
      f"{np.abs(rates.session_rate.astype(float) - rates.men.astype(float)).max():.3f} Hz")
# duplicate recordings: identical spike-count vectors in the cue 1 window
sig = {}
for u, d in U.items():
    key = (d["sb"], int(d["snum"]), tuple(np.round(d["X1"][:, 40] * 1000, 3)))
    sig.setdefault(key, []).append(u)
dups = [v for v in sig.values() if len(v) > 1]
print("pairs of units with identical cue 1 activity in every trial:", dups)
# behaviour in the unit files against the behavioural files (one unit per session)
chk = []
for (sb, sn), grp in info[info.area.isin([1, 2, 3])].groupby(["subject", "session"]):
    d = U[grp.index[0]]
    bs = beh[(beh.subject == sb)]
    sess_ids = sorted(bs.session.unique())
    chk.append(dict(subject=sb, session=sn, unit_trials=int(d["nInfoGatheringTrials"])))
chk = pd.DataFrame(chk)
print("sessions with units in ACC/DLPFC/OFC:", chk.groupby("subject").size().to_dict())
raw recording sessions (zip files): {'M': 29, 'F': 25}
behavioural sessions: {'F': 25, 'M': 32}  trials: {'F': 9863, 'M': 14251}
trial errors in the behavioural files: {0: 19359, 6: 4755}  conditions: {4: 12104, 3: 12010}
units in all_units_info.mat by area: {'ACC': 198, 'OFC': 195, 'VMPFC': 160, 'DLPFC': 156, '[]': 15}
subject by session counts of units (all areas): {'F': 25, 'M': 29}
units whose file disagrees with all_units_info.mat on subject, session, channel or area: []
subject letter as stored in the unit files: {'F': 312, 'M': 198, 'm': 39} ; lower case in units [681, 682, 683] ... [724] ; their sessions: [('M', 5), ('M', 11), ('M', 23), ('M', 27)]
probabilities: [np.float64(0.1), np.float64(0.3), np.float64(0.5), np.float64(0.7), np.float64(0.9)]
magnitudes: [np.float64(0.15), np.float64(0.35), np.float64(0.55), np.float64(0.75), np.float64(0.95)]
pictures viewed (eye codes): {2: 1581, 3: 9833, 4: 12700}
joystick movement time found on 24114 of 24114 trials
response time from cue 1, ms: median 1415, range 732 to 7241
rasters: Cue1_MatrixRaw holds 0/1 per ms (spikes, not the 1000 per spike of neuron_matrix.m); GLM bins 61 centred -100 to 500 ms
mean rate (Hz) per unit, medians by area:
      session_rate trial_rate       men info_rate
area                                             
ACC       7.643562   6.749231   7.64354  7.121908
DLPFC     4.583736   4.650717  4.583021  4.566408
OFC       5.062659   5.159219  5.062621  5.155348
whole-session rate from OverallSpikeCodes against the stored men: max |diff| 0.004 Hz
pairs of units with identical cue 1 activity in every trial: []
sessions with units in ACC/DLPFC/OFC: {'F': 24, 'M': 29}

The GLM written here (pfc7.fit_glm) is checked against the T-statistics the authors stored in neuronal_regression_results/info_gathering_cue123_alltrials_attentional_final.mat, which the data set's scripts load for Figures 5 to 7. This checks the implementation; no result below uses the stored values.

In [4]:
G = {u: pfc7.fit_glm(d, with_cpd=(int(d["brain_region"]) == 3)) for u, d in U.items()}
print(f"GLM fitted, {time.time() - T0:.0f} s")
import io as _io
import scipy.io as _sio
_raw = pfc7.read_bytes(READ[4])
_st = _sio.loadmat(_io.BytesIO(_raw), variable_names=["t_stats1", "t_stats2", "t_stats3", "t_statsR", "randproj_trials",
                                                     "subspace_belief_proj", "subspace_RL_proj"], squeeze_me=True)
del _raw
dev = []
for u in G:
    for k, ep in [("t_stats1", "tX1"), ("t_stats2", "tX2"), ("t_stats3", "tX3"), ("t_statsR", "tXR")]:
        a = np.asarray(_st[k][u - 1], float).T
        b = G[u][ep][:35]
        ok = np.isfinite(a) & np.isfinite(b)
        dev.append(np.abs(a[ok] - b[ok]).max() if ok.any() else 0.0)
# the 100 random halves of Figure 6 that the scripts drew and stored, and the weights they computed from them
RANDPROJ = {u: np.asarray(_st["randproj_trials"][u - 1], bool) for u in G if int(U[u]["brain_region"]) == 1}
STORED_W = {"belief": np.asarray(_st["subspace_belief_proj"], float), "RL": np.asarray(_st["subspace_RL_proj"], float)}
del _st
print(f"max |T here - T stored| over {len(G)} units and 4 epochs: {max(dev):.2e}")
nan_units = [u for u in G if not all(np.isfinite(G[u][ep][:35]).all() for ep in ("tX1", "tX2", "tX3", "tXR"))]
print("units with non-finite T-statistics here:", nan_units)
for u in sorted(set(nan_units) | set(pfc7.NAN_TSTAT_UNITS)):
    print(f"  unit {u} ({info.loc[u, 'area_name']}, rate {info.loc[u, 'info_rate']:.2f} Hz): non-finite T per epoch",
          {ep: int((~np.isfinite(G[u][ep][:35])).sum()) for ep in ("tX1", "tX2", "tX3", "tXR")},
          "; spikes in the cue 3 epoch on trials with 3+ cues:", int(U[u]["X3"][U[u]["num_pics_viewed"] >= 3].sum() * 200))
GLM fitted, 205 s
max |T here - T stored| over 549 units and 4 epochs: 1.59e-06
units with non-finite T-statistics here: [154, 556, 653]
  unit 154 (OFC, rate 0.26 Hz): non-finite T per epoch {'tX1': 245, 'tX2': 210, 'tX3': 105, 'tXR': 0} ; spikes in the cue 3 epoch on trials with 3+ cues: 504
  unit 556 (OFC, rate 0.23 Hz): non-finite T per epoch {'tX1': 315, 'tX2': 0, 'tX3': 0, 'tXR': 0} ; spikes in the cue 3 epoch on trials with 3+ cues: 402
  unit 653 (OFC, rate 1.83 Hz): non-finite T per epoch {'tX1': 0, 'tX2': 70, 'tX3': 0, 'tXR': 0} ; spikes in the cue 3 epoch on trials with 3+ cues: 716

Clock check¶

Every stream shares the clock of the trial table: the cue 1 rasters are cut from each trial's spike times at the cue 1 onset code, the GLM T-statistic for the attended cue 1 value (EVs 1 + 5) rises only after cue 1 onset, and with the trial labels shifted by one trial the response vanishes. The contrast is shown for OFC, the region with the strongest value code.

In [5]:
ofc_sel = [u for u in U if int(U[u]["brain_region"]) == 3 and info.loc[u, "info_rate"] >= 1 and u != 87]
def mean_abs_t(shift):
    out = []
    for u in ofc_sel:
        d = dict(U[u])
        if shift:
            for k in ["reg_mat", "condition", "attendsac1", "Left_choice", "num_pics_viewed"]:
                d[k] = np.roll(d[k], shift, axis=0)
        out.append(np.abs(pfc7.fit_glm(d, epochs=("X1",), halves=False)["tX1"][18]))
    return np.mean(out, axis=0)
clk = pd.DataFrame({"true labels": mean_abs_t(0), "labels shifted 1 trial": mean_abs_t(1)},
                   index=pfc7.TIMEBINS)
print("mean |T| of cue 1 value across OFC neurons, by bin centre (ms after cue 1):")
print(clk.iloc[::5].round(2).T)
mean |T| of cue 1 value across OFC neurons, by bin centre (ms after cue 1):
                        -100  -50    0     50    100   150   200   250   300   350   400   450   500
true labels              0.8  0.79  0.79  0.80  0.95  1.40  1.79  2.26  2.35  2.36  2.29  2.13  2.02
labels shifted 1 trial   0.8  0.78  0.77  0.79  0.78  0.87  0.91  0.94  0.89  0.84  0.81  0.83  0.83

Lines of the paper's scripts cited here¶

The scripts are a file of the data set (scripts.zip). The lines below are read from it, so that the details taken from them can be checked: the unit exclusions (units 87 and 653), the one-sided RSA permutation test, the variables stacked for Supplementary Figure 5C (the rt numbering: 3 stimulus identity, 4 attended value, 5 accept/reject, 6 spatial attention, 7 left/right value; areas 1 ACC, 2 DLPFC, 3 OFC) and the 10% peak CPD rule, the cluster test of Figure 5g-j, the response bin of the Figure 6 action weights (index 30, centred 210 ms before the response) and the per-unit random halves, the Figure 7 thresholds, and the Figure 8 binomial formula.

In [6]:
for name, lines in [("Fig4_RSA.m", [24, 88, 89, 92, 93, 94, 185, 363, 368, 421]),
                    ("Fig5_OFCcrosscorrelation.m", [26, 138, 167]),
                    ("essential_scripts/cross_corr_tstats.m", [84]),
                    ("Fig6_ACCmultiplesignals_R3_version.m", [27, 173]),
                    ("InfoGathering_Neurons_Cue123_alltrials_attentional_value_final.m", [111, 112, 113, 126, 305]),
                    ("Fig7_single_neurons_cue2and3.m", [24, 31, 119]),
                    ("Fig8_single_neuron_coding.m", [23, 164])]:
    print("\n".join(pfc7.script_lines(name, lines)))
Fig4_RSA.m:24: area([87 find(average_firing_rate<1)]) = nan; %bad cells
Fig4_RSA.m:88: r3 = [zeros(10) eye(10); eye(10) zeros(10)]; rt{3} = 'stimulus identity';
Fig4_RSA.m:89: r4 = repmat(m1.*m2,4,4); rt{4} = 'attended value';
Fig4_RSA.m:92: r5 = repmat((m1<0&m2<0)|(m1>0&m2>0),4,4) - repmat((m1>0&m2<0)|(m1<0&m2>0),4,4); rt{5} = 'accept/reject';
Fig4_RSA.m:93: r6 = [ones(10,10) zeros(10,10); zeros(10,10) ones(10,10)]; rt{6} = 'spatial attention';
Fig4_RSA.m:94: r7  = (r6>0).*r4; rt{7} = 'left/right value';
Fig4_RSA.m:185: stack_order = [6 1; 6 3; 6 2; 4 3; 5 3; 5 1; 3 3;  7 2; 7 1;];
Fig4_RSA.m:363: tmax(maxval<10) = nan;
Fig4_RSA.m:368: if maxval(i,r)>10
Fig4_RSA.m:421: sigmat = 1-squeeze(mean(permute(repmat(t,1,1,nP),[3 1 2])>tp,1)); %signficance for all
Fig5_OFCcrosscorrelation.m:26: area([87 653 find(average_firing_rate<1)]) = nan; %bad cells - 653 contains nans in T-stats
Fig5_OFCcrosscorrelation.m:138: cform_thresh = 0.2; %cluster-forming threshold for permutation test
Fig5_OFCcrosscorrelation.m:167: if sum(l(:)==c)>prctile(nullclust{i,j},99.9) %check if this cluster if larger than 99th prctile of null distribution
essential_scripts/cross_corr_tstats.m:84: bb = bwconncomp(abs(corrd1d2p)>cform_thresh);
Fig6_ACCmultiplesignals_R3_version.m:27: area([87 find(average_firing_rate<1)]) = nan; %bad cells
Fig6_ACCmultiplesignals_R3_version.m:173: subspace_RL = (squeeze(ttR(30,17,area==aoi))+squeeze(ttR(30,18,area==aoi)))/2;
InfoGathering_Neurons_Cue123_alltrials_attentional_value_final.m:111: nProj = 100; %number of projections
InfoGathering_Neurons_Cue123_alltrials_attentional_value_final.m:112: randproj_trials{u} = logical(zeros(size(regression_matrix,1),nProj));
InfoGathering_Neurons_Cue123_alltrials_attentional_value_final.m:113: randproj_trials{u}(rand(size(randproj_trials{u}))>0.5) = 1;
InfoGathering_Neurons_Cue123_alltrials_attentional_value_final.m:126: randproj_trials{u}(num_pics_viewed<3,:) = [];
InfoGathering_Neurons_Cue123_alltrials_attentional_value_final.m:305: subspace_RL_proj(u,:) = (squeeze(t_statsR_proj(30,17,:))+squeeze(t_statsR_proj(30,18,:)))/2;
Fig7_single_neurons_cue2and3.m:24: area([87 653 find(average_firing_rate<1)]) = nan; %bad cells - 653 contains nans in T-stats
Fig7_single_neurons_cue2and3.m:31: thresh = 1.64; %norminv(0.05)
Fig7_single_neurons_cue2and3.m:119: thresh = 1.96; %norminv(0.05/2)
Fig8_single_neuron_coding.m:23: area([87 find(average_firing_rate<1)]) = nan; %bad cells
Fig8_single_neuron_coding.m:164: bino_pvals(1,i) = (1-binocdf(sum(significant_neuron(area==area_index(i),26)),sum(area==area_index(i)),0.05))*2;

Unit selection¶

Units in ACC, DLPFC and OFC with mean rate of at least 1 Hz. The paper's scripts take the rate from all_units_info.mat and also drop unit 87 (Fig4_RSA.m and the other figure scripts) and, for Figures 5 and 7, unit 653. That is the selection used below (SEL, SEL5); the claim neuron-counts compares the counts under the claims file's readings of the rate.

In [7]:
base = info[info.area.isin([1, 2, 3])].copy()
base["session_rate"] = [U[u]["rate_session"] for u in base.index]
base["trial_rate"] = [U[u]["rate_trials"] for u in base.index]
keep = (base.info_rate >= 1) & ~base.index.isin(pfc7.BAD_UNITS)
SEL = {a: base.index[keep & (base.area == a)].tolist() for a in (1, 2, 3)}
SEL5 = {a: [u for u in SEL[a] if u not in pfc7.NAN_TSTAT_UNITS] for a in (1, 2, 3)}
print({pfc7.AREAS[a]: len(v) for a, v in SEL.items()}, "Figures 5 and 7:",
      {pfc7.AREAS[a]: len(v) for a, v in SEL5.items()})
NAMES = pfc7.AREAS
{'ACC': 189, 'DLPFC': 134, 'OFC': 183} Figures 5 and 7: {'ACC': 189, 'DLPFC': 134, 'OFC': 182}

sessions-and-trials¶

Behaviour comes from 25 sessions of monkey F and 32 of monkey M, 9,863 trials for F and 14,251 for M.

The behavioural files hold only completed option and attribute trials (trial errors 0 and 6), so reading (a) is their trial count. Aborted trials are counted from the full trial lists (BhvInfo) in the unit files, which exist only for sessions with units; reading (c) drops trials of equal expected value. "Miles" is M and "Frank" is F (the unit files' sb field and the data descriptor's naming).

In [8]:
sess = beh.groupby("subject").session.nunique()
ntr_a = beh.groupby("subject").size()
ntr_c = beh[beh.LEV != beh.REV].groupby("subject").size()
ab = {}
for (sb, sn), grp in base.groupby(["subject", "session"]):
    d = U[grp.index[0]]
    ab[(sb, sn)] = (d["n_info_trials_all"], d["n_info_completed"])
ab = pd.DataFrame(ab, index=["all info trials", "completed"]).T
ab.index.names = ["subject", "session"]
abs_ = ab.groupby(level=0).sum()
abs_["sessions with units"] = ab.groupby(level=0).size()
print("sessions:", sess.to_dict(), " expected F 25, M 32")
print("(a) completed option and attribute trials:", ntr_a.to_dict(), " expected F 9863, M 14251")
print("(c) the same without equal expected values:", ntr_c.to_dict())
print("(b) with aborted trials, sessions with units only:")
print(abs_)
cs = beh.groupby(["subject", "session"]).size()
print("completed trials per session, unit files against behavioural files (sessions in both, by order):")
for sb in ["F", "M"]:
    a = ab.loc[sb, "completed"].values
    b_ = cs.loc[sb].values
    print(sb, "unit-file sessions", len(a), "behaviour sessions", len(b_),
          "unit-file counts all found among behaviour counts:", set(a) <= set(b_))
sessions: {'F': 25, 'M': 32}  expected F 25, M 32
(a) completed option and attribute trials: {'F': 9863, 'M': 14251}  expected F 9863, M 14251
(c) the same without equal expected values: {'F': 9479, 'M': 13691}
(b) with aborted trials, sessions with units only:
         all info trials  completed  sessions with units
subject                                                 
F                  10688       9463                   24
M                  14391      13155                   29
completed trials per session, unit files against behavioural files (sessions in both, by order):
F unit-file sessions 24 behaviour sessions 25 unit-file counts all found among behaviour counts: True
M unit-file sessions 29 behaviour sessions 32 unit-file counts all found among behaviour counts: True

Result: reproduced. The behavioural files hold 25 sessions of monkey F (Frank) and 32 of monkey M (Miles), with 9,863 and 14,251 completed option and attribute trials, the paper's counts exactly under reading (a). Reading (c) gives 9,479 and 13,691; reading (b) can be counted only for the 24 and 29 sessions with units (10,688 and 14,391 trials there).

neuron-counts¶

After excluding units with mean firing rate below 1 Hz (9 ACC, 21 DLPFC, 12 OFC), the analyses use 189 ACC, 135 DLPFC and 183 OFC neurons.

In [9]:
rows = []
for name, col in [("(a) whole session (OverallSpikeCodes)", "session_rate"),
                  ("(b) analysed trials, start to response", "trial_rate"),
                  ("all_units_info.mat average_firing_rate", "info_rate")]:
    for drop87 in (False, True):
        k = base[col] >= 1
        if drop87:
            k &= ~base.index.isin(pfc7.BAD_UNITS)
        r = dict(reading=name + (", unit 87 dropped" if drop87 else ""))
        for a in (1, 2, 3):
            r[NAMES[a]] = int((k & (base.area == a)).sum())
            r[NAMES[a] + " excluded"] = int((~k & (base.area == a)).sum())
        rows.append(r)
nc = pd.DataFrame(rows).set_index("reading")
print(nc)
print("expected: ACC 189, DLPFC 135, OFC 183; excluded 9, 21, 12")
print("units recorded in these areas:", base.area.map(NAMES).value_counts().to_dict())
tab = base.assign(ok=base.info_rate >= 1).groupby(["subject", "session", "area_name"]).size().unstack(fill_value=0)
print("sessions with units:", tab.groupby(level=0).size().to_dict(),
      " units per area over those sessions:", tab.sum().to_dict())
print("unit 87:", base.loc[87, ["area_name", "subject", "session", "info_rate", "session_rate"]].to_dict())
# Supplementary Table 1, per session (ACC, OFC, DLPFC), as printed in the supplement (page 16)
ST1 = {"M": {5: (9, 0, 1), 7: (3, 1, 0), 10: (4, 3, 0), 11: (9, 2, 0), 12: (2, 0, 3), 14: (4, 0, 7), 15: (3, 0, 2),
             16: (6, 0, 5), 18: (0, 0, 2), 19: (1, 0, 1), 21: (4, 5, 0), 22: (1, 4, 0), 23: (6, 1, 0), 25: (4, 2, 0),
             26: (4, 3, 0), 27: (6, 5, 0), 29: (4, 2, 0), 30: (7, 6, 3), 33: (3, 3, 3), 35: (4, 4, 0), 36: (2, 3, 0),
             40: (3, 11, 2), 41: (4, 8, 5), 42: (1, 3, 3), 44: (0, 9, 1), 45: (1, 3, 3), 46: (4, 5, 3), 48: (0, 3, 0),
             49: (2, 1, 5)},
       "F": {2: (9, 0, 7), 3: (8, 0, 4), 4: (10, 0, 8), 8: (8, 7, 0), 9: (7, 8, 0), 10: (10, 9, 4), 12: (14, 5, 2),
             13: (8, 11, 0), 15: (2, 13, 5), 16: (3, 4, 13), 17: (3, 12, 14), 18: (0, 0, 11), 19: (1, 0, 12),
             20: (2, 0, 8), 22: (1, 0, 2), 23: (1, 5, 3), 24: (2, 3, 0), 25: (2, 7, 2), 27: (1, 5, 3), 30: (4, 4, 2),
             31: (1, 6, 3), 33: (0, 7, 1), 34: (0, 2, 2), 36: (0, 0, 1)}}
st1 = pd.DataFrame([dict(subject=sb, session=sn, ACC=v[0], OFC=v[1], DLPFC=v[2]) for sb, d in ST1.items()
                    for sn, v in d.items()]).set_index(["subject", "session"])
for label, sel in (("all units", base), ("units at or above 1 Hz (average_firing_rate)", base[base.info_rate >= 1])):
    data = sel.groupby(["subject", "session", "area_name"]).size().unstack(fill_value=0)
    data = data.reindex(st1.index.union(data.index), fill_value=0)[["ACC", "OFC", "DLPFC"]]
    cmp_ = st1.reindex(data.index, fill_value=0)
    diff = (data != cmp_).any(axis=1)
    print(f"Supplementary Table 1 against the data, {label}: {int((~diff).sum())} of {len(data)} sessions agree "
          f"in all three areas; sessions that differ: {int(diff.sum())}"
          + (f", e.g. {data[diff].head(3).to_dict('index')} against {cmp_[diff].head(3).to_dict('index')}" if diff.any() else ""))
                                                    ACC  ACC excluded  DLPFC  DLPFC excluded  OFC  OFC excluded
reading                                                                                                        
(a) whole session (OverallSpikeCodes)               190             8    136              20  182            13
(a) whole session (OverallSpikeCodes), unit 87 ...  190             8    135              21  182            13
(b) analysed trials, start to response              186            12    137              19  179            16
(b) analysed trials, start to response, unit 87...  186            12    136              20  179            16
all_units_info.mat average_firing_rate              189             9    135              21  183            12
all_units_info.mat average_firing_rate, unit 87...  189             9    134              22  183            12
expected: ACC 189, DLPFC 135, OFC 183; excluded 9, 21, 12
units recorded in these areas: {'ACC': 198, 'OFC': 195, 'DLPFC': 156}
sessions with units: {'F': 24, 'M': 29}  units per area over those sessions: {'ACC': 198, 'DLPFC': 156, 'OFC': 195}
unit 87: {'area_name': 'DLPFC', 'subject': 'F', 'session': 10, 'info_rate': 4.8446352812473865, 'session_rate': 3.6315668209726124}
Supplementary Table 1 against the data, all units: 53 of 53 sessions agree in all three areas; sessions that differ: 0
Supplementary Table 1 against the data, units at or above 1 Hz (average_firing_rate): 26 of 53 sessions agree in all three areas; sessions that differ: 27, e.g. {('F', 13): {'ACC': 7, 'OFC': 10, 'DLPFC': 0}, ('F', 15): {'ACC': 2, 'OFC': 11, 'DLPFC': 5}, ('F', 17): {'ACC': 3, 'OFC': 12, 'DLPFC': 12}} against {('F', 13): {'ACC': 8, 'OFC': 11, 'DLPFC': 0}, ('F', 15): {'ACC': 2, 'OFC': 13, 'DLPFC': 5}, ('F', 17): {'ACC': 3, 'OFC': 12, 'DLPFC': 14}}

Result: reproduced, with the rate the paper's scripts use. The data set holds 198 ACC, 156 DLPFC and 195 OFC units over 24 F and 29 M sessions, the totals and session counts the claims file derives from Supplementary Table 1. With the average_firing_rate of all_units_info.mat, which every figure script uses to select units, 189 ACC, 135 DLPFC and 183 OFC units are at or above 1 Hz, and 9, 21 and 12 are excluded, as the paper says. Neither of the claims file's readings gives these counts: the whole-session rate gives 190, 136 and 182, the trial rate 186, 137 and 179. The scripts also drop unit 87 (DLPFC), so the analyses here, as the paper's, use 134 DLPFC units. Session by session, Supplementary Table 1 agrees with the data in all 53 sessions and all three areas when every unit is counted, and in only 26 of 53 when units below 1 Hz are left out, so the table counts all units although its caption says units above 1 Hz.

choice-accuracy-ev¶

Monkeys F and M chose the option with the higher expected value on 76.6% and 79.8% of trials.

In [10]:
def acc_ev(b, ties):
    hi_left = b.LEV > b.REV
    eq = b.LEV == b.REV
    corr = (hi_left & (b.left_choice == 1)) | (~hi_left & ~eq & (b.left_choice == 0))
    if ties == "out":
        return 100 * corr[~eq].mean()
    if ties == "wrong":
        return 100 * corr.mean()
    return 100 * (corr | eq).mean()   # InfoGathering_Behaviour.m counts ties as correct
r = pd.DataFrame({t: beh.groupby("subject").apply(acc_ev, ties=t) for t in ["out", "wrong", "right"]})
r.columns = ["(a) ties left out", "(b) ties counted wrong", "script: ties counted right"]
print(r.round(2))
print("ties:", beh[beh.LEV == beh.REV].groupby("subject").size().to_dict())
print("expected F 76.6 +/- 7.66, M 79.8 +/- 7.98")
print("by session (reading a): ", beh.groupby(["subject", "session"]).apply(acc_ev, ties="out")
      .groupby(level=0).agg(["min", "median", "max"]).round(1).to_dict("index"))
         (a) ties left out  (b) ties counted wrong  script: ties counted right
subject                                                                       
F                    75.71                   72.77                       76.66
M                    79.01                   75.90                       79.83
ties: {'F': 384, 'M': 560}
expected F 76.6 +/- 7.66, M 79.8 +/- 7.98
by session (reading a):  {'F': {'min': 69.3, 'median': 75.7, 'max': 80.3}, 'M': {'min': 74.1, 'median': 79.1, 'max': 83.6}}

Result: reproduced. With ties left out (reading a) F chose the higher expected value on 75.71% and M on 79.01% of trials, within 7.66 and 7.98 points of 76.6% and 79.8%. Counting the 384 and 560 tied trials as correct, as InfoGathering_Behaviour.m does, gives 76.66% and 79.83%.

chose-on-partial-information¶

Monkeys F and M chose before seeing all four cues on 85.5% and 71.4% of trials.

The claims file gives no method. InfoGathering_Behaviour.m counts a trial as an early choice when, after correcting the number of pictures for a joystick movement made before the last picture was fixated (num_pics_viewedprezero), fewer than four were viewed (out.earlychoices = 1 - mean(num_pics_viewedprezero==4)); that is taken here, and the raw count of fixated pictures is shown too.

In [11]:
pp = pd.DataFrame({
    "script (joystick-corrected)": beh.groupby("subject").apply(lambda b: 100 * (b.npv_prezero < 4).mean()),
    "pictures fixated": beh.groupby("subject").apply(lambda b: 100 * (b.npv < 4).mean()),
    "250 ms rule": beh.groupby("subject").apply(lambda b: 100 * (b.npv250 < 4).mean())})
print(pp.round(2))
print("expected F 85.5 +/- 8.55, M 71.4 +/- 7.14")
         script (joystick-corrected)  pictures fixated  250 ms rule
subject                                                            
F                              85.52             54.23        95.59
M                              71.43             42.56        92.25
expected F 85.5 +/- 8.55, M 71.4 +/- 7.14

Result: reproduced, resting on an assumption. With the script's joystick-corrected count, F chose before all four cues on 85.52% and M on 71.43% of trials (paper 85.5% and 71.4%). The paper does not define "evaluated", and the outcome depends on the definition: the raw count of fixated pictures gives 54.23% and 42.56%, outside the tolerance, and the 250 ms rule gives 95.59% and 92.25%, outside it too. The script's count (InfoGathering_Behaviour.m, out.earlychoices) is taken as the paper's definition.

choice-accuracy-observed¶

Judged by the pictures observed, choice accuracy was 86.3% for monkey F and 87.4% for monkey M.

Which pictures count as observed is taken from InfoGathering_Behaviour.m (accuracy_seen): those fixated before the joystick moved, dropping a last picture fixated for 250 ms or less (num_pics_viewed250). The script also sets unseen cues to 0.5, shifts magnitudes by -0.05 and counts ties as correct; that is shown as a variant.

In [12]:
def acc_seen(b, npv_col, reading):
    if reading == "script":
        v = pfc7.seen_values(b, npv_col, unseen=(0.5, 0.5), mag_shift=True)
        L, R = v[:, 0] * v[:, 1], v[:, 2] * v[:, 3]
        ties = "right"
    elif reading in ("a", "b"):
        v = pfc7.seen_values(b, npv_col, unseen=(0.5, 0.55), mag_shift=False)
        L, R = v[:, 0] * v[:, 1], v[:, 2] * v[:, 3]
        ties = "out" if reading == "a" else "wrong"
    else:  # (c) sum of the observed ranks per option
        L = np.zeros(len(b)); R = np.zeros(len(b))
        for k, row in enumerate(b.itertuples()):
            n = getattr(row, npv_col)
            for rk, lf in zip(row.seq_rank[:n], row.seq_left[:n]):
                if lf:
                    L[k] += rk
                else:
                    R[k] += rk
        ties = "out"
    L = np.round(L, 6); R = np.round(R, 6)
    lc = b.left_choice.values == 1
    eq = L == R
    corr = ((L > R) & lc) | ((R > L) & ~lc)
    if ties == "out":
        return 100 * corr[~eq].mean()
    if ties == "wrong":
        return 100 * corr.mean()
    return 100 * (corr | eq).mean()
rows = {}
for npv_col in ["npv250", "npv"]:
    for rd in ["a", "b", "c", "script"]:
        rows[(npv_col, rd)] = beh.groupby("subject").apply(acc_seen, npv_col=npv_col, reading=rd)
aso = pd.DataFrame(rows).T
aso.index.names = ["pictures seen", "reading"]
print(aso.round(2))
print("expected F 86.3 +/- 8.63, M 87.4 +/- 8.74")
subject                    F      M
pictures seen reading              
npv250        a        86.00  87.75
              b        79.88  82.26
              c        89.17  89.20
              script   87.80  89.48
npv           a        79.14  81.35
              b        75.03  77.28
              c        82.56  82.90
              script   81.68  83.68
expected F 86.3 +/- 8.63, M 87.4 +/- 8.74

Result: reproduced. Under reading (a), with the pictures seen as the script counts them (num_pics_viewed250), accuracy is 86.00% for F and 87.75% for M, within 8.63 and 8.74 points of 86.3% and 87.4%. Readings (c) and the script's own measure also fall within tolerance (89.17/89.20 and 87.80/89.48); reading (b) gives 79.88/82.26.

figs1ab-cue-weights¶

In logistic regressions of choice, both monkeys weighted reward probability and magnitude about equally and used all four viewed cues, with a slight upweighting of the antepenultimate (n-2) cue, and both showed a small bias towards choosing the second side on option trials.

Model B follows InfoGathering_Behaviour.m (choice on left minus right seen probability and seen magnitude, unseen at 0.5, with a constant and a first-side term, separately for option and attribute trials, no further constant). Model A regresses choice on a constant and the final, n-1, n-2 and n-3 viewed pictures, signed + left and - right (the script uses lastLreg - lastRreg on the pictures fixated).

In [13]:
def model_b(b, seen=True):
    if seen:
        v = pfc7.seen_values(b, "npv250", unseen=(0.5, 0.5), mag_shift=True)
        dp, dm = v[:, 0] - v[:, 2], v[:, 1] - v[:, 3]
    else:
        dp, dm = (b.LP - b.RP).values, (b.LM - b.RM).values
    fs = np.array([r.seq_left[0] for r in b.itertuples()], float)
    base_ = np.column_stack([np.ones(len(b)), dp, dm, fs])
    X = np.hstack([base_ * (b.condition.values == 3)[:, None], base_ * (b.condition.values == 4)[:, None]])
    res = sm.GLM(b.left_choice.values, X, family=sm.families.Binomial()).fit()
    names = [f"{t} {n}" for t in ("option", "attribute") for n in ("left bias", "prob", "mag", "first side")]
    out = pd.DataFrame({"b": res.params, "se": res.bse, "p": res.pvalues}, index=names)
    waldp = {}
    for t, o in (("option", 0), ("attribute", 4)):
        c = np.zeros(8); c[o + 1] = 1; c[o + 2] = -1
        w = res.t_test(c)
        waldp[t] = float(w.pvalue)
    return out, waldp
def model_a(b, scale):
    Xs = np.zeros((len(b), 4))
    for k, r in enumerate(b.itertuples()):
        n = r.npv
        for j in range(min(n, 4)):
            idx = n - 1 - j
            rk = r.seq_rank[idx]
            val = rk if scale == "rank" else (0.1 + 0.2 * (rk + 2))
            Xs[k, j] = val if r.seq_left[idx] else -val
    X = np.column_stack([np.ones(len(b)), Xs])
    res = sm.GLM(b.left_choice.values, X, family=sm.families.Binomial()).fit()
    return pd.DataFrame({"b": res.params, "se": res.bse, "p": res.pvalues},
                        index=["left bias", "final", "n-1", "n-2", "n-3"])
S1 = {}
for sb in ["F", "M"]:
    b = beh[beh.subject == sb]
    for seen in (True, False):
        mb, wp = model_b(b, seen)
        ci = mb.b.values[:, None] + np.array([-1.96, 1.96]) * mb.se.values[:, None]
        print(f"--- {sb}, model B, {'seen values (script)' if seen else 'true values'}")
        print(mb.round(4))
        for t, o in (("option", 0), ("attribute", 4)):
            ov = not (ci[o + 1, 1] < ci[o + 2, 0] or ci[o + 2, 1] < ci[o + 1, 0])
            print(f"  {t}: prob/mag ratio {mb.b.iloc[o + 1] / mb.b.iloc[o + 2]:.2f}, 95% CIs overlap {ov},"
                  f" Wald p(prob = mag) {wp[t]:.3g}")
            S1[(sb, seen, t)] = dict(pos=(mb.b.iloc[o + 1] > 0) and (mb.b.iloc[o + 2] > 0), overlap=ov, wald=wp[t])
        S1[(sb, seen, "first")] = (mb.b.iloc[3], mb.p.iloc[3])
    for scale in ("rank", "raw"):
        ma = model_a(b, scale)
        print(f"--- {sb}, model A, {scale}")
        print(ma.round(4))
        S1[(sb, "A", scale)] = ma
--- F, model B, seen values (script)
                           b      se       p
option left bias     -0.1738  0.0624  0.0053
option prob           6.4899  0.2027  0.0000
option mag            6.6013  0.2066  0.0000
option first side    -0.4674  0.0890  0.0000
attribute left bias  -0.6871  0.0613  0.0000
attribute prob        5.8953  0.1897  0.0000
attribute mag         6.5366  0.2102  0.0000
attribute first side  0.5472  0.0849  0.0000
  option: prob/mag ratio 0.98, 95% CIs overlap True, Wald p(prob = mag) 0.53
  attribute: prob/mag ratio 0.90, 95% CIs overlap True, Wald p(prob = mag) 0.002
--- F, model B, true values
                           b      se       p
option left bias     -0.1977  0.0501  0.0001
option prob           3.0400  0.1088  0.0000
option mag            2.9232  0.1063  0.0000
option first side    -0.1746  0.0715  0.0146
attribute left bias  -0.5363  0.0509  0.0000
attribute prob        3.0838  0.1076  0.0000
attribute mag         3.0296  0.1068  0.0000
attribute first side  0.4168  0.0706  0.0000
  option: prob/mag ratio 1.04, 95% CIs overlap True, Wald p(prob = mag) 0.327
  attribute: prob/mag ratio 1.02, 95% CIs overlap True, Wald p(prob = mag) 0.647
--- F, model A, rank
                b      se    p
left bias -0.4048  0.0300  0.0
final      0.2696  0.0210  0.0
n-1        1.3469  0.0285  0.0
n-2        1.1865  0.0291  0.0
n-3        1.0380  0.0363  0.0
--- F, model A, raw
                b      se    p
left bias -0.5337  0.0275  0.0
final      2.1556  0.0646  0.0
n-1        2.8923  0.0617  0.0
n-2        2.1736  0.0655  0.0
n-3        2.2485  0.0820  0.0
--- M, model B, seen values (script)
                           b      se       p
option left bias      0.4555  0.0528  0.0000
option prob           6.9931  0.1772  0.0000
option mag            6.2765  0.1655  0.0000
option first side    -1.2196  0.0786  0.0000
attribute left bias  -0.1045  0.0514  0.0420
attribute prob        6.7339  0.1740  0.0000
attribute mag         5.9603  0.1629  0.0000
attribute first side -0.0914  0.0715  0.2011
  option: prob/mag ratio 1.11, 95% CIs overlap False, Wald p(prob = mag) 1.1e-06
  attribute: prob/mag ratio 1.13, 95% CIs overlap False, Wald p(prob = mag) 4.08e-07
--- M, model B, true values
                           b      se       p
option left bias      0.2191  0.0432  0.0000
option prob           3.5310  0.0972  0.0000
option mag            3.1836  0.0930  0.0000
option first side    -0.6482  0.0613  0.0000
attribute left bias  -0.0441  0.0431  0.3059
attribute prob        3.4220  0.0942  0.0000
attribute mag         2.9677  0.0904  0.0000
attribute first side -0.1238  0.0600  0.0390
  option: prob/mag ratio 1.11, 95% CIs overlap True, Wald p(prob = mag) 0.00062
  attribute: prob/mag ratio 1.15, 95% CIs overlap False, Wald p(prob = mag) 5.04e-06
--- M, model A, rank
                b      se    p
left bias -0.1587  0.0245  0.0
final      0.2843  0.0177  0.0
n-1        1.2289  0.0229  0.0
n-2        1.1614  0.0229  0.0
n-3        1.1760  0.0283  0.0
--- M, model A, raw
                b      se       p
left bias -0.0447  0.0227  0.0486
final      2.3829  0.0583  0.0000
n-1        3.4941  0.0578  0.0000
n-2        2.2209  0.0534  0.0000
n-3        2.4088  0.0668  0.0000
In [14]:
for seen in (True, False):
    for eq in ("overlap", "wald"):
        ok = True
        for sb in ["F", "M"]:
            for t in ("option", "attribute"):
                s = S1[(sb, seen, t)]
                ok &= s["pos"] and (s["overlap"] if eq == "overlap" else s["wald"] > 0.05)
        print(f"model B {'seen' if seen else 'true'} values, equal weight by {eq}: holds in both monkeys = {ok}")
for sb in ["F", "M"]:
    for seen in (True, False):
        b_, p_ = S1[(sb, seen, "first")]
        print(f"{sb} first-side bias, option trials ({'seen' if seen else 'true'}): b = {b_:.3f}, p = {p_:.2g}")
    for scale in ("rank", "raw"):
        ma = S1[(sb, "A", scale)]
        w = ma.loc[["final", "n-1", "n-2", "n-3"]]
        print(f"{sb} model A {scale}: all picture weights > 0 with p < 0.05: {bool(((w.b > 0) & (w.p < 0.05)).all())};"
              f" n-2 weight {w.b['n-2']:.3f} against final {w.b['final']:.3f} and n-1 {w.b['n-1']:.3f}")
model B seen values, equal weight by overlap: holds in both monkeys = False
model B seen values, equal weight by wald: holds in both monkeys = False
model B true values, equal weight by overlap: holds in both monkeys = False
model B true values, equal weight by wald: holds in both monkeys = False
F first-side bias, option trials (seen): b = -0.467, p = 1.5e-07
F first-side bias, option trials (true): b = -0.175, p = 0.015
F model A rank: all picture weights > 0 with p < 0.05: True; n-2 weight 1.186 against final 0.270 and n-1 1.347
F model A raw: all picture weights > 0 with p < 0.05: True; n-2 weight 2.174 against final 2.156 and n-1 2.892
M first-side bias, option trials (seen): b = -1.220, p = 2.7e-54
M first-side bias, option trials (true): b = -0.648, p = 3.8e-26
M model A rank: all picture weights > 0 with p < 0.05: True; n-2 weight 1.161 against final 0.284 and n-1 1.229
M model A raw: all picture weights > 0 with p < 0.05: True; n-2 weight 2.221 against final 2.383 and n-1 3.494

Result: partially reproduced. In model A every picture weight is positive with p < 0.05 in both monkeys under both scales, and the first-side term on option trials is negative in both (F b = -0.467, p = 1.5e-07; M b = -1.220, p = 2.7e-54, seen values). Equal weighting of probability and magnitude fails in M: the ratio is 1.11 on option and 1.13 on attribute trials, the 95% CIs do not overlap and the Wald test gives p = 1.1e-06 and 4.1e-07; with true values the ratios are 1.11 and 1.15 and the attribute CIs do not overlap. In F the CIs overlap on both trial types. The n-2 weight (F 1.186, M 1.161 on ranks) is below the n-1 weight (1.347, 1.229), so the slight upweighting of the antepenultimate cue is not seen against n-1; it is above the final weight.

figs1cd-fewer-cues-more-accurate¶

Choices were more often optimal on trials where 2 pictures were viewed than on trials with 3 or 4, because trials ended early when the first two cues gave a larger value difference.

The number of pictures viewed is taken from InfoGathering_Behaviour.m (num_pics_viewed250, used for Supplementary Figure 1c/d); the raw count of fixated pictures is shown too. The claims file, as amended after a reader's answer (questions/hunt-2018.yaml), allows two measures of accuracy: (A) the choice of the higher true expected value, reading (a) of choice-accuracy-ev (ties left out); (B) the choice of the higher expected value of the pictures observed, under the readings of choice-accuracy-observed. Trials are pooled over sessions; the script's mean over sessions is shown as a variant.

In [15]:
def vd_cues12(b):
    out = np.zeros(len(b))
    for k, r in enumerate(b.itertuples()):
        lp, lm, rp, rm = 0.5, 0.55, 0.5, 0.55
        for p in r.positions[:2]:
            isprob = (p in (91, 93)) == (r.prob_top == 1)
            left = p in (91, 92)
            if isprob and left: lp = r.LP
            elif isprob: rp = r.RP
            elif left: lm = r.LM
            else: rm = r.RM
        out[k] = abs(lp * lm - rp * rm)
    return out
beh["vd_true"] = (beh.LEV - beh.REV).abs()
beh["vd_12"] = vd_cues12(beh)
rows = []
for col in ["npv250", "npv"]:
    for sb in ["F", "M"]:
        b = beh[beh.subject == sb]
        for n in (2, 3, 4):
            bb = b[b[col] == n]
            rows.append(dict(count=col, subject=sb, n=n, trials=len(bb), accuracy=acc_ev(bb, "out"),
                             vd_true=bb.vd_true.mean(), vd_cues12=bb.vd_12.mean()))
s1cd = pd.DataFrame(rows).set_index(["count", "subject", "n"]).sort_index()
# InfoGathering_Behaviour.m (accuracyNPV, mvd): accuracy judged on the seen values (unseen 0.5,
# magnitudes shifted, ties counted right), per session, then averaged over sessions
sv = pfc7.seen_values(beh, "npv250", unseen=(0.5, 0.5), mag_shift=True)
beh["Lseen"], beh["Rseen"] = sv[:, 0] * sv[:, 1], sv[:, 2] * sv[:, 3]
beh["acc_seen"] = (((beh.Lseen >= beh.Rseen) & (beh.left_choice == 1)) | ((beh.Rseen >= beh.Lseen) & (beh.left_choice == 0)))
scr = (beh.groupby(["subject", "session", "npv250"]).agg(acc=("acc_seen", "mean"), vd=("vd_true", "mean"))
       .groupby(level=[0, 2]).mean())
print("script's measure (mean over sessions of accuracy on seen values; mean |EV difference|):")
print((scr.assign(acc=100 * scr.acc)).round(3))
print(s1cd.round(3))
for col in ["npv250", "npv"]:
    for sb in ["F", "M"]:
        t = s1cd.loc[(col, sb)]
        print(col, sb, "accuracy 2 > 3 and 2 > 4:", bool(t.accuracy[2] > t.accuracy[3] and t.accuracy[2] > t.accuracy[4]),
              "| largest mean value difference at 2 cues, true EV:", bool(t.vd_true.idxmax() == 2),
              ", cues 1-2:", bool(t.vd_cues12.idxmax() == 2))
for sb in ["F", "M"]:
    t = scr.loc[sb]
    print("script measure", sb, "accuracy 2 > 3 and 2 > 4:", bool(t.acc[2] > t.acc[3] and t.acc[2] > t.acc[4]),
          "| largest value difference at 2:", bool(t.vd.idxmax() == 2))
script's measure (mean over sessions of accuracy on seen values; mean |EV difference|):
                   acc     vd
subject npv250               
F       2       90.188  0.268
        3       82.631  0.227
        4       82.270  0.219
M       2       93.652  0.272
        3       85.196  0.239
        4       83.694  0.226
                  trials  accuracy  vd_true  vd_cues12
count  subject n                                      
npv    F       2    1230    78.939    0.305      0.241
               3    4119    74.068    0.249      0.175
               4    4514    76.341    0.227      0.155
       M       2     351    72.086    0.223      0.167
               3    5714    79.463    0.270      0.198
               4    8186    78.977    0.232      0.160
npv250 F       2    4638    74.955    0.266      0.198
               3    4790    76.103    0.229      0.153
               4     435    79.616    0.219      0.148
       M       2    3639    78.833    0.271      0.213
               3    9507    78.789    0.240      0.165
               4    1105    81.513    0.228      0.140
npv250 F accuracy 2 > 3 and 2 > 4: False | largest mean value difference at 2 cues, true EV: True , cues 1-2: True
npv250 M accuracy 2 > 3 and 2 > 4: False | largest mean value difference at 2 cues, true EV: True , cues 1-2: True
npv F accuracy 2 > 3 and 2 > 4: True | largest mean value difference at 2 cues, true EV: True , cues 1-2: True
npv M accuracy 2 > 3 and 2 > 4: False | largest mean value difference at 2 cues, true EV: False , cues 1-2: False
script measure F accuracy 2 > 3 and 2 > 4: True | largest value difference at 2: True
script measure M accuracy 2 > 3 and 2 > 4: True | largest value difference at 2: True
In [16]:
# Reading (B): accuracy on the expected values of the pictures observed, under the readings of
# choice-accuracy-observed (acc_seen above), trials pooled over sessions; the pictures observed
# are those the count of pictures uses
rows = []
for col in ["npv250", "npv"]:
    for sb in ["F", "M"]:
        b = beh[beh.subject == sb]
        for n in (2, 3, 4):
            bb = b[b[col] == n]
            rows.append(dict(count=col, subject=sb, n=n, **{rd: acc_seen(bb, col, rd) for rd in ["a", "b", "c", "script"]}))
s1c_obs = pd.DataFrame(rows).set_index(["count", "subject", "n"]).sort_index()
print("reading (B), % correct on the pictures observed, trials pooled:")
print(s1c_obs.round(2))
for col in ["npv250", "npv"]:
    for rd in ["a", "b", "c", "script"]:
        ok = {sb: bool(s1c_obs.loc[(col, sb, 2), rd] > max(s1c_obs.loc[(col, sb, 3), rd], s1c_obs.loc[(col, sb, 4), rd]))
              for sb in ["F", "M"]}
        print(f"count {col}, reading (B{rd}): accuracy 2 > 3 and 2 > 4, F {ok['F']}, M {ok['M']}")
reading (B), % correct on the pictures observed, trials pooled:
                      a      b      c  script
count  subject n                             
npv    F       2  92.54  85.77  95.00   93.09
               3  78.00  74.12  82.61   80.60
               4  76.63  72.93  78.97   79.55
       M       2  89.29  64.10  94.89   92.31
               3  84.09  80.87  86.58   86.03
               4  79.17  75.34  79.95   81.66
npv250 F       2  90.24  81.35  92.42   91.20
               3  82.67  78.79  86.46   84.97
               4  79.81  76.32  84.41   82.76
       M       2  94.62  84.58  96.59   95.19
               3  85.98  82.01  87.16   87.86
               4  81.70  76.74  82.58   84.62
count npv250, reading (Ba): accuracy 2 > 3 and 2 > 4, F True, M True
count npv250, reading (Bb): accuracy 2 > 3 and 2 > 4, F True, M True
count npv250, reading (Bc): accuracy 2 > 3 and 2 > 4, F True, M True
count npv250, reading (Bscript): accuracy 2 > 3 and 2 > 4, F True, M True
count npv, reading (Ba): accuracy 2 > 3 and 2 > 4, F True, M True
count npv, reading (Bb): accuracy 2 > 3 and 2 > 4, F True, M False
count npv, reading (Bc): accuracy 2 > 3 and 2 > 4, F True, M True
count npv, reading (Bscript): accuracy 2 > 3 and 2 > 4, F True, M True

Result: reproduced. Under measure (B), with trials pooled and the script's count of pictures, accuracy on 2-picture trials is the highest in both monkeys under every reading of choice-accuracy-observed: under reading (a) F 90.24% against 82.67% and 79.81% on 3 and 4 pictures, M 94.62% against 85.98% and 81.70%. The mean value difference is largest on 2-picture trials in both monkeys under both readings (true expected values, F 0.266 against 0.229 and 0.219, M 0.271 against 0.240 and 0.228). Under measure (A) accuracy on 2-picture trials is not the highest (F 74.96% against 76.10% and 79.62%; M 78.83% against 78.79% and 81.51%). The script's mean over sessions gives the same order as (B) (F 90.19% against 82.63% and 82.27%; M 93.65% against 85.20% and 83.69%). With the raw count of fixated pictures, (B) holds in both monkeys under readings (a), (c) and the script's, and in F only under (b).

fig2a-sample-the-favourite¶

On attribute trials, the free third saccade went preferentially to the option with the higher value between cue 1 and cue 2.

Attribute trials with a third picture fixated (num_pics_viewed > 2, as the script's AvSaccDir12Att); the third saccade returns to the first option when the third picture is on the first picture's side.

In [17]:
for sb in ["F", "M", "both"]:
    b = beh[(beh.condition == 4) & (beh.npv >= 3)]
    if sb != "both":
        b = b[b.subject == sb]
    back = np.array([r.seq_left[2] == r.seq_left[0] for r in b.itertuples()], float)
    d12 = np.array([r.seq_rank[0] - r.seq_rank[1] for r in b.itertuples()], float)
    res = sm.GLM(back, sm.add_constant(d12), family=sm.families.Binomial()).fit()
    hi1, lo1 = back[d12 > 0], back[d12 < 0]
    chi, pchi, _, _ = stats.chi2_contingency([[hi1.sum(), len(hi1) - hi1.sum()], [lo1.sum(), len(lo1) - lo1.sum()]])
    print(f"{sb}: n = {len(b)}; (a) slope on rank1 - rank2 {res.params[1]:.3f}, p = {res.pvalues[1]:.2g};"
          f" (b) back to option 1 when cue 1 > cue 2 {hi1.mean():.3f} (n={len(hi1)}), when cue 1 < cue 2"
          f" {lo1.mean():.3f} (n={len(lo1)}), chi2 = {chi:.1f}, p = {pchi:.2g}")
F: n = 4508; (a) slope on rank1 - rank2 0.729, p = 3.3e-190; (b) back to option 1 when cue 1 > cue 2 0.598 (n=1641), when cue 1 < cue 2 0.087 (n=1914), chi2 = 1051.0, p = 1.5e-230
M: n = 6910; (a) slope on rank1 - rank2 1.210, p = 0; (b) back to option 1 when cue 1 > cue 2 0.867 (n=2735), when cue 1 < cue 2 0.100 (n=2852), chi2 = 3290.1, p = 0
both: n = 11418; (a) slope on rank1 - rank2 0.944, p = 0; (b) back to option 1 when cue 1 > cue 2 0.766 (n=4376), when cue 1 < cue 2 0.095 (n=4766), chi2 = 4226.9, p = 0

Result: reproduced. On attribute trials with a third picture, the third saccade returned to the first option on 59.8% (F) and 86.7% (M) of trials when cue 1 outranked cue 2, against 8.7% and 10.0% when it did not (chi-square p = 1.5e-230, and printed as 0 for M); the logistic slopes are 0.729 and 1.210 (p = 3.3e-190, and printed as 0).

fig2b-positive-evidence¶

On option trials, subjects sampled the fewest cues when cues 1 and 2 were highest in value and the most when they were lowest.

The count is num_pics_viewed250, as the script's nPicView12Opt for Figure 2b; the raw count is shown too.

In [18]:
for col in ["npv250", "npv"]:
    for sb in ["F", "M", "both"]:
        b = beh[beh.condition == 3]
        if sb != "both":
            b = b[b.subject == sb]
        r1 = np.array([r.seq_rank[0] for r in b.itertuples()])
        r2 = np.array([r.seq_rank[1] for r in b.itertuples()])
        n = b[col].values
        hi = n[(r1 == 2) & (r2 == 2)]
        lo = n[(r1 == -2) & (r2 == -2)]
        rho, prho = stats.spearmanr(r1 + r2, n)
        print(f"{col} {sb}: (a) mean cues, both ranks +2: {hi.mean():.2f} (n={len(hi)}); both -2: "
              f"{lo.mean():.2f} (n={len(lo)}); (b) Spearman rho {rho:.3f}, p = {prho:.2g}")
b = beh[(beh.condition == 3) & (beh.subject == "M")]
tbl = pd.crosstab(np.array([r.seq_rank[0] for r in b.itertuples()]), np.array([r.seq_rank[1] for r in b.itertuples()]),
                  values=b.npv250.values, aggfunc="mean")
print("monkey M, mean npv250 by cue 1 rank (rows) and cue 2 rank (columns):")
print(tbl.round(2))
npv250 F: (a) mean cues, both ranks +2: 2.05 (n=184); both -2: 2.69 (n=189); (b) Spearman rho -0.356, p = 7.1e-144
npv250 M: (a) mean cues, both ranks +2: 2.22 (n=274); both -2: 3.15 (n=317); (b) Spearman rho -0.499, p = 0
npv250 both: (a) mean cues, both ranks +2: 2.15 (n=458); both -2: 2.98 (n=506); (b) Spearman rho -0.434, p = 0
npv F: (a) mean cues, both ranks +2: 2.47 (n=184); both -2: 3.54 (n=189); (b) Spearman rho -0.425, p = 2.5e-211
npv M: (a) mean cues, both ranks +2: 3.06 (n=274); both -2: 3.86 (n=317); (b) Spearman rho -0.461, p = 0
npv both: (a) mean cues, both ranks +2: 2.82 (n=458); both -2: 3.74 (n=506); (b) Spearman rho -0.436, p = 0
monkey M, mean npv250 by cue 1 rank (rows) and cue 2 rank (columns):
col_0    -2    -1     0     1     2
row_0                              
-2     3.15  3.13  3.06  3.12  3.05
-1     3.09  3.07  3.11  3.02  3.00
 0     3.01  2.99  2.88  2.83  2.65
 1     2.87  2.79  2.59  2.30  2.27
 2     2.81  2.67  2.40  2.21  2.22

Result: reproduced. On option trials with both cues at rank +2 F sampled 2.05 and M 2.22 pictures on average, against 2.69 and 3.15 with both at -2 (script count; raw count 2.47/3.06 against 3.54/3.86), and the Spearman correlation with the summed rank is negative in each monkey and pooled (rho -0.356, -0.499, -0.434, all p < 1e-143).

RSA at cue 1 (claims fig4d to fig4h, figs2, figs4, figs11)¶

Fig4_RSA.m and calculate_RSA_matrices.m: per unit the mean spike count 100 < t < 500 ms after cue 1 in each of 20 conditions, z-scored across conditions; Pearson correlation between conditions; OLS of the 400 elements on the seven columns of pfc7.rsa_design. T-statistics and the between-region F-statistics are compared with 10,000 permutations of the 20 condition labels. The script's test is one-sided (1 - mean(t > tp)), reading (a) of O8; reading (b), two-sided on |T|, is shown too. Reading (a) of O9 (all completed trials) is what calculate_RSA_matrices.m uses; reading (b) keeps trials with 3 or more cues.

In [19]:
def rsa_unitmat(units, key="rsa", field="m20"):
    return np.column_stack([U[u][key][field] for u in units])

DM, TN = pfc7.rsa_design()
DM_ALT, _ = pfc7.rsa_design(alternative=True)
FTP = pfc7.rsa_ftest_parts(DM)
FTP_ALT = pfc7.rsa_ftest_parts(DM_ALT)
NPERM = 10000

def rsa_run(mats, dm, ftp, rng, nperm=NPERM):
    """mats: list of three conditions x units matrices (ACC, DLPFC, OFC)."""
    Y = np.column_stack([pfc7.rsa_matrix(M).ravel(order="F") for M in mats])
    C = np.eye(dm.shape[1])
    _, _, t = pfc7.ols(Y, dm, C)
    cp = pfc7.cpd(Y, dm)
    F = pfc7.rsa_fstats(Y.ravel(order="F"), ftp)
    tp = np.zeros((nperm,) + t.shape)
    Fp = np.zeros((nperm, len(F)))
    for p in range(nperm):
        pp = rng.permutation(20)
        Yp = np.column_stack([pfc7.rsa_matrix(M[pp]).ravel(order="F") for M in mats])
        tp[p] = pfc7.ols(Yp, dm, C)[2]
        Fp[p] = pfc7.rsa_fstats(Yp.ravel(order="F"), ftp)
    p1 = 1 - (t[None] > tp).mean(0)
    p2 = (np.abs(tp) >= np.abs(t)[None]).mean(0)
    pF = 1 - (F[None] > Fp).mean(0)
    pdiff = {}
    for i in range(2, 7):
        for r1 in range(3):
            for r2 in range(3):
                if r1 != r2:
                    pdiff[(i, r1, r2)] = 1 - ((t[i, r1] - t[i, r2]) > (tp[:, i, r1] - tp[:, i, r2])).mean()
    return dict(Y=Y, t=t, cpd=cp, F=F, p1=p1, p2=p2, pF=pF, pdiff=pdiff)

def rsa_table(res, names=TN):
    rows = []
    for i in range(2, 7):
        for r in range(3):
            rows.append(dict(template=names[i], area=NAMES[r + 1], T=res["t"][i, r],
                             p_one=res["p1"][i, r], p_two=res["p2"][i, r], CPD=100 * res["cpd"][i, r]))
    tb = pd.DataFrame(rows).pivot(index="template", columns="area")
    return tb

t_rsa = time.time()
MATS = {"a": [rsa_unitmat(SEL[a]) for a in (1, 2, 3)]}
print("units entering the RSA:", {NAMES[a]: int((~np.all(m == 0, 0)).sum()) for a, m in zip((1, 2, 3), MATS["a"])})
RSA = {"a": rsa_run(MATS["a"], DM, FTP, section_rng("rsa-a"))}
print(f"RSA reading (a) with {NPERM} permutations: {time.time() - t_rsa:.0f} s")
print(rsa_table(RSA["a"]).round(4))
print("between-region F:", {TN[i]: (round(RSA["a"]["F"][i], 2), RSA["a"]["pF"][i]) for i in range(2, 7)})
units entering the RSA: {'ACC': 189, 'DLPFC': 134, 'OFC': 183}
RSA reading (a) with 10000 permutations: 43 s
                         T                     p_one                   p_two                      CPD                  
area                   ACC    DLPFC      OFC     ACC   DLPFC     OFC     ACC   DLPFC     OFC      ACC    DLPFC      OFC
template                                                                                                               
accept/reject      10.3000   4.3869   8.7141  0.0000  0.0101  0.0001  0.0000  0.0136  0.0001  21.2568   4.6684  16.1933
attended value      2.1924   0.7291   5.8642  0.0632  0.2724  0.0019  0.1264  0.5767  0.0022   1.2082   0.1351   8.0462
left/right value    6.0493   6.5065   0.0672  0.0073  0.0036  0.4059  0.0073  0.0036  0.9614   8.5182   9.7245   0.0011
spatial attention   7.8992  39.9022   4.5754  0.0028  0.0000  0.0181  0.0028  0.0000  0.0181  13.7017  80.2034   5.0573
stimulus identity   3.8517   4.4998  14.8158  0.0059  0.0020  0.0000  0.0111  0.0040  0.0000   3.6376   4.8998  35.8375
between-region F: {'stimulus identity': (np.float64(23.84), np.float64(0.0)), 'attended value': (np.float64(4.84), np.float64(0.029200000000000004)), 'accept/reject': (np.float64(14.43), np.float64(0.0016000000000000458)), 'spatial attention': (np.float64(348.53), np.float64(0.0)), 'left/right value': (np.float64(14.43), np.float64(0.0038000000000000256))}
In [20]:
MATS["b"] = [rsa_unitmat(SEL[a], key="rsa3") for a in (1, 2, 3)]
RSA["b"] = rsa_run(MATS["b"], DM, FTP, section_rng("rsa-b"))
print("O9 reading (b), trials with 3 or more cues:")
print(rsa_table(RSA["b"]).round(4))
print("between-region F:", {TN[i]: (round(RSA["b"]["F"][i], 2), RSA["b"]["pF"][i]) for i in range(2, 7)})
fig, ax = plt.subplots(1, 3, figsize=(12, 4))
for k, a in enumerate((3, 2, 1)):
    M = RSA["a"]["Y"][:, a - 1].reshape(20, 20, order="F")
    ax[k].imshow(M, vmin=-0.3, vmax=0.3, cmap="hot")
    ax[k].set_title(f"{NAMES[a]} (values {M[~np.eye(20, dtype=bool)].min():.2f} to "
                    f"{M[~np.eye(20, dtype=bool)].max():.2f} off the diagonal)", fontsize=8)
plt.show()
O9 reading (b), trials with 3 or more cues:
                        T                     p_one                   p_two                      CPD                  
area                  ACC    DLPFC      OFC     ACC   DLPFC     OFC     ACC   DLPFC     OFC      ACC    DLPFC      OFC
template                                                                                                              
accept/reject      9.5741   3.9682   6.9427  0.0001  0.0142  0.0007  0.0001  0.0194  0.0007  18.9127   3.8525  10.9248
attended value     3.5392   2.0626   6.4313  0.0189  0.0810  0.0006  0.0301  0.1561  0.0007   3.0888   1.0709   9.5225
left/right value   4.6988   5.0229  -0.2728  0.0155  0.0108  0.5089  0.0155  0.0108  0.8393   5.3192   6.0325   0.0189
spatial attention  7.9616  38.3664   3.4670  0.0038  0.0000  0.0324  0.0038  0.0000  0.0331  13.8888  78.9274   2.9678
stimulus identity  2.7333   3.9579  12.3830  0.0371  0.0044  0.0000  0.0697  0.0080  0.0000   1.8655   3.8333  28.0665
between-region F: {'stimulus identity': (np.float64(19.8), np.float64(0.0)), 'attended value': (np.float64(3.7), np.float64(0.05159999999999998)), 'accept/reject': (np.float64(13.66), np.float64(0.0012999999999999678)), 'spatial attention': (np.float64(304.82), np.float64(0.0)), 'left/right value': (np.float64(9.46), np.float64(0.010499999999999954))}
No description has been provided for this image

A helper to judge the template claims under each reading (O8 sidedness, O9 trials).

In [21]:
IDX = {n: i for i, n in enumerate(TN)}
def sig(res, tmpl, area, side):
    return (res["p1"] if side == "one" else res["p2"])[IDX[tmpl], area - 1] < 0.05
def cpdv(res, tmpl, area):
    return res["cpd"][IDX[tmpl], area - 1]
def readings():
    for o9 in ("a", "b"):
        for o8 in ("one", "two"):
            yield o9, o8

fig4d-spatial-attention¶

At cue 1, DLPFC representational similarity reflects whether the subject is attending left or right; spatial attention is also represented in OFC and ACC.

In [22]:
for o9, o8 in readings():
    r = RSA[o9]
    ok = (sig(r, "spatial attention", 2, o8) and cpdv(r, "spatial attention", 2) > cpdv(r, "spatial attention", 1)
          and cpdv(r, "spatial attention", 2) > cpdv(r, "spatial attention", 3)
          and sig(r, "spatial attention", 3, o8) and sig(r, "spatial attention", 1, o8))
    print(f"O9 ({o9}) O8 {o8}-sided: CPD % ACC {100*cpdv(r,'spatial attention',1):.2f}, DLPFC "
          f"{100*cpdv(r,'spatial attention',2):.2f}, OFC {100*cpdv(r,'spatial attention',3):.2f}; p ACC/DLPFC/OFC "
          f"{[round(float(x), 4) for x in (r['p1'] if o8 == 'one' else r['p2'])[IDX['spatial attention']]]};"
          f" F p = {r['pF'][IDX['spatial attention']]:.4f} -> criterion holds: {ok}")
O9 (a) O8 one-sided: CPD % ACC 13.70, DLPFC 80.20, OFC 5.06; p ACC/DLPFC/OFC [0.0028, 0.0, 0.0181]; F p = 0.0000 -> criterion holds: True
O9 (a) O8 two-sided: CPD % ACC 13.70, DLPFC 80.20, OFC 5.06; p ACC/DLPFC/OFC [0.0028, 0.0, 0.0181]; F p = 0.0000 -> criterion holds: True
O9 (b) O8 one-sided: CPD % ACC 13.89, DLPFC 78.93, OFC 2.97; p ACC/DLPFC/OFC [0.0038, 0.0, 0.0324]; F p = 0.0000 -> criterion holds: True
O9 (b) O8 two-sided: CPD % ACC 13.89, DLPFC 78.93, OFC 2.97; p ACC/DLPFC/OFC [0.0038, 0.0, 0.0331]; F p = 0.0000 -> criterion holds: True

Result: reproduced. The spatial attention template is significant in DLPFC (T = 39.90, permutation p < 0.0001), OFC (T = 4.58, p = 0.018) and ACC (T = 7.90, p = 0.0028), and its CPD is largest in DLPFC (80.2% against 13.7% in ACC and 5.1% in OFC); the between-region F is 348.5 (p < 0.0001). All four readings of O8 and O9 agree.

fig4e-ofc-stimulus-identity¶

At cue 1, OFC representational similarity reflects the attended stimulus identity irrespective of its spatial position.

In [23]:
def judge_ofc(tmpl):
    for o9, o8 in readings():
        r = RSA[o9]
        ok = sig(r, tmpl, 3, o8) and cpdv(r, tmpl, 3) > cpdv(r, tmpl, 1) and cpdv(r, tmpl, 3) > cpdv(r, tmpl, 2)
        print(f"O9 ({o9}) O8 {o8}-sided: T OFC {r['t'][IDX[tmpl], 2]:.2f}, p "
              f"{(r['p1'] if o8 == 'one' else r['p2'])[IDX[tmpl], 2]:.4f}; CPD % ACC {100*cpdv(r,tmpl,1):.2f}, DLPFC "
              f"{100*cpdv(r,tmpl,2):.2f}, OFC {100*cpdv(r,tmpl,3):.2f}; F p = {r['pF'][IDX[tmpl]]:.4f} -> holds: {ok}")
judge_ofc("stimulus identity")
O9 (a) O8 one-sided: T OFC 14.82, p 0.0000; CPD % ACC 3.64, DLPFC 4.90, OFC 35.84; F p = 0.0000 -> holds: True
O9 (a) O8 two-sided: T OFC 14.82, p 0.0000; CPD % ACC 3.64, DLPFC 4.90, OFC 35.84; F p = 0.0000 -> holds: True
O9 (b) O8 one-sided: T OFC 12.38, p 0.0000; CPD % ACC 1.87, DLPFC 3.83, OFC 28.07; F p = 0.0000 -> holds: True
O9 (b) O8 two-sided: T OFC 12.38, p 0.0000; CPD % ACC 1.87, DLPFC 3.83, OFC 28.07; F p = 0.0000 -> holds: True

Result: reproduced. Stimulus identity is significant in OFC (T = 14.82, p < 0.0001) with a CPD of 35.8% against 3.6% (ACC) and 4.9% (DLPFC), under all four readings.

fig4f-ofc-attended-value¶

At cue 1, OFC representational similarity is high for cues of similar attended value, consistent with a linear value code.

In [24]:
judge_ofc("attended value")
O9 (a) O8 one-sided: T OFC 5.86, p 0.0019; CPD % ACC 1.21, DLPFC 0.14, OFC 8.05; F p = 0.0292 -> holds: True
O9 (a) O8 two-sided: T OFC 5.86, p 0.0022; CPD % ACC 1.21, DLPFC 0.14, OFC 8.05; F p = 0.0292 -> holds: True
O9 (b) O8 one-sided: T OFC 6.43, p 0.0006; CPD % ACC 3.09, DLPFC 1.07, OFC 9.52; F p = 0.0516 -> holds: True
O9 (b) O8 two-sided: T OFC 6.43, p 0.0007; CPD % ACC 3.09, DLPFC 1.07, OFC 9.52; F p = 0.0516 -> holds: True

Result: reproduced. Attended value is significant in OFC (T = 5.86, one-sided p = 0.0019) with a CPD of 8.05% against 1.21% (ACC) and 0.14% (DLPFC), under all four readings.

fig4g-left-right-value¶

At cue 1, ACC and DLPFC representational similarity shows a value code modulated by whether the subject attends the left or right option.

In [25]:
def judge_lr(res_by_reading, tmpl="left/right value"):
    out = {}
    for o9, o8 in readings():
        r = res_by_reading[o9]
        ok = (sig(r, tmpl, 1, o8) and sig(r, tmpl, 2, o8) and cpdv(r, tmpl, 1) > cpdv(r, tmpl, 3)
              and cpdv(r, tmpl, 2) > cpdv(r, tmpl, 3))
        pv = (r['p1'] if o8 == 'one' else r['p2'])[IDX[tmpl]]
        print(f"O9 ({o9}) O8 {o8}-sided: T ACC/DLPFC/OFC {np.round(r['t'][IDX[tmpl]], 2)}, p {np.round(pv, 4)};"
              f" CPD % {np.round(100 * r['cpd'][IDX[tmpl]], 2)}; F p = {r['pF'][IDX[tmpl]]:.4f} -> holds: {ok}")
        out[(o9, o8)] = ok
    return out
LR_OK = judge_lr(RSA)
O9 (a) O8 one-sided: T ACC/DLPFC/OFC [6.05 6.51 0.07], p [0.0073 0.0036 0.4059]; CPD % [8.52 9.72 0.  ]; F p = 0.0038 -> holds: True
O9 (a) O8 two-sided: T ACC/DLPFC/OFC [6.05 6.51 0.07], p [0.0073 0.0036 0.9614]; CPD % [8.52 9.72 0.  ]; F p = 0.0038 -> holds: True
O9 (b) O8 one-sided: T ACC/DLPFC/OFC [ 4.7   5.02 -0.27], p [0.0155 0.0108 0.5089]; CPD % [5.32 6.03 0.02]; F p = 0.0105 -> holds: True
O9 (b) O8 two-sided: T ACC/DLPFC/OFC [ 4.7   5.02 -0.27], p [0.0155 0.0108 0.8393]; CPD % [5.32 6.03 0.02]; F p = 0.0105 -> holds: True

Result: reproduced. Left/right value is significant in ACC (T = 6.05, p = 0.0073) and DLPFC (T = 6.51, p = 0.0036) and absent in OFC (T = 0.07), with CPDs of 8.5% and 9.7% against 0.0%, under all four readings.

fig4h-acc-accept-reject¶

At cue 1, ACC representational similarity divides high-valued from low-valued cues, best explained as a categorical (accept/reject) function of value.

In [26]:
for o9, o8 in readings():
    r = RSA[o9]
    pv = r['p1'] if o8 == 'one' else r['p2']
    ra = cpdv(r, "accept/reject", 1) > cpdv(r, "attended value", 1)
    rb = sig(r, "accept/reject", 1, o8) and not sig(r, "attended value", 1, o8)
    ok = sig(r, "accept/reject", 1, o8) and cpdv(r, "accept/reject", 1) > cpdv(r, "accept/reject", 2) and (ra or rb)
    print(f"O9 ({o9}) O8 {o8}-sided: accept/reject T ACC/DLPFC/OFC {np.round(r['t'][IDX['accept/reject']], 2)},"
          f" p {np.round(pv[IDX['accept/reject']], 4)}, CPD % {np.round(100 * r['cpd'][IDX['accept/reject']], 2)};"
          f" attended value in ACC T {r['t'][IDX['attended value'], 0]:.2f}, p {pv[IDX['attended value'], 0]:.4f},"
          f" CPD % {100 * cpdv(r, 'attended value', 1):.2f}; (a) {ra}, (b) {rb} -> holds: {ok}")
O9 (a) O8 one-sided: accept/reject T ACC/DLPFC/OFC [10.3   4.39  8.71], p [0.     0.0101 0.0001], CPD % [21.26  4.67 16.19]; attended value in ACC T 2.19, p 0.0632, CPD % 1.21; (a) True, (b) True -> holds: True
O9 (a) O8 two-sided: accept/reject T ACC/DLPFC/OFC [10.3   4.39  8.71], p [0.     0.0136 0.0001], CPD % [21.26  4.67 16.19]; attended value in ACC T 2.19, p 0.1264, CPD % 1.21; (a) True, (b) True -> holds: True
O9 (b) O8 one-sided: accept/reject T ACC/DLPFC/OFC [9.57 3.97 6.94], p [0.0001 0.0142 0.0007], CPD % [18.91  3.85 10.92]; attended value in ACC T 3.54, p 0.0189, CPD % 3.09; (a) True, (b) False -> holds: True
O9 (b) O8 two-sided: accept/reject T ACC/DLPFC/OFC [9.57 3.97 6.94], p [0.0001 0.0194 0.0007], CPD % [18.91  3.85 10.92]; attended value in ACC T 3.54, p 0.0301, CPD % 3.09; (a) True, (b) False -> holds: True

Result: reproduced. Accept/reject is significant in ACC (T = 10.30, p < 0.0001) with a CPD of 21.3% against 4.7% in DLPFC, and it exceeds the attended value CPD in ACC (1.2%; reading a); the attended value template is not significant in ACC with all trials (p = 0.063) but is with 3 or more cues (p = 0.019). In OFC accept/reject has T = 8.71 and a CPD of 16.2%.

figs2-consistent-across-subjects¶

The triple dissociation of RSA matrices at cue 1 is consistent across the two monkeys.

Fig4_RSA.m, with the commented lines area(isfrank) = nan / area(ismiles) = nan that the script names for Supplementary Figure 2: the same RSA on each monkey's units.

In [27]:
CHECKS = [("spatial attention", 2), ("stimulus identity", 3), ("attended value", 3),
          ("left/right value", 1), ("left/right value", 2), ("accept/reject", 1)]
for o9 in ("a", "b"):
    hold = {}
    for sb in ["M", "F"]:
        mats = [rsa_unitmat([u for u in SEL[a] if info.loc[u, "subject"] == sb],
                            key="rsa" if o9 == "a" else "rsa3") for a in (1, 2, 3)]
        Y = np.column_stack([pfc7.rsa_matrix(M).ravel(order="F") for M in mats])
        b_, _, t_ = pfc7.ols(Y, DM, np.eye(7))
        vals = {f"{tm} {NAMES[a]}": b_[IDX[tm], a - 1] for tm, a in CHECKS}
        hold[sb] = sum(v > 0 for v in vals.values())
        print(f"O9 ({o9}) monkey {sb}, units {[m.shape[1] for m in mats]}: coefficients",
              {k: round(float(v), 4) for k, v in vals.items()})
    print(f"  positive of 6: {hold}")
O9 (a) monkey M, units [94, 37, 82]: coefficients {'spatial attention DLPFC': 0.152, 'stimulus identity OFC': 0.245, 'attended value OFC': 0.1404, 'left/right value ACC': 0.1772, 'left/right value DLPFC': 0.1399, 'accept/reject ACC': 0.1269}
O9 (a) monkey F, units [95, 97, 101]: coefficients {'spatial attention DLPFC': 0.4008, 'stimulus identity OFC': 0.278, 'attended value OFC': 0.0739, 'left/right value ACC': 0.0618, 'left/right value DLPFC': 0.074, 'accept/reject ACC': 0.1541}
  positive of 6: {'M': np.int64(6), 'F': np.int64(6)}
O9 (b) monkey M, units [94, 37, 82]: coefficients {'spatial attention DLPFC': 0.1534, 'stimulus identity OFC': 0.2446, 'attended value OFC': 0.1506, 'left/right value ACC': 0.164, 'left/right value DLPFC': 0.0919, 'accept/reject ACC': 0.1208}
O9 (b) monkey F, units [95, 97, 101]: coefficients {'spatial attention DLPFC': 0.3689, 'stimulus identity OFC': 0.2079, 'attended value OFC': 0.0847, 'left/right value ACC': 0.014, 'left/right value DLPFC': 0.0556, 'accept/reject ACC': 0.1342}
  positive of 6: {'M': np.int64(6), 'F': np.int64(6)}

Result: reproduced. In each monkey all six coefficients are positive under both trial readings (smallest 0.014, left/right value in ACC of F with 3 or more cues).

figs4-dlpfc-top-bottom¶

Split by top and bottom cue position (40 conditions), the RSA results replicate, and DLPFC similarity is also modulated by top/bottom position, so DLPFC represents spatial position more than left/right action.

40 conditions as calculate_RSA_matrices_updown.m (conditions 1-20 with cue 1 on top, 21-40 at the bottom; within each, LP, LM, RP, RM). The measure is the criterion's: mean similarity of pairs in the same quadrant against pairs on the same side in different rows, off the diagonal.

In [28]:
side = np.r_[np.zeros(10), np.ones(10), np.zeros(10), np.ones(10)]
row = np.r_[np.zeros(20), np.ones(20)]
same_q = (side[:, None] == side[None]) & (row[:, None] == row[None]) & ~np.eye(40, dtype=bool)
same_side_diff_row = (side[:, None] == side[None]) & (row[:, None] != row[None])
S4 = {}
for a in (1, 2, 3):
    M = pfc7.rsa_matrix(rsa_unitmat(SEL[a], field="m40"))
    S4[a] = M[same_q].mean() - M[same_side_diff_row].mean()
    print(f"{NAMES[a]}: same quadrant {M[same_q].mean():.4f}, same side other row "
          f"{M[same_side_diff_row].mean():.4f}, difference {S4[a]:.4f}; matrix range "
          f"{M[~np.eye(40, dtype=bool)].min():.2f} to {M[~np.eye(40, dtype=bool)].max():.2f}")
# null for the difference: permute the 40 condition labels within each unit set
rng = section_rng("figs4")
null = {a: [] for a in (1, 2, 3)}
for a in (1, 2, 3):
    X = rsa_unitmat(SEL[a], field="m40")
    for p in range(1000):
        M = pfc7.rsa_matrix(X[rng.permutation(40)])
        null[a].append(M[same_q].mean() - M[same_side_diff_row].mean())
    print(f"{NAMES[a]}: permutation p (one-sided, 1000 label permutations, a reference not in the criterion) "
          f"{np.mean(np.array(null[a]) >= S4[a]):.3f}")
print("criterion: DLPFC difference > 0 and larger than ACC and OFC:", S4[2] > 0 and S4[2] > S4[1] and S4[2] > S4[3])
ACC: same quadrant 0.0164, same side other row -0.0254, difference 0.0418; matrix range -0.38 to 0.38
DLPFC: same quadrant 0.1391, same side other row 0.0268, difference 0.1123; matrix range -0.36 to 0.39
OFC: same quadrant -0.0226, same side other row -0.0213, difference -0.0013; matrix range -0.35 to 0.42
ACC: permutation p (one-sided, 1000 label permutations, a reference not in the criterion) 0.022
DLPFC: permutation p (one-sided, 1000 label permutations, a reference not in the criterion) 0.000
OFC: permutation p (one-sided, 1000 label permutations, a reference not in the criterion) 0.464
criterion: DLPFC difference > 0 and larger than ACC and OFC: True

Result: reproduced. In the 40-condition matrices, pairs in the same quadrant are more similar than pairs on the same side in different rows by 0.112 in DLPFC, against 0.042 in ACC and -0.001 in OFC (a label-permutation reference, not part of the criterion, gives p < 0.001, 0.022 and 0.46).

fig4-t75-latencies¶

Spatial attention reached 75% of its peak CPD at about the saccade (24, 72 and 67 ms in ACC, DLPFC, OFC); stimulus identity and attended value in OFC (269, 241 ms) and accept/reject (238 ms ACC, 224 ms OFC) followed; left/right value came later (457 ms ACC, 369 ms DLPFC).

Fig4_RSA.m computes the RSA matrix at every 1 ms from 200 ms boxcar-smoothed condition means, the CPD of each template over time, and t75 with calculate_t75max.m over the whole epoch (-199 to 600 ms). Readings of the claims file: step (a) 10 ms, (b) 1 ms; range -100 to 500 ms, with -200 to 600 ms (the script's) reported.

In [29]:
TIMEIND = np.arange(-199, 601)
def sliding_rsa_cpd(units_by_area, dm):
    Ys = []
    for units in units_by_area:
        S = np.stack([U[u]["rsa"]["s20"] for u in units], axis=1)   # 20 x units x 800
        Yt = np.zeros((400, S.shape[2]))
        for k in range(S.shape[2]):
            Yt[:, k] = pfc7.rsa_matrix(S[:, :, k]).ravel(order="F")
        Ys.append(Yt)
    Yall = np.hstack(Ys)
    c = pfc7.cpd(Yall, dm) * 100
    return Yall, c.reshape(dm.shape[1], 3, -1)   # templates x areas x time
YT, CPDT = sliding_rsa_cpd([SEL[a] for a in (1, 2, 3)], DM)
EXP75 = [("spatial attention", 1, 24), ("spatial attention", 2, 72), ("spatial attention", 3, 67),
         ("stimulus identity", 3, 269), ("attended value", 3, 241), ("accept/reject", 1, 238),
         ("accept/reject", 3, 224), ("left/right value", 1, 457), ("left/right value", 2, 369)]
TOL75 = [10, 10, 10, 26.9, 24.1, 23.8, 22.4, 45.7, 36.9]
rows = []
for step in (10, 1):
    for lo, hi in ((-100, 500), (-200, 600)):
        sel = (TIMEIND >= lo) & (TIMEIND <= hi)
        idx = np.flatnonzero(sel)[::step]
        r = dict(step=step, range=f"{lo} to {hi}")
        nwithin = 0
        for (tm, a, e), tol in zip(EXP75, TOL75):
            v, tmax, mx = pfc7.t75(CPDT[IDX[tm], a - 1, idx], TIMEIND[idx])
            r[f"{tm} {NAMES[a]}"] = v
            nwithin += abs(v - e) <= tol
        r["within tolerance"] = nwithin
        rows.append(r)
T75 = pd.DataFrame(rows).set_index(["step", "range"])
print(T75.T)
print("expected:", {f"{tm} {NAMES[a]}": e for tm, a, e in EXP75})
peak = {f"{tm} {NAMES[a]}": round(float(CPDT[IDX[tm], a - 1].max()), 2) for tm, a, e in EXP75}
print("peak CPD (%) of each curve:", peak)
fig, ax = plt.subplots(1, 3, figsize=(13, 3.5))
for a in (1, 2, 3):
    for i in range(2, 7):
        ax[a - 1].plot(TIMEIND, CPDT[i, a - 1], label=TN[i])
    ax[a - 1].set_title(NAMES[a]); ax[a - 1].set_xlabel("ms after cue 1")
ax[0].legend(fontsize=7); ax[0].set_ylabel("CPD (%)")
plt.show()
print("CPD range plotted:", round(float(CPDT[2:].min()), 2), "to", round(float(CPDT[2:].max()), 2), "%")
step                             10                      1             
range                   -100 to 500 -200 to 600 -100 to 500 -200 to 600
spatial attention ACC          20.0        41.0        24.0        24.0
spatial attention DLPFC        80.0        81.0        72.0        72.0
spatial attention OFC          70.0        71.0        67.0        67.0
stimulus identity OFC         270.0       271.0       269.0       269.0
attended value OFC            250.0       241.0       241.0       241.0
accept/reject ACC             240.0       241.0       238.0       238.0
accept/reject OFC             230.0       231.0       224.0       224.0
left/right value ACC          470.0       471.0       457.0       457.0
left/right value DLPFC        360.0       381.0       358.0       369.0
within tolerance                9.0         8.0         9.0         9.0
expected: {'spatial attention ACC': 24, 'spatial attention DLPFC': 72, 'spatial attention OFC': 67, 'stimulus identity OFC': 269, 'attended value OFC': 241, 'accept/reject ACC': 238, 'accept/reject OFC': 224, 'left/right value ACC': 457, 'left/right value DLPFC': 369}
peak CPD (%) of each curve: {'spatial attention ACC': 56.74, 'spatial attention DLPFC': 83.96, 'spatial attention OFC': 34.38, 'stimulus identity OFC': 45.43, 'attended value OFC': 12.93, 'accept/reject ACC': 34.19, 'accept/reject OFC': 15.03, 'left/right value ACC': 19.28, 'left/right value DLPFC': 16.71}
No description has been provided for this image
CPD range plotted: 0.0 to 83.96 %

Result: reproduced. With the sliding RSA at every 1 ms (reading b), over -200 to 600 ms all nine t75 values equal the paper's to the millisecond (24, 72, 67, 269, 241, 238, 224, 457 and 369 ms). Over -100 to 500 ms at 1 ms eight are equal and DLPFC left/right value is 358 ms (paper 369, within tolerance). With a 10 ms step all nine are within tolerance over -100 to 500 ms.

figs5c-latency-order¶

Spatial attention is encoded significantly earlier than stimulus identity, attended value and accept/reject, and left/right value (in ACC and DLPFC) significantly later than the other variables.

Fig4_RSA.m: 100 simulations adding permuted residuals of the sliding template regression to its fitted values; the script draws one permutation of the 400 elements and applies it at every time point (reading (b)). Reading (a) draws one per time point. t75 over -199 to 600 ms at 1 ms, as the script. The variables compared in each region are those whose template is significant at 100-500 ms (one-sided permutation p < 0.05, O9 reading (a)).

In [30]:
rng = section_rng("figs5c")
Xb = DM @ np.linalg.pinv(DM) @ YT
RX = YT - Xb
sims = {"a": [], "b": []}
for rd in ("a", "b"):
    for p in range(100):
        if rd == "b":
            new = Xb + RX[rng.permutation(400)]
        else:
            perm = np.argsort(rng.random(RX.shape), axis=0)
            new = Xb + np.take_along_axis(RX, perm, axis=0)
        c = (pfc7.cpd(new, DM) * 100).reshape(7, 3, -1)
        sims[rd].append({(i, a): pfc7.t75(c[i, a - 1], TIMEIND)[0] for i in range(2, 7) for a in (1, 2, 3)})
# the script's set: the variables Fig4_RSA.m stacks for Supplementary Figure 5C (peak CPD above 10%)
SCRIPT_SET = {1: [IDX["accept/reject"], IDX["left/right value"]], 2: [IDX["left/right value"]],
              3: [IDX["attended value"], IDX["accept/reject"], IDX["stimulus identity"]]}
print("t75 point estimate (ms, 1 ms step, -199 to 600 ms) by template and area:",
      {f"{TN[i]} {NAMES[a]}": float(pfc7.t75(CPDT[i, a - 1], TIMEIND)[0]) for i in range(2, 7) for a in (1, 2, 3)})
print("significant at 100-500 ms (one-sided p < 0.05, reading (a)):",
      [f"{TN[i]} {NAMES[a]}" for i in range(2, 7) for a in (1, 2, 3) if RSA["a"]["p1"][i, a - 1] < 0.05])
print("peak CPD (%) by template and area:", {f"{TN[i]} {NAMES[a]}": round(float(CPDT[i, a - 1].max()), 1)
                                              for i in range(2, 7) for a in (1, 2, 3)})
for rd, vset in [(r_, v_) for r_ in ("a", "b") for v_ in ("significant", "script")]:
    df = pd.DataFrame(sims[rd])
    print(f"--- reading ({rd}), variables {vset}: t75 range (min to max over 100 simulations), ms")
    ok_all = True
    for a in (1, 2, 3):
        if vset == "script":
            keep_v = SCRIPT_SET[a]
        else:
            keep_v = [i for i in (2, 3, 4) if RSA["a"]["p1"][i, a - 1] < 0.05]
            if a in (1, 2) and RSA["a"]["p1"][IDX["left/right value"], a - 1] < 0.05:
                keep_v.append(IDX["left/right value"])
        rng_ = {TN[i]: (df[(i, a)].min(), df[(i, a)].max()) for i in [IDX["spatial attention"]] + keep_v}
        print(NAMES[a], {k: (float(v[0]), float(v[1])) for k, v in rng_.items()})
        sp = rng_["spatial attention"]
        others = [v for k, v in rng_.items() if k not in ("spatial attention", "left/right value")]
        early = all(sp[1] < o[0] for o in others)
        late = True
        if "left/right value" in rng_:
            lr = rng_["left/right value"]
            late = all(lr[0] > v[1] for k, v in rng_.items() if k != "left/right value")
        elif a in (1, 2):
            late = False
        print(f"   spatial attention below all others: {early}; left/right value above all others: {late}")
        ok_all &= early and late
    print(f"reading ({rd}), variables {vset}: criterion holds in every region: {ok_all}")
t75 point estimate (ms, 1 ms step, -199 to 600 ms) by template and area: {'stimulus identity ACC': 262.0, 'stimulus identity DLPFC': 277.0, 'stimulus identity OFC': 269.0, 'attended value ACC': 164.0, 'attended value DLPFC': 249.0, 'attended value OFC': 241.0, 'accept/reject ACC': 238.0, 'accept/reject DLPFC': 491.0, 'accept/reject OFC': 224.0, 'spatial attention ACC': 24.0, 'spatial attention DLPFC': 72.0, 'spatial attention OFC': 67.0, 'left/right value ACC': 457.0, 'left/right value DLPFC': 369.0, 'left/right value OFC': -193.0}
significant at 100-500 ms (one-sided p < 0.05, reading (a)): ['stimulus identity ACC', 'stimulus identity DLPFC', 'stimulus identity OFC', 'attended value OFC', 'accept/reject ACC', 'accept/reject DLPFC', 'accept/reject OFC', 'spatial attention ACC', 'spatial attention DLPFC', 'spatial attention OFC', 'left/right value ACC', 'left/right value DLPFC']
peak CPD (%) by template and area: {'stimulus identity ACC': 5.8, 'stimulus identity DLPFC': 9.0, 'stimulus identity OFC': 45.4, 'attended value ACC': 6.7, 'attended value DLPFC': 2.5, 'attended value OFC': 12.9, 'accept/reject ACC': 34.2, 'accept/reject DLPFC': 13.8, 'accept/reject OFC': 15.0, 'spatial attention ACC': 56.7, 'spatial attention DLPFC': 84.0, 'spatial attention OFC': 34.4, 'left/right value ACC': 19.3, 'left/right value DLPFC': 16.7, 'left/right value OFC': 1.9}
--- reading (a), variables significant: t75 range (min to max over 100 simulations), ms
ACC {'spatial attention': (4.0, 45.0), 'stimulus identity': (121.0, 342.0), 'accept/reject': (229.0, 272.0), 'left/right value': (252.0, 492.0)}
   spatial attention below all others: True; left/right value above all others: False
DLPFC {'spatial attention': (69.0, 75.0), 'stimulus identity': (-196.0, 433.0), 'accept/reject': (269.0, 537.0), 'left/right value': (319.0, 399.0)}
   spatial attention below all others: False; left/right value above all others: False
OFC {'spatial attention': (13.0, 93.0), 'stimulus identity': (261.0, 284.0), 'attended value': (-10.0, 286.0), 'accept/reject': (190.0, 442.0)}
   spatial attention below all others: False; left/right value above all others: True
reading (a), variables significant: criterion holds in every region: False
--- reading (a), variables script: t75 range (min to max over 100 simulations), ms
ACC {'spatial attention': (4.0, 45.0), 'accept/reject': (229.0, 272.0), 'left/right value': (252.0, 492.0)}
   spatial attention below all others: True; left/right value above all others: False
DLPFC {'spatial attention': (69.0, 75.0), 'left/right value': (319.0, 399.0)}
   spatial attention below all others: True; left/right value above all others: True
OFC {'spatial attention': (13.0, 93.0), 'attended value': (-10.0, 286.0), 'accept/reject': (190.0, 442.0), 'stimulus identity': (261.0, 284.0)}
   spatial attention below all others: False; left/right value above all others: True
reading (a), variables script: criterion holds in every region: False
--- reading (b), variables significant: t75 range (min to max over 100 simulations), ms
ACC {'spatial attention': (9.0, 93.0), 'stimulus identity': (-132.0, 474.0), 'accept/reject': (227.0, 291.0), 'left/right value': (246.0, 528.0)}
   spatial attention below all others: False; left/right value above all others: False
DLPFC {'spatial attention': (69.0, 79.0), 'stimulus identity': (-198.0, 453.0), 'accept/reject': (268.0, 536.0), 'left/right value': (330.0, 515.0)}
   spatial attention below all others: False; left/right value above all others: False
OFC {'spatial attention': (13.0, 99.0), 'stimulus identity': (249.0, 304.0), 'attended value': (-13.0, 367.0), 'accept/reject': (-10.0, 437.0)}
   spatial attention below all others: False; left/right value above all others: True
reading (b), variables significant: criterion holds in every region: False
--- reading (b), variables script: t75 range (min to max over 100 simulations), ms
ACC {'spatial attention': (9.0, 93.0), 'accept/reject': (227.0, 291.0), 'left/right value': (246.0, 528.0)}
   spatial attention below all others: True; left/right value above all others: False
DLPFC {'spatial attention': (69.0, 79.0), 'left/right value': (330.0, 515.0)}
   spatial attention below all others: True; left/right value above all others: True
OFC {'spatial attention': (13.0, 99.0), 'attended value': (-13.0, 367.0), 'accept/reject': (-10.0, 437.0), 'stimulus identity': (249.0, 304.0)}
   spatial attention below all others: False; left/right value above all others: True
reading (b), variables script: criterion holds in every region: False

Result: not reproduced. The criterion asks for the spatial attention range to lie below every other kept variable and, in ACC and DLPFC, the left/right value range above every other, under one reading; no reading gives this. In OFC the attended value range reaches down to -10 ms (reading a) or -13 ms (reading b), below the top of the spatial attention range (93 or 99 ms). In ACC left/right value (252 to 492 ms, reading a; 246 to 528 ms, reading b) overlaps accept/reject (229 to 272 ms; 227 to 291 ms). Parts hold: in DLPFC, with the script's set of variables, spatial attention lies below left/right value and left/right value above it under both readings, and in ACC spatial attention lies below the other kept variables with the script's set. The test fails in at least two of the three regions under every reading, so the outcome is not reproduced; in figs1ab-cue-weights, by contrast, one component fails in one monkey and the rest holds, which is partially reproduced. The t75 point estimates of the nine claimed curves follow the paper's order. With all the significant templates, in DLPFC accept/reject (491 ms) comes after left/right value (369 ms); the other regions keep the order (ACC: spatial attention 24 ms, accept/reject 238, stimulus identity 262, left/right value 457; OFC: spatial attention 67, accept/reject 224, attended value 241, stimulus identity 269).

GLM claims (Figures 5 to 7)¶

T-statistics of the shared GLM for every unit (fitted above). Bin indices: the bin centred at 250 ms after a cue is index 35, at 300 ms index 40; response locked, the bin centred at -200 ms is index 30 (the scripts' ttR(30, ...), 1-based, is the bin centred at -210 ms; both are shown where they matter). Contrast numbers are the GLM script's (19 = EV1 + EV5, 20 = EV2 + EV6).

In [31]:
B250, B300 = int(np.flatnonzero(pfc7.TIMEBINS == 250)[0]), int(np.flatnonzero(pfc7.TIMEBINS == 300)[0])
def tst(units, ep, con, b, kind="t"):
    """T-statistic (or `kind`='b' the contrast estimate) of contrast number `con` at bin `b`."""
    return np.array([G[u][kind + ep][con - 1, b] for u in units])
def tmean(units, ep, evs, b):
    """Reading (a): the mean of the EVs' T-statistics."""
    return np.mean([tst(units, ep, e, b) for e in evs], axis=0)
def pear(x, y):
    ok = np.isfinite(x) & np.isfinite(y)
    r, p = stats.pearsonr(x[ok], y[ok])
    return r, p, int(ok.sum())

fig5a-ofc-value-cpd¶

Value encoding by OFC neurons peaked about 300 ms after each cue was revealed and stayed above baseline as further cues were attended.

Mean CPD across OFC neurons (Fig5_OFCcrosscorrelation.m plots cpd1(area==3, 1, :) and so on, the option-trial EVs). Readings (a) mean of the CPDs of the option and attribute EVs of a cue; (b) each trial type separately.

In [32]:
ofc = SEL5[3]
CP = {ep: np.nanmean([G[u]["cpd" + ep] for u in ofc], axis=0) * 100 for ep in ("X1", "X2", "X3")}
EVSETS = {"a": {1: [0, 4], 2: [1, 5], 3: [2, 6, 8]}, "b-option": {1: [0], 2: [1], 3: [2]},
          "b-attribute": {1: [4], 2: [5], 3: [6, 8]}}
post = pfc7.TIMEBINS >= 0
for rd, sets in EVSETS.items():
    curves = {(c, ep): CP[ep][sets[c]].mean(0) for c in (1, 2, 3) for ep in ("X1", "X2", "X3")}
    peaks = {c: int(pfc7.TIMEBINS[post][np.argmax(curves[(c, f"X{c}")][post])]) for c in (1, 2, 3)}
    for bl in ("i", "ii"):
        base_v = {c: (curves[(1, "X1")][0] if bl == "i" else curves[(c, "X1")][pfc7.TIMEBINS <= 0].mean())
                  for c in (1, 2)}
        above_all = (bool((curves[(1, "X2")] > base_v[1]).all() and (curves[(1, "X3")] > base_v[1]).all()
                          and (curves[(2, "X3")] > base_v[2]).all()))
        means = {f"cue{c} in X{e}": round(float(curves[(c, f'X{e}')].mean() - base_v[c]), 3)
                 for c, e in ((1, 2), (1, 3), (2, 3))}
        within = all(abs(peaks[c] - 300) <= 30 for c in (1, 2, 3))
        print(f"reading ({rd}), baseline ({bl}): peaks after own onset {peaks} ms; baselines "
              f"{ {c: round(float(v), 3) for c, v in base_v.items()} } %; above baseline at every later bin: "
              f"{above_all}; epoch mean minus baseline {means} -> holds: {within and above_all}")
fig, ax = plt.subplots(1, 3, figsize=(12, 3), sharey=True)
for k, ep in enumerate(("X1", "X2", "X3")):
    for c in (1, 2, 3):
        ax[k].plot(pfc7.TIMEBINS, CP[ep][EVSETS["a"][c]].mean(0), label=f"cue {c} value")
    ax[k].set_title(f"locked to cue {k + 1}"); ax[k].set_xlabel("ms")
ax[0].legend(); ax[0].set_ylabel("mean CPD (%), OFC")
plt.show()
print("plotted range:", round(min(CP[ep][[0, 1, 2, 4, 5, 6, 8]].min() for ep in CP), 3), "to",
      round(max(CP[ep][[0, 1, 2, 4, 5, 6, 8]].max() for ep in CP), 3))
reading (a), baseline (i): peaks after own onset {1: 290, 2: 300, 3: 290} ms; baselines {1: 0.342, 2: 0.342} %; above baseline at every later bin: True; epoch mean minus baseline {'cue1 in X2': 0.495, 'cue1 in X3': 0.18, 'cue2 in X3': 0.491} -> holds: True
reading (a), baseline (ii): peaks after own onset {1: 290, 2: 300, 3: 290} ms; baselines {1: 0.344, 2: 0.318} %; above baseline at every later bin: True; epoch mean minus baseline {'cue1 in X2': 0.493, 'cue1 in X3': 0.178, 'cue2 in X3': 0.515} -> holds: True
reading (b-option), baseline (i): peaks after own onset {1: 290, 2: 300, 3: 290} ms; baselines {1: 0.317, 2: 0.317} %; above baseline at every later bin: True; epoch mean minus baseline {'cue1 in X2': 0.501, 'cue1 in X3': 0.248, 'cue2 in X3': 0.514} -> holds: True
reading (b-option), baseline (ii): peaks after own onset {1: 290, 2: 300, 3: 290} ms; baselines {1: 0.327, 2: 0.283} %; above baseline at every later bin: True; epoch mean minus baseline {'cue1 in X2': 0.491, 'cue1 in X3': 0.238, 'cue2 in X3': 0.548} -> holds: True
reading (b-attribute), baseline (i): peaks after own onset {1: 320, 2: 310, 3: 320} ms; baselines {1: 0.367, 2: 0.367} %; above baseline at every later bin: True; epoch mean minus baseline {'cue1 in X2': 0.488, 'cue1 in X3': 0.111, 'cue2 in X3': 0.467} -> holds: True
reading (b-attribute), baseline (ii): peaks after own onset {1: 320, 2: 310, 3: 320} ms; baselines {1: 0.362, 2: 0.353} %; above baseline at every later bin: True; epoch mean minus baseline {'cue1 in X2': 0.494, 'cue1 in X3': 0.117, 'cue2 in X3': 0.482} -> holds: True
No description has been provided for this image
plotted range: 0.257 to 2.063

Result: reproduced. The mean OFC CPD of each cue's value peaks 290, 300 and 290 ms after the cue's own onset (reading a), and the cue 1 and cue 2 value CPDs stay above either baseline at every bin of the later cue epochs (epoch means 0.18 to 0.52 points above baseline).

fig5b-stable-attended-value-subspace¶

In OFC, T-statistics for cue 1 value at cue 1 correlate positively across neurons with those for cue 2 value at cue 2, a stable subspace for the currently attended value.

Fig5_OFCcrosscorrelation.m correlates contrast 19 at cue 1 with contrast 20 at cue 2 (reading (b)); reading (a) averages the T-statistics.

In [33]:
def c5b(units):
    ra = pear(tmean(units, "X1", [1, 5], B250), tmean(units, "X2", [2, 6], B250))
    rb = pear(tst(units, "X1", 19, B250), tst(units, "X2", 20, B250))
    return ra, rb
for a in (3, 2, 1):
    ra, rb = c5b(SEL5[a])
    print(f"{NAMES[a]}: (a) r = {ra[0]:.3f}, p = {ra[1]:.2g}, n = {ra[2]};  (b) r = {rb[0]:.3f}, p = {rb[1]:.2g}")
for sb in ("M", "F"):
    ra, rb = c5b([u for u in SEL5[3] if info.loc[u, "subject"] == sb])
    print(f"OFC monkey {sb}: (b) r = {rb[0]:.3f}, p = {rb[1]:.2g}, n = {rb[2]}")
OFC: (a) r = 0.843, p = 2.4e-50, n = 182;  (b) r = 0.845, p = 7.7e-51
DLPFC: (a) r = 0.658, p = 5.4e-18, n = 134;  (b) r = 0.658, p = 6.1e-18
ACC: (a) r = 0.851, p = 3.7e-54, n = 189;  (b) r = 0.852, p = 1.8e-54
OFC monkey M: (b) r = 0.860, p = 7.9e-25, n = 81
OFC monkey F: (b) r = 0.809, p = 1.5e-24, n = 101

Result: reproduced. In OFC the cue 1 value T-statistics at cue 1 correlate with the cue 2 value T-statistics at cue 2, r = 0.845 (p = 7.7e-51, n = 182; reading a r = 0.843), in each monkey (r = 0.860 and 0.809).

fig5c-attribute-cue2-vs-cue1¶

In OFC, at cue 2 of attribute trials, the attended cue 2 value subspace correlates negatively with the stored cue 1 value subspace (the other option).

In [34]:
CORR5 = {}
for a in (1, 2, 3):
    u = SEL5[a]
    CORR5[a] = {"6v5@2": pear(tst(u, "X2", 6, B250), tst(u, "X2", 5, B250)),
                "3v1@3": pear(tst(u, "X3", 3, B250), tst(u, "X3", 1, B250)),
                "3v2@3": pear(tst(u, "X3", 3, B250), tst(u, "X3", 2, B250)),
                "1v2@3": pear(tst(u, "X3", 1, B250), tst(u, "X3", 2, B250)),
                "1v2@2": pear(tst(u, "X2", 1, B250), tst(u, "X2", 2, B250))}
print(pd.DataFrame({NAMES[a]: {k: f"r={v[0]:.3f} p={v[1]:.2g} n={v[2]}" for k, v in CORR5[a].items()}
                    for a in (3, 2, 1)}))
for sb in ("M", "F"):
    u = [x for x in SEL5[3] if info.loc[x, "subject"] == sb]
    print(f"OFC monkey {sb}: EV6 vs EV5 at cue 2 r = {pear(tst(u, 'X2', 6, B250), tst(u, 'X2', 5, B250))[0]:.3f}")
                            OFC                    DLPFC                    ACC
6v5@2  r=-0.270 p=0.00023 n=182    r=-0.040 p=0.64 n=134   r=0.031 p=0.67 n=189
3v1@3  r=-0.283 p=0.00011 n=182    r=-0.080 p=0.36 n=134   r=0.084 p=0.25 n=189
3v2@3  r=-0.379 p=1.3e-07 n=182    r=-0.105 p=0.23 n=134   r=0.058 p=0.43 n=189
1v2@3   r=0.523 p=3.4e-14 n=182  r=0.519 p=1.3e-10 n=134  r=0.559 p=6e-17 n=189
1v2@2     r=-0.033 p=0.66 n=182   r=-0.188 p=0.029 n=134   r=0.037 p=0.61 n=189
OFC monkey M: EV6 vs EV5 at cue 2 r = -0.236
OFC monkey F: EV6 vs EV5 at cue 2 r = -0.356

Result: reproduced. In OFC at cue 2 of attribute trials, EV 6 and EV 5 correlate negatively, r = -0.270 (p = 0.00023, n = 182); M r = -0.236, F r = -0.356.

fig5de-option-cue3-vs-stored¶

In OFC, at cue 3 of option trials, the attended cue 3 value subspace correlates negatively with both the stored cue 1 and the stored cue 2 value subspaces.

In [35]:
for k in ("3v1@3", "3v2@3"):
    r, p, n = CORR5[3][k]
    print(f"OFC EV{k[0]} vs EV{k[2]} at cue 3: r = {r:.3f}, p = {p:.2g}, n = {n}; negative with p < 0.05: {r < 0 and p < 0.05}")
OFC EV3 vs EV1 at cue 3: r = -0.283, p = 0.00011, n = 182; negative with p < 0.05: True
OFC EV3 vs EV2 at cue 3: r = -0.379, p = 1.3e-07, n = 182; negative with p < 0.05: True

Result: reproduced. In OFC at cue 3 of option trials, EV 3 correlates negatively with EV 1 (r = -0.283, p = 0.00011) and with EV 2 (r = -0.379, p = 1.3e-07).

fig5f-option-stored-combined¶

In OFC, at cue 3 of option trials, the stored cue 1 and stored cue 2 value subspaces correlate positively, so the two previously attended cues are combined.

In [36]:
for k in ("1v2@3", "1v2@2"):
    r, p, n = CORR5[3][k]
    print(f"OFC EV1 vs EV2 at cue {k[-1]}: r = {r:.3f}, p = {p:.2g}, n = {n}")
OFC EV1 vs EV2 at cue 3: r = 0.523, p = 3.4e-14, n = 182
OFC EV1 vs EV2 at cue 2: r = -0.033, p = 0.66, n = 182

Result: reproduced. At cue 3 of option trials EV 1 and EV 2 correlate positively in OFC (r = 0.523, p = 3.4e-14); at cue 2 they do not (r = -0.033, p = 0.66), as the Discussion says.

fig5gj-cross-correlation-dynamics¶

Cross-correlating the OFC value subspaces across time shows the same population subspace shifting its value encoding from positive to negative as the subject saccades around the screen.

Fig5_OFCcrosscorrelation.m and cross_corr_tstats.m: for each of four EV pairs (EV6/EV5, EV2/EV1, EV3/EV1, EV3/EV2) the correlation across OFC neurons of the T-statistics at every pair of bins, for every pair of cue epochs (rows: the first EV's epoch). The script computes each pair of epochs as its own 61 x 61 map, with its own null: clusters of |r| > 0.2, 8-connected (bwconncomp), significant when larger than the 99.9th percentile of the largest cluster in 1000 permutations of the neurons of the second EV. All nine blocks of each map are computed. As a variant, each map is also computed as one 183 x 183 map over the three epochs with a single null, the reading of the criterion's "every pair of time points over the cue 1, 2 and 3 epochs" that the verifier raised.

In [37]:
rng = section_rng("fig5gj")
EPS = ("X1", "X2", "X3")
def tmat(units, ep, ev):
    return np.stack([G[u]["t" + ep][ev - 1] for u in units])   # neurons x bins
def ccmat(A, B):
    A = (A - A.mean(0)) / A.std(0); B = (B - B.mean(0)) / B.std(0)
    return A.T @ B / A.shape[0]
def cluster_test(A, B, thr=0.2, nperm=1000):
    """cross_corr_tstats.m: map, clusters of |r| > thr (8-connected, as bwconncomp), and the
    99.9th percentile of the largest cluster over `nperm` permutations of B's neurons."""
    cm = ccmat(A, B)
    lab, n = pfc7.clusters(np.abs(cm) > thr)
    sizes = np.bincount(lab.ravel())[1:]
    null = np.zeros(nperm)
    for p in range(nperm):
        cp = ccmat(A, B[rng.permutation(B.shape[0])])
        l2, n2 = pfc7.clusters(np.abs(cp) > thr)
        null[p] = np.bincount(l2.ravel())[1:].max() if n2 else 0
    crit = np.percentile(null, 99.9)
    return cm, lab, sizes, crit
def at_point(res, i, j):
    """Size of the cluster through bin (i, j), whether it passes, and r there."""
    cm, lab, sizes, crit = res
    l = lab[i, j]
    return (int(sizes[l - 1]) if l else 0), bool(l and sizes[l - 1] > crit), float(cm[i, j])
units = SEL5[3]
PAIRS = [(6, 5, "X2", "X2"), (2, 1, "X3", "X3"), (3, 1, "X3", "X3"), (3, 2, "X3", "X3")]
SIGN = {(6, 5): -1, (2, 1): 1, (3, 1): -1, (3, 2): -1}
# Fig5_OFCcrosscorrelation.m: each pair of cue epochs is its own 61 x 61 map with its own null
BLOCKS = {}
rows = []
for e1, e2, _, _ in PAIRS:
    for ep1 in EPS:
        for ep2 in EPS:
            res = cluster_test(tmat(units, ep1, e1), tmat(units, ep2, e2))
            BLOCKS[(e1, e2, ep1, ep2)] = res
            cm, lab, sizes, crit = res
            sgn = np.array([np.sign(cm[lab == k + 1].mean()) for k in range(len(sizes))])
            big = sizes > crit
            rows.append(dict(map=f"EV{e1} x EV{e2}", rows=ep1, cols=ep2, threshold=round(crit),
                             n_sig_clusters=int(big.sum()), largest_pos=int(sizes[big & (sgn > 0)].max(initial=0)),
                             largest_neg=int(sizes[big & (sgn < 0)].max(initial=0)),
                             r_250=round(float(cm[B250, B250]), 3)))
print("every block of the four maps (clusters larger than the block's 99.9th percentile):")
print(pd.DataFrame(rows).to_string(index=False))
GJ = {}
for e1, e2, ep1, ep2 in PAIRS:
    size, sig_, r = at_point(BLOCKS[(e1, e2, ep1, ep2)], B250, B250)
    GJ[(e1, e2)] = sig_ and np.sign(r) == SIGN[(e1, e2)]
    print(f"EV{e1} ({ep1}) x EV{e2} ({ep2}): r at (250, 250) = {r:.3f}; cluster there of {size} bins, threshold "
          f"{BLOCKS[(e1, e2, ep1, ep2)][3]:.0f}; significant with the expected sign: {GJ[(e1, e2)]}")
size, sig_, r = at_point(BLOCKS[(6, 5, "X2", "X1")], B250, B250)
pos_early = sig_ and r > 0
print(f"EV6 (cue 2) x EV5 (cue 1): r at (250, 250) = {r:.3f}; cluster {size} bins, "
      f"threshold {BLOCKS[(6, 5, 'X2', 'X1')][3]:.0f}; significant positive: {pos_early}")
print("criterion holds (separate blocks, as the script):", all(GJ.values()) and pos_early)
# Variant: one 183 x 183 map over the three epochs (cue 1, 2, 3 bins concatenated), one null
nb = len(pfc7.TIMEBINS)
off = {ep: k * nb for k, ep in enumerate(EPS)}
FULL = {}
for e1, e2, _, _ in PAIRS:
    FULL[(e1, e2)] = cluster_test(np.hstack([tmat(units, ep, e1) for ep in EPS]),
                                  np.hstack([tmat(units, ep, e2) for ep in EPS]))
ok_full = []
for e1, e2, ep1, ep2 in PAIRS:
    size, sig_, r = at_point(FULL[(e1, e2)], off[ep1] + B250, off[ep2] + B250)
    ok_full.append(sig_ and np.sign(r) == SIGN[(e1, e2)])
    print(f"183 x 183 map EV{e1} x EV{e2}: cluster through ({ep1} 250, {ep2} 250) {size} bins, threshold "
          f"{FULL[(e1, e2)][3]:.0f}, expected sign and significant: {ok_full[-1]}")
size, sig_, r = at_point(FULL[(6, 5)], off["X2"] + B250, off["X1"] + B250)
ok_full.append(sig_ and r > 0)
print(f"183 x 183 map EV6 x EV5: cluster through (X2 250, X1 250) {size} bins, r = {r:.3f}, significant positive: {ok_full[-1]}")
print("criterion holds (one map over the three epochs):", all(ok_full))
# The two cue 3 option maps pass the single-map variant by narrow margins: their thresholds with
# 10 other seeds (1000 permutations each) and with 10000 permutations
for e1, e2 in ((3, 1), (3, 2)):
    A_ = np.hstack([tmat(units, ep, e1) for ep in EPS]); B_ = np.hstack([tmat(units, ep, e2) for ep in EPS])
    size = at_point(FULL[(e1, e2)], off["X3"] + B250, off["X3"] + B250)[0]
    crits = []
    for sd in range(10):
        rng = np.random.default_rng(sd)
        crits.append(cluster_test(A_, B_)[3])
    rng = section_rng("fig5gj-10000")
    c10k = cluster_test(A_, B_, nperm=10000)[3]
    print(f"183 x 183 map EV{e1} x EV{e2}: cluster {size} bins; thresholds over 10 seeds {min(crits):.0f} to "
          f"{max(crits):.0f}, passing in {sum(size > c for c in crits)} of 10; with 10000 permutations {c10k:.0f}, "
          f"passing {size > c10k}")
fig, ax = plt.subplots(1, 4, figsize=(14, 3.6))
for k, (e1, e2, _, _) in enumerate(PAIRS):
    m = FULL[(e1, e2)][0]
    ax[k].imshow(m, vmin=-0.3, vmax=0.3, cmap="RdBu_r", origin="lower")
    for x in (nb, 2 * nb):
        ax[k].axhline(x - 0.5, color="k", lw=0.5); ax[k].axvline(x - 0.5, color="k", lw=0.5)
    ax[k].set_title(f"EV{e1} x EV{e2}, cues 1-3 (range {m.min():.2f} to {m.max():.2f})", fontsize=8)
    ax[k].set_xlabel(f"EV{e2}: cue 1, 2, 3 epochs", fontsize=7); ax[k].set_ylabel(f"EV{e1}: cue 1, 2, 3 epochs", fontsize=7)
plt.show()
every block of the four maps (clusters larger than the block's 99.9th percentile):
      map rows cols  threshold  n_sig_clusters  largest_pos  largest_neg  r_250
EV6 x EV5   X1   X1        385               0            0            0  0.154
EV6 x EV5   X1   X2        300               0            0            0  0.077
EV6 x EV5   X1   X3        396               0            0            0  0.003
EV6 x EV5   X2   X1        640               1         1622            0  0.755
EV6 x EV5   X2   X2        442               2          755          884 -0.270
EV6 x EV5   X2   X3        393               0            0            0  0.099
EV6 x EV5   X3   X1        593               1          934            0 -0.150
EV6 x EV5   X3   X2        431               1         2072            0  0.399
EV6 x EV5   X3   X3        624               0            0            0  0.006
EV2 x EV1   X1   X1        388               0            0            0 -0.018
EV2 x EV1   X1   X2        354               0            0            0  0.096
EV2 x EV1   X1   X3        291               0            0            0  0.079
EV2 x EV1   X2   X1        588               1         1589            0  0.781
EV2 x EV1   X2   X2        520               1          887            0 -0.033
EV2 x EV1   X2   X3        546               1            0          620 -0.257
EV2 x EV1   X3   X1        577               1          825            0 -0.270
EV2 x EV1   X3   X2        414               1         1687            0  0.333
EV2 x EV1   X3   X3        444               1         1839            0  0.523
EV3 x EV1   X1   X1        283               0            0            0  0.065
EV3 x EV1   X1   X2        410               0            0            0 -0.059
EV3 x EV1   X1   X3        522               0            0            0 -0.037
EV3 x EV1   X2   X1        417               0            0            0 -0.168
EV3 x EV1   X2   X2        443               0            0            0  0.003
EV3 x EV1   X2   X3        355               0            0            0 -0.020
EV3 x EV1   X3   X1        398               1         1479            0  0.771
EV3 x EV1   X3   X2        581               1          793            0 -0.134
EV3 x EV1   X3   X3        453               1            0         1105 -0.283
EV3 x EV2   X1   X1        283               0            0            0  0.012
EV3 x EV2   X1   X2        391               0            0            0  0.075
EV3 x EV2   X1   X3        389               0            0            0 -0.126
EV3 x EV2   X2   X1        401               0            0            0 -0.004
EV3 x EV2   X2   X2        614               0            0            0 -0.141
EV3 x EV2   X2   X3        359               0            0            0 -0.046
EV3 x EV2   X3   X1        477               0            0            0 -0.089
EV3 x EV2   X3   X2        506               1         1490            0  0.739
EV3 x EV2   X3   X3        487               2          796          817 -0.379
EV6 (X2) x EV5 (X2): r at (250, 250) = -0.270; cluster there of 884 bins, threshold 442; significant with the expected sign: True
EV2 (X3) x EV1 (X3): r at (250, 250) = 0.523; cluster there of 1839 bins, threshold 444; significant with the expected sign: True
EV3 (X3) x EV1 (X3): r at (250, 250) = -0.283; cluster there of 1105 bins, threshold 453; significant with the expected sign: True
EV3 (X3) x EV2 (X3): r at (250, 250) = -0.379; cluster there of 817 bins, threshold 487; significant with the expected sign: True
EV6 (cue 2) x EV5 (cue 1): r at (250, 250) = 0.755; cluster 1622 bins, threshold 640; significant positive: True
criterion holds (separate blocks, as the script): True
183 x 183 map EV6 x EV5: cluster through (X2 250, X2 250) 1943 bins, threshold 1414, expected sign and significant: True
183 x 183 map EV2 x EV1: cluster through (X3 250, X3 250) 6827 bins, threshold 1056, expected sign and significant: True
183 x 183 map EV3 x EV1: cluster through (X3 250, X3 250) 1105 bins, threshold 1083, expected sign and significant: True
183 x 183 map EV3 x EV2: cluster through (X3 250, X3 250) 817 bins, threshold 810, expected sign and significant: True
183 x 183 map EV6 x EV5: cluster through (X2 250, X1 250) 5741 bins, r = 0.755, significant positive: True
criterion holds (one map over the three epochs): True
183 x 183 map EV3 x EV1: cluster 1105 bins; thresholds over 10 seeds 783 to 1212, passing in 7 of 10; with 10000 permutations 984, passing True
183 x 183 map EV3 x EV2: cluster 817 bins; thresholds over 10 seeds 853 to 1262, passing in 0 of 10; with 10000 permutations 990, passing False
No description has been provided for this image

Result: reproduced. With each pair of epochs as its own 61 x 61 map and null, as the script computes them, each of the four maps has a cluster through the 250 ms point of its cue of the expected sign and larger than the 99.9th percentile of 1000 permutations (884, 1839, 1105 and 817 bins against thresholds of 442 to 487), and EV 6 at cue 2 with EV 5 at cue 1 forms a positive cluster (r = 0.755 at 250, 250 ms; 1622 bins against 640). With one 183 x 183 map over the three epochs and a single null, the criterion also holds, with narrow margins for the two cue 3 option maps (EV 3 with EV 1, 1105 bins against 1083; EV 3 with EV 2, 817 against 810). That variant depends on the seed: with 10 other seeds the EV 3 with EV 2 cluster passes in 0 of 10 (thresholds 853 to 1262) and fails with 10000 permutations (threshold 990); EV 3 with EV 1 passes in 7 of 10 and with 10000 permutations (984). So the single-map reading does not hold, and the outcome rests on the script's separate maps, which pass by wide margins.

fig5k-ofc-comparison-unique¶

The value comparison correlations of Figure 5c-e are stronger in OFC than in DLPFC (p = 0.040, 0.067, 0.011) and than in ACC (p = 0.003, 0.0003, 0.00013), by Fisher r-to-Z tests.

Fig5_OFCcrosscorrelation.m tests two-sided (reading (a) of O1), with n the region's units.

In [38]:
rows = []
for k in ("6v5@2", "3v1@3", "3v2@3"):
    for other in (2, 1):
        r_o, n_o = CORR5[3][k][0], len(SEL5[3])
        r_x, n_x = CORR5[other][k][0], len(SEL5[other])
        z, p2 = pfc7.fisher_z(r_o, n_o, r_x, n_x)
        rows.append(dict(corr=k, versus=NAMES[other], r_OFC=r_o, r_other=r_x, z=z, p_two=p2,
                         p_one=stats.norm.cdf(z), ofc_more_negative=r_o < r_x))
f5k = pd.DataFrame(rows)
print(f5k.round(4))
print("paper: p = 0.040, 0.067, 0.011 (DLPFC); 0.003, 0.0003, 0.00013 (ACC)")
for col in ("p_two", "p_one"):
    print(f"{col}: all six OFC more negative {bool(f5k.ofc_more_negative.all())}, p < 0.05 in {int((f5k[col] < 0.05).sum())} of 6")
# Variant: the paper's n (OFC 183, DLPFC 135, ACC 189). Unit 87 is put back in DLPFC; unit 653, whose
# cue 2 T-statistics are not finite, is put back in OFC for the cue 3 correlations only.
def corr_k(units, k):
    ev1, ev2, ep = int(k[0]), int(k[2]), "X" + k[-1]
    return pear(tst(units, ep, ev1, B250), tst(units, ep, ev2, B250))[0]
units_n = {1: SEL5[1], 2: sorted(SEL5[2] + list(pfc7.BAD_UNITS)), 3: sorted(SEL5[3] + list(pfc7.NAN_TSTAT_UNITS))}
rows = []
for k in ("6v5@2", "3v1@3", "3v2@3"):
    ofc_u = SEL5[3] if k == "6v5@2" else units_n[3]
    for other in (2, 1):
        r_o, r_x = corr_k(ofc_u, k), corr_k(units_n[other], k)
        z, p2 = pfc7.fisher_z(r_o, 183, r_x, {1: 189, 2: 135}[other])
        rows.append(dict(corr=k, versus=NAMES[other], r_OFC=r_o, r_other=r_x, z=z, p_two=p2))
f5kn = pd.DataFrame(rows)
print("with units 87 and 653 back and the paper's n (183, 135, 189) in the test:")
print(f5kn.round(4))
print(f"all six OFC more negative {bool((f5kn.r_OFC < f5kn.r_other).all())}, two-sided p < 0.05 in {int((f5kn.p_two < 0.05).sum())} of 6")
    corr versus   r_OFC  r_other       z   p_two   p_one  ofc_more_negative
0  6v5@2  DLPFC -0.2700  -0.0404 -2.0566  0.0397  0.0199               True
1  6v5@2    ACC -0.2700   0.0314 -2.9451  0.0032  0.0016               True
2  3v1@3  DLPFC -0.2827  -0.0798 -1.8317  0.0670  0.0335               True
3  3v1@3    ACC -0.2827   0.0842 -3.5816  0.0003  0.0002               True
4  3v2@3  DLPFC -0.3788  -0.1052 -2.5487  0.0108  0.0054               True
5  3v2@3    ACC -0.3788   0.0575 -4.3572  0.0000  0.0000               True
paper: p = 0.040, 0.067, 0.011 (DLPFC); 0.003, 0.0003, 0.00013 (ACC)
p_two: all six OFC more negative True, p < 0.05 in 5 of 6
p_one: all six OFC more negative True, p < 0.05 in 6 of 6
with units 87 and 653 back and the paper's n (183, 135, 189) in the test:
    corr versus   r_OFC  r_other       z   p_two
0  6v5@2  DLPFC -0.2700  -0.0045 -2.3769  0.0175
1  6v5@2    ACC -0.2700   0.0314 -2.9493  0.0032
2  3v1@3  DLPFC -0.2779  -0.0753 -1.8324  0.0669
3  3v1@3    ACC -0.2779   0.0842 -3.5377  0.0004
4  3v2@3  DLPFC -0.3750  -0.1099 -2.4772  0.0132
5  3v2@3    ACC -0.3750   0.0575 -4.3208  0.0000
all six OFC more negative True, two-sided p < 0.05 in 5 of 6

Result: reproduced. All six OFC correlations are more negative than the DLPFC and ACC ones, and the two-sided Fisher tests give p = 0.040, 0.067, 0.011 (DLPFC) and 0.0032, 0.0003 (ACC), the paper's values, and for EV 3 against EV 2 against ACC z = -4.357, p = 1.3e-05, ten times smaller than the paper's 0.00013; five of six are below 0.05, as in the paper. With units 87 and 653 put back and the paper's n (183, 135, 189) in the test, all six are still more negative and five of six have p < 0.05 (p = 0.018, 0.067, 0.013 against DLPFC).

figs67-no-comparison-acc-dlpfc¶

ACC and DLPFC carry the currently attended value subspace (and stored subspaces) but show no negative correlation between attended and stored value subspaces.

In [39]:
for a in (1, 2):
    ra, rb = c5b(SEL5[a])
    f = CORR5[a]["1v2@3"]
    pres = (rb[0] > 0 and rb[1] < 0.05) and (f[0] > 0 and f[1] < 0.05)
    pres_a = (ra[0] > 0 and ra[1] < 0.05) and (f[0] > 0 and f[1] < 0.05)
    neg = [k for k in ("6v5@2", "3v1@3", "3v2@3") if CORR5[a][k][0] < 0 and CORR5[a][k][1] < 0.05]
    print(f"{NAMES[a]}: fig5b r = {rb[0]:.3f} (p = {rb[1]:.2g}; reading (a) r = {ra[0]:.3f}, p = {ra[1]:.2g}),"
          f" fig5f r = {f[0]:.3f} (p = {f[1]:.2g}); presence {pres} (reading (a) {pres_a});"
          f" attended-against-stored r = {[round(CORR5[a][k][0], 3) for k in ('6v5@2', '3v1@3', '3v2@3')]},"
          f" p = {[float('%.2g' % CORR5[a][k][1]) for k in ('6v5@2', '3v1@3', '3v2@3')]}; negative with p < 0.05: {neg}")
ACC: fig5b r = 0.852 (p = 1.8e-54; reading (a) r = 0.851, p = 3.7e-54), fig5f r = 0.559 (p = 6e-17); presence True (reading (a) True); attended-against-stored r = [np.float64(0.031), np.float64(0.084), np.float64(0.058)], p = [0.67, 0.25, 0.43]; negative with p < 0.05: []
DLPFC: fig5b r = 0.658 (p = 6.1e-18; reading (a) r = 0.658, p = 5.4e-18), fig5f r = 0.519 (p = 1.3e-10); presence True (reading (a) True); attended-against-stored r = [np.float64(-0.04), np.float64(-0.08), np.float64(-0.105)], p = [0.64, 0.36, 0.23]; negative with p < 0.05: []

Result: reproduced. The attended value subspace is present in ACC (r = 0.852) and DLPFC (r = 0.658) and the stored subspaces correlate at cue 3 (r = 0.559 and 0.519), all p < 1e-9; none of the attended-against-stored correlations is negative with p < 0.05 (ACC r = 0.031 to 0.084, DLPFC r = -0.105 to -0.040, smallest p 0.23).

fig6a-acc-belief-subspace¶

In ACC the T-statistics of the four belief confirmation regressors (cues 2 and 3, option and attribute trials) correlate positively with each other and with cue 1 value, a stable belief confirmation code not present in OFC or DLPFC.

Fig6_ACCmultiplesignals_R3_version.m: contrast 19 at cue 1 and EVs 13 and 14 at cue 2, 15 and 16 at cue 3, all at 300 ms, correlated across neurons in each region (units: SEL, the script's selection). Readings of the claims file: (a) T-statistics, (b) OLS coefficients; cue 1 value as the mean of the EV1 and EV5 T-statistics or as contrast 19.

In [40]:
LAB6 = ["cue1 value", "EV13", "EV14", "EV15", "EV16"]
iu5 = np.triu_indices(5, 1)
def belief_mat(units, kind, cue1):
    if kind == "t" and cue1 == "mean":
        c1 = tmean(units, "X1", [1, 5], B300)
    else:
        c1 = tst(units, "X1", 19, B300, kind)
    return np.column_stack([c1, tst(units, "X2", 13, B300, kind), tst(units, "X2", 14, B300, kind),
                            tst(units, "X3", 15, B300, kind), tst(units, "X3", 16, B300, kind)])
R6 = {}
for kind in ("t", "b"):
    for cue1 in ("contrast", "mean"):
        if kind == "b" and cue1 == "mean":
            continue
        for a in (1, 2, 3):
            M = belief_mat(SEL[a], kind, cue1)
            M = M[np.isfinite(M).all(1)]
            r = np.corrcoef(M.T)
            p = np.ones_like(r)
            for i in range(5):
                for j in range(5):
                    if i != j:
                        p[i, j] = stats.pearsonr(M[:, i], M[:, j])[1]
            iu = np.triu_indices(5, 1)
            R6[(kind, cue1, a)] = dict(r=r, p=p, n=len(M))
            npos = int(((r[iu] > 0) & (p[iu] < 0.05)).sum())
            print(f"{'T-statistics' if kind == 't' else 'coefficients'}, cue 1 as {cue1}, {NAMES[a]} (n = {len(M)}):"
                  f" r = {np.round(r[iu], 3)}, positive with p < 0.05: {npos} of 10")
    print()
T-statistics, cue 1 as contrast, ACC (n = 189): r = [0.185 0.461 0.483 0.298 0.165 0.209 0.344 0.48  0.324 0.45 ], positive with p < 0.05: 10 of 10
T-statistics, cue 1 as contrast, DLPFC (n = 134): r = [ 0.221  0.095  0.138  0.209 -0.004  0.02   0.023  0.203  0.052  0.027], positive with p < 0.05: 3 of 10
T-statistics, cue 1 as contrast, OFC (n = 183): r = [-0.017  0.108  0.12   0.028  0.009 -0.089  0.162  0.169  0.041 -0.067], positive with p < 0.05: 2 of 10
T-statistics, cue 1 as mean, ACC (n = 189): r = [0.183 0.46  0.483 0.297 0.165 0.209 0.344 0.48  0.324 0.45 ], positive with p < 0.05: 10 of 10
T-statistics, cue 1 as mean, DLPFC (n = 134): r = [ 0.222  0.097  0.13   0.209 -0.004  0.02   0.023  0.203  0.052  0.027], positive with p < 0.05: 3 of 10
T-statistics, cue 1 as mean, OFC (n = 183): r = [-0.018  0.112  0.118  0.025  0.009 -0.089  0.162  0.169  0.041 -0.067], positive with p < 0.05: 2 of 10

coefficients, cue 1 as contrast, ACC (n = 189): r = [0.208 0.37  0.39  0.262 0.149 0.042 0.039 0.405 0.229 0.548], positive with p < 0.05: 8 of 10
coefficients, cue 1 as contrast, DLPFC (n = 134): r = [-0.113  0.099  0.263  0.272 -0.262 -0.165  0.193  0.026  0.061  0.149], positive with p < 0.05: 3 of 10
coefficients, cue 1 as contrast, OFC (n = 183): r = [-0.091  0.057  0.074  0.12   0.121  0.06   0.079  0.147  0.183 -0.057], positive with p < 0.05: 2 of 10

In [41]:
for sb in ("M", "F"):
    for a in (1, 2, 3):
        M = belief_mat([u for u in SEL[a] if info.loc[u, "subject"] == sb], "t", "contrast")
        M = M[np.isfinite(M).all(1)]
        r = np.corrcoef(M.T)
        npos = sum(1 for i, j in zip(*iu5) if r[i, j] > 0 and stats.pearsonr(M[:, i], M[:, j])[1] < 0.05)
        print(f"monkey {sb}, {NAMES[a]} (n = {len(M)}): T-statistics, positive with p < 0.05 in {npos} of 10; "
              f"median r {np.median(r[iu5]):.3f}")
monkey M, ACC (n = 94): T-statistics, positive with p < 0.05 in 10 of 10; median r 0.395
monkey M, DLPFC (n = 37): T-statistics, positive with p < 0.05 in 0 of 10; median r 0.084
monkey M, OFC (n = 82): T-statistics, positive with p < 0.05 in 1 of 10; median r 0.021
monkey F, ACC (n = 95): T-statistics, positive with p < 0.05 in 7 of 10; median r 0.328
monkey F, DLPFC (n = 97): T-statistics, positive with p < 0.05 in 2 of 10; median r 0.107
monkey F, OFC (n = 101): T-statistics, positive with p < 0.05 in 0 of 10; median r 0.048

Result: reproduced. With T-statistics all 10 ACC correlations are positive with p < 0.05 (r = 0.165 to 0.483), against 3 of 10 in DLPFC and 2 of 10 in OFC. With OLS coefficients ACC has 8 of 10. By monkey, ACC has 10 of 10 in M and 7 of 10 in F.

fig6b-acc-belief-stronger¶

Virtually all belief confirmation correlations are stronger in ACC than in OFC and DLPFC, and most of the individual comparisons are significant by Fisher r-to-Z.

In [42]:
iu = np.triu_indices(5, 1)
for key in [("t", "contrast"), ("t", "mean"), ("b", "contrast")]:
    rA = R6[key + (1,)]
    for side in ("two", "one"):
        larger = 0; nsig = 0
        for other in (2, 3):
            rO = R6[key + (other,)]
            z, p2 = pfc7.fisher_z(rA["r"][iu], rA["n"], rO["r"][iu], rO["n"], two_sided=(side == "two"))
            larger += int((rA["r"][iu] > rO["r"][iu]).sum())
            nsig += int((p2 < 0.05).sum()) if side == "two" else int((p2 < 0.05).sum())
        print(f"{key}, {side}-sided: ACC larger in {larger} of 20, p < 0.05 in {nsig} of 20")
('t', 'contrast'), two-sided: ACC larger in 19 of 20, p < 0.05 in 13 of 20
('t', 'contrast'), one-sided: ACC larger in 19 of 20, p < 0.05 in 16 of 20
('t', 'mean'), two-sided: ACC larger in 19 of 20, p < 0.05 in 13 of 20
('t', 'mean'), one-sided: ACC larger in 19 of 20, p < 0.05 in 16 of 20
('b', 'contrast'), two-sided: ACC larger in 16 of 20, p < 0.05 in 10 of 20
('b', 'contrast'), one-sided: ACC larger in 16 of 20, p < 0.05 in 11 of 20

Result: reproduced. The ACC correlation is the larger in 19 of 20 comparisons, and 13 of 20 are significant by the two-sided Fisher test (16 one-sided).

Projections onto the ACC subspaces (fig6c, fig6d, fig6e)¶

Fig6_ACCmultiplesignals_R3_version.m and InfoGathering_Neurons_Ramp_to_choice.m. Weights per ACC unit from the GLM on one half of trials: belief confirmation, the mean of the T-statistics of EVs 13 to 16 at 300 ms after their cues; action, the mean of EVs 17 and 18 at the response bin the scripts index as 30 (centred 210 ms before the response); the scripts' design is [demeaned belief, demeaned action, constant, mean of EVs 11 and 12 at that bin], and the projected data are each unit's mean firing in five reaction-time bins (all trials of the other half, including those with 2 cues), z-scored by the session mean and SD, 200 ms boxcar every 10 ms; baseline the projection at cue 1 onset +/- 50 ms of the same bin (and choice). The scripts' RT bins are fixed: below 1200, 1200-1400, 1400-1600, 1600-1800 and from 1800 ms after cue 1 onset. The claims file's readings: O4 (a) odd/even, (b) 100 random halves, here the halves the scripts drew and stored (drawn per unit), and (c) 100 random halves drawn once per session and shared by its units; O5 (a) quintiles per session, (b) quintiles per monkey, and the scripts' fixed bins; O6 (a) Hz, (b) z-scored; O7 (a) mean of T-statistics, (b) T-statistic of the mean coefficient.

Every combination is also run with the projection of the Methods (Projection of ACC activity: "we then regressed this matrix onto a projection matrix composed of two key 'weights' per neuron", "This projection matrix therefore had dimensions neurons*(2 PEs)"), the design [belief, action] with no constant, and with the action weights at the bin centred 200 ms before the response ("EV 17 and EV 18, 200ms prior to response onset"). The tables below are for the scripts' design and bin; a summary follows each for the four combinations of design and bin.

In [43]:
acc = SEL[1]
RBS = {-210: 29, -200: 30}   # response bins for the action weights: the scripts' index 30 (1-based), centred -210 ms; and -200 ms (Methods)
def weights_from(tg, kind, rb):
    """tg: dict of epoch -> (cope, t) arrays (contrasts x bins) from one half."""
    def comb(items):
        if kind == "a":
            return np.mean([tg[ep][1][ev - 1, b] for ep, ev, b in items])
        cs = np.array([tg[ep][0][ev - 1, b] for ep, ev, b in items])
        vs = np.array([(tg[ep][0][ev - 1, b] / tg[ep][1][ev - 1, b]) ** 2 for ep, ev, b in items])
        return cs.mean() / np.sqrt(vs.mean() / len(items))
    bel = comb([("X3", 15, B300), ("X3", 16, B300), ("X2", 14, B300), ("X2", 13, B300)])
    lr = comb([("XR", 17, rb), ("XR", 18, rb)])
    o, a_ = tg["XR"][1][10, rb], tg["XR"][1][11, rb]
    return np.array([bel, lr, o, a_])
def half_fit(d, k):
    """GLM on the trials of `k` (all with 3 or more cues), at the bins the weights use only."""
    X = pfc7.glm_design(d)
    P = np.linalg.pinv(X[k])
    dof = k.sum() - np.linalg.matrix_rank(X[k])
    pre = np.diag(P @ P.T)
    out = {}
    for ep, bins in (("X2", [B300]), ("X3", [B300]), ("XR", list(RBS.values()))):
        cope = np.full((18, 61), np.nan); t = np.full((18, 61), np.nan)
        for b in bins:
            y = d[ep][k][:, b].astype(float)
            pe = P @ y
            sig2 = ((y - X[k] @ pe) ** 2).sum() / dof
            cope[:, b] = pe
            with np.errstate(divide="ignore", invalid="ignore"):
                t[:, b] = pe / np.sqrt(pre * sig2)
        out[ep] = (cope, t)
    return out
# RT bins
rt_all = {u: U[u]["Response_time"] - U[u]["Cue1_ON"] for u in acc}
sess_rt = {}
for u in acc:
    sess_rt.setdefault((U[u]["sb"], U[u]["snum"]), rt_all[u])
mon_rt = {sb: np.concatenate([v for (s_, _), v in sess_rt.items() if s_ == sb]) for sb in ("M", "F")}
def rt_labels(u, rd):
    rt = rt_all[u]
    if rd == "script":
        edges = [1200, 1400, 1600, 1800]
    elif rd == "a":
        edges = np.quantile(sess_rt[(U[u]["sb"], U[u]["snum"])], [0.2, 0.4, 0.6, 0.8])
    else:
        edges = np.quantile(mon_rt[U[u]["sb"]], [0.2, 0.4, 0.6, 0.8])
    return np.searchsorted(edges, rt, side="right")
O5S = ("script", "a", "b")
LAB = {rd: {u: rt_labels(u, rd) for u in acc} for rd in O5S}
print("trials per RT bin, pooled over ACC units:",
      {rd: np.bincount(np.concatenate(list(v.values())), minlength=5).tolist() for rd, v in LAB.items()})
def averages(u, mask, labels):
    """Mean z-scored activity per RT bin: cue locked (c5), and per bin and choice, cue and response
    locked (c10, r10: left, right), and the choice-signed mean (csg, rsg; right trials times -1).
    Also the mean sign per bin (for converting the signed mean to Hz)."""
    d = U[u]
    left = d["Left_choice"] == 1
    sgn = np.where(left, 1.0, -1.0)
    W5 = np.full((len(mask), 5), 0.0); W10 = np.zeros((len(mask), 10)); Wsg = np.zeros((len(mask), 5))
    msg = np.full(5, np.nan)
    for k in range(5):
        s_ = mask & (labels == k)
        if s_.any():
            W5[s_, k] = 1 / s_.sum(); Wsg[s_, k] = sgn[s_] / s_.sum(); msg[k] = sgn[s_].mean()
        else:
            W5[:, k] = np.nan; Wsg[:, k] = np.nan
        for c, cs in enumerate((left, ~left)):
            s2 = s_ & cs
            if s2.any():
                W10[s2, 2 * k + c] = 1 / s2.sum()
            else:
                W10[:, 2 * k + c] = np.nan
    L1, LR = d["L1"], d["LR"]
    return dict(c5=W5.T @ L1, c10=W10.T @ L1, r10=W10.T @ LR, csg=Wsg.T @ L1, rsg=Wsg.T @ LR, msg=msg)
def to_hz(A, u):
    d = U[u]
    out = {k: A[k] * d["sdev"] + d["men"] for k in ("c5", "c10", "r10")}
    for k in ("csg", "rsg"):
        out[k] = A[k] * d["sdev"] + d["men"] * A["msg"][:, None]
    return out
def project(W, D, design="script"):
    """OLS of the neurons x columns data on the design built from the neurons x 4 weights:
    "script", Fig6_ACCmultiplesignals_R3_version.m, [demeaned belief, demeaned action, constant,
    mean of EVs 11 and 12]; "methods", the neurons x 2 matrix of the Methods (Projection of ACC
    activity: "a projection matrix composed of two key 'weights' per neuron"), [belief, action]."""
    ok = np.isfinite(D).all(1) & np.isfinite(W).all(1)
    if design == "methods":
        cols = [W[ok, 0], W[ok, 1]]
    else:
        cols = [W[ok, 0] - W[ok, 0].mean(), W[ok, 1] - W[ok, 1].mean(), np.ones(ok.sum()),
                (W[ok, 2] + W[ok, 3]) / 2]
    return np.linalg.pinv(np.column_stack(cols)) @ D[ok], int(ok.sum())
CUE_T, RESP_T = pfc7.CUE1_LONG, pfc7.RESP_LONG
BASE_W = (CUE_T >= -50) & (CUE_T <= 50)
KEYS = ("c5", "c10", "r10", "csg", "rsg")
VARS6 = [("script", -210), ("script", -200), ("methods", -210), ("methods", -200)]
def proj_one(tg, avs, o7, design, rbt):
    W = np.array([weights_from(tg[u], o7, RBS[rbt]) for u in acc])
    out, ns = {}, []
    for k in KEYS:
        coef, n = project(W, avs[k], design)
        out[k] = coef.reshape(coef.shape[0], avs["shape"][k], -1)
        ns.append(n)
    return out, ns

t6 = time.time()
SPLITS = {}
# O4 (a): odd/even, weights from one half's GLM (already fitted), data from the other half
tg_oe, dm_oe = [], []
for wh, dh in (("odd", "even"), ("even", "odd")):
    tg_oe.append({u: {ep: (G[u][f"b{ep}_{wh}"], G[u][f"t{ep}_{wh}"]) for ep in ("X2", "X3", "XR")} for u in acc})
    dm_oe.append({u: (G[u]["odd"] if dh == "odd" else ~G[u]["odd"]) for u in acc})
SPLITS["a"] = (tg_oe, dm_oe)
# O4 (b): the 100 random halves the scripts drew and stored (randproj_trials of
# info_gathering_cue123_alltrials_attentional_final.mat, drawn per unit over its trials with 3 or
# more cues); weights from one half, data from all other trials (InfoGathering_Neurons_Ramp_to_choice.m)
def split_fits(draws):
    tgs, dms = [], []
    for s_ in range(100):
        tg, dmk = {}, {}
        for u in acc:
            d = U[u]
            k3 = np.flatnonzero(d["num_pics_viewed"] >= 3)
            k = np.zeros(len(d["condition"]), bool)
            k[k3[draws[u][:, s_]]] = True
            tg[u] = half_fit(d, k)
            dmk[u] = ~k
        tgs.append(tg); dms.append(dmk)
    return tgs, dms
SPLITS["b"] = split_fits({u: RANDPROJ[u] for u in acc})
# check: the weights from the stored halves against the weights the scripts stored for them
wb = np.array([[weights_from(SPLITS["b"][0][s_][u], "a", RBS[-210])[:2] for s_ in range(100)] for u in acc])
print("weights from the scripts' stored halves, max |here - stored| over", len(acc), "ACC units x 100 halves:",
      f"belief {np.nanmax(np.abs(wb[:, :, 0] - STORED_W['belief'][[u - 1 for u in acc]])):.2e},",
      f"action {np.nanmax(np.abs(wb[:, :, 1] - STORED_W['RL'][[u - 1 for u in acc]])):.2e}")
# O4 (c): 100 random halves drawn once per session and shared by its units, so that no trial of a
# unit's weights is a projected trial of a simultaneously recorded unit (verifier, round 1, point 6)
rng = section_rng("fig6-projection")
n3 = {}
for u in acc:
    n3.setdefault((U[u]["sb"], U[u]["snum"]), int((U[u]["num_pics_viewed"] >= 3).sum()))
sess_draw = {s: rng.random((n, 100)) > 0.5 for s, n in n3.items()}
SPLITS["c"] = split_fits({u: sess_draw[(U[u]["sb"], U[u]["snum"])] for u in acc})
print(f"weights for 2 x 100 random halves: {time.time() - t6:.0f} s")
PROJV, NKEEP, SPLIT6C = {v: {} for v in VARS6}, set(), {}
W6C = {"a": (100, 500), "b": (0, 500)}
for o4, (tgl, dml) in SPLITS.items():
    for o5 in O5S:
        acc_ = {}
        for s_ in range(len(dml)):
            avz = {u: averages(u, dml[s_][u], LAB[o5][u]) for u in acc}
            avh = {u: to_hz(avz[u], u) for u in acc}
            for o6, av in (("a", avh), ("b", avz)):
                avs = {k: np.stack([av[u][k].ravel() for u in acc]) for k in KEYS}
                avs["shape"] = {k: av[acc[0]][k].shape[0] for k in KEYS}
                for o7 in ("a", "b"):
                    for var in VARS6:
                        pr, ns = proj_one(tgl[s_], avs, o7, *var)
                        NKEEP.update(ns)
                        cb = pr["c5"][0] - pr["c5"][0][:, BASE_W].mean(1, keepdims=True)
                        for wn, (lo, hi) in W6C.items():
                            w = (CUE_T >= lo) & (CUE_T <= hi)
                            SPLIT6C.setdefault((var, o4, o5, o6, o7, wn), []).append(bool(cb[0, w].mean() > cb[4, w].mean()))
                        for k, v in pr.items():
                            acc_.setdefault((var, o6, o7, k), []).append(v)
        for (var, o6, o7, k), v in acc_.items():
            PROJV[var].setdefault((o4, o5, o6, o7), {})[k] = np.mean(v, axis=0)
        del acc_
PROJ = PROJV[("script", -210)]
print(f"projections for {len(PROJ)} reading combinations x {len(VARS6)} designs: {time.time() - t6:.0f} s; "
      f"neurons kept per projection {min(NKEEP)} to {max(NKEEP)} of {len(acc)}")

def bl(P, comp, key):
    """Baseline-corrected projection of component `comp` (0 belief, 1 action) for data `key`."""
    base_key = {"c5": "c5", "c10": "c10", "r10": "c10", "csg": "csg", "rsg": "csg"}[key]
    b0 = P[base_key][comp][:, BASE_W].mean(1, keepdims=True)
    return P[key][comp] - b0
trials per RT bin, pooled over ACC units: {'script': [17835, 19090, 19302, 10368, 15674], 'a': [16024, 16251, 16414, 16908, 16672], 'b': [13979, 15089, 15899, 17990, 19312]}
weights from the scripts' stored halves, max |here - stored| over 189 ACC units x 100 halves: belief 1.35e-07, action 2.55e-07
weights for 2 x 100 random halves: 27 s
projections for 36 reading combinations x 4 designs: 223 s; neurons kept per projection 186 to 189 of 189

The data the projections use are checked against those the scripts stored (av_Cue1L_proj and av_RespRT_LR_proj of neuronal_regression_results/info_gathering_ramp_to_choice.mat, written by InfoGathering_Neurons_Ramp_to_choice.m: each unit's z-scored mean activity in the five fixed RT bins, cue 1 locked, and per choice response locked, on the trials outside each of the stored random halves). The file is 5.3 GB; its arrays have the half as their last axis, so only the first five halves are read, by range requests.

In [44]:
PATH6 = "neuronal_regression_results/info_gathering_ramp_to_choice.mat"
NS6 = 5
dims_c, v_c = pfc7.mat_leading_values(PATH6, "av_Cue1L_proj", 724 * 331 * 5 * NS6)
dims_r, v_r = pfc7.mat_leading_values(PATH6, "av_RespRT_LR_proj", 724 * 331 * 5 * 2 * NS6)
ST_C = v_c.reshape((724, 331, 5, NS6), order="F")
ST_R = v_r.reshape((724, 331, 5, 2, NS6), order="F")   # last but one axis: left, right choice
print("stored arrays:", dims_c, dims_r, "; read the first", NS6, "halves")
# MATLAB's mean of a one-trial selection averages over time, so the script stores a flat line for a
# bin with one trial; those traces are compared with the time average of the trial here
dev = {"c": [], "r": []}; one = {"c": [0, 0], "r": [0, 0]}
for s_ in range(NS6):
    for u in acc:
        d = U[u]
        mask, lab = SPLITS["b"][1][s_][u], LAB["script"][u]
        av = averages(u, mask, lab)
        left = d["Left_choice"] == 1
        for kind, here, stored, sel in (
                ("c", av["c5"], ST_C[u - 1, :, :, s_].T, [mask & (lab == k) for k in range(5)]),
                ("r", av["r10"], ST_R[u - 1, :, :, :, s_].transpose(1, 2, 0).reshape(10, -1),
                 [mask & (lab == k) & cs for k in range(5) for cs in (left, ~left)])):
            for j, m in enumerate(sel):
                if m.sum() == 1:
                    one[kind][0] += 1
                    one[kind][1] += bool(np.allclose(stored[j], here[j].mean(), atol=1e-5))
                elif m.sum() > 1:
                    dev[kind].append(np.abs(here[j] - stored[j]).max())
for kind, name in (("c", "cue 1 locked, per RT bin"), ("r", "response locked, per RT bin and choice")):
    print(f"{name}: max |here - stored| over {len(acc)} ACC units x {NS6} halves, traces of 2 or more trials, "
          f"{max(dev[kind]):.2e}; one-trial traces {one[kind][0]}, stored as the trial's time average in {one[kind][1]}")
del v_c, v_r, ST_C, ST_R
stored arrays: (724, 331, 5, 100) (724, 331, 5, 2, 100) ; read the first 5 halves
cue 1 locked, per RT bin: max |here - stored| over 189 ACC units x 5 halves, traces of 2 or more trials, 9.04e-08; one-trial traces 1, stored as the trial's time average in 1
response locked, per RT bin and choice: max |here - stored| over 189 ACC units x 5 halves, traces of 2 or more trials, 1.38e-07; one-trial traces 14, stored as the trial's time average in 14

fig6c-belief-subspace-rt¶

ACC activity in the belief confirmation subspace separates short from long reaction time trials early in the trial, even at cue 1 presentation.

In [45]:
def f6c_table(PR, var):
    rows = []
    for key, P in PR.items():
        c = bl(P, 0, "c5")
        r = dict(zip(("O4", "O5", "O6", "O7"), key))
        for wn, (lo, hi) in W6C.items():
            w = (CUE_T >= lo) & (CUE_T <= hi)
            r[f"short-long {lo}-{hi}"] = c[0, w].mean() - c[4, w].mean()
            if key[0] != "a":
                r[f"splits {lo}-{hi}"] = int(np.sum(SPLIT6C[(var,) + key + (wn,)]))
        w2 = (CUE_T >= 500) & (CUE_T <= 1000)
        r["short-long 500-1000"] = c[0, w2].mean() - c[4, w2].mean()
        rows.append(r)
    return pd.DataFrame(rows).set_index(["O4", "O5", "O6", "O7"])
f6c = f6c_table(PROJV[("script", -210)], ("script", -210))
print(f6c.round(4).to_string())
print("readings where the shortest RT bin is above the longest, 100-500 ms:", int((f6c["short-long 100-500"] > 0).sum()),
      "of", len(f6c), "; 0-500 ms:", int((f6c["short-long 0-500"] > 0).sum()))
print("by projection design and action bin (readings holding, 100-500 / 0-500 ms; smallest difference; splits holding, fewest):")
for var in VARS6:
    t = f6c_table(PROJV[var], var)
    print(f"  {var[0]:8s} {var[1]} ms: {int((t['short-long 100-500'] > 0).sum())} / {int((t['short-long 0-500'] > 0).sum())} of {len(t)};"
          f" min {t[['short-long 100-500', 'short-long 0-500']].min().min():.4f}; splits min {int(t[['splits 100-500', 'splits 0-500']].min().min())} of 100")
P = PROJ[("a", "script", "b", "a")]
fig, ax = plt.subplots(1, 3, figsize=(14, 3.5))
c = bl(P, 0, "c5")
for k in range(5):
    m = (CUE_T >= -100) & (CUE_T <= 2200)
    ax[0].plot(CUE_T[m], c[k, m], label=f"RT bin {k + 1}")
ax[0].set_title("belief, cue 1 locked (odd/even, script bins, z, mean T)", fontsize=8); ax[0].legend(fontsize=7)
rb_ = np.stack([bl(P, 0, "r10")[0::2], bl(P, 0, "r10")[1::2]]).mean(0)
m = (RESP_T >= -500) & (RESP_T <= 100)
for k in range(5):
    ax[1].plot(RESP_T[m], rb_[k, m])
ax[1].set_title("belief, response locked", fontsize=8)
lr = bl(P, 1, "r10")
for k in range(5):
    ax[2].plot(RESP_T[m], lr[2 * k, m] - lr[2 * k + 1, m])
ax[2].set_title("action, response locked, left minus right", fontsize=8)
plt.show()
print("plotted ranges:", [round(float(x), 3) for x in (c[:, (CUE_T >= -100) & (CUE_T <= 2200)].min(),
      c[:, (CUE_T >= -100) & (CUE_T <= 2200)].max(), rb_[:, m].min(), rb_[:, m].max())])
                 short-long 100-500  short-long 0-500  short-long 500-1000  splits 100-500  splits 0-500
O4 O5     O6 O7                                                                                         
a  script a  a               0.4449            0.3631               0.6196             NaN           NaN
             b               0.2224            0.1826               0.3042             NaN           NaN
          b  a               0.0401            0.0330               0.0597             NaN           NaN
             b               0.0193            0.0160               0.0274             NaN           NaN
   a      a  a               0.3370            0.2733               0.5887             NaN           NaN
             b               0.1669            0.1361               0.2834             NaN           NaN
          b  a               0.0360            0.0295               0.0619             NaN           NaN
             b               0.0171            0.0140               0.0279             NaN           NaN
   b      a  a               0.4218            0.3516               0.7360             NaN           NaN
             b               0.2098            0.1756               0.3603             NaN           NaN
          b  a               0.0410            0.0347               0.0681             NaN           NaN
             b               0.0196            0.0167               0.0315             NaN           NaN
b  script a  a               0.3640            0.2976               0.5662           100.0         100.0
             b               0.1819            0.1489               0.2747           100.0         100.0
          b  a               0.0353            0.0290               0.0593           100.0         100.0
             b               0.0169            0.0139               0.0271           100.0         100.0
   a      a  a               0.3361            0.2762               0.6300           100.0         100.0
             b               0.1656            0.1364               0.3052           100.0         100.0
          b  a               0.0336            0.0278               0.0647           100.0         100.0
             b               0.0159            0.0132               0.0297            99.0          99.0
   b      a  a               0.4276            0.3560               0.6795           100.0         100.0
             b               0.2119            0.1768               0.3303           100.0         100.0
          b  a               0.0406            0.0343               0.0649           100.0         100.0
             b               0.0193            0.0164               0.0298           100.0         100.0
c  script a  a               0.3824            0.3125               0.5801           100.0         100.0
             b               0.1902            0.1556               0.2821           100.0         100.0
          b  a               0.0361            0.0297               0.0606           100.0         100.0
             b               0.0172            0.0142               0.0279            98.0          98.0
   a      a  a               0.3536            0.2902               0.6437           100.0         100.0
             b               0.1743            0.1432               0.3132           100.0         100.0
          b  a               0.0349            0.0288               0.0661           100.0         100.0
             b               0.0165            0.0137               0.0307           100.0         100.0
   b      a  a               0.4432            0.3692               0.6951           100.0         100.0
             b               0.2191            0.1829               0.3381           100.0         100.0
          b  a               0.0419            0.0353               0.0669           100.0         100.0
             b               0.0199            0.0168               0.0309           100.0         100.0
readings where the shortest RT bin is above the longest, 100-500 ms: 36 of 36 ; 0-500 ms: 36
by projection design and action bin (readings holding, 100-500 / 0-500 ms; smallest difference; splits holding, fewest):
  script   -210 ms: 36 / 36 of 36; min 0.0132; splits min 98 of 100
  script   -200 ms: 36 / 36 of 36; min 0.0132; splits min 98 of 100
  methods  -210 ms: 36 / 36 of 36; min 0.0120; splits min 98 of 100
  methods  -200 ms: 36 / 36 of 36; min 0.0120; splits min 98 of 100
No description has been provided for this image
plotted ranges: [-0.064, 0.049, -0.044, 0.049]

Result: reproduced. In all 36 combinations of readings the belief projection is higher for the shortest than for the longest RT bin over 100-500 ms and 0-500 ms after cue 1 (for example a difference of 0.445 with odd/even halves, the scripts' bins and rates in Hz), and with 100 random halves in 98 to 100 of the splits. The same holds in all 36 with the Methods' two-column projection and with the action weights at -200 ms (smallest difference 0.012). The data projected here equal those the scripts stored for their first five random halves to within 1.4e-07 (every ACC unit, cue and response locked), apart from bins with a single trial, which the script stores as that trial's average over time (a quirk of MATLAB's mean on one row).

fig6d-belief-ramp-to-choice¶

Irrespective of reaction time, ACC activity in the belief confirmation subspace ramps up shortly before the joystick movement.

The scripts' response-locked belief trace averages the left- and right-choice projections; the criterion compares the mean over -200 to 0 ms with that over -500 to -300 ms in each RT bin.

In [46]:
late = (RESP_T >= -200) & (RESP_T <= 0)
early = (RESP_T >= -500) & (RESP_T <= -300)
def f6d_table(PR):
    rows = []
    for key, P in PR.items():
        r10 = bl(P, 0, "r10")
        tr = np.stack([r10[0::2], r10[1::2]]).mean(0)
        rise = tr[:, late].mean(1) - tr[:, early].mean(1)
        rows.append(dict(zip(("O4", "O5", "O6", "O7"), key), **{f"bin{k + 1}": rise[k] for k in range(5)},
                         n_rising=int((rise > 0).sum())))
    return pd.DataFrame(rows).set_index(["O4", "O5", "O6", "O7"])
f6d = f6d_table(PROJ)
print(f6d.round(4).to_string())
print("readings with all five bins rising:", int((f6d.n_rising == 5).sum()), "of", len(f6d))
print("by projection design and action bin (readings with all five bins rising; smallest rise):")
for var in VARS6:
    t = f6d_table(PROJV[var])
    print(f"  {var[0]:8s} {var[1]} ms: {int((t.n_rising == 5).sum())} of {len(t)}; min {t.filter(like='bin').min().min():.4f}")
                   bin1    bin2    bin3    bin4    bin5  n_rising
O4 O5     O6 O7                                                  
a  script a  a   0.2247  0.1651  0.3865  0.3391  0.0477         5
             b   0.0980  0.0761  0.1849  0.1474  0.0069         5
          b  a   0.0516  0.0460  0.0593  0.0536  0.0132         5
             b   0.0235  0.0216  0.0278  0.0232  0.0041         5
   a      a  a   0.2348  0.1997  0.2947  0.2781  0.2283         5
             b   0.1010  0.0880  0.1356  0.1278  0.0954         5
          b  a   0.0509  0.0512  0.0587  0.0415  0.0349         5
             b   0.0228  0.0236  0.0271  0.0184  0.0148         5
   b      a  a   0.3029  0.1813  0.1081  0.4039  0.1616         5
             b   0.1429  0.0809  0.0461  0.1901  0.0638         5
          b  a   0.0556  0.0525  0.0384  0.0585  0.0284         5
             b   0.0260  0.0244  0.0175  0.0268  0.0118         5
b  script a  a   0.1818  0.0729  0.4248  0.3999  0.1172         5
             b   0.0792  0.0294  0.2088  0.1901  0.0400         5
          b  a   0.0468  0.0379  0.0636  0.0581  0.0257         5
             b   0.0214  0.0178  0.0308  0.0270  0.0105         5
   a      a  a   0.1670  0.1186  0.2999  0.3197  0.2402         5
             b   0.0700  0.0520  0.1434  0.1529  0.1088         5
          b  a   0.0450  0.0391  0.0592  0.0466  0.0388         5
             b   0.0201  0.0185  0.0283  0.0217  0.0177         5
   b      a  a   0.2620  0.1574  0.0920  0.3949  0.2285         5
             b   0.1219  0.0645  0.0421  0.1904  0.1020         5
          b  a   0.0526  0.0424  0.0381  0.0593  0.0367         5
             b   0.0245  0.0192  0.0183  0.0280  0.0165         5
c  script a  a   0.1830  0.0636  0.4051  0.3899  0.1223         5
             b   0.0800  0.0232  0.1993  0.1846  0.0454         5
          b  a   0.0462  0.0355  0.0618  0.0569  0.0245         5
             b   0.0212  0.0166  0.0301  0.0266  0.0103         5
   a      a  a   0.1638  0.1184  0.2789  0.2886  0.2300         5
             b   0.0685  0.0512  0.1321  0.1390  0.1047         5
          b  a   0.0438  0.0388  0.0557  0.0436  0.0374         5
             b   0.0197  0.0184  0.0266  0.0206  0.0173         5
   b      a  a   0.2616  0.1647  0.0696  0.3693  0.2254         5
             b   0.1219  0.0690  0.0293  0.1777  0.1018         5
          b  a   0.0520  0.0417  0.0344  0.0577  0.0352         5
             b   0.0243  0.0191  0.0164  0.0274  0.0161         5
readings with all five bins rising: 36 of 36
by projection design and action bin (readings with all five bins rising; smallest rise):
  script   -210 ms: 36 of 36; min 0.0041
  script   -200 ms: 36 of 36; min 0.0040
  methods  -210 ms: 36 of 36; min 0.0039
  methods  -200 ms: 36 of 36; min 0.0038

Result: reproduced. In all 36 combinations the belief projection is higher over -200 to 0 ms than over -500 to -300 ms before the response in each of the five RT bins, and in all 36 with the Methods' two-column projection and with the action weights at -200 ms.

fig6e-action-subspace-ramp¶

ACC activity in the left/right action selection subspace ramps up as evidence is revealed and peaks immediately before the response.

In [47]:
win = (RESP_T >= -500) & (RESP_T <= 100)
def f6e_table(PR):
    rows = []
    for key, P in PR.items():
        r10 = bl(P, 1, "r10")
        for sgn_rd, tr in (("a", r10[0::2] - r10[1::2]), ("b", bl(P, 1, "rsg"))):
            rise = tr[:, late].mean(1) - tr[:, early].mean(1)
            tpk = RESP_T[win][np.argmax(tr[:, win], axis=1)]
            ok = (rise > 0) & (tpk >= -200) & (tpk <= 100)
            rows.append(dict(zip(("O4", "O5", "O6", "O7"), key), sign=sgn_rd,
                             **{f"rise{k + 1}": rise[k] for k in range(5)},
                             **{f"peak{k + 1}": int(tpk[k]) for k in range(5)}, n_ok=int(ok.sum())))
    return pd.DataFrame(rows).set_index(["O4", "O5", "O6", "O7", "sign"])
f6e = f6e_table(PROJ)
print(f6e.round(3).to_string())
print("readings where every bin rises and peaks between -200 and 100 ms:", int((f6e.n_ok == 5).sum()), "of", len(f6e))
print("by projection design and action bin:")
F6E = {}
for var in VARS6:
    t = f6e_table(PROJV[var]); F6E[var] = t
    pk = t.filter(like="peak")
    print(f"  {var[0]:8s} {var[1]} ms: every bin rises in {int((t.filter(like='rise') > 0).all(axis=1).sum())} of {len(t)};"
          f" all five peaks in -200 to 100 ms in {int((t.n_ok == 5).sum())} of {len(t)}; earliest peak {int(pk.min().min())} ms;"
          f" readings with a peak before -250 ms {int((pk < -250).any(axis=1).sum())}")
    print("    holding:", [k for k in t.index[t.n_ok == 5]])
                      rise1  rise2  rise3  rise4  rise5  peak1  peak2  peak3  peak4  peak5  n_ok
O4 O5     O6 O7 sign                                                                            
a  script a  a  a     0.399  0.240  0.545  0.531  0.283   -160   -140   -190   -180   -230     4
                b     0.193  0.124  0.259  0.273  0.136   -200   -140   -190   -180   -230     4
             b  a     0.282  0.172  0.387  0.376  0.200   -160   -140   -190   -180   -230     4
                b     0.137  0.089  0.184  0.193  0.096   -200   -140   -190   -180   -230     4
          b  a  a     0.035  0.018  0.047  0.050  0.034   -160   -210   -190   -160   -160     4
                b     0.018  0.009  0.021  0.026  0.015   -200   -210   -190   -160   -160     4
             b  a     0.025  0.013  0.033  0.035  0.024   -160   -210   -190   -160   -160     4
                b     0.012  0.006  0.015  0.018  0.010   -160   -210   -190   -160   -160     4
   a      a  a  a     0.321  0.234  0.483  0.455  0.415   -160   -190   -190   -170   -230     4
                b     0.160  0.117  0.252  0.226  0.203   -160   -200   -190   -180   -120     5
             b  a     0.227  0.163  0.343  0.326  0.292   -160   -190   -190   -170   -230     4
                b     0.113  0.083  0.179  0.162  0.144   -160   -200   -190   -180   -120     5
          b  a  a     0.028  0.018  0.040  0.045  0.040   -160   -210   -190   -170   -120     4
                b     0.015  0.009  0.020  0.022  0.019   -160   -210   -190   -170   -120     4
             b  a     0.020  0.012  0.028  0.032  0.029   -160   -210   -190   -170   -120     4
                b     0.010  0.006  0.014  0.016  0.013   -160   -210   -190   -170   -120     4
   b      a  a  a     0.394  0.173  0.462  0.534  0.369   -160   -200   -180   -220   -160     4
                b     0.197  0.101  0.237  0.264  0.173   -160   -200   -160   -220   -160     4
             b  a     0.279  0.120  0.331  0.380  0.260   -160   -200   -180   -220   -160     4
                b     0.140  0.070  0.170  0.188  0.122   -160   -200   -160   -220   -160     4
          b  a  a     0.035  0.010  0.039  0.050  0.039   -160   -200   -190   -260   -160     4
                b     0.018  0.007  0.018  0.024  0.017   -160   -200   -190   -260   -160     4
             b  a     0.025  0.007  0.028  0.036  0.027   -160   -200   -190   -260   -160     4
                b     0.013  0.005  0.013  0.017  0.012   -160   -200   -190   -260   -160     4
b  script a  a  a     0.359  0.190  0.520  0.574  0.259   -160   -200   -190   -180   -240     4
                b     0.161  0.107  0.251  0.284  0.122   -160   -100   -190   -180   -240     4
             b  a     0.254  0.137  0.372  0.410  0.184   -160   -200   -190   -180   -240     4
                b     0.114  0.077  0.179  0.203  0.087   -160   -100   -190   -180   -240     4
          b  a  a     0.031  0.012  0.044  0.054  0.029   -160   -200   -190   -180   -160     5
                b     0.015  0.006  0.019  0.027  0.013   -160   -200   -190   -180   -240     4
             b  a     0.022  0.009  0.032  0.038  0.021   -160   -200   -190   -180   -160     5
                b     0.011  0.005  0.014  0.019  0.009   -160   -200   -190   -180   -240     4
   a      a  a  a     0.317  0.177  0.470  0.472  0.380   -160   -200   -190   -180   -250     4
                b     0.147  0.095  0.251  0.243  0.184   -160   -200   -190   -180   -240     4
             b  a     0.224  0.125  0.335  0.339  0.271   -160   -200   -190   -180   -240     4
                b     0.103  0.068  0.179  0.174  0.131   -160   -200   -190   -180   -240     4
          b  a  a     0.027  0.012  0.039  0.045  0.036   -160   -200   -190   -180   -120     5
                b     0.014  0.006  0.020  0.023  0.016   -160   -200   -190   -180   -240     4
             b  a     0.019  0.008  0.028  0.032  0.026   -160   -200   -190   -180   -120     5
                b     0.010  0.004  0.014  0.016  0.012   -160   -200   -190   -180   -240     4
   b      a  a  a     0.339  0.211  0.416  0.520  0.347   -160   -200   -160   -210   -240     3
                b     0.152  0.100  0.216  0.256  0.164   -160   -200   -160   -220   -240     3
             b  a     0.240  0.150  0.297  0.373  0.247   -160   -200   -180   -210   -240     3
                b     0.107  0.071  0.155  0.184  0.117   -160   -200   -160   -220   -240     3
          b  a  a     0.029  0.014  0.032  0.049  0.034   -160   -200   -190   -260   -160     4
                b     0.014  0.006  0.015  0.023  0.015   -160   -200   -190   -260   -160     4
             b  a     0.020  0.010  0.023  0.035  0.024   -160   -200   -190   -260   -160     4
                b     0.010  0.005  0.011  0.017  0.011   -160   -200   -190   -260   -160     4
c  script a  a  a     0.360  0.202  0.527  0.547  0.278   -160   -200   -190   -180   -240     4
                b     0.164  0.112  0.252  0.277  0.130   -160   -100   -190   -180   -240     4
             b  a     0.254  0.146  0.376  0.391  0.197   -160   -200   -190   -180   -240     4
                b     0.115  0.081  0.179  0.198  0.092   -160   -100   -190   -180   -240     4
          b  a  a     0.031  0.012  0.045  0.050  0.031   -160   -200   -190   -180   -160     5
                b     0.016  0.006  0.019  0.025  0.013   -160   -200   -190   -180   -240     4
             b  a     0.022  0.009  0.032  0.036  0.022   -160   -200   -190   -170   -160     5
                b     0.011  0.005  0.014  0.018  0.010   -160   -200   -190   -180   -240     4
   a      a  a  a     0.314  0.194  0.472  0.476  0.400   -160   -200   -190   -180   -240     4
                b     0.148  0.103  0.250  0.247  0.192   -160   -200   -190   -180   -240     4
             b  a     0.221  0.137  0.336  0.341  0.285   -160   -200   -190   -180   -240     4
                b     0.104  0.073  0.178  0.177  0.137   -160   -200   -190   -180   -240     4
          b  a  a     0.027  0.013  0.039  0.045  0.038   -160   -200   -190   -180   -120     5
                b     0.014  0.006  0.019  0.023  0.017   -160   -200   -190   -180   -120     5
             b  a     0.019  0.009  0.028  0.032  0.027   -160   -200   -190   -180   -120     5
                b     0.010  0.004  0.014  0.017  0.012   -160   -200   -190   -180   -120     5
   b      a  a  a     0.339  0.220  0.417  0.520  0.365   -160   -200   -180   -210   -160     4
                b     0.154  0.105  0.214  0.258  0.172   -160   -200   -180   -220   -240     3
             b  a     0.238  0.156  0.298  0.372  0.260   -160   -200   -180   -210   -160     4
                b     0.108  0.075  0.153  0.185  0.123   -160   -200   -180   -220   -240     3
          b  a  a     0.028  0.014  0.032  0.048  0.036   -160   -200   -190   -260   -160     4
                b     0.015  0.007  0.015  0.023  0.016   -160   -200   -190   -260   -160     4
             b  a     0.020  0.010  0.023  0.034  0.025   -160   -200   -190   -260   -160     4
                b     0.010  0.005  0.011  0.017  0.011   -160   -200   -190   -260   -160     4
readings where every bin rises and peaks between -200 and 100 ms: 12 of 72
by projection design and action bin:
  script   -210 ms: every bin rises in 72 of 72; all five peaks in -200 to 100 ms in 12 of 72; earliest peak -260 ms; readings with a peak before -250 ms 12
    holding: [('a', 'a', 'a', 'a', 'b'), ('a', 'a', 'a', 'b', 'b'), ('b', 'script', 'b', 'a', 'a'), ('b', 'script', 'b', 'b', 'a'), ('b', 'a', 'b', 'a', 'a'), ('b', 'a', 'b', 'b', 'a'), ('c', 'script', 'b', 'a', 'a'), ('c', 'script', 'b', 'b', 'a'), ('c', 'a', 'b', 'a', 'a'), ('c', 'a', 'b', 'a', 'b'), ('c', 'a', 'b', 'b', 'a'), ('c', 'a', 'b', 'b', 'b')]
  script   -200 ms: every bin rises in 72 of 72; all five peaks in -200 to 100 ms in 16 of 72; earliest peak -260 ms; readings with a peak before -250 ms 12
    holding: [('a', 'a', 'a', 'a', 'a'), ('a', 'a', 'a', 'a', 'b'), ('a', 'a', 'a', 'b', 'b'), ('a', 'a', 'b', 'a', 'b'), ('a', 'a', 'b', 'b', 'b'), ('b', 'script', 'b', 'a', 'a'), ('b', 'script', 'b', 'b', 'a'), ('b', 'a', 'b', 'a', 'a'), ('b', 'a', 'b', 'b', 'a'), ('c', 'script', 'b', 'a', 'a'), ('c', 'script', 'b', 'b', 'a'), ('c', 'script', 'b', 'b', 'b'), ('c', 'a', 'b', 'a', 'a'), ('c', 'a', 'b', 'a', 'b'), ('c', 'a', 'b', 'b', 'a'), ('c', 'a', 'b', 'b', 'b')]
  methods  -210 ms: every bin rises in 72 of 72; all five peaks in -200 to 100 ms in 6 of 72; earliest peak -260 ms; readings with a peak before -250 ms 12
    holding: [('a', 'a', 'b', 'a', 'b'), ('a', 'a', 'b', 'b', 'b'), ('c', 'script', 'b', 'a', 'a'), ('c', 'script', 'b', 'b', 'a'), ('c', 'a', 'b', 'a', 'a'), ('c', 'a', 'b', 'b', 'a')]
  methods  -200 ms: every bin rises in 72 of 72; all five peaks in -200 to 100 ms in 6 of 72; earliest peak -260 ms; readings with a peak before -250 ms 12
    holding: [('a', 'a', 'b', 'a', 'b'), ('a', 'a', 'b', 'b', 'b'), ('c', 'script', 'b', 'a', 'a'), ('c', 'script', 'b', 'b', 'a'), ('c', 'a', 'b', 'a', 'a'), ('c', 'a', 'b', 'b', 'a')]

Result: reproduced, under 12 of 72 readings. The action projection rises before the response in every RT bin under all 72 readings and all four combinations of design and bin. With the scripts' design and bin its peak falls between -200 and 100 ms in all five bins under 12 of 72 readings, among them the scripts' own (their stored halves, their RT bins, z-scored rates, mean T-statistics, left minus right). With the action weights at -200 ms 16 of 72 hold, with the Methods' two-column projection 6 of 72 at either bin. In the other readings one or two bins peak 10 to 60 ms before -200 ms (for example -240 ms in the longest bin, -260 ms in the fourth bin with quintiles per monkey and z-scored rates).

fig7a-ofc-value-difference-neurons¶

At all three time points (cue 2 against cue 1, cue 3 against cue 1, cue 3 against cue 2), a greater proportion of single neurons encoded value difference between attended and unattended cues in OFC than in ACC and DLPFC.

Units SEL5 (Fig7_single_neurons_cue2and3.m). The significance level has three readings in the claims file, as amended after a reader's answer (questions/hunt-2018.yaml): p < 0.05 (|T| > 1.96), p < 0.01 (|T| > 2.576), and (c) |T| > 1.64 on each of the three tests, the script's threshold (its comment reads norminv(0.05)). The claim holds when OFC leads at all three tests under one reading of the bin, the trial types and the level.

In [48]:
TESTS = {"a": [("X2", 6, 5, 31), ("X3", 3, 1, 32), ("X3", 3, 2, 33)],
         "b": [("X2", 6, 5, 31), ("X3", (7, 9), 5, (36, 38)), ("X3", (7, 9), 6, (37, 39))]}
def passes(units, test, b, thr):
    ep, att, un, dif = test
    out = np.zeros(len(units), bool)
    atts = att if isinstance(att, tuple) else (att,)
    difs = dif if isinstance(dif, tuple) else (dif,)
    for at, df in zip(atts, difs):
        ta, tu, td = tst(units, ep, at, b), tst(units, ep, un, b), tst(units, ep, df, b)
        out |= (np.abs(ta) > thr) & (np.abs(tu) > thr) & (np.abs(td) > thr) & (np.sign(ta) != np.sign(tu))
    return out
F7 = {}
for tt in ("a", "b"):
    for o3, b in (("250", B250), ("300", B300)):
        for o2, thr in (("0.05", 1.96), ("0.01", 2.576), ("script 1.64", 1.64)):
            fr = {}
            anyp = {}
            for a in (1, 2, 3):
                ps = [passes(SEL5[a], t, b, thr) for t in TESTS[tt]]
                fr[a] = [100 * p.mean() for p in ps]
                anyp[a] = 100 * np.any(ps, axis=0).mean()
            ofc_top = all(fr[3][i] > fr[1][i] and fr[3][i] > fr[2][i] for i in range(3))
            F7[(tt, o3, o2)] = dict(fr=fr, any=anyp, ofc_top=ofc_top,
                                    any_top=anyp[3] > anyp[1] and anyp[3] > anyp[2])
            chis = [pfc7.chi2_yates(round(fr[3][i] * len(SEL5[3]) / 100), len(SEL5[3]),
                                    round(fr[x][i] * len(SEL5[x]) / 100), len(SEL5[x]))[1] for i in range(3) for x in (1, 2)]
            print(f"trial types ({tt}), bin {o3} ms, threshold {o2}: % ACC {np.round(fr[1], 1)}, DLPFC "
                  f"{np.round(fr[2], 1)}, OFC {np.round(fr[3], 1)}; OFC highest at all three: {ofc_top};"
                  f" chi2 p OFC vs ACC/DLPFC {[float('%.2g' % c) for c in chis]}")
# time course with the script's threshold, any bin: the script plots the percentage per bin
for a in (1, 2, 3):
    ps = np.mean([[passes(SEL5[a], t, b, 1.64) for b in range(61)] for t in TESTS["a"]], axis=2)
    print(f"{NAMES[a]}: % passing per bin (script threshold), max over bins of each test: {np.round(ps.max(1) * 100, 1)}")
trial types (a), bin 250 ms, threshold 0.05: % ACC [5.3 3.2 4.8], DLPFC [1.5 2.2 2.2], OFC [6.  4.4 6.6]; OFC highest at all three: True; chi2 p OFC vs ACC/DLPFC [0.93, 0.084, 0.73, 0.47, 0.59, 0.13]
trial types (a), bin 250 ms, threshold 0.01: % ACC [1.6 1.6 1.6], DLPFC [0.  2.2 0. ], OFC [2.7 1.6 2.2]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.68, nan, 0.72, 0.97, 0.96, nan]
trial types (a), bin 250 ms, threshold script 1.64: % ACC [6.3 4.8 7.4], DLPFC [6. 3. 3.], OFC [ 8.2  7.7 11. ]; OFC highest at all three: True; chi2 p OFC vs ACC/DLPFC [0.62, 0.58, 0.34, 0.12, 0.31, 0.015]
trial types (a), bin 300 ms, threshold 0.05: % ACC [3.2 4.8 4.2], DLPFC [3.7 3.  3.7], OFC [5.5 4.4 6.6]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.4, 0.64, 0.94, 0.73, 0.44, 0.39]
trial types (a), bin 300 ms, threshold 0.01: % ACC [1.1 0.5 1.1], DLPFC [1.5 1.5 1.5], OFC [1.6 1.6 3.3]; OFC highest at all three: True; chi2 p OFC vs ACC/DLPFC [0.97, 0.73, 0.59, 0.73, 0.26, 0.52]
trial types (a), bin 300 ms, threshold script 1.64: % ACC [5.8 6.3 6.9], DLPFC [5.2 5.2 7.5], OFC [11.   6.6 10.4]; OFC highest at all three: True; chi2 p OFC vs ACC/DLPFC [0.11, 0.11, 0.91, 0.79, 0.3, 0.48]
trial types (b), bin 250 ms, threshold 0.05: % ACC [5.3 4.2 6.9], DLPFC [1.5 0.  2.2], OFC [6.  1.6 4.4]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.93, 0.084, 0.25, nan, 0.42, 0.47]
trial types (b), bin 250 ms, threshold 0.01: % ACC [1.6 2.1 2.1], DLPFC [0. 0. 0.], OFC [2.7 0.  1.1]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.68, nan, nan, nan, 0.72, nan]
trial types (b), bin 250 ms, threshold script 1.64: % ACC [ 6.3  7.4 10.1], DLPFC [6.  2.2 3.7], OFC [8.2 4.4 9.9]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.62, 0.58, 0.31, 0.47, 0.9, 0.062]
trial types (b), bin 300 ms, threshold 0.05: % ACC [3.2 5.3 5.3], DLPFC [3.7 0.7 3. ], OFC [5.5 1.1 3.8]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.4, 0.64, 0.047, 0.79, 0.68, 0.92]
trial types (b), bin 300 ms, threshold 0.01: % ACC [1.1 1.6 2.1], DLPFC [1.5 0.  1.5], OFC [1.6 0.  0.5]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.97, 0.73, nan, nan, 0.39, 0.79]
trial types (b), bin 300 ms, threshold script 1.64: % ACC [5.8 5.8 7.9], DLPFC [5.2 3.7 6. ], OFC [11.   4.9  8.8]; OFC highest at all three: False; chi2 p OFC vs ACC/DLPFC [0.11, 0.11, 0.89, 0.81, 0.91, 0.47]
ACC: % passing per bin (script threshold), max over bins of each test: [7.4 7.4 7.9]
DLPFC: % passing per bin (script threshold), max over bins of each test: [7.5 6.  7.5]
OFC: % passing per bin (script threshold), max over bins of each test: [11.5  8.2 12.1]
In [49]:
for sb in ("M", "F"):
    for o3, b in (("250", B250), ("300", B300)):
        fr = {a: [100 * passes([u for u in SEL5[a] if info.loc[u, "subject"] == sb], t, b, 1.96).mean()
                  for t in TESTS["a"]] for a in (1, 2, 3)}
        print(f"monkey {sb}, trial types (a), bin {o3}, p < 0.05: % ACC {np.round(fr[1], 1)}, DLPFC {np.round(fr[2], 1)},"
              f" OFC {np.round(fr[3], 1)}")
monkey M, trial types (a), bin 250, p < 0.05: % ACC [5.3 3.2 2.1], DLPFC [0.  2.7 0. ], OFC [6.2 6.2 8.6]
monkey M, trial types (a), bin 300, p < 0.05: % ACC [3.2 6.4 2.1], DLPFC [5.4 5.4 5.4], OFC [7.4 4.9 6.2]
monkey F, trial types (a), bin 250, p < 0.05: % ACC [5.3 3.2 7.4], DLPFC [2.1 2.1 3.1], OFC [5.9 3.  5. ]
monkey F, trial types (a), bin 300, p < 0.05: % ACC [3.2 3.2 6.3], DLPFC [3.1 2.1 3.1], OFC [4.  4.  6.9]

Result: reproduced. With the Figure 5 trial types (reading a), OFC has the largest proportion at all three tests at 250 ms and p < 0.05 (OFC 6.0, 4.4, 6.6% against ACC 5.3, 3.2, 4.8% and DLPFC 1.5, 2.2, 2.2%), at 300 ms and p < 0.01 (OFC 1.6, 1.6, 3.3% against ACC 1.1, 0.5, 1.1% and DLPFC 1.5, 1.5, 1.5%), and with the script's threshold at both bins (250 ms: OFC 8.2, 7.7, 11.0% against ACC 6.3, 4.8, 7.4% and DLPFC 6.0, 3.0, 3.0%). It fails at 250 ms with p < 0.01 and at 300 ms with p < 0.05, and under the attribute-trial reading (b) in every combination. The differences are small: at 250 ms and p < 0.05 none of the six pairwise chi-square tests is below 0.05 (smallest p = 0.084), and by monkey OFC leads at all three tests in M (6.2, 6.2, 8.6%) but not in F, where ACC is higher at both cue 3 tests (3.2 and 7.4% against OFC 3.0 and 5.0%).

fig7b-ofc-value-difference-any¶

Collapsed across the three tests, the fraction of neurons passing the value difference criteria at any of the three cues is greater in OFC than in ACC and DLPFC.

In [50]:
for k, v in F7.items():
    print(f"{k}: any of three, % ACC {v['any'][1]:.1f}, DLPFC {v['any'][2]:.1f}, OFC {v['any'][3]:.1f}; OFC highest: {v['any_top']}")
('a', '250', '0.05'): any of three, % ACC 9.0, DLPFC 6.0, OFC 11.5; OFC highest: True
('a', '250', '0.01'): any of three, % ACC 2.6, DLPFC 2.2, OFC 4.9; OFC highest: True
('a', '250', 'script 1.64'): any of three, % ACC 12.2, DLPFC 9.0, OFC 18.1; OFC highest: True
('a', '300', '0.05'): any of three, % ACC 9.5, DLPFC 6.7, OFC 11.5; OFC highest: True
('a', '300', '0.01'): any of three, % ACC 1.6, DLPFC 3.7, OFC 4.4; OFC highest: True
('a', '300', 'script 1.64'): any of three, % ACC 13.8, DLPFC 11.2, OFC 22.0; OFC highest: True
('b', '250', '0.05'): any of three, % ACC 11.6, DLPFC 3.7, OFC 11.0; OFC highest: False
('b', '250', '0.01'): any of three, % ACC 4.2, DLPFC 0.0, OFC 3.3; OFC highest: False
('b', '250', 'script 1.64'): any of three, % ACC 18.5, DLPFC 10.4, OFC 18.1; OFC highest: False
('b', '300', '0.05'): any of three, % ACC 10.6, DLPFC 6.0, OFC 8.8; OFC highest: False
('b', '300', '0.01'): any of three, % ACC 3.2, DLPFC 2.2, OFC 2.2; OFC highest: False
('b', '300', 'script 1.64'): any of three, % ACC 14.3, DLPFC 12.7, OFC 20.9; OFC highest: True

Result: reproduced. With the Figure 5 trial types, the fraction passing any of the three tests is highest in OFC at both bins and every threshold (for example 11.5% against 9.0% in ACC and 6.0% in DLPFC at 250 ms, p < 0.05).

fig7c-acc-belief-neurons¶

At all four time points, a greater proportion of single neurons significantly encoded belief confirmation in ACC than in OFC or DLPFC.

Fig7_single_neurons_cue2and3.m uses |T| > 1.96 (its comment, norminv(0.05/2)).

In [51]:
for o3, b in (("250", B250), ("300", B300)):
    for o2, thr in (("0.05", 1.96), ("0.01", 2.576)):
        fr = {a: [100 * np.mean(np.abs(tst(SEL5[a], ep, ev, b)) > thr) for ep, ev in
                  (("X2", 13), ("X2", 14), ("X3", 15), ("X3", 16))] for a in (1, 2, 3)}
        n_top = sum(fr[1][i] > fr[2][i] and fr[1][i] > fr[3][i] for i in range(4))
        chis = [float('%.2g' % pfc7.chi2_yates(round(fr[1][i] * len(SEL5[1]) / 100), len(SEL5[1]),
                                                round(fr[x][i] * len(SEL5[x]) / 100), len(SEL5[x]))[1])
                for i in range(4) for x in (2, 3)]
        print(f"bin {o3} ms, p < {o2}: % EV13/14/15/16 ACC {np.round(fr[1], 1)}, DLPFC {np.round(fr[2], 1)},"
              f" OFC {np.round(fr[3], 1)}; ACC highest in {n_top} of 4; chi2 p ACC vs DLPFC/OFC {chis}")
bin 250 ms, p < 0.05: % EV13/14/15/16 ACC [17.5 16.9 13.8 11.6], DLPFC [9.7 9.7 4.5 8.2], OFC [3.8 8.2 7.7 2.7]; ACC highest in 4 of 4; chi2 p ACC vs DLPFC/OFC [0.071, 4.9e-05, 0.092, 0.018, 0.01, 0.086, 0.41, 0.002]
bin 250 ms, p < 0.01: % EV13/14/15/16 ACC [7.4 8.5 8.5 5.8], DLPFC [2.2 2.2 0.7 4.5], OFC [1.6 2.2 2.2 0. ]; ACC highest in 4 of 4; chi2 p ACC vs DLPFC/OFC [0.072, 0.016, 0.035, 0.015, 0.005, 0.015, 0.78, nan]
bin 300 ms, p < 0.05: % EV13/14/15/16 ACC [16.4 20.1 19.6 11.1], DLPFC [10.4 12.7  6.7  6.7], OFC [6.6 8.2 8.2 1.6]; ACC highest in 4 of 4; chi2 p ACC vs DLPFC/OFC [0.17, 0.0053, 0.11, 0.0018, 0.002, 0.0028, 0.25, 0.00048]
bin 300 ms, p < 0.01: % EV13/14/15/16 ACC [ 7.4  9.  10.1  6.9], DLPFC [4.5 3.  0.7 2.2], OFC [2.2 3.3 3.3 0. ]; ACC highest in 4 of 4; chi2 p ACC vs DLPFC/OFC [0.4, 0.036, 0.054, 0.039, 0.0014, 0.017, 0.1, nan]
In [52]:
for sb in ("M", "F"):
    fr = {a: [100 * np.mean(np.abs(tst([u for u in SEL5[a] if info.loc[u, "subject"] == sb], ep, ev, B300)) > 1.96)
              for ep, ev in (("X2", 13), ("X2", 14), ("X3", 15), ("X3", 16))] for a in (1, 2, 3)}
    print(f"monkey {sb}, bin 300, p < 0.05: % ACC {np.round(fr[1], 1)}, DLPFC {np.round(fr[2], 1)}, OFC {np.round(fr[3], 1)}")
monkey M, bin 300, p < 0.05: % ACC [12.8 23.4 19.1  9.6], DLPFC [16.2 10.8  5.4 10.8], OFC [ 9.9  8.6 14.8  2.5]
monkey F, bin 300, p < 0.05: % ACC [20.  16.8 20.  12.6], DLPFC [ 8.2 13.4  7.2  5.2], OFC [4.  7.9 3.  1. ]

Result: reproduced. ACC has the largest proportion for all four belief confirmation EVs at both bins and both thresholds (at 300 ms, p < 0.05: 16.4, 20.1, 19.6, 11.1% against at most 10.4, 12.7, 8.2, 6.7%).

Cue 1 single-neuron regression (claims fig8-*)¶

The claims file's readings: regressors (a) value (rank -2 to 2), value x side (left 1, right -1), value x attribute (probability 1, magnitude -1), value x row (top 1, bottom -1), the three main effects and a constant; (b) the four value regressors and a constant. Windows (i) 100-500 ms (the mean of the bins centred at 200 and 400 ms, which tile 101-500 ms), (ii) the bin at 250 ms, (iii) at 300 ms. Trials O9 (a) all, (b) 3 or more cues. Significance O2 (a) p < 0.05, (b) p < 0.01, two-sided on the coefficient. The binomial test is the script's, 2 x P(X > k) at a chance rate equal to the significance level; the chi-square is chi2.m (Yates). Units SEL (Fig8 script).

The script's own regression (InfoGathering_Neurons_Cue1_regression.m: 13 regressors on raw values, significance from 1000 permutations corrected over the bins from 0 to 500 ms) is run as a further variant.

In [53]:
B200, B400 = int(np.flatnonzero(pfc7.TIMEBINS == 200)[0]), int(np.flatnonzero(pfc7.TIMEBINS == 400)[0])
def cue1_X(d, rd):
    v = d["Lreg"][:, 0] + d["Rreg"][:, 0] - 3
    s_ = np.where(d["Lreg"][:, 0] > 0, 1.0, -1.0)
    a_ = np.where(d["P_first"] > 0, 1.0, -1.0)
    r_ = np.where(np.isin(d["First_pos"], (1, 3)), 1.0, -1.0)
    cols = [v, v * s_, v * a_, v * r_]
    if rd == "a":
        cols += [s_, a_, r_]
    return np.column_stack(cols + [np.ones(len(v))])
def cue1_y(d, win):
    X1 = d["X1"].astype(float) * 1000
    return {"i": (X1[:, B200] + X1[:, B400]) / 2, "ii": X1[:, B250], "iii": X1[:, B300]}[win]
F8 = {}
for rd in ("a", "b"):
    for win in ("i", "ii", "iii"):
        for o9 in ("a", "b"):
            P_ = {}
            for a in (1, 2, 3):
                ps = []
                for u in SEL[a]:
                    d = U[u]
                    k = np.ones(len(d["condition"]), bool) if o9 == "a" else d["num_pics_viewed"] >= 3
                    X = cue1_X(d, rd)[k]
                    y = cue1_y(d, win)[k]
                    _, _, t = pfc7.ols(y[:, None], X, np.eye(X.shape[1])[:4])
                    dof = X.shape[0] - np.linalg.matrix_rank(X)
                    ps.append(2 * stats.t.sf(np.abs(t[:, 0]), dof))
                P_[a] = np.array(ps)   # units x 4 (value, action, attribute, spatial)
            F8[(rd, win, o9)] = P_
VAR8 = ["value", "action value", "attribute value", "spatial value"]
def f8_counts(key, alpha):
    P_ = F8[key]
    return {a: (P_[a] < alpha).sum(0) for a in (1, 2, 3)}, {a: len(P_[a]) for a in (1, 2, 3)}
rng = section_rng("fig8-script")
C8 = pfc7.cue1_script_contrasts()
SIG8, T8 = {}, {}
t8 = time.time()
for a in (1, 2, 3):
    res = [pfc7.perm_significant(U[u]["X1"].astype(float) * 1000, pfc7.cue1_script_design(U[u]), C8, rng)
           for u in SEL[a]]
    SIG8[a] = np.array([r_[0] for r_ in res]); T8[a] = [r_[1] for r_ in res]
print(f"script regression with permutations: {time.time() - t8:.0f} s")
rows = []
for key in F8:
    for o2, alpha in (("0.05", 0.05), ("0.01", 0.01)):
        k_, n_ = f8_counts(key, alpha)
        r = dict(regressors=key[0], window=key[1], trials=key[2], alpha=o2)
        for a in (1, 2, 3):
            for j, vn in enumerate(VAR8):
                r[f"{NAMES[a]} {vn} %"] = 100 * k_[a][j] / n_[a]
        rows.append(r)
r = dict(regressors="script", window="0-500 corrected", trials="all", alpha="0.05")
for a in (1, 2, 3):
    for j, vn in enumerate(VAR8):
        r[f"{NAMES[a]} {vn} %"] = 100 * SIG8[a][:, j].mean()
rows.append(r)
F8T = pd.DataFrame(rows).set_index(["regressors", "window", "trials", "alpha"])
print(F8T.round(1).to_string())
print("by monkey, the script's reading (% significant: value, action, attribute, spatial):")
for sb in ("M", "F"):
    print(sb, {NAMES[a]: np.round(100 * SIG8[a][[info.loc[u, "subject"] == sb for u in SEL[a]]].mean(0), 1).tolist()
               for a in (1, 2, 3)})
def f8_all():
    """(key, alpha, counts k[a][var], n[a]) for every reading, then the script's with its flags
    computed here and with the flags the authors stored (SIG8_STORED, next cell)."""
    for key in F8:
        for alpha in (0.05, 0.01):
            k_, n_ = f8_counts(key, alpha)
            yield key + (str(alpha),), alpha, k_, n_
    yield ("script",), 0.05, {a: SIG8[a].sum(0) for a in (1, 2, 3)}, {a: len(SIG8[a]) for a in (1, 2, 3)}
    yield ("script", "stored flags"), 0.05, {a: SIG8_STORED[a].sum(0) for a in (1, 2, 3)}, {a: len(SIG8_STORED[a]) for a in (1, 2, 3)}
script regression with permutations: 61 s
                                         ACC value %  ACC action value %  ACC attribute value %  ACC spatial value %  DLPFC value %  DLPFC action value %  DLPFC attribute value %  DLPFC spatial value %  OFC value %  OFC action value %  OFC attribute value %  OFC spatial value %
regressors window          trials alpha                                                                                                                                                                                                                                               
a          i               a      0.05          48.7                19.0                    5.8                  5.3           38.1                  18.7                     11.9                   11.9         47.0                10.4                   26.2                  6.6
                                  0.01          39.2                13.2                    1.1                  2.6           20.9                   7.5                      6.7                    8.2         36.6                 1.6                   13.7                  2.7
                           b      0.05          47.1                14.8                    4.8                  5.8           29.9                  16.4                     10.4                   11.2         44.8                 7.1                   20.2                  8.7
                                  0.01          33.9                10.6                    1.1                  3.2           21.6                   4.5                      6.7                    5.2         32.2                 1.6                   12.0                  1.6
           ii              a      0.05          47.6                19.0                    5.8                  4.8           21.6                  10.4                     11.2                    9.0         45.4                 6.0                   19.1                  6.6
                                  0.01          37.0                13.2                    1.1                  1.1           15.7                   4.5                      6.7                    3.0         36.6                 1.1                   10.9                  1.1
                           b      0.05          45.0                15.3                    6.3                  5.3           24.6                  10.4                     11.9                    9.7         43.2                 7.7                   16.4                  8.2
                                  0.01          34.4                 7.9                    0.0                  2.1           14.9                   4.5                      4.5                    3.7         32.8                 1.6                    6.6                  2.7
           iii             a      0.05          48.1                22.8                    4.8                  8.5           35.8                  14.2                     12.7                   11.2         46.4                 4.9                   24.0                  7.7
                                  0.01          41.8                13.2                    1.1                  3.7           21.6                   7.5                      7.5                    4.5         38.8                 1.6                   13.1                  1.6
                           b      0.05          48.1                18.5                    5.3                  8.5           31.3                  13.4                     14.2                    9.0         44.3                 8.2                   20.2                  7.1
                                  0.01          39.7                11.1                    0.5                  4.2           19.4                   6.0                      7.5                    3.7         33.9                 1.6                   12.0                  1.6
b          i               a      0.05          48.1                19.6                    5.8                  5.8           36.6                  15.7                     12.7                   15.7         46.4                 9.3                   25.1                  5.5
                                  0.01          39.2                13.2                    1.1                  2.1           18.7                   9.0                      4.5                    7.5         36.1                 1.1                   12.6                  2.7
                           b      0.05          45.5                16.9                    4.2                  6.3           29.9                  13.4                      9.0                   12.7         44.8                 6.6                   20.2                  8.2
                                  0.01          34.9                10.1                    0.5                  3.2           14.9                   3.7                      5.2                    6.0         33.9                 1.6                   10.9                  1.1
           ii              a      0.05          47.6                18.5                    4.8                  5.3           22.4                   9.0                      9.7                    7.5         44.8                 6.0                   20.2                  6.0
                                  0.01          36.5                13.8                    0.5                  1.1           14.9                   3.7                      7.5                    3.0         36.1                 1.6                   10.9                  1.1
                           b      0.05          45.5                15.3                    5.3                  7.4           22.4                   6.0                     11.9                   12.7         42.6                 6.6                   16.4                  9.8
                                  0.01          34.9                 9.0                    0.5                  1.6           14.9                   2.2                      3.7                    3.0         32.8                 0.5                    6.0                  2.2
           iii             a      0.05          49.2                22.2                    7.4                  8.5           35.1                  16.4                     12.7                    9.7         45.9                 5.5                   23.0                  7.7
                                  0.01          40.7                12.7                    1.1                  3.2           21.6                   6.0                      6.7                    4.5         38.3                 1.6                   11.5                  2.2
                           b      0.05          48.1                18.0                    4.2                  9.5           30.6                  14.9                     11.9                   10.4         43.2                 6.6                   23.5                  8.7
                                  0.01          40.2                 9.5                    0.5                  3.7           19.4                   4.5                      4.5                    3.0         34.4                 1.6                   10.4                  2.2
script     0-500 corrected all    0.05          54.0                20.6                    7.9                  9.0           41.8                  17.9                     11.2                   15.7         59.0                 6.0                   23.0                  7.7
by monkey, the script's reading (% significant: value, action, attribute, spatial):
M {'ACC': [51.1, 24.5, 2.1, 7.4], 'DLPFC': [43.2, 24.3, 0.0, 10.8], 'OFC': [62.2, 8.5, 14.6, 9.8]}
F {'ACC': [56.8, 16.8, 13.7, 10.5], 'DLPFC': [41.2, 15.5, 15.5, 17.5], 'OFC': [56.4, 4.0, 29.7, 5.9]}

The script's regression is checked against the results the authors stored in the data set (neuronal_regression_results/info_gathering_cue1_both.mat, written by InfoGathering_Neurons_Cue1_regression.m): its T-statistics of contrasts 26, 41, 51 and 42 for each unit, and its significant_neuron flags, from which Fig8_single_neuron_coding.m computes the fractions and binomial tests. The stored flags come from the authors' own permutations, so they agree with the flags here up to permutation noise; the fractions they give are shown as the paper's own.

In [54]:
_raw = pfc7.read_bytes("neuronal_regression_results/info_gathering_cue1_both.mat")
_c1 = _sio.loadmat(_io.BytesIO(_raw), variable_names=["t_stats1", "significant_neuron"], squeeze_me=True)
del _raw
CI8 = [25, 40, 50, 41]   # contrasts 26, 41, 51, 42 (1-based): value, action, attribute, spatial value
dev8 = max(np.nanmax(np.abs(np.asarray(_c1["t_stats1"][u - 1], float)[:, CI8].T - T8[a][j]))
           for a in (1, 2, 3) for j, u in enumerate(SEL[a]))
print(f"max |T here - T stored| over {sum(len(v) for v in SEL.values())} units, 4 contrasts, 61 bins: {dev8:.2e}")
SIG8_STORED = {a: _c1["significant_neuron"][[u - 1 for u in SEL[a]]][:, CI8].astype(bool) for a in (1, 2, 3)}
del _c1
for a in (1, 2, 3):
    agree = (SIG8_STORED[a] == SIG8[a]).mean(0) * 100
    print(f"{NAMES[a]} (n = {len(SEL[a])}): stored flags, % significant (value, action, attribute, spatial) "
          f"{np.round(100 * SIG8_STORED[a].mean(0), 1).tolist()}; here {np.round(100 * SIG8[a].mean(0), 1).tolist()}; "
          f"units with the same flag {np.round(agree, 1).tolist()} %")
print("the scripts' binomial p on the stored flags (value, action, attribute, spatial):")
for a in (1, 2, 3):
    print(f"  {NAMES[a]}:", [f"{pfc7.binom_p_code(k, len(SEL[a])):.1g}" for k in SIG8_STORED[a].sum(0)])
max |T here - T stored| over 506 units, 4 contrasts, 61 bins: 3.29e-07
ACC (n = 189): stored flags, % significant (value, action, attribute, spatial) [54.5, 18.5, 8.5, 7.9]; here [54.0, 20.6, 7.9, 9.0]; units with the same flag [99.5, 97.9, 98.4, 96.8] %
DLPFC (n = 134): stored flags, % significant (value, action, attribute, spatial) [41.0, 17.2, 11.2, 14.9]; here [41.8, 17.9, 11.2, 15.7]; units with the same flag [96.3, 99.3, 100.0, 96.3] %
OFC (n = 183): stored flags, % significant (value, action, attribute, spatial) [56.8, 6.0, 23.5, 7.7]; here [59.0, 6.0, 23.0, 7.7]; units with the same flag [97.8, 100.0, 98.4, 98.9] %
the scripts' binomial p on the stored flags (value, action, attribute, spatial):
  ACC: ['2e-82', '1e-11', '0.03', '0.06']
  DLPFC: ['1e-36', '1e-07', '0.002', '7e-06']
  OFC: ['9e-86', '0.4', '5e-18', '0.08']

fig8-cue1-value-all-regions¶

At cue 1, a significant fraction of neurons in all three regions encoded the cue's value irrespective of its attribute, action or spatial position.

In [55]:
nrd = 0; nok = 0; nok_x = 0
for key, alpha, k_, n_ in f8_all():
    pb = {a: pfc7.binom_p_code(k_[a][0], n_[a], alpha) for a in (1, 2, 3)}
    px = {a: pfc7.binom_p_exact(k_[a][0], n_[a], alpha) for a in (1, 2, 3)}
    ok = all(p < 1e-7 for p in pb.values())
    nrd += 1; nok += ok; nok_x += all(p < 1e-7 for p in px.values())
    print(key, {NAMES[a]: f"{100 * k_[a][0] / n_[a]:.1f}% p={pb[a]:.1g} (exact {px[a]:.1g})" for a in (1, 2, 3)}, "holds:", ok)
print(f"holds under {nok} of {nrd} readings (the last two are the script's, flags here and flags stored); "
      f"with the exact binomial test under {nok_x}")
('a', 'i', 'a', '0.05') {'ACC': '48.7% p=7e-68 (exact 6e-67)', 'DLPFC': '38.1% p=4e-32 (exact 2e-31)', 'OFC': '47.0% p=6e-62 (exact 5e-61)'} holds: True
('a', 'i', 'a', '0.01') {'ACC': '39.2% p=5e-97 (exact 2e-95)', 'DLPFC': '20.9% p=2e-29 (exact 2e-28)', 'OFC': '36.6% p=1e-85 (exact 3e-84)'} holds: True
('a', 'i', 'b', '0.05') {'ACC': '47.1% p=4e-64 (exact 3e-63)', 'DLPFC': '29.9% p=4e-21 (exact 2e-20)', 'OFC': '44.8% p=4e-57 (exact 3e-56)'} holds: True
('a', 'i', 'b', '0.01') {'ACC': '33.9% p=2e-79 (exact 6e-78)', 'DLPFC': '21.6% p=5e-31 (exact 8e-30)', 'OFC': '32.2% p=7e-72 (exact 2e-70)'} holds: True
('a', 'ii', 'a', '0.05') {'ACC': '47.6% p=2e-65 (exact 2e-64)', 'DLPFC': '21.6% p=8e-12 (exact 2e-11)', 'OFC': '45.4% p=3e-58 (exact 2e-57)'} holds: True
('a', 'ii', 'a', '0.01') {'ACC': '37.0% p=8e-90 (exact 2e-88)', 'DLPFC': '15.7% p=6e-20 (exact 6e-19)', 'OFC': '36.6% p=1e-85 (exact 3e-84)'} holds: True
('a', 'ii', 'b', '0.05') {'ACC': '45.0% p=3e-59 (exact 2e-58)', 'DLPFC': '24.6% p=6e-15 (exact 2e-14)', 'OFC': '43.2% p=2e-53 (exact 1e-52)'} holds: True
('a', 'ii', 'b', '0.01') {'ACC': '34.4% p=5e-81 (exact 1e-79)', 'DLPFC': '14.9% p=1e-18 (exact 1e-17)', 'OFC': '32.8% p=1e-73 (exact 4e-72)'} holds: True
('a', 'iii', 'a', '0.05') {'ACC': '48.1% p=1e-66 (exact 1e-65)', 'DLPFC': '35.8% p=6e-29 (exact 3e-28)', 'OFC': '46.4% p=1e-60 (exact 8e-60)'} holds: True
('a', 'iii', 'a', '0.01') {'ACC': '41.8% p=3e-106 (exact 1e-104)', 'DLPFC': '21.6% p=5e-31 (exact 8e-30)', 'OFC': '38.8% p=7e-93 (exact 2e-91)'} holds: True
('a', 'iii', 'b', '0.05') {'ACC': '48.1% p=1e-66 (exact 1e-65)', 'DLPFC': '31.3% p=6e-23 (exact 3e-22)', 'OFC': '44.3% p=7e-56 (exact 5e-55)'} holds: True
('a', 'iii', 'b', '0.01') {'ACC': '39.7% p=8e-99 (exact 3e-97)', 'DLPFC': '19.4% p=1e-26 (exact 1e-25)', 'OFC': '33.9% p=6e-77 (exact 1e-75)'} holds: True
('b', 'i', 'a', '0.05') {'ACC': '48.1% p=1e-66 (exact 1e-65)', 'DLPFC': '36.6% p=5e-30 (exact 3e-29)', 'OFC': '46.4% p=1e-60 (exact 8e-60)'} holds: True
('b', 'i', 'a', '0.01') {'ACC': '39.2% p=5e-97 (exact 2e-95)', 'DLPFC': '18.7% p=3e-25 (exact 3e-24)', 'OFC': '36.1% p=6e-84 (exact 2e-82)'} holds: True
('b', 'i', 'b', '0.05') {'ACC': '45.5% p=2e-60 (exact 1e-59)', 'DLPFC': '29.9% p=4e-21 (exact 2e-20)', 'OFC': '44.8% p=4e-57 (exact 3e-56)'} holds: True
('b', 'i', 'b', '0.01') {'ACC': '34.9% p=8e-83 (exact 2e-81)', 'DLPFC': '14.9% p=1e-18 (exact 1e-17)', 'OFC': '33.9% p=6e-77 (exact 1e-75)'} holds: True
('b', 'ii', 'a', '0.05') {'ACC': '47.6% p=2e-65 (exact 2e-64)', 'DLPFC': '22.4% p=1e-12 (exact 4e-12)', 'OFC': '44.8% p=4e-57 (exact 3e-56)'} holds: True
('b', 'ii', 'a', '0.01') {'ACC': '36.5% p=5e-88 (exact 1e-86)', 'DLPFC': '14.9% p=1e-18 (exact 1e-17)', 'OFC': '36.1% p=6e-84 (exact 2e-82)'} holds: True
('b', 'ii', 'b', '0.05') {'ACC': '45.5% p=2e-60 (exact 1e-59)', 'DLPFC': '22.4% p=1e-12 (exact 4e-12)', 'OFC': '42.6% p=2e-52 (exact 2e-51)'} holds: True
('b', 'ii', 'b', '0.01') {'ACC': '34.9% p=8e-83 (exact 2e-81)', 'DLPFC': '14.9% p=1e-18 (exact 1e-17)', 'OFC': '32.8% p=1e-73 (exact 4e-72)'} holds: True
('b', 'iii', 'a', '0.05') {'ACC': '49.2% p=4e-69 (exact 3e-68)', 'DLPFC': '35.1% p=6e-28 (exact 3e-27)', 'OFC': '45.9% p=2e-59 (exact 1e-58)'} holds: True
('b', 'iii', 'a', '0.01') {'ACC': '40.7% p=2e-102 (exact 6e-101)', 'DLPFC': '21.6% p=5e-31 (exact 8e-30)', 'OFC': '38.3% p=5e-91 (exact 1e-89)'} holds: True
('b', 'iii', 'b', '0.05') {'ACC': '48.1% p=1e-66 (exact 1e-65)', 'DLPFC': '30.6% p=5e-22 (exact 2e-21)', 'OFC': '43.2% p=2e-53 (exact 1e-52)'} holds: True
('b', 'iii', 'b', '0.01') {'ACC': '40.2% p=1e-100 (exact 4e-99)', 'DLPFC': '19.4% p=1e-26 (exact 1e-25)', 'OFC': '34.4% p=1e-78 (exact 3e-77)'} holds: True
('script',) {'ACC': '54.0% p=5e-81 (exact 6e-80)', 'DLPFC': '41.8% p=1e-37 (exact 7e-37)', 'OFC': '59.0% p=2e-91 (exact 3e-90)'} holds: True
('script', 'stored flags') {'ACC': '54.5% p=2e-82 (exact 3e-81)', 'DLPFC': '41.0% p=1e-36 (exact 9e-36)', 'OFC': '56.8% p=9e-86 (exact 1e-84)'} holds: True
holds under 26 of 26 readings (the last two are the script's, flags here and flags stored); with the exact binomial test under 26

Result: reproduced. Under all 24 readings and the script's own regression, the fraction encoding cue 1 value is above chance with binomial p < 1e-7 in every region (script: ACC 54.0%, DLPFC 41.8%, OFC 59.0%), also with the exact binomial test. The script's regression gives the T-statistics the authors stored to within 3.3e-07, and the authors' stored flags give 54.5%, 41.0% and 56.8%.

fig8-action-value-acc-dlpfc¶

About 18% of ACC and DLPFC neurons encoded left/right action value at cue 1, above chance and more than OFC, which encoded action value at chance level.

In [56]:
nok = nok_x = nrd = 0
for key, alpha, k_, n_ in f8_all():
    fr = {a: 100 * k_[a][1] / n_[a] for a in (1, 2, 3)}
    pb = {a: pfc7.binom_p_code(k_[a][1], n_[a], alpha) for a in (1, 2, 3)}
    px = {a: pfc7.binom_p_exact(k_[a][1], n_[a], alpha) for a in (1, 2, 3)}
    pc = {a: pfc7.chi2_yates(k_[a][1], n_[a], k_[3][1], n_[3])[1] for a in (1, 2)}
    above = all(fr[a] > fr[3] and pc[a] < 0.05 for a in (1, 2))
    tests = all(pb[a] < 1e-5 for a in (1, 2)) and above and pb[3] >= 0.05
    tests_x = all(px[a] < 1e-5 for a in (1, 2)) and above and px[3] >= 0.05
    within = all(abs(fr[a] - 18) <= 1.8 for a in (1, 2))
    nrd += 1; nok += tests and within; nok_x += tests_x and within
    print(key, f"ACC {fr[1]:.1f}% (binom p={pb[1]:.1g}, exact {px[1]:.1g}, chi2 vs OFC p={pc[1]:.2g}), DLPFC {fr[2]:.1f}% "
          f"(p={pb[2]:.1g}, exact {px[2]:.1g}, chi2 p={pc[2]:.2g}), OFC {fr[3]:.1f}% (p={pb[3]:.2g}, exact {px[3]:.2g}); "
          f"tests hold {tests} (exact {tests_x}), within 18 +/- 1.8 {within}")
print(f"tests hold with both fractions within tolerance under {nok} of {nrd} readings; with the exact test under {nok_x}")
('a', 'i', 'a', '0.05') ACC 19.0% (binom p=2e-12, exact 5e-12, chi2 vs OFC p=0.027), DLPFC 18.7% (p=6e-09, exact 1e-08, chi2 p=0.052), OFC 10.4% (p=0.0018, exact 0.0022); tests hold False (exact False), within 18 +/- 1.8 True
('a', 'i', 'a', '0.01') ACC 13.2% (binom p=3e-21, exact 2e-20, chi2 vs OFC p=5.4e-05), DLPFC 7.5% (p=3e-07, exact 1e-06, chi2 p=0.022), OFC 1.6% (p=0.23, exact 0.28); tests hold True (exact True), within 18 +/- 1.8 False
('a', 'i', 'b', '0.05') ACC 14.8% (binom p=2e-07, exact 3e-07, chi2 vs OFC p=0.027), DLPFC 16.4% (p=5e-07, exact 9e-07, chi2 p=0.015), OFC 7.1% (p=0.15, exact 0.13); tests hold True (exact True), within 18 +/- 1.8 False
('a', 'i', 'b', '0.01') ACC 10.6% (binom p=2e-15, exact 1e-14, chi2 vs OFC p=0.00077), DLPFC 4.5% (p=0.0009, exact 0.002, chi2 p=0.25), OFC 1.6% (p=0.23, exact 0.28); tests hold False (exact False), within 18 +/- 1.8 False
('a', 'ii', 'a', '0.05') ACC 19.0% (binom p=2e-12, exact 5e-12, chi2 vs OFC p=0.00029), DLPFC 10.4% (p=0.006, exact 0.007, chi2 p=0.22), OFC 6.0% (p=0.41, exact 0.31); tests hold False (exact False), within 18 +/- 1.8 False
('a', 'ii', 'a', '0.01') ACC 13.2% (binom p=3e-21, exact 2e-20, chi2 vs OFC p=1.6e-05), DLPFC 4.5% (p=0.0009, exact 0.002, chi2 p=0.12), OFC 1.1% (p=0.55, exact 0.55); tests hold False (exact False), within 18 +/- 1.8 False
('a', 'ii', 'b', '0.05') ACC 15.3% (binom p=5e-08, exact 9e-08, chi2 vs OFC p=0.031), DLPFC 10.4% (p=0.006, exact 0.007, chi2 p=0.5), OFC 7.7% (p=0.084, exact 0.076); tests hold False (exact False), within 18 +/- 1.8 False
('a', 'ii', 'b', '0.01') ACC 7.9% (binom p=3e-10, exact 1e-09, chi2 vs OFC p=0.0097), DLPFC 4.5% (p=0.0009, exact 0.002, chi2 p=0.25), OFC 1.6% (p=0.23, exact 0.28); tests hold False (exact False), within 18 +/- 1.8 False
('a', 'iii', 'a', '0.05') ACC 22.8% (binom p=2e-17, exact 6e-17, chi2 vs OFC p=1.5e-06), DLPFC 14.2% (p=2e-05, exact 4e-05, chi2 p=0.0076), OFC 4.9% (p=0.87, exact 0.57); tests hold False (exact False), within 18 +/- 1.8 False
('a', 'iii', 'a', '0.01') ACC 13.2% (binom p=3e-21, exact 2e-20, chi2 vs OFC p=5.4e-05), DLPFC 7.5% (p=3e-07, exact 1e-06, chi2 p=0.022), OFC 1.6% (p=0.23, exact 0.28); tests hold True (exact True), within 18 +/- 1.8 False
('a', 'iii', 'b', '0.05') ACC 18.5% (binom p=1e-11, exact 2e-11, chi2 vs OFC p=0.0057), DLPFC 13.4% (p=8e-05, exact 0.0001, chi2 p=0.19), OFC 8.2% (p=0.044, exact 0.042); tests hold False (exact False), within 18 +/- 1.8 False
('a', 'iii', 'b', '0.01') ACC 11.1% (binom p=1e-16, exact 8e-16, chi2 vs OFC p=0.00045), DLPFC 6.0% (p=2e-05, exact 7e-05, chi2 p=0.077), OFC 1.6% (p=0.23, exact 0.28); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'i', 'a', '0.05') ACC 19.6% (binom p=4e-13, exact 1e-12, chi2 vs OFC p=0.0076), DLPFC 15.7% (p=2e-06, exact 3e-06, chi2 p=0.12), OFC 9.3% (p=0.01, exact 0.011); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'i', 'a', '0.01') ACC 13.2% (binom p=3e-21, exact 2e-20, chi2 vs OFC p=1.6e-05), DLPFC 9.0% (p=3e-09, exact 1e-08, chi2 p=0.002), OFC 1.1% (p=0.55, exact 0.55); tests hold True (exact True), within 18 +/- 1.8 False
('b', 'i', 'b', '0.05') ACC 16.9% (binom p=8e-10, exact 2e-09, chi2 vs OFC p=0.0033), DLPFC 13.4% (p=8e-05, exact 0.0001, chi2 p=0.061), OFC 6.6% (p=0.26, exact 0.21); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'i', 'b', '0.01') ACC 10.1% (binom p=2e-14, exact 1e-13, chi2 vs OFC p=0.0013), DLPFC 3.7% (p=0.005, exact 0.01, chi2 p=0.42), OFC 1.6% (p=0.23, exact 0.28); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'ii', 'a', '0.05') ACC 18.5% (binom p=1e-11, exact 2e-11, chi2 vs OFC p=0.00045), DLPFC 9.0% (p=0.03, exact 0.04, chi2 p=0.44), OFC 6.0% (p=0.41, exact 0.31); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'ii', 'a', '0.01') ACC 13.8% (binom p=2e-22, exact 1e-21, chi2 vs OFC p=3.1e-05), DLPFC 3.7% (p=0.005, exact 0.01, chi2 p=0.42), OFC 1.6% (p=0.23, exact 0.28); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'ii', 'b', '0.05') ACC 15.3% (binom p=5e-08, exact 9e-08, chi2 vs OFC p=0.011), DLPFC 6.0% (p=0.5, exact 0.4, chi2 p=0.98), OFC 6.6% (p=0.26, exact 0.21); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'ii', 'b', '0.01') ACC 9.0% (binom p=3e-12, exact 1e-11, chi2 vs OFC p=0.00038), DLPFC 2.2% (p=0.09, exact 0.2, chi2 p=0.41), OFC 0.5% (p=1.1, exact 0.84); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'iii', 'a', '0.05') ACC 22.2% (binom p=1e-16, exact 3e-16, chi2 vs OFC p=6.5e-06), DLPFC 16.4% (p=5e-07, exact 9e-07, chi2 p=0.0026), OFC 5.5% (p=0.62, exact 0.43); tests hold True (exact True), within 18 +/- 1.8 False
('b', 'iii', 'a', '0.01') ACC 12.7% (binom p=4e-20, exact 3e-19, chi2 vs OFC p=9.2e-05), DLPFC 6.0% (p=2e-05, exact 7e-05, chi2 p=0.077), OFC 1.6% (p=0.23, exact 0.28); tests hold False (exact False), within 18 +/- 1.8 False
('b', 'iii', 'b', '0.05') ACC 18.0% (binom p=4e-11, exact 1e-10, chi2 vs OFC p=0.0014), DLPFC 14.9% (p=7e-06, exact 1e-05, chi2 p=0.024), OFC 6.6% (p=0.26, exact 0.21); tests hold True (exact False), within 18 +/- 1.8 False
('b', 'iii', 'b', '0.01') ACC 9.5% (binom p=2e-13, exact 1e-12, chi2 vs OFC p=0.0021), DLPFC 4.5% (p=0.0009, exact 0.002, chi2 p=0.25), OFC 1.6% (p=0.23, exact 0.28); tests hold False (exact False), within 18 +/- 1.8 False
('script',) ACC 20.6% (binom p=2e-14, exact 5e-14, chi2 vs OFC p=6.8e-05), DLPFC 17.9% (p=3e-08, exact 6e-08, chi2 p=0.0016), OFC 6.0% (p=0.41, exact 0.31); tests hold True (exact True), within 18 +/- 1.8 False
('script', 'stored flags') ACC 18.5% (binom p=1e-11, exact 2e-11, chi2 vs OFC p=0.00045), DLPFC 17.2% (p=1e-07, exact 2e-07, chi2 p=0.0028), OFC 6.0% (p=0.41, exact 0.31); tests hold True (exact True), within 18 +/- 1.8 True
tests hold with both fractions within tolerance under 1 of 26 readings; with the exact test under 1

Result: partially reproduced. The tests hold under several readings, the script's included (ACC 20.6% and DLPFC 17.9%, binomial p = 2e-14 and 3e-08, both above OFC by chi-square p = 6.8e-05 and 0.0016, OFC 6.0% at chance, p = 0.41), but in no reading computed here are both fractions within 18 +/- 1.8% with the tests holding: ACC is 20.6% in the script's reading, and where both fall within tolerance (19.0 and 18.7%, reading a, i, all trials, p < 0.05) OFC is above chance (10.4%, p = 0.0018). The tests hold in six readings with the scripts' binomial formula and in five with the exact test (reading b, iii, b, p < 0.05 fails it, DLPFC exact p = 1e-05); neither gives both fractions within tolerance. The significance flags the authors stored, from the same regression with their own permutations, give ACC 18.5% and DLPFC 17.2% with every test holding; they differ from the flags here in 2.1% of ACC units, so the difference is permutation noise around the threshold, but those flags are the paper's result, not one computed here.

fig8-spatial-value-dlpfc¶

In DLPFC, top/bottom spatial value neurons are as prevalent as left/right action value neurons, while in ACC they are significantly fewer, so DLPFC encodes value by spatial position and ACC by action.

In [57]:
nok = nok_x = nrd = 0
for key, alpha, k_, n_ in f8_all():
    pb = pfc7.binom_p_code(k_[2][3], n_[2], alpha)
    px = pfc7.binom_p_exact(k_[2][3], n_[2], alpha)
    pd_ = pfc7.chi2_yates(k_[2][3], n_[2], k_[2][1], n_[2])[1]
    pa_ = pfc7.chi2_yates(k_[1][3], n_[1], k_[1][1], n_[1])[1]
    rest = pd_ >= 0.05 and k_[1][3] < k_[1][1] and pa_ < 0.05
    ok = pb < 1e-6 and rest
    nrd += 1; nok += ok; nok_x += px < 1e-6 and rest
    print(key, f"DLPFC spatial {100 * k_[2][3] / n_[2]:.1f}% (binom p={pb:.1g}, exact {px:.1g}) vs action {100 * k_[2][1] / n_[2]:.1f}% "
          f"(chi2 p={pd_:.2g}); ACC spatial {100 * k_[1][3] / n_[1]:.1f}% vs action {100 * k_[1][1] / n_[1]:.1f}% "
          f"(chi2 p={pa_:.2g}) -> holds {ok}")
print(f"holds under {nok} of {nrd} readings; with the exact binomial test under {nok_x}")
('a', 'i', 'a', '0.05') DLPFC spatial 11.9% (binom p=0.0008, exact 0.001) vs action 18.7% (chi2 p=0.17); ACC spatial 5.3% vs action 19.0% (chi2 p=8.4e-05) -> holds False
('a', 'i', 'a', '0.01') DLPFC spatial 8.2% (binom p=3e-08, exact 1e-07) vs action 7.5% (chi2 p=1); ACC spatial 2.6% vs action 13.2% (chi2 p=0.0003) -> holds True
('a', 'i', 'b', '0.05') DLPFC spatial 11.2% (binom p=0.002, exact 0.003) vs action 16.4% (chi2 p=0.29); ACC spatial 5.8% vs action 14.8% (chi2 p=0.0068) -> holds False
('a', 'i', 'b', '0.01') DLPFC spatial 5.2% (binom p=0.0001, exact 0.0004) vs action 4.5% (chi2 p=1); ACC spatial 3.2% vs action 10.6% (chi2 p=0.0082) -> holds False
('a', 'ii', 'a', '0.05') DLPFC spatial 9.0% (binom p=0.03, exact 0.04) vs action 10.4% (chi2 p=0.84); ACC spatial 4.8% vs action 19.0% (chi2 p=3.6e-05) -> holds False
('a', 'ii', 'a', '0.01') DLPFC spatial 3.0% (binom p=0.02, exact 0.05) vs action 4.5% (chi2 p=0.75); ACC spatial 1.1% vs action 13.2% (chi2 p=1.1e-05) -> holds False
('a', 'ii', 'b', '0.05') DLPFC spatial 9.7% (binom p=0.01, exact 0.02) vs action 10.4% (chi2 p=1); ACC spatial 5.3% vs action 15.3% (chi2 p=0.0023) -> holds False
('a', 'ii', 'b', '0.01') DLPFC spatial 3.7% (binom p=0.005, exact 0.01) vs action 4.5% (chi2 p=1); ACC spatial 2.1% vs action 7.9% (chi2 p=0.019) -> holds False
('a', 'iii', 'a', '0.05') DLPFC spatial 11.2% (binom p=0.002, exact 0.003) vs action 14.2% (chi2 p=0.58); ACC spatial 8.5% vs action 22.8% (chi2 p=0.00023) -> holds False
('a', 'iii', 'a', '0.01') DLPFC spatial 4.5% (binom p=0.0009, exact 0.002) vs action 7.5% (chi2 p=0.44); ACC spatial 3.7% vs action 13.2% (chi2 p=0.0017) -> holds False
('a', 'iii', 'b', '0.05') DLPFC spatial 9.0% (binom p=0.03, exact 0.04) vs action 13.4% (chi2 p=0.33); ACC spatial 8.5% vs action 18.5% (chi2 p=0.0067) -> holds False
('a', 'iii', 'b', '0.01') DLPFC spatial 3.7% (binom p=0.005, exact 0.01) vs action 6.0% (chi2 p=0.57); ACC spatial 4.2% vs action 11.1% (chi2 p=0.02) -> holds False
('b', 'i', 'a', '0.05') DLPFC spatial 15.7% (binom p=2e-06, exact 3e-06) vs action 15.7% (chi2 p=0.87); ACC spatial 5.8% vs action 19.6% (chi2 p=0.00011) -> holds False
('b', 'i', 'a', '0.01') DLPFC spatial 7.5% (binom p=3e-07, exact 1e-06) vs action 9.0% (chi2 p=0.82); ACC spatial 2.1% vs action 13.2% (chi2 p=0.00011) -> holds True
('b', 'i', 'b', '0.05') DLPFC spatial 12.7% (binom p=0.0003, exact 0.0004) vs action 13.4% (chi2 p=1); ACC spatial 6.3% vs action 16.9% (chi2 p=0.0023) -> holds False
('b', 'i', 'b', '0.01') DLPFC spatial 6.0% (binom p=2e-05, exact 7e-05) vs action 3.7% (chi2 p=0.57); ACC spatial 3.2% vs action 10.1% (chi2 p=0.013) -> holds False
('b', 'ii', 'a', '0.05') DLPFC spatial 7.5% (binom p=0.1, exact 0.1) vs action 9.0% (chi2 p=0.82); ACC spatial 5.3% vs action 18.5% (chi2 p=0.00014) -> holds False
('b', 'ii', 'a', '0.01') DLPFC spatial 3.0% (binom p=0.02, exact 0.05) vs action 3.7% (chi2 p=1); ACC spatial 1.1% vs action 13.8% (chi2 p=6.3e-06) -> holds False
('b', 'ii', 'b', '0.05') DLPFC spatial 12.7% (binom p=0.0003, exact 0.0004) vs action 6.0% (chi2 p=0.093); ACC spatial 7.4% vs action 15.3% (chi2 p=0.023) -> holds False
('b', 'ii', 'b', '0.01') DLPFC spatial 3.0% (binom p=0.02, exact 0.05) vs action 2.2% (chi2 p=1); ACC spatial 1.6% vs action 9.0% (chi2 p=0.0028) -> holds False
('b', 'iii', 'a', '0.05') DLPFC spatial 9.7% (binom p=0.01, exact 0.02) vs action 16.4% (chi2 p=0.15); ACC spatial 8.5% vs action 22.2% (chi2 p=0.00036) -> holds False
('b', 'iii', 'a', '0.01') DLPFC spatial 4.5% (binom p=0.0009, exact 0.002) vs action 6.0% (chi2 p=0.78); ACC spatial 3.2% vs action 12.7% (chi2 p=0.0012) -> holds False
('b', 'iii', 'b', '0.05') DLPFC spatial 10.4% (binom p=0.006, exact 0.007) vs action 14.9% (chi2 p=0.36); ACC spatial 9.5% vs action 18.0% (chi2 p=0.025) -> holds False
('b', 'iii', 'b', '0.01') DLPFC spatial 3.0% (binom p=0.02, exact 0.05) vs action 4.5% (chi2 p=0.75); ACC spatial 3.7% vs action 9.5% (chi2 p=0.038) -> holds False
('script',) DLPFC spatial 15.7% (binom p=2e-06, exact 3e-06) vs action 17.9% (chi2 p=0.74); ACC spatial 9.0% vs action 20.6% (chi2 p=0.0024) -> holds False
('script', 'stored flags') DLPFC spatial 14.9% (binom p=7e-06, exact 1e-05) vs action 17.2% (chi2 p=0.74); ACC spatial 7.9% vs action 18.5% (chi2 p=0.0039) -> holds False
holds under 2 of 26 readings; with the exact binomial test under 1

Result: reproduced, under 2 of 26 readings. With the full model, the 100-500 ms window, all trials and p < 0.01, DLPFC spatial value (8.2%, binomial p = 3e-08, exact 1e-07) equals action value (7.5%, chi-square p = 1), while in ACC spatial value (2.6%) is below action value (13.2%, p = 0.0003); the same holds with the value-only model (binomial p = 3e-07), which fails with the exact test (1e-06, not below the 1e-6 bound). In the script's reading the DLPFC binomial p is 2e-06, above the bound, with spatial 15.7% and action 17.9% (p = 0.74) and ACC 9.0% against 20.6% (p = 0.0024); the authors' stored flags give the same (binomial p = 7e-06).

fig8-attribute-value-ofc¶

About 24% of OFC neurons encoded attribute value at cue 1 (preferring probability or magnitude cues), above chance and more than in ACC or DLPFC.

In [58]:
nok = nok_x = nrd = 0
for key, alpha, k_, n_ in f8_all():
    fr = {a: 100 * k_[a][2] / n_[a] for a in (1, 2, 3)}
    pb = pfc7.binom_p_code(k_[3][2], n_[3], alpha)
    px = pfc7.binom_p_exact(k_[3][2], n_[3], alpha)
    pc = {a: pfc7.chi2_yates(k_[3][2], n_[3], k_[a][2], n_[a])[1] for a in (1, 2)}
    rest = all(fr[3] > fr[a] and pc[a] < 0.05 for a in (1, 2))
    tests = pb < 1e-7 and rest
    nrd += 1; nok += tests; nok_x += px < 1e-7 and rest
    print(key, f"OFC {fr[3]:.1f}% (binom p={pb:.1g}, exact {px:.1g}); ACC {fr[1]:.1f}% (chi2 p={pc[1]:.2g}); DLPFC {fr[2]:.1f}% "
          f"(chi2 p={pc[2]:.2g}); tests hold {tests}, within 24 +/- 2.4 {abs(fr[3] - 24) <= 2.4}")
print(f"tests hold under {nok} of {nrd} readings; with the exact binomial test under {nok_x}")
('a', 'i', 'a', '0.05') OFC 26.2% (binom p=4e-22, exact 1e-21); ACC 5.8% (chi2 p=1.6e-07); DLPFC 11.9% (chi2 p=0.0028); tests hold True, within 24 +/- 2.4 True
('a', 'i', 'a', '0.01') OFC 13.7% (binom p=1e-21, exact 9e-21); ACC 1.1% (chi2 p=7.3e-06); DLPFC 6.7% (chi2 p=0.073); tests hold False, within 24 +/- 2.4 False
('a', 'i', 'b', '0.05') OFC 20.2% (binom p=2e-13, exact 4e-13); ACC 4.8% (chi2 p=1.2e-05); DLPFC 10.4% (chi2 p=0.029); tests hold True, within 24 +/- 2.4 False
('a', 'i', 'b', '0.01') OFC 12.0% (binom p=4e-18, exact 3e-17); ACC 1.1% (chi2 p=4.3e-05); DLPFC 6.7% (chi2 p=0.17); tests hold False, within 24 +/- 2.4 False
('a', 'ii', 'a', '0.05') OFC 19.1% (binom p=4e-12, exact 9e-12); ACC 5.8% (chi2 p=0.00018); DLPFC 11.2% (chi2 p=0.079); tests hold False, within 24 +/- 2.4 False
('a', 'ii', 'a', '0.01') OFC 10.9% (binom p=8e-16, exact 5e-15); ACC 1.1% (chi2 p=0.00014); DLPFC 6.7% (chi2 p=0.28); tests hold False, within 24 +/- 2.4 False
('a', 'ii', 'b', '0.05') OFC 16.4% (binom p=6e-09, exact 1e-08); ACC 6.3% (chi2 p=0.0038); DLPFC 11.9% (chi2 p=0.34); tests hold False, within 24 +/- 2.4 False
('a', 'ii', 'b', '0.01') OFC 6.6% (binom p=1e-07, exact 4e-07); ACC 0.0% (chi2 p=nan); DLPFC 4.5% (chi2 p=0.59); tests hold False, within 24 +/- 2.4 False
('a', 'iii', 'a', '0.05') OFC 24.0% (binom p=8e-19, exact 3e-18); ACC 4.8% (chi2 p=2.3e-07); DLPFC 12.7% (chi2 p=0.017); tests hold True, within 24 +/- 2.4 True
('a', 'iii', 'a', '0.01') OFC 13.1% (binom p=2e-20, exact 1e-19); ACC 1.1% (chi2 p=1.3e-05); DLPFC 7.5% (chi2 p=0.15); tests hold False, within 24 +/- 2.4 False
('a', 'iii', 'b', '0.05') OFC 20.2% (binom p=2e-13, exact 4e-13); ACC 5.3% (chi2 p=3e-05); DLPFC 14.2% (chi2 p=0.21); tests hold False, within 24 +/- 2.4 False
('a', 'iii', 'b', '0.01') OFC 12.0% (binom p=4e-18, exact 3e-17); ACC 0.5% (chi2 p=1.2e-05); DLPFC 7.5% (chi2 p=0.25); tests hold False, within 24 +/- 2.4 False
('b', 'i', 'a', '0.05') OFC 25.1% (binom p=2e-20, exact 7e-20); ACC 5.8% (chi2 p=5e-07); DLPFC 12.7% (chi2 p=0.0093); tests hold True, within 24 +/- 2.4 True
('b', 'i', 'a', '0.01') OFC 12.6% (binom p=3e-19, exact 2e-18); ACC 1.1% (chi2 p=2.4e-05); DLPFC 4.5% (chi2 p=0.023); tests hold True, within 24 +/- 2.4 False
('b', 'i', 'b', '0.05') OFC 20.2% (binom p=2e-13, exact 4e-13); ACC 4.2% (chi2 p=4.9e-06); DLPFC 9.0% (chi2 p=0.0098); tests hold True, within 24 +/- 2.4 False
('b', 'i', 'b', '0.01') OFC 10.9% (binom p=8e-16, exact 5e-15); ACC 0.5% (chi2 p=3.8e-05); DLPFC 5.2% (chi2 p=0.11); tests hold False, within 24 +/- 2.4 False
('b', 'ii', 'a', '0.05') OFC 20.2% (binom p=2e-13, exact 4e-13); ACC 4.8% (chi2 p=1.2e-05); DLPFC 9.7% (chi2 p=0.017); tests hold True, within 24 +/- 2.4 False
('b', 'ii', 'a', '0.01') OFC 10.9% (binom p=8e-16, exact 5e-15); ACC 0.5% (chi2 p=3.8e-05); DLPFC 7.5% (chi2 p=0.4); tests hold False, within 24 +/- 2.4 False
('b', 'ii', 'b', '0.05') OFC 16.4% (binom p=6e-09, exact 1e-08); ACC 5.3% (chi2 p=0.001); DLPFC 11.9% (chi2 p=0.34); tests hold False, within 24 +/- 2.4 False
('b', 'ii', 'b', '0.01') OFC 6.0% (binom p=8e-07, exact 3e-06); ACC 0.5% (chi2 p=0.007); DLPFC 3.7% (chi2 p=0.51); tests hold False, within 24 +/- 2.4 False
('b', 'iii', 'a', '0.05') OFC 23.0% (binom p=3e-17, exact 9e-17); ACC 7.4% (chi2 p=5.2e-05); DLPFC 12.7% (chi2 p=0.03); tests hold True, within 24 +/- 2.4 True
('b', 'iii', 'a', '0.01') OFC 11.5% (binom p=6e-17, exact 4e-16); ACC 1.1% (chi2 p=7.6e-05); DLPFC 6.7% (chi2 p=0.22); tests hold False, within 24 +/- 2.4 False
('b', 'iii', 'b', '0.05') OFC 23.5% (binom p=5e-18, exact 2e-17); ACC 4.2% (chi2 p=1.5e-07); DLPFC 11.9% (chi2 p=0.014); tests hold True, within 24 +/- 2.4 True
('b', 'iii', 'b', '0.01') OFC 10.4% (binom p=1e-14, exact 6e-14); ACC 0.5% (chi2 p=6.8e-05); DLPFC 4.5% (chi2 p=0.086); tests hold False, within 24 +/- 2.4 False
('script',) OFC 23.0% (binom p=3e-17, exact 9e-17); ACC 7.9% (chi2 p=0.00011); DLPFC 11.2% (chi2 p=0.011); tests hold True, within 24 +/- 2.4 True
('script', 'stored flags') OFC 23.5% (binom p=5e-18, exact 2e-17); ACC 8.5% (chi2 p=0.00013); DLPFC 11.2% (chi2 p=0.008); tests hold True, within 24 +/- 2.4 True
tests hold under 11 of 26 readings; with the exact binomial test under 11

Result: reproduced. In the script's reading 23.0% of OFC neurons encode attribute value (binomial p = 3e-17, exact 9e-17), more than ACC (7.9%, chi-square p = 0.00011) and DLPFC (11.2%, p = 0.011); the full model on all trials at p < 0.05 gives 26.2%, 19.1% and 24.0% in the three windows. The authors' stored flags give 23.5%.

figs9-ev16-correlation¶

The GLM's regressors of interest are decorrelated by design except EV 16, whose mean r2 with EVs 7 and 9 is 0.167 and 0.194.

The criterion uses trials with 3 or more cues; the GLM script computes DM_crosscorr before dropping trials with 2 cues, over all 724 units (shown as a variant over the units loaded here).

In [59]:
def r2mats(trials):
    out = {}
    for u, d in U.items():
        X = pfc7.glm_design(d)
        if trials == "3+":
            X = X[d["num_pics_viewed"] >= 3]
        with np.errstate(invalid="ignore", divide="ignore"):
            out[u] = np.corrcoef(X.T) ** 2
    return out
INT = list(range(0, 6)) + list(range(12, 18))
for trials in ("3+", "all"):
    R2 = r2mats(trials)
    by_sess = {}
    for u, m in R2.items():
        by_sess.setdefault((U[u]["sb"], U[u]["snum"]), m)
    for over, mats in (("sessions", list(by_sess.values())), ("neurons", list(R2.values()))):
        M = np.nanmean(np.stack(mats), axis=0)
        pairs = [(M[i, j], i, j) for i in INT for j in INT if i < j and 15 not in (i, j)]
        mx = max(pairs)
        print(f"trials {trials}, mean over {over} (n = {len(mats)}): r2 EV16-EV7 {M[15, 6]:.3f}, EV16-EV9 {M[15, 8]:.3f};"
              f" largest other pair among EVs 1-6 and 13-18: EV{mx[1] + 1}-EV{mx[2] + 1} {mx[0]:.3f}")
trials 3+, mean over sessions (n = 53): r2 EV16-EV7 0.190, EV16-EV9 0.204; largest other pair among EVs 1-6 and 13-18: EV2-EV13 0.042
trials 3+, mean over neurons (n = 549): r2 EV16-EV7 0.180, EV16-EV9 0.190; largest other pair among EVs 1-6 and 13-18: EV2-EV13 0.046
trials all, mean over sessions (n = 53): r2 EV16-EV7 0.190, EV16-EV9 0.211; largest other pair among EVs 1-6 and 13-18: EV3-EV15 0.013
trials all, mean over neurons (n = 549): r2 EV16-EV7 0.180, EV16-EV9 0.198; largest other pair among EVs 1-6 and 13-18: EV3-EV15 0.015

Result: reproduced. Averaged over neurons on trials with 3 or more cues (reading b), the mean r2 of EV 16 is 0.180 with EV 7 and 0.190 with EV 9, within tolerance of 0.167 and 0.194, and the largest other pair among EVs 1-6 and 13-18 is 0.046. Averaged over sessions the values are 0.190 and 0.204, the first outside tolerance.

figs11-alternative-value-template¶

Replacing the attended value and left/right value templates by a uniform-diagonal form (negative absolute value difference) gives qualitatively the same functional dissociation across OFC, DLPFC and ACC.

The commented line of Fig4_RSA.m for Supplementary Figure 11 (r4 = -repmat(abs(m1-m2),4,4); r4 = r4 - mean(r4(:))), with left/right value following it.

In [60]:
RSA_ALT = {o9: rsa_run(MATS[o9], DM_ALT, FTP_ALT, section_rng("rsa-alt-" + o9)) for o9 in ("a", "b")}
print(rsa_table(RSA_ALT["a"]).round(4))
for o9, o8 in readings():
    r = RSA_ALT[o9]
    tm = "attended value"
    f = sig(r, tm, 3, o8) and cpdv(r, tm, 3) > cpdv(r, tm, 1) and cpdv(r, tm, 3) > cpdv(r, tm, 2)
    print(f"O9 ({o9}) O8 {o8}: attended value in OFC T {r['t'][IDX[tm], 2]:.2f}, p "
          f"{(r['p1'] if o8 == 'one' else r['p2'])[IDX[tm], 2]:.4f}, CPD % {np.round(100 * r['cpd'][IDX[tm]], 2)}"
          f" -> fig4f holds {f}")
ALT_LR = judge_lr(RSA_ALT)
                         T                     p_one                   p_two                      CPD                  
area                   ACC    DLPFC      OFC     ACC   DLPFC     OFC     ACC   DLPFC     OFC      ACC    DLPFC      OFC
template                                                                                                               
accept/reject      14.8084   7.6680  14.6658  0.0000  0.0000  0.0000  0.0000  0.0000  0.0000  35.8145  13.0143  35.3710
attended value      1.2029  -1.0759   3.3145  0.1435  0.8384  0.0021  0.2793  0.3361  0.0057   0.3668   0.2937   2.7193
left/right value    6.7475   6.5608  -0.0146  0.0025  0.0027  0.4383  0.0025  0.0027  0.9924  10.3822   9.8714   0.0001
spatial attention   8.3112  39.6581   4.3931  0.0021  0.0000  0.0188  0.0021  0.0000  0.0188  14.9491  80.0078   4.6810
stimulus identity   3.5297   4.4778  13.0860  0.0096  0.0021  0.0000  0.0208  0.0035  0.0000   3.0727   4.8542  30.3492
O9 (a) O8 one: attended value in OFC T 3.31, p 0.0021, CPD % [0.37 0.29 2.72] -> fig4f holds True
O9 (a) O8 two: attended value in OFC T 3.31, p 0.0057, CPD % [0.37 0.29 2.72] -> fig4f holds True
O9 (b) O8 one: attended value in OFC T 3.30, p 0.0031, CPD % [1.61 0.03 2.69] -> fig4f holds True
O9 (b) O8 two: attended value in OFC T 3.30, p 0.0079, CPD % [1.61 0.03 2.69] -> fig4f holds True
O9 (a) O8 one-sided: T ACC/DLPFC/OFC [ 6.75  6.56 -0.01], p [0.0025 0.0027 0.4383]; CPD % [10.38  9.87  0.  ]; F p = 0.0016 -> holds: True
O9 (a) O8 two-sided: T ACC/DLPFC/OFC [ 6.75  6.56 -0.01], p [0.0025 0.0027 0.9924]; CPD % [10.38  9.87  0.  ]; F p = 0.0016 -> holds: True
O9 (b) O8 one-sided: T ACC/DLPFC/OFC [4.99 5.86 0.24], p [0.0102 0.0049 0.3834]; CPD % [5.96 8.04 0.01]; F p = 0.0076 -> holds: True
O9 (b) O8 two-sided: T ACC/DLPFC/OFC [4.99 5.86 0.24], p [0.0102 0.0049 0.8674]; CPD % [5.96 8.04 0.01]; F p = 0.0076 -> holds: True

Result: reproduced. With the uniform-diagonal templates, attended value is significant in OFC (T = 3.31, p = 0.0021) with the largest CPD (2.72% against 0.37% and 0.29%), and left/right value is significant in ACC and DLPFC (T = 6.75 and 6.56) and absent in OFC (T = -0.01), under all four readings.

In [61]:
print(f"total run time {(time.time() - T0) / 60:.1f} min, peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
total run time 12.4 min, peak memory 6.0 GB

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
sessions-and-trials reproduced
neuron-counts reproduced
choice-accuracy-ev reproduced
chose-on-partial-information reproduced (assumed)
choice-accuracy-observed reproduced
figs1ab-cue-weights partially reproduced
figs1cd-fewer-cues-more-accurate reproduced
fig2a-sample-the-favourite reproduced
fig2b-positive-evidence reproduced
fig4d-spatial-attention reproduced
fig4e-ofc-stimulus-identity reproduced
fig4f-ofc-attended-value reproduced
fig4g-left-right-value reproduced
fig4h-acc-accept-reject reproduced
figs2-consistent-across-subjects reproduced
figs4-dlpfc-top-bottom reproduced
fig4-t75-latencies reproduced
figs5c-latency-order not reproduced
fig5a-ofc-value-cpd reproduced
fig5b-stable-attended-value-subspace reproduced
fig5c-attribute-cue2-vs-cue1 reproduced
fig5de-option-cue3-vs-stored reproduced
fig5f-option-stored-combined reproduced
fig5gj-cross-correlation-dynamics reproduced
fig5k-ofc-comparison-unique reproduced
figs67-no-comparison-acc-dlpfc reproduced
fig6a-acc-belief-subspace reproduced
fig6b-acc-belief-stronger reproduced
fig6c-belief-subspace-rt reproduced
fig6d-belief-ramp-to-choice reproduced
fig6e-action-subspace-ramp reproduced (12 of 72 readings)
fig7a-ofc-value-difference-neurons reproduced (4 of 12 readings)
fig7b-ofc-value-difference-any reproduced
fig7c-acc-belief-neurons reproduced
fig8-cue1-value-all-regions reproduced
fig8-action-value-acc-dlpfc partially reproduced
fig8-spatial-value-dlpfc reproduced (2 of 26 readings)
fig8-attribute-value-ofc reproduced
figs9-ev16-correlation reproduced
figs11-alternative-value-template reproduced

How the analysis differs from the paper's. The data are the authors' preprocessed units and behavioural files of the data set, not the raw recordings. Where the claims file names readings, each was run, and the paper's scripts (files of the data set) settled the rest: the unit selection (the stored mean rate, unit 87 dropped, unit 653 dropped for Figures 5 and 7), the count of pictures viewed (joystick-corrected), the RSA conditions and permutation test, the projection design and reaction-time bins, and the cue 1 regression shown as a further reading for Figure 8. The GLM written here gives the T-statistics the authors stored in the data set to within 1.6e-06. The script's cue 1 regression gives the T-statistics stored in info_gathering_cue1_both.mat to within 3.3e-07, and the Figure 6 weights computed on the random halves the scripts stored equal the weights they stored to within 2.6e-07. Figure 6 is shown with the scripts' projection design and with the Methods' two-column projection, and with the action weights at -210 ms (scripts) and -200 ms (Methods). The data the projections use equal those the scripts stored in info_gathering_ramp_to_choice.mat for their first five random halves, apart from bins with one trial, which MATLAB's mean turns into a flat line in the script. The Figure 6 traces are not cut at each bin's longest reaction time, as the script does for plotting; the windows the criteria use lie before those cuts.

Revision after the first verification. figs5c-latency-order is now not reproduced (it was partially reproduced), as the criterion's test fails under every reading. Added: the Methods' projection and the -200 ms action bin for Figure 6, the scripts' stored random halves and halves shared within a session, the full 183 x 183 cross-correlation maps for Figure 5g-j with 8-connected clusters as in the script, the paper's n for the Fisher tests, the exact binomial test and the authors' stored flags for Figure 8, the per-session comparison with Supplementary Table 1, and the script lines the analysis cites.

Revision after the second verification. No outcome changed. Added: the t75 point estimates of every template for Supplementary Figure 5c, the single 183 x 183 map of Figure 5g-j with 10 other seeds and with 10000 permutations (under which it no longer passes for EV 3 with EV 2, so that outcome rests on the script's separate maps), and the check of the Figure 6 projected data against the scripts' stored data. Corrected: the t75 range, the Fisher p-value against ACC for EV 3 with EV 2, the count of Figure 8 readings under the exact test, and the rationale for the figs5c and figs1ab labels. The table marks the outcomes that hold under a minority of readings.

What was found about the data set. Its files hold what the paper describes: 25 and 32 behavioural sessions with the paper's trial counts, 549 units in the three regions over 24 and 29 sessions, every unit file agreeing with the units table on subject, session, channel and area, and the rasters on the clock of the trial events (the cue 1 value code rises after cue 1 and vanishes when trial labels are shifted by one trial). The mean rate that selects units (average_firing_rate in all_units_info.mat) is not documented and is not the whole-session or trial rate; unit files 681 to 724 (sessions 5, 11, 23 and 27 of M) store the subject as "m" where all others store "M"; and the data descriptor names the preprocessed folder LTH_preprocessed_data while the archive holds LTH_processed_data.zip. Supplementary Table 1 counts every unit of each session, although its caption says units above 1 Hz.