Reproducing Moaddab & McDannald (2021) from CRCNS rrf-1¶

Paper: Moaddab M, McDannald MA (2021). Retrorubral field is a hub for diverse threat and aversive outcome signals. Current Biology 31:2099-2110, doi:10.1016/j.cub.2021.02.055.

Dataset: CRCNS rrf-1, "Recordings from retrorubral field neurons in male rats undergoing fear discrimination", doi:10.6080/K04B2ZJ5, read from the public S3 bucket crcnsarchive (rrf-1/live/data.zip). CRCNS data sets are not versioned; the version is recorded as unversioned. There is only one published state to pin: the bucket holds one live copy, with data descriptor version 0.6 (April 23, 2021), the only version in its change history. The files read are identified by the MD5 sums in the data set's checksums.md5: data.zip bf5cb2951c928394084d7b67c6b4663b (the same as the S3 ETag; the notebook checks it). Inside the zip, data/cubeFile/cube.mat (the authors' derived file of all units) and data/matFiles.tar (one file per unit with spike and event times) are read in memory.

Claims: claims/crcns-rrf-1/10.1016-j.cub.2021.02.055.yaml, written from the version of record with its supplement (Figures S1 to S6, Tables S1 to S4).

The data set also holds the paper's MATLAB code (cubeScriptPR25.m, rrfAnalysis.m). The claims file's last check asks an author who finds the code to follow it where it settles an open reading; the helper rrf.py cites the lines followed.

Claim Tested here
units-and-sessions tested
cue-responsive-units tested
behavior-discrimination tested
kmeans-elbow tested
kmeans-clusters tested
cluster-firing-characteristics tested
k1-k3-low-baseline tested
table1-cue-interaction tested
fig3b-excitatory-clusters tested
fig3d-inhibitory-clusters tested
figs4-onset-and-ramp tested
fig4abc-threat-bias tested
fig4def-danger-uncertainty-correlation tested
fig4ghi-danger-safety-correlation tested
fig4-correlations-differ tested
fig5a-tuning-peaks-exaggerated tested
fig5a-tuning-peaks-inhibited tested
fig5a-tuning-anova tested
fig5e-peak-probability-over-fear-output tested
fig5-regressor-cluster tested
table-s3-cluster-regression tested
fig5f-fear-output-vs-peak-probability tested
table1-outcome-anova tested
fig6a-k1-shock to fig6h-k8-ppe-then-unsigned (7 claims) tested
In [1]:
import collections
import warnings

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.cluster import KMeans

import rrf

warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 160)
pd.set_option("display.max_columns", 30)


def seeded(name):
    """One generator per claim section, seeded from the claim id."""
    return np.random.default_rng(sum(ord(ch) * (i + 1) for i, ch in enumerate(name)))


z = rrf.open_zip()
head = z.fp.fs.info(rrf.ZIP_URL)
print("data.zip size", head["size"], "ETag", head.get("ETag"))
assert head.get("ETag", "").strip('"') == rrf.ZIP_MD5
print([i.filename for i in z.infolist()])
cube = rrf.load_cube(z)
units = rrf.load_units(z)
print(len(units), "unit files;", len(cube["name"]), "units in cube.mat")
data.zip size 83946238 ETag "bf5cb2951c928394084d7b67c6b4663b"
['data/', 'data/cubeScriptPR25.m', 'data/cue3.wav', 'data/rrfAnalysis.m', 'data/cue2.wav', 'data/matFiles.tar', 'data/cue1.wav', 'data/cubeFile/', 'data/cubeFile/cube.mat']
743 unit files; 743 units in cube.mat

Data check¶

What is loaded, and checks of the description against the values: counts of rats, sessions and units; the trial table (16 trials per session, 4/2/6/4 by type); that the authors' cube matches the spike times of the unit files; shock timing; units and ranges of the variables used; duplicate recordings; and that spike times share the clock of the trial events.

In [2]:
names = cube["name"]
session = np.array([n[:16] for n in names])     # rat, date, behavior program
rat = np.array([n[:4] for n in names])
print("units", len(names), "unique names", len(set(names)))
print("sessions", len(set(session)), "rats", len(set(rat)))
print(pd.DataFrame({"units": pd.Series(rat).value_counts().sort_index(),
                    "sessions": pd.Series(session).groupby(rat).nunique().sort_index()}).T)
print("program letters", collections.Counter(n[15] for n in names))
print("trial tags identical in every unit:", bool((cube["tag"][:, 0, :] == rrf.TRIAL_TYPE[:, None]).all()),
      "counts", collections.Counter(rrf.TRIAL_TYPE))

# Rebuild the cube's arrays from the unit files' spike and event times (cubeScriptPR25.m)
by_name = {u["filename"] + u["neuron"]: u for u in units}
mismatch = collections.Counter()
shock_lat, iti, odd_shock = [], [], []
for i, n in enumerate(names):
    u = by_name[n]
    on, tg = rrf.trial_onsets(u)
    if not (np.allclose(on, cube["tag"][:, 1, i]) and (tg == cube["tag"][:, 0, i]).all()):
        mismatch["trial onsets or tags"] += 1
        continue
    for key, w, nb in (("ms250", 0.25, 200), ("s1", 1.0, 50)):
        if not np.array_equal(rrf.binned_rates(u["spike"], on, w, nb), cube[f"fire.raw.{key}.interval"][:, :, i]):
            mismatch[f"{key} rates"] += 1
    if not np.array_equal(rrf.binned_rates(u["spike"], on, 2, 1, start=-2)[:, 0], cube["fire.raw.base2"][:, i]):
        mismatch["2-s baseline"] += 1
    if not np.allclose(u["wave"], cube["wave"][:, i]):
        mismatch["waveform"] += 1
    if np.any(np.diff(u["spike"]) < 0):
        mismatch["unsorted spikes"] += 1
    sh = u.get("EVT01", np.array([]))
    for t, ty in zip(on, tg):
        d = sh[(sh > t) & (sh <= t + 30)] - t
        if ty in (1, 2):
            shock_lat.extend(d)
            if len(d) != 1 or abs(d[0] - 12) > 0.01:
                odd_shock.append((n, ty, np.round(d, 3)))
    iti.extend(np.diff(np.sort(on)))
print("mismatches between cube.mat and the unit files:", dict(mismatch) or "none")
shock_lat = np.array(shock_lat)
print(f"shock onset after cue onset: {len(shock_lat)} shocks, median {np.median(shock_lat):.3f} s, "
      f"range {shock_lat.min():.3f} to {shock_lat.max():.3f} s")
print("trials whose shock is not one event at 12 s:", odd_shock)
print(f"inter-trial interval (onset to onset): mean {np.mean(iti)/60:.2f} min, "
      f"range {np.min(iti):.0f} to {np.max(iti):.0f} s")
wave = cube["wave"]
print(f"waveforms: {wave.shape[0]} samples per unit, values {wave.min():.4f} to {wave.max():.4f} (units not stated)")
r250 = cube["fire.raw.ms250.interval"]
print(f"250-ms rates: {r250.min():.0f} to {r250.max():.0f} Hz; 1-s rates {cube['fire.raw.s1.interval'].max():.0f} Hz max")
cer = cube["cer.cue"]
print(f"suppression ratio per trial: {np.nanmin(cer):.2f} to {np.nanmax(cer):.2f}, NaN {np.isnan(cer).sum()} "
      f"(the code sets NaN, no pokes in baseline or cue, to 1)")
print(f"baseline poke rate (pokes/min, 20 s before cue): {cube['poke.base'].min()} to {cube['poke.base'].max()}")
units 743 unique names 743
sessions 228 rats 11
          rb01  rb03  rb04  rb06  rb07  rb09  rb10  rb11  rb12  rb13  rb14
units       92   108    40   107    37    55    34    29    81    88    72
sessions    28    26    20    21    19    23    15    14    22    20    20
program letters Counter({'a': 396, 'b': 313, 'c': 34})
trial tags identical in every unit: True counts Counter({np.int64(3): 6, np.int64(1): 4, np.int64(4): 4, np.int64(2): 2})
mismatches between cube.mat and the unit files: none
shock onset after cue onset: 4458 shocks, median 12.000 s, range 12.000 to 12.040 s
trials whose shock is not one event at 12 s: [(np.str_('rb09030320epr25aSPK04a'), np.int64(1), array([12.04])), (np.str_('rb09030320epr25aSPK14a'), np.int64(1), array([12.04]))]
inter-trial interval (onset to onset): mean 3.89 min, range 203 to 265 s
waveforms: 32 samples per unit, values -0.5958 to 0.3150 (units not stated)
250-ms rates: 0 to 504 Hz; 1-s rates 241 Hz max
suppression ratio per trial: -1.00 to 1.00, NaN 0 (the code sets NaN, no pokes in baseline or cue, to 1)
baseline poke rate (pokes/min, 20 s before cue): 0 to 108
In [3]:
# The z-scored arrays of cube.mat are the code's normalization of its raw arrays
zs1 = rrf.z_code(cube["fire.raw.s1.interval"].astype(float), cube["fire.raw.base2"].astype(float))
z250 = rrf.z_code(cube["fire.raw.ms250.interval"].astype(float), cube["fire.raw.base2"].astype(float))
print("max |z recomputed - cube z|: 1-s", float(np.nanmax(np.abs(zs1 - cube["fire.z.s1.interval"]))),
      "250-ms", float(np.nanmax(np.abs(z250 - cube["fire.z.ms250.interval"]))))

# Suppression ratios are the same for all units of a session
sr_spread = pd.DataFrame(cer.T).groupby(session).agg(lambda x: np.nanmax(x) - np.nanmin(x)).to_numpy()
print("largest within-session difference in a trial's suppression ratio:", np.nanmax(sr_spread))

# Duplicate recordings: identical spike trains, and sessions with identical event times
spk = collections.defaultdict(list)
ev = collections.defaultdict(set)
for u in units:
    spk[hash(u["spike"].tobytes())].append(u["filename"] + u["neuron"])
    ev[hash(np.concatenate([u[k] for k in sorted(u) if k.startswith("EVT")]).tobytes())].add(u["filename"])
dup_units = [v for v in spk.values() if len(v) > 1]
dup_sessions = [sorted(v) for v in ev.values() if len(v) > 1]
print("units with identical spike trains:", dup_units or "none")
print("different session names with identical event times:", dup_sessions or "none")
same_events_sessions = len(ev)
print("distinct event sets", same_events_sessions, "for", len(set(session)), "session names")
max |z recomputed - cube z|: 1-s 1.5276668818842154e-13 250-ms 7.709388682997087e-13
largest within-session difference in a trial's suppression ratio: 0.0
units with identical spike trains: none
different session names with identical event times: none
distinct event sets 228 for 228 session names
In [4]:
# The unit files hold spikes only from 20 s before to about 33.5 s after each cue onset: the
# recording was paused between trials (event EVT14, "Pause recording" in cubeScriptPR25.m, comes
# 31.5 s after each cue onset). The descriptor does not say so.
rel_lo, rel_hi = [], []
for u in units:
    on = np.sort(rrf.trial_onsets(u)[0])
    k = np.clip(np.searchsorted(on, u["spike"] + 20.01) - 1, 0, len(on) - 1)
    rel = u["spike"] - on[k]
    rel_lo.append(rel.min()); rel_hi.append(rel.max())
print(f"spike times relative to the trial's cue onset: from {min(rel_lo):.2f} to {max(rel_hi):.2f} s")
ev14 = np.concatenate([np.sort(u["EVT14"]) - np.sort(rrf.trial_onsets(u)[0]) for u in units])
print(f"EVT14 after cue onset: {ev14.min():.3f} to {ev14.max():.3f} s")

# Clock check: spikes against the trial table. For each unit, danger against safety spike count
# (t test over trials) in the 12 s from cue onset; in the 12 s from 20 s before cue onset (no cue);
# and from cue onset with the trial labels moved one trial later in time (each trial takes the
# type of the trial before it).
def frac_discriminating(start, shift_labels=False):
    hits = []
    for i, n in enumerate(names):
        u = by_name[n]
        on = cube["tag"][:, 1, i]
        lab = rrf.TRIAL_TYPE.copy()
        if shift_labels:
            order = np.argsort(on)
            lab[order[1:]] = lab[order[:-1]]
            lab[order[0]] = 0
        t0 = on + start
        cnt = np.diff(np.searchsorted(u["spike"], np.stack([t0, t0 + 12]).T, side="right"), axis=1)[:, 0]
        p = stats.ttest_ind(cnt[lab == 1], cnt[lab == 4]).pvalue
        hits.append(np.nan_to_num(p, nan=1.0) < 0.05)
    return np.mean(hits)

for label, start, sh in (("cue onset to +12 s, true labels", 0.0, False),
                         ("-20 to -8 s, true labels", -20.0, False),
                         ("cue onset to +12 s, labels shifted one trial", 0.0, True)):
    print(f"{label}: {100 * frac_discriminating(start, sh):.1f}% of 743 units differ between danger "
          "and safety (p < 0.05)")
pk = cube["poke.s1.interval"].astype(float)
first = ~pd.Series(session).duplicated().to_numpy()      # one unit per session
pk_cue, pk_pre = pk[:, 20:30, first].mean(1), pk[:, 0:20, first].mean(1)
print("nose pokes per min, mean over 228 sessions: danger cue", round(float(pk_cue[rrf.DANGER].mean()), 1),
      "safety cue", round(float(pk_cue[rrf.SAFETY].mean()), 1), "20 s before cue", round(float(pk_pre.mean()), 1))
spike times relative to the trial's cue onset: from -20.01 to 33.57 s
EVT14 after cue onset: 31.495 to 33.540 s
cue onset to +12 s, true labels: 30.8% of 743 units differ between danger and safety (p < 0.05)
-20 to -8 s, true labels: 5.0% of 743 units differ between danger and safety (p < 0.05)
cue onset to +12 s, labels shifted one trial: 7.4% of 743 units differ between danger and safety (p < 0.05)
nose pokes per min, mean over 228 sessions: danger cue 2.1 safety cue 30.0 20 s before cue 29.0

The paper's code at the lines followed¶

The helper cites the code where it settles a reading the claims file left open. These are the lines, read from data.zip: the normalization (floored 2-s baseline, differential firing, the z-score over all trials and bins of a unit, and the trial-type means), the k-means matrix and run, the elbow measure, the map from the code's cluster numbers to k1..k8, the tuning-curve columns of each cluster, the bootstrap call, the code's post-shock windows, and the axis of the Figure 6 traces.

In [5]:
CODE_LINES = [
    ("cubeScriptPR25.m", 265, 272, "2-s pre-cue rate, floored"),
    ("cubeScriptPR25.m", 460, 472, "differential firing and z-score over all trials and bins"),
    ("rrfAnalysis.m", 466, 470, "normalized firing of a trial type: mean of the trial z-scores"),
    ("rrfAnalysis.m", 911, 915, "k-means matrix (1-s bins 21-30: 0-10 s; 34-39: 13-19 s after cue onset) and run"),
    ("rrfAnalysis.m", 945, 993, "elbow runs, the plotted measure and its bar plot (y axis 0 to 9000)"),
    ("rrfAnalysis.m", 999, 999, "cluster map"), ("rrfAnalysis.m", 1013, 1013, ""), ("rrfAnalysis.m", 1027, 1027, ""),
    ("rrfAnalysis.m", 1041, 1041, ""), ("rrfAnalysis.m", 1055, 1055, ""), ("rrfAnalysis.m", 1069, 1069, ""),
    ("rrfAnalysis.m", 1083, 1083, ""), ("rrfAnalysis.m", 1097, 1097, ""),
    ("rrfAnalysis.m", 3403, 3403, "tuning-curve columns of the 14 regression bins"), ("rrfAnalysis.m", 3435, 3435, ""),
    ("rrfAnalysis.m", 3467, 3467, ""), ("rrfAnalysis.m", 3499, 3499, ""), ("rrfAnalysis.m", 3532, 3532, ""),
    ("rrfAnalysis.m", 3564, 3564, ""), ("rrfAnalysis.m", 3597, 3597, ""),
    ("rrfAnalysis.m", 1744, 1744, "bootstrap: studentized, no StdErr given"),
    ("rrfAnalysis.m", 6097, 6097, "post-shock windows: 250-ms bins 131-138 (0-2 s) and 161-200 (7.5-17.5 s)"),
    ("rrfAnalysis.m", 6135, 6135, ""),
    ("rrfAnalysis.m", 6177, 6183, "Figure 6 traces: shock types from bin 131, the others from 129, x ticks"),
    ("rrfAnalysis.m", 6197, 6198, ""), ("rrfAnalysis.m", 6209, 6210, ""),
]
for member, first, last, what in CODE_LINES:
    if what:
        print(f"--- {member}: {what}")
    print(rrf.code_lines(z, f"data/{member}", first, last))
print("code's map, as in rrf.CODE_IDX:", rrf.CODE_IDX)
--- cubeScriptPR25.m: 2-s pre-cue rate, floored
  265      % 2-s prior to cue onset
  266          
  267      aa = spike(spike>time.cue(iii,2)-2); % find first time point for spike counting
  268      bb = spike(spike<=time.cue(iii,2)); % final last time point for spike counting
  269      cc = intersect(aa,bb); % find spikes between first and last time point
  270      ee = length(cc)/2; % calculate rate in spikes/s
  271      ee = floor(ee); % round down to nearest integer
  272      fire.raw.base2(iii,1) = ee; % save firing rate for that trial
--- cubeScriptPR25.m: differential firing and z-score over all trials and bins
  460      fire.diff.s1.interval    = bsxfun(@minus,fire.raw.s1.interval,fire.raw.base2);
  461      fire.diff.ms500.interval = bsxfun(@minus,fire.raw.ms500.interval,fire.raw.base2);
  462      fire.diff.ms250.interval = bsxfun(@minus,fire.raw.ms250.interval,fire.raw.base2);
  463      fire.diff.ms100.interval = bsxfun(@minus,fire.raw.ms100.interval,fire.raw.base2);
  464      
  465      %%%%%%%%%%%%%%%%%
  466      % find z firing %
  467      %%%%%%%%%%%%%%%%%
  468     
  469      fire.z.s1.interval = zscore(fire.diff.s1.interval,0,'all');
  470      fire.z.ms500.interval = zscore(fire.diff.ms500.interval,0,'all');
  471      fire.z.ms250.interval = zscore(fire.diff.ms250.interval,0,'all');
  472      fire.z.ms100.interval = zscore(fire.diff.ms100.interval,0,'all');
--- rrfAnalysis.m: normalized firing of a trial type: mean of the trial z-scores
  466      cueR.fire.z.s1.cue100(ii,:) = mean(cueR.fire.z.s1.interval(1:4,:,ii));
  467      cueR.fire.z.s1.cueSPR(ii,:) = mean(cueR.fire.z.s1.interval(5:6,:,ii));
  468      cueR.fire.z.s1.cueNsPR(ii,:) = mean(cueR.fire.z.s1.interval(7:12,:,ii));
  469      cueR.fire.z.s1.cuePR(ii,:) = mean(cueR.fire.z.s1.interval(5:12,:,ii));
  470      cueR.fire.z.s1.cue0(ii,:) = mean(cueR.fire.z.s1.interval(13:16,:,ii));
--- rrfAnalysis.m: k-means matrix (1-s bins 21-30: 0-10 s; 34-39: 13-19 s after cue onset) and run
  911  aa = [cueR.fire.z.s1.cue100(:,21:30),cueR.fire.z.s1.cuePR(:,21:30),cueR.fire.z.s1.cue0(:,21:30),...
  912        cueR.fire.z.s1.cue100(:,34:39),cueR.fire.z.s1.cueSPR(:,34:39),cueR.fire.z.s1.cueNsPR(:,34:39),cueR.fire.z.s1.cue0(:,34:39)];
  913    
  914  rng(1);
  915  [idx,~,~,~] = kmeans(aa,8);
--- rrfAnalysis.m: elbow runs, the plotted measure and its bar plot (y axis 0 to 9000)
  945  rng(1);
  946  [~,~,sumd13,~] = kmeans(aa,13);
  947  rng(1);
  948  [~,~,sumd14,~] = kmeans(aa,14);
  949  rng(1);
  950  [~,~,sumd15,~] = kmeans(aa,15);
  951  
  952  kmeansSumdPlot (1,1) = sumd1;
  953  kmeansSumdPlot (1,2) = sum(sumd2);
  954  kmeansSumdPlot (1,3) = mean(sumd3);
  955  kmeansSumdPlot (1,4) = mean(sumd4);
  956  kmeansSumdPlot (1,5) = mean(sumd5);
  957  kmeansSumdPlot (1,6) = mean(sumd6);
  958  kmeansSumdPlot (1,7) = mean(sumd7);
  959  kmeansSumdPlot (1,8) = mean(sumd8);
  960  kmeansSumdPlot (1,9) = mean(sumd9);
  961  kmeansSumdPlot (1,10) = mean(sumd10);
  962  kmeansSumdPlot (1,11) = mean(sumd11);
  963  kmeansSumdPlot (1,12) = mean(sumd12);
  964  kmeansSumdPlot (1,13) = mean(sumd13);
  965  kmeansSumdPlot (1,14) = mean(sumd14);
  966  kmeansSumdPlot (1,15) = mean(sumd15);
  967  
  968  for jj = 1:14
  969      
  970     bb(1,jj) = (kmeansSumdPlot(1,jj+1)/kmeansSumdPlot(1,jj));
  971      
  972  end
  973  
  974  kmeansSumdPlotPer = [NaN,bb];
  975  
  976  clear jj bb;
  977  
  978  % bar plot
  979  
  980  xx = 1:15;
  981  
  982  yyaxis left
  983  h = bar(xx,kmeansSumdPlot);
  984  axis([0.25 15.75 0 9000]);
  985  set(gca,'YTick',0:2000:9000);
  986  set(gca,'YTickLabel',{'0','2000','4000','6000','8000','10000'},'fontsize',8);
  987  box off;
  988  yyaxis right
  989  h = plot(xx,kmeansSumdPlotPer);
  990  axis([0.25 15.75 0 1]);
  991  hline(0.9,'k-');
  992  box off;
  993  set(gcf,'Position',[100 100 275 180]);
--- rrfAnalysis.m: cluster map
  999  cueR.k1.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 5),1:50); %#ok<*FNDSB>
 1013  cueR.k2.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 6),1:50); %#ok<*FNDSB>
 1027  cueR.k3.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 7),1:50); %#ok<*FNDSB>
 1041  cueR.k4.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 1),1:50); %#ok<*FNDSB>
 1055  cueR.k5.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 4),1:50); %#ok<*FNDSB>
 1069  cueR.k6.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 8),1:50); %#ok<*FNDSB>
 1083  cueR.k7.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 3),1:50); %#ok<*FNDSB>
 1097  cueR.k8.fire.z.s1.cue100 = cueR.fire.z.s1.cue100(find(idx == 2),1:50); %#ok<*FNDSB>
--- rrfAnalysis.m: tuning-curve columns of the 14 regression bins
 3403  cueR.k1.fire.z.s1.reg.tune(:,1) = cueR.k1.fire.z.s1.reg.prob0(:,3);
 3435  cueR.k3.fire.z.s1.reg.tune(:,1) = mean(cueR.k3.fire.z.s1.reg.prob0(:,3:14),2);
 3467  cueR.k4.fire.z.s1.reg.tune(:,1) = mean(cueR.k4.fire.z.s1.reg.prob0(:,3:14),2)*-1;
 3499  cueR.k5.fire.z.s1.reg.tune(:,1) = mean(cueR.k5.fire.z.s1.reg.prob0(:,8:12),2);
 3532  cueR.k6.fire.z.s1.reg.tune(:,1) = mean(cueR.k6.fire.z.s1.reg.prob0(:,3:14),2)*-1;
 3564  cueR.k7.fire.z.s1.reg.tune(:,1) = mean(cueR.k7.fire.z.s1.reg.prob0(:,13:14),2);
 3597  cueR.k8.fire.z.s1.reg.tune(:,1) = mean(cueR.k8.fire.z.s1.reg.prob0(:,3:14),2)*-1;
--- rrfAnalysis.m: bootstrap: studentized, no StdErr given
 1744  [cueR.cerIndcue100cuePRboot(2:3,1),bootstat] = bootci(1000,{@mean,a},'type','student');
--- rrfAnalysis.m: post-shock windows: 250-ms bins 131-138 (0-2 s) and 161-200 (7.5-17.5 s)
 6097  cueR.k1.fire.z.ms250.cue100postShock1 = mean(cueR.k1.fire.z.ms250.cue100(:,131:138),2);
 6135  cueR.k1.fire.z.ms250.cue100postShock2 = mean(cueR.k1.fire.z.ms250.cue100(:,161:200),2);
--- rrfAnalysis.m: Figure 6 traces: shock types from bin 131, the others from 129, x ticks
 6177  a = [cueR.k1.fire.z.ms250.cue100mean(:,131:200);...
 6178       cueR.k1.fire.z.ms250.cueSPRmean(:,131:200)];
 6179  
 6180  aa = sgolayfilt(a',1,7);
 6181  
 6182  b = [cueR.k1.fire.z.ms250.cueNsPRmean(:,129:200);...
 6183       cueR.k1.fire.z.ms250.cue0mean(:,129:200)];
 6197  axis([1 72 -.5 1.25]);
 6198  rectangle('Position',[1 -1 2 3],'FaceColor',[1 1 0],'EdgeColor','none');
 6209  set(gca,'XTick',3:8:74);
 6210  set(gca,'XTickLabel',{'0','2','4','6','8','10','12','14','16','18','20'},'fontsize',8);
code's map, as in rrf.CODE_IDX: {'k1': 5, 'k2': 6, 'k3': 7, 'k4': 1, 'k5': 4, 'k6': 8, 'k7': 3, 'k8': 2}

units-and-sessions¶

The paper recorded 743 single units from 11 rats over 228 fear discrimination sessions.

In [6]:
n_units, n_sessions, n_rats = len(names), len(set(session)), len(set(rat))
print(f"units {n_units} (expected 743 +/- 74), sessions {n_sessions} (228 +/- 23), rats {n_rats} (11 exactly)")
print("units per session: median", int(np.median(pd.Series(session).value_counts())),
      "range", pd.Series(session).value_counts().min(), "to", pd.Series(session).value_counts().max())
units 743 (expected 743 +/- 74), sessions 228 (228 +/- 23), rats 11 (11 exactly)
units per session: median 3 range 1 to 10

Result: reproduced. The data set holds 743 units from 228 sessions of 11 rats, the three counts of the paper. No unit or session is deposited twice (data check).

cue-responsive-units¶

423 units, from 190 sessions, were cue responsive, with no fewer than 11 per rat.

The screen of the criterion (STAR Methods, Identifying cue-responsive neurons), run as the code runs it (rrfAnalysis.m 5-60): the rates are the cube's floored integer rates, and a test that returns NaN (no variance) counts as not significant. A variant uses unfloored rates from the spike times.

In [7]:
def cue_screen(base10, onset, last5):
    sig = []
    for rows in (rrf.DANGER, rrf.UNC, rrf.SAFETY):
        for x in (onset, last5):
            p = stats.ttest_rel(base10[rows], x[rows], axis=0).pvalue
            sig.append(np.nan_to_num(p, nan=1.0) < 0.05)
    return np.array(sig).T

sig = cue_screen(cube["fire.raw.base10"].astype(float), cube["fire.raw.select.cueOnset"].astype(float),
                 cube["fire.raw.select.cueLastFive"].astype(float))
resp = sig.any(1)
per_rat = pd.Series(rat[resp]).value_counts().sort_index()
paper_s1 = {"rb01": 35, "rb03": 53, "rb04": 24, "rb06": 59, "rb07": 29, "rb09": 33, "rb10": 18,
            "rb11": 11, "rb12": 47, "rb13": 69, "rb14": 45}
print(f"cue-responsive units {resp.sum()} (expected 423 +/- 42); sessions {len(set(session[resp]))} "
      f"(190 +/- 19); fewest per rat {per_rat.min()} (11 +/- 1.1)")
print(pd.DataFrame({"here": per_rat, "Figure S1": pd.Series(paper_s1)}).T)
print("units significant in each of the six tests (D onset, D last 5 s, U onset, U last 5 s, S onset, S last 5 s):",
      sig[:, [0, 1, 2, 3, 4, 5]].sum(0))

# Variant: unfloored rates from the spike times
raw_rates = np.zeros((3, 16, len(names)))
for i, n in enumerate(names):
    u, on = by_name[n], cube["tag"][:, 1, i]
    raw_rates[0, :, i] = rrf.binned_rates(u["spike"], on, 10, 1, start=-10, floor=False)[:, 0]
    raw_rates[1, :, i] = rrf.binned_rates(u["spike"], on, 1, 1, start=0, floor=False)[:, 0]
    raw_rates[2, :, i] = rrf.binned_rates(u["spike"], on, 5, 1, start=5, floor=False)[:, 0]
resp_unfloored = cue_screen(*raw_rates).any(1)
print("variant, unfloored rates:", resp_unfloored.sum(), "units;", (resp_unfloored & resp).sum(), "in common")
R = np.flatnonzero(resp)          # indices of the 423 units used below
cue-responsive units 423 (expected 423 +/- 42); sessions 190 (190 +/- 19); fewest per rat 11 (11 +/- 1.1)
           rb01  rb03  rb04  rb06  rb07  rb09  rb10  rb11  rb12  rb13  rb14
here         35    53    24    59    29    33    18    11    47    69    45
Figure S1    35    53    24    59    29    33    18    11    47    69    45
units significant in each of the six tests (D onset, D last 5 s, U onset, U last 5 s, S onset, S last 5 s): [138 145 189 187  71  45]
variant, unfloored rates: 461 units; 409 in common

Result: reproduced. The paper's screen finds 423 cue-responsive units from 190 sessions, and the per-rat counts equal those of Figure S1 (fewest 11, rb11).

behavior-discrimination¶

In the sessions that yielded cue-responsive units, rats fully discriminated the cues by suppression ratio (danger > uncertainty > safety), with a main effect of cue and 95% bootstrap CIs of every differential suppression ratio excluding zero.

Suppression ratio per trial is the cube's cer.cue (20-s baseline, 10-s cue; NaN set to 1 as in cubeScriptPR25.m). Each session with a cue-responsive unit counts once.

In [8]:
g = seeded("behavior-discrimination")
first_of_session = ~pd.Series(session[R]).duplicated().to_numpy()
S_idx = R[first_of_session]
sr = cube["cer.cue"][:, S_idx]
ses_df = pd.DataFrame({"rat": rat[S_idx], "D": sr[rrf.DANGER].mean(0), "U": sr[rrf.UNC].mean(0),
                       "S": sr[rrf.SAFETY].mean(0)})
print("sessions", len(ses_df))

def behaviour(per_rat_df, label):
    y = per_rat_df[["D", "U", "S"]].to_numpy()
    a = rrf.mixed_anova(y)["w1"]
    print(f"{label}: cue effect F({a[1]}, {a[2]}) = {a[0]:.2f}, p = {a[3]:.3g}, partial eta2 = {a[4]:.2f}")
    print("  means D, U, S:", np.round(y.mean(0), 3))
    res = {}
    for nm, d, expv, tol in (("D-U", y[:, 0] - y[:, 1], 0.42, 0.14), ("U-S", y[:, 1] - y[:, 2], 0.40, 0.34),
                             ("D-S", y[:, 0] - y[:, 2], 0.82, 0.12)):
        ci = rrf.boot_ci(d, g)
        res[nm] = ci
        print(f"  {nm}: mean {ci[0]:.3f} CI [{ci[1]:.3f}, {ci[2]:.3f}]; expected {expv} +/- {tol}: "
              f"{'within' if abs(ci[0] - expv) <= tol else 'outside'}")
    return a, res

per_rat_mean = ses_df.groupby("rat")[["D", "U", "S"]].mean()
print(per_rat_mean.round(3).T)
beh_main = behaviour(per_rat_mean, "per rat, mean over sessions (main)")
trials = []
for i in S_idx:
    trials.append(pd.DataFrame({"rat": rat[i], "type": rrf.TRIAL_TYPE, "sr": cube["cer.cue"][:, i]}))
trials = pd.concat(trials)
trials["cue"] = trials["type"].map({1: "D", 2: "U", 3: "U", 4: "S"})
pooled = trials.groupby(["rat", "cue"])["sr"].mean().unstack()
beh_var = behaviour(pooled, "variant, per rat over pooled trials")
sessions 190
rat   rb01   rb03   rb04   rb06   rb07   rb09   rb10   rb11   rb12   rb13   rb14
D    0.938  0.949  0.791  0.907  0.966  0.878  0.477  0.957  0.803  0.958  0.963
U    0.306  0.360  0.448  0.386  0.455  0.387  0.038  0.733  0.374  0.553  0.899
S    0.103  0.044 -0.090  0.060  0.165  0.045 -0.029  0.028  0.070  0.227 -0.065
per rat, mean over sessions (main): cue effect F(2, 20) = 103.57, p = 2.8e-11, partial eta2 = 0.91
  means D, U, S: [0.871 0.449 0.051]
  D-U: mean 0.422 CI [0.264, 0.516]; expected 0.42 +/- 0.14: within
  U-S: mean 0.398 CI [0.261, 0.748]; expected 0.4 +/- 0.34: within
  D-S: mean 0.821 CI [0.704, 0.891]; expected 0.82 +/- 0.12: within
variant, per rat over pooled trials: cue effect F(2, 20) = 103.57, p = 2.8e-11, partial eta2 = 0.91
  means D, U, S: [0.871 0.449 0.051]
  D-U: mean 0.422 CI [0.260, 0.520]; expected 0.42 +/- 0.14: within
  U-S: mean 0.398 CI [0.273, 0.718]; expected 0.4 +/- 0.34: within
  D-S: mean 0.821 CI [0.706, 0.892]; expected 0.82 +/- 0.12: within

Result: reproduced. Over the 190 sessions and 11 rats, suppression is ordered danger > uncertainty > safety, the cue effect is significant, all three bootstrap CIs exclude zero, and the three mean differences fall within their tolerances under both readings (numbers above).

Normalized firing¶

The code's normalization (trial z-scores over all trials and bins of a unit; see the helper) is what cube.mat holds and what the code analyses. The Methods describe z-scoring the trial-type means; the claims file names two readings of that, z-a (four trial types) and z-b (three). Both are computed here as variants where they apply. The code's version is the main reading (the claims file asks an author who finds the code to follow it), so every outcome that uses normalized firing, or the clusters built from it, rests on the assumption that the code, not the Methods' wording, is what the paper did.

In [9]:
m250 = rrf.type_means(cube["fire.z.ms250.interval"][:, :, R])        # code reading
m1 = rrf.type_means(cube["fire.z.s1.interval"][:, :, R])
raw250 = cube["fire.raw.ms250.interval"][:, :, R].astype(float)
m250_za = rrf.z_methods(raw250, n_types=4)
m250_zb = rrf.z_methods(raw250, n_types=3)
NORMS = {"code": m250, "z-a": m250_za, "z-b": m250_zb}
print({k: (round(float(np.nanmin(v["D"])), 2), round(float(np.nanmax(v["D"])), 2)) for k, v in NORMS.items()},
      "range of danger normalized firing per reading")
print("units with a NaN z-score:", {k: int(np.isnan(v["D"]).any(0).sum()) for k, v in NORMS.items()})
{'code': (-2.86, 8.02), 'z-a': (-4.82, 11.77), 'z-b': (-5.11, 12.24)} range of danger normalized firing per reading
units with a NaN z-score: {'code': 0, 'z-a': 0, 'z-b': 0}

kmeans-elbow¶

In k-means clustering of the 423 cue-responsive units, the mean squared Euclidean distance to the centroid falls as the cluster number rises from 1 to 15, and the decrease diminishes after eight clusters.

The matrix is the code's: 1-s normalized firing, cue bins 0-10 s for danger, uncertainty and safety, and six 1-s bins from 13 s after cue onset for the four outcome types (rrfAnalysis.m, "K means clustering"; the code starts the outcome epochs at 13 s, 0.5 s after shock offset). The code runs rng(1); kmeans(aa, k) once for each k. MATLAB's k-means with its default generator is reproduced exactly here (rrf.matlab_kmeans; the next section shows it gives the paper's eight cluster sizes), so the main reading is the code's own run. The measure is the mean over units of the squared distance to the centroid (Methods); the code's measure, the mean over clusters of the summed squared distances (mean(sumd), sum at k = 2, which is what the code plots for Figure 1E), is shown too. Variants: the claims file's readings of the outcome start (e-a: 12 s, or 12.5 s from the 250-ms z-scores) and of "10 times" (e-b: best of 10 replicates, or the mean of 10 runs), and the Methods' normalizations z-a and z-b. The 10 runs are made two ways: continuing the MATLAB stream after rng(1) (rrf.matlab_kmeans with replicates=10, an assumption about how 'Replicates' draws, since the code never uses it), and with scikit-learn's k-means++, whose greedy seeding differs from MATLAB's.

In [10]:
def kmeans_matrix(start, mm1=None, mm250=None):
    """start: outcome epoch start in s after cue onset (13 code, 12 or 12.5 claims e-a)."""
    to1 = lambda a, b0, n: a[b0:b0 + 4 * n].reshape(n, 4, -1).mean(1)
    if mm1 is not None and start in (12, 13):
        b = slice(20 + start, 26 + start)                  # 1-s bin j covers (j-20, j-19] s
        parts = [mm1[t][20:30] for t in ("D", "U", "S")] + [mm1[t][b] for t in ("D", "US", "UO", "S")]
    else:                                                  # from 250-ms bins
        b0 = int(round((start + 20) * 4))
        parts = [to1(mm250[t], 80, 10) for t in ("D", "U", "S")] + [to1(mm250[t], b0, 6) for t in ("D", "US", "UO", "S")]
    return np.concatenate(parts, axis=0).T

def elbow(X, mode, seed=0):
    rows = []
    for k in range(1, 16):
        if mode == "code":
            lab, sumd = rrf.matlab_kmeans(X, k, seed=1)
            sumds = [sumd]
        elif mode.startswith("MATLAB"):
            runs = rrf.matlab_kmeans(X, k, seed=1, replicates=10, all_runs=True)
            sumds = [min(runs, key=lambda r: r[1].sum())[1]] if mode == "MATLAB best of 10" else [r[1] for r in runs]
        else:
            fits = [KMeans(k, n_init=10, random_state=seed).fit(X)] if mode == "best of 10" else \
                   [KMeans(k, n_init=1, random_state=seed + r).fit(X) for r in range(10)]
            sumds = [np.bincount(f.labels_, weights=((X - f.cluster_centers_[f.labels_]) ** 2).sum(1), minlength=k)
                     for f in fits]
        msd = np.mean([sd.sum() / len(X) for sd in sumds])
        code_measure = np.mean([sd.sum() if k == 2 else sd.mean() for sd in sumds])
        rows.append((k, msd, code_measure))
    return pd.DataFrame(rows, columns=["k", "mean sq distance", "code mean(sumd)"]).set_index("k")

def elbow_verdict(curve):
    d = -np.diff(curve.to_numpy())           # drop from k to k+1, k = 1..14
    return bool((d > 0).all()), bool((d[7:] < d[6]).all()), d

X_main = kmeans_matrix(13, mm1=m1)
e_main = elbow(X_main, "code")
print(e_main.round(3).T)
dec, after, d = elbow_verdict(e_main["mean sq distance"])
print(f"main (code's runs, Methods measure): decreasing {dec}; every drop after 8 clusters below the 7->8 drop {after}")
print("  drops k -> k+1:", np.round(d, 3))
dec_c, after_c, d_c = elbow_verdict(e_main["code mean(sumd)"])
print(f"code's measure: decreasing {dec_c}; criterion {after_c}; drops", np.round(d_c, 1))

elbow_rows = []
for nm in ("code", "z-a", "z-b"):
    for start in (13, 12, 12.5):
        X = kmeans_matrix(start, mm1=m1 if nm == "code" else None, mm250=NORMS[nm])
        for mode in ("code", "MATLAB best of 10", "MATLAB mean of 10", "best of 10", "mean of 10 runs"):
            dec_v, after_v, d_v = elbow_verdict(elbow(X, mode)["mean sq distance"])
            elbow_rows.append((nm, start, mode, dec_v, after_v, round(d_v[6], 3), round(d_v[7:].max(), 3)))
elbow_tab = pd.DataFrame(elbow_rows, columns=["normalization", "outcome start (s)", "runs", "decreasing",
                                              "criterion met", "drop 7->8", "largest later drop"])
print(elbow_tab.to_string(index=False))
print("readings meeting the criterion:", int(elbow_tab["criterion met"].sum()), "of", len(elbow_tab))
ea_eb = elbow_tab[(elbow_tab["outcome start (s)"] != 13) & elbow_tab["runs"].str.contains("of 10")]
print("the claims file's readings (z-a or z-b; start 12 or 12.5 s; best of 10 or mean of 10), met per normalization:")
print(ea_eb[ea_eb.normalization != "code"].groupby(["normalization", ea_eb.runs.str.startswith("MATLAB")])["criterion met"]
      .agg(["sum", "count"]).rename_axis(["normalization", "MATLAB stream"]))
fig, ax = plt.subplots(figsize=(4, 3))
ax.plot(e_main.index, e_main["mean sq distance"], "o-")
ax.set_xlabel("clusters"); ax.set_ylabel("mean squared distance to centroid")
plt.show()
print("plotted range:", round(float(e_main["mean sq distance"].min()), 3), "to",
      round(float(e_main["mean sq distance"].max()), 3))
k                       1         2         3         4         5        6        7        8        9        10       11       12       13       14       15
mean sq distance    19.443    16.568    15.317    14.567    14.001   13.388   13.209   12.671   12.576   12.308   12.068   11.829   11.981   11.736   11.638
code mean(sumd)   8224.488  7008.165  2159.753  1540.445  1184.462  943.836  798.198  669.993  591.071  520.650  464.083  416.986  389.831  354.589  328.180
main (code's runs, Methods measure): decreasing False; every drop after 8 clusters below the 7->8 drop True
  drops k -> k+1: [ 2.875  1.25   0.751  0.566  0.613  0.179  0.538  0.095  0.267  0.24
  0.239 -0.151  0.245  0.098]
code's measure: decreasing True; criterion True; drops [1216.3 4848.4  619.3  356.   240.6  145.6  128.2   78.9   70.4   56.6
   47.1   27.2   35.2   26.4]
normalization  outcome start (s)              runs  decreasing  criterion met  drop 7->8  largest later drop
         code               13.0              code       False           True      0.538               0.267
         code               13.0 MATLAB best of 10        True           True      0.369               0.232
         code               13.0 MATLAB mean of 10        True           True      0.320               0.253
         code               13.0        best of 10        True          False      0.306               0.306
         code               13.0   mean of 10 runs        True           True      0.339               0.231
         code               12.0              code       False          False      0.196               0.530
         code               12.0 MATLAB best of 10        True           True      0.349               0.314
         code               12.0 MATLAB mean of 10        True           True      0.321               0.307
         code               12.0        best of 10        True           True      0.346               0.301
         code               12.0   mean of 10 runs        True           True      0.407               0.284
         code               12.5              code        True          False      0.134               0.395
         code               12.5 MATLAB best of 10        True          False      0.178               0.212
         code               12.5 MATLAB mean of 10        True          False      0.186               0.237
         code               12.5        best of 10        True           True      0.210               0.196
         code               12.5   mean of 10 runs        True           True      0.259               0.169
          z-a               13.0              code        True          False      0.170               0.832
          z-a               13.0 MATLAB best of 10        True           True      0.626               0.515
          z-a               13.0 MATLAB mean of 10        True           True      0.583               0.561
          z-a               13.0        best of 10        True           True      0.486               0.448
          z-a               13.0   mean of 10 runs        True           True      0.574               0.447
          z-a               12.0              code        True           True      0.868               0.765
          z-a               12.0 MATLAB best of 10        True          False      0.578               0.638
          z-a               12.0 MATLAB mean of 10        True          False      0.459               0.699
          z-a               12.0        best of 10        True           True      0.651               0.543
          z-a               12.0   mean of 10 runs        True           True      0.685               0.494
          z-a               12.5              code        True           True      0.973               0.568
          z-a               12.5 MATLAB best of 10        True          False      0.490               0.563
          z-a               12.5 MATLAB mean of 10        True          False      0.596               0.603
          z-a               12.5        best of 10        True          False      0.479               0.628
          z-a               12.5   mean of 10 runs        True           True      0.741               0.473
          z-b               13.0              code        True          False      0.650               0.766
          z-b               13.0 MATLAB best of 10        True          False      0.608               0.721
          z-b               13.0 MATLAB mean of 10        True          False      0.615               0.820
          z-b               13.0        best of 10        True           True      0.898               0.602
          z-b               13.0   mean of 10 runs        True           True      0.853               0.682
          z-b               12.0              code        True           True      1.015               0.781
          z-b               12.0 MATLAB best of 10        True           True      0.922               0.886
          z-b               12.0 MATLAB mean of 10        True          False      0.726               0.756
          z-b               12.0        best of 10        True           True      0.971               0.671
          z-b               12.0   mean of 10 runs        True           True      0.797               0.735
          z-b               12.5              code        True           True      1.332               0.842
          z-b               12.5 MATLAB best of 10        True           True      0.840               0.629
          z-b               12.5 MATLAB mean of 10        True           True      0.958               0.762
          z-b               12.5        best of 10        True           True      0.884               0.679
          z-b               12.5   mean of 10 runs        True           True      0.881               0.679
readings meeting the criterion: 30 of 45
the claims file's readings (z-a or z-b; start 12 or 12.5 s; best of 10 or mean of 10), met per normalization:
                             sum  count
normalization MATLAB stream            
z-a           False            3      4
              True             0      4
z-b           False            4      4
              True             3      4
No description has been provided for this image
plotted range: 11.638 to 19.443

Result: reproduced, resting on an assumption. The claims file's readings meet the criterion with z-b and scikit-learn's k-means in all 4 combinations of outcome start (12 or 12.5 s) and runs (best of 10, mean of 10): the curve falls at every step from 1 to 15 clusters and every drop after eight clusters is smaller than the drop from 7 to 8. The outcome rests on these readings. The others are mixed: z-b with 10 runs of the MATLAB stream meets it in 3 of 4 combinations, z-a in 3 of 4 with scikit-learn and 0 of 4 with the MATLAB stream, and 30 of the 45 readings in the table meet it. The code's own runs (rng(1) before each k) meet it with the measure the code plots (mean(sumd), drawn as a bar plot on a 0 to 9000 axis, rrfAnalysis.m 980 to 986 above), but that measure is a sum at k = 2, so its drop from 2 to 3 (4848) is larger than its drop from 1 to 2 (1216). With the Methods' measure (mean squared distance per unit) the same runs rise once, from 12 to 13 clusters.

kmeans-clusters¶

Eight k-means clusters were kept, of sizes k1 33, k2 59, k3 18, k4 63, k5 58, k6 61, k7 64 and k8 67.

Main reading: the code's run, rng(1); kmeans(aa, 8), reproduced with rrf.matlab_kmeans, and the code's own map from cluster numbers to k1..k8 (rrf.CODE_IDX). This recovers the paper's labels (reading c-a of the claims file: the data set holds no label file, but its code fixes them). The claims file's matching by firing pattern (c-b) is run on these clusters as a check, and on scikit-learn k-means solutions as a variant.

In [11]:
PAPER_SIZES = {"k1": 33, "k2": 59, "k3": 18, "k4": 63, "k5": 58, "k6": 61, "k7": 64, "k8": 67}
idx8, _ = rrf.matlab_kmeans(X_main, 8, seed=1)
inv = {v: k for k, v in rrf.CODE_IDX.items()}
cl = np.array([inv[i] for i in idx8])                       # paper cluster of each of the 423 units
sizes = pd.Series(cl).value_counts().reindex(rrf.CLUSTERS)
print(pd.DataFrame({"here": sizes, "paper": pd.Series(PAPER_SIZES)}).T)
within = {k: abs(sizes[k] - PAPER_SIZES[k]) <= 0.1 * PAPER_SIZES[k] for k in rrf.CLUSTERS}
print("sizes within 10%:", sum(within.values()), "of 8")

pattern_rows = []
for k in rrf.CLUSTERS:
    pr = rrf.cluster_profile(m250, cl == k)
    chk = rrf.pattern_checks(pr)[k]
    pattern_rows.append((k, int(sizes[k]), all(v for _, v in chk), "; ".join(f"{n}: {bool(v)}" for n, v in chk),
                         np.round(pr["onset"], 2), np.round(pr["whole"], 2), np.round(pr["delay"], 2)))
pat = pd.DataFrame(pattern_rows, columns=["cluster", "n", "pattern found", "tests", "onset D,U,S",
                                          "cue+delay D,U,S", "delay D,U,S"])
print(pat.drop(columns="tests").to_string(index=False))
for r in pattern_rows:
    print(r[0], r[3])
match, score = rrf.match_clusters(m250, idx8)
print("pattern matching (c-b) of the code's clusters:", {k: inv[v] for k, v in match.items()},
      "agrees with the code's map for", sum(inv[v] == k for k, v in match.items()), "of 8")

# kmeans-clusters under every reading of the claims file: outcome start 13 (code), 12 or 12.5 s (e-a);
# normalization code, z-a, z-b; the code's single run after rng(1), the best of 10 runs of the same
# MATLAB stream (e-b, best of 10), and each of those 10 runs alone (e-b, runs of the mean of 10).
def judge_partition(lab, mm):
    mp, sc = rrf.match_clusters(mm, lab)
    found = list(np.unique(lab))
    allpat = all(sc[found.index(mp[k]), rrf.CLUSTERS.index(k)] == 1 for k in rrf.CLUSTERS)
    nwithin = sum(abs((lab == mp[k]).sum() - PAPER_SIZES[k]) <= 0.1 * PAPER_SIZES[k] for k in rrf.CLUSTERS)
    return allpat, nwithin

km_rows = []
for nm in ("code", "z-a", "z-b"):
    mm = m250 if nm == "code" else NORMS[nm]
    for start in (13, 12, 12.5):
        X = kmeans_matrix(start, mm1=m1 if nm == "code" else None, mm250=NORMS[nm])
        runs = rrf.matlab_kmeans(X, 8, seed=1, replicates=10, all_runs=True)
        best = min(runs, key=lambda r: r[1].sum())
        for label, lab in (("code: rng(1), one run", runs[0][0]), ("best of 10 (MATLAB stream)", best[0])):
            allpat, nwithin = judge_partition(lab, mm)
            km_rows.append((nm, start, label, allpat, nwithin, allpat and nwithin == 8))
        each = [judge_partition(r[0], mm) for r in runs]
        km_rows.append((nm, start, "each of the 10 runs: how many", sum(a for a, _ in each),
                        int(np.median([w for _, w in each])), sum(a and w == 8 for a, w in each)))
km_tab = pd.DataFrame(km_rows, columns=["normalization", "outcome start (s)", "runs", "all 8 patterns",
                                        "sizes within 10% (of 8; median for 10 runs)", "criterion met"])
print(km_tab.to_string(index=False))

# Variant: scikit-learn k-means (k-means++, other generator), matched by pattern
var_rows = []
for mode, n_init in (("single run", 1), ("best of 10", 10)):
    for seed in range(50):
        lab = KMeans(8, n_init=n_init, random_state=seed).fit(X_main).labels_
        mp, sc = rrf.match_clusters(m250, lab)
        found = list(np.unique(lab))
        allpat = all(sc[found.index(mp[k]), rrf.CLUSTERS.index(k)] == 1 for k in rrf.CLUSTERS)
        nwithin = sum(abs((lab == mp[k]).sum() - PAPER_SIZES[k]) <= 0.1 * PAPER_SIZES[k] for k in rrf.CLUSTERS)
        var_rows.append((mode, seed, allpat, nwithin))
var = pd.DataFrame(var_rows, columns=["runs", "seed", "all patterns", "sizes within 10%"])
print(var.groupby("runs").agg(all_patterns=("all patterns", "mean"),
                              median_sizes_within=("sizes within 10%", "median"),
                              reproduced=("sizes within 10%", lambda s: np.mean((s == 8) & var.loc[s.index, "all patterns"]))))
       k1  k2  k3  k4  k5  k6  k7  k8
here   33  59  18  63  58  61  64  67
paper  33  59  18  63  58  61  64  67
sizes within 10%: 8 of 8
cluster  n  pattern found           onset D,U,S       cue+delay D,U,S           delay D,U,S
     k1 33           True     [1.5, 0.98, 0.73]    [0.35, 0.23, 0.27]    [0.17, 0.04, 0.21]
     k2 59           True [-0.05, -0.22, -0.03]   [0.01, -0.26, 0.04]   [0.13, -0.18, 0.03]
     k3 18           True     [1.28, 0.61, 0.1]    [1.23, 0.5, -0.12]    [1.0, 0.49, -0.13]
     k4 63           True  [-0.25, -0.25, 0.06]  [-0.32, -0.32, 0.18]  [-0.24, -0.34, 0.15]
     k5 58           True   [0.08, 0.04, -0.09]   [0.36, 0.14, -0.14]   [0.57, 0.27, -0.14]
     k6 61           True   [-0.21, -0.03, 0.2]  [-0.36, -0.12, 0.24]  [-0.28, -0.17, 0.21]
     k7 64           True    [0.06, 0.0, -0.22]  [0.02, -0.06, -0.27]   [0.21, -0.0, -0.27]
     k8 67           True [-0.43, -0.05, -0.14] [-0.48, -0.03, -0.09] [-0.35, -0.04, -0.14]
k1 onset D > 0: True; onset D > U and D > S: True; onset U and S similar: |U - S| < D - U: True; phasic: onset D > delay D: True
k2 U < 0: True; U below D and S: True; D not inhibited as strongly: |D| < |U|: True
k3 D > U > S: True; D > 0: True; sustained: onset and delay D > 0: True; sustained: delay D at least half of onset D: True
k4 D < 0 and U < 0: True; D and U similar: |D - U| < U-S distance: True; S above U: True
k5 D > U > S: True; D > 0: True; ramping: late+delay D > onset D: True; ramping: late+delay U > onset U: True
k6 D < U < S: True; D < 0: True; S > 0: True
k7 delay D > U > S: True; delay D > 0: True; minimal cue: |cue D| < delay D: True
k8 D < 0: True; D below U and S: True; U and S similar: |U - S| < U - D: True
pattern matching (c-b) of the code's clusters: {'k4': 'k4', 'k8': 'k8', 'k7': 'k7', 'k5': 'k5', 'k1': 'k1', 'k2': 'k2', 'k3': 'k3', 'k6': 'k6'} agrees with the code's map for 8 of 8
normalization  outcome start (s)                          runs all 8 patterns  sizes within 10% (of 8; median for 10 runs) criterion met
         code               13.0         code: rng(1), one run           True                                            8          True
         code               13.0    best of 10 (MATLAB stream)          False                                            3         False
         code               13.0 each of the 10 runs: how many              3                                            3             1
         code               12.0         code: rng(1), one run          False                                            1         False
         code               12.0    best of 10 (MATLAB stream)          False                                            2         False
         code               12.0 each of the 10 runs: how many              1                                            1             0
         code               12.5         code: rng(1), one run          False                                            0         False
         code               12.5    best of 10 (MATLAB stream)          False                                            2         False
         code               12.5 each of the 10 runs: how many              0                                            2             0
          z-a               13.0         code: rng(1), one run          False                                            2         False
          z-a               13.0    best of 10 (MATLAB stream)           True                                            4         False
          z-a               13.0 each of the 10 runs: how many              3                                            2             0
          z-a               12.0         code: rng(1), one run          False                                            1         False
          z-a               12.0    best of 10 (MATLAB stream)          False                                            2         False
          z-a               12.0 each of the 10 runs: how many              2                                            2             0
          z-a               12.5         code: rng(1), one run          False                                            0         False
          z-a               12.5    best of 10 (MATLAB stream)           True                                            2         False
          z-a               12.5 each of the 10 runs: how many              2                                            2             0
          z-b               13.0         code: rng(1), one run          False                                            1         False
          z-b               13.0    best of 10 (MATLAB stream)          False                                            2         False
          z-b               13.0 each of the 10 runs: how many              2                                            2             0
          z-b               12.0         code: rng(1), one run           True                                            3         False
          z-b               12.0    best of 10 (MATLAB stream)          False                                            2         False
          z-b               12.0 each of the 10 runs: how many              1                                            2             0
          z-b               12.5         code: rng(1), one run          False                                            4         False
          z-b               12.5    best of 10 (MATLAB stream)          False                                            4         False
          z-b               12.5 each of the 10 runs: how many              0                                            2             0
            all_patterns  median_sizes_within  reproduced
runs                                                     
best of 10          0.46                  3.0         0.0
single run          0.16                  3.0         0.0

Result: reproduced. The code's k-means run, repeated outside MATLAB, gives clusters of exactly the paper's sizes (33, 59, 18, 63, 58, 61, 64, 67), and with the code's map each cluster shows its pattern by the tests printed above. Other k-means runs (scikit-learn, other seeds) give different partitions, rarely of these sizes: the eight clusters depend on the run. No other reading in the table gives all eight sizes within 10%: not the claims file's outcome starts of 12 or 12.5 s, nor z-a or z-b, nor the best of 10 runs of the MATLAB stream (at most 4 of 8 sizes). The outcome rests on the code's normalization, outcome start and single run. All later claims use the code's clusters.

cluster-firing-characteristics¶

Clusters differed in baseline firing rate, coefficient of variance and coefficient of skewness, but not in anterior-posterior location, waveform half-duration or waveform amplitude ratio.

Measures as the code computes them: baseline rate the mean over trials of the floored 10-s pre-cue rate; CV and skewness from the inter-spike intervals of the 20 s before each cue, pooled over the 16 trials (cube.mat fire.CV, fire.CS, cubeScriptPR25.m; the claims file's main reading); half duration and amplitude ratio from the mean waveform (rrfAnalysis.m); bregma level per rat (rrfAnalysis.m). The variant averages CV and skewness over trials.

In [12]:
from statsmodels.multivariate.manova import MANOVA

wf = np.array([rrf.waveform_measures(cube["wave"][:, i]) for i in R])
char = pd.DataFrame({
    "cluster": cl,
    "baseline": cube["fire.raw.base10"][:, R].astype(float).mean(0),
    "CV": cube["fire.CV"][R], "CS": cube["fire.CS"][R],
    "bregma": [rrf.BREGMA[int(rat[i][2:])] for i in R],
    "half_duration": wf[:, 0], "amplitude_ratio": wf[:, 1]})
print(char.describe().round(3).T)
print(char.groupby("cluster").mean().round(3))

def char_tests(df, label):
    print(label)
    mv = MANOVA.from_formula("baseline + CV + CS + bregma + half_duration + amplitude_ratio ~ C(cluster)", data=df)
    wilks = mv.mv_test().results["C(cluster)"]["stat"].loc["Wilks' lambda"]
    print(f"  MANOVA Wilks' lambda {wilks['Value']:.3f}, F({wilks['Num DF']:.0f}, {wilks['Den DF']:.0f}) = "
          f"{wilks['F Value']:.2f}, p = {wilks['Pr > F']:.3g}")
    out = {}
    for m in ("baseline", "CV", "CS", "bregma", "half_duration", "amplitude_ratio"):
        groups = [df.loc[df.cluster == k, m].dropna() for k in rrf.CLUSTERS]
        F, p = stats.f_oneway(*groups)
        ss_b = sum(len(g_) * (g_.mean() - df[m].mean()) ** 2 for g_ in groups)
        ss_t = ((df[m] - df[m].mean()) ** 2).sum()
        out[m] = (F, p)
        print(f"  {m}: F(7, {len(df) - 8}) = {F:.2f}, p = {p:.3g}, eta2 = {ss_b / ss_t:.3f}")
    return out

ch_main = char_tests(char, "main: ISIs pooled over the 16 trials")
# Variant: CV and skewness per trial, then averaged
cv_t, cs_t = [], []
for i in R:
    u, on = by_name[names[i]], cube["tag"][:, 1, i]
    cvs, css = [], []
    for t in on:
        isi = np.diff(u["spike"][(u["spike"] > t - 20) & (u["spike"] <= t)])
        if len(isi) > 2:
            cvs.append(isi.std(ddof=1) / isi.mean())
            css.append(3 * (isi.mean() - np.median(isi)) / isi.std(ddof=1))
    cv_t.append(np.mean(cvs) if cvs else np.nan); cs_t.append(np.mean(css) if css else np.nan)
char_v = char.assign(CV=cv_t, CS=cs_t).dropna()
print("variant drops", len(char) - len(char_v), "units with too few spikes")
ch_var = char_tests(char_v, "variant: CV and skewness averaged over trials")
def pooled_isi(i):
    sp, on = by_name[names[i]]["spike"], cube["tag"][:, 1, i]
    return np.concatenate([np.diff(sp[(sp > t - 20) & (sp <= t)]) for t in on])

cv_check = np.array([pooled_isi(i).std(ddof=1) / pooled_isi(i).mean() for i in R])
print("cube CV against CV recomputed from spike times, max |difference| over 423 units:",
      float(np.nanmax(np.abs(cv_check - cube["fire.CV"][R]))))
                 count    mean     std    min    25%     50%     75%     max
baseline         423.0  16.430  15.831  0.000  4.781  10.812  23.656  78.750
CV               423.0   2.212   1.073  0.410  1.336   2.017   2.948   5.661
CS               423.0   0.849   0.219  0.092  0.702   0.839   0.981   1.654
bregma           423.0  -6.692   0.181 -7.080 -6.720  -6.720  -6.600  -6.360
half_duration    423.0   0.088   0.040  0.050  0.075   0.075   0.088   0.288
amplitude_ratio  423.0   0.528   0.225 -0.290  0.384   0.542   0.664   1.000
         baseline     CV     CS  bregma  half_duration  amplitude_ratio
cluster                                                                
k1          9.759  1.858  0.921  -6.695          0.086            0.513
k2         17.572  2.322  0.846  -6.696          0.090            0.527
k3          9.583  1.840  0.726  -6.713          0.113            0.654
k4         18.319  2.365  0.833  -6.693          0.084            0.500
k5         13.239  2.344  0.843  -6.687          0.086            0.577
k6         18.895  1.897  0.914  -6.720          0.083            0.502
k7         16.117  2.244  0.856  -6.712          0.084            0.555
k8         19.591  2.389  0.803  -6.643          0.095            0.488
main: ISIs pooled over the 16 trials
  MANOVA Wilks' lambda 0.744, F(42, 1927) = 2.99, p = 7.53e-10
  baseline: F(7, 415) = 2.48, p = 0.0166, eta2 = 0.040
  CV: F(7, 415) = 2.28, p = 0.0272, eta2 = 0.037
  CS: F(7, 415) = 2.65, p = 0.011, eta2 = 0.043
  bregma: F(7, 415) = 1.08, p = 0.377, eta2 = 0.018
  half_duration: F(7, 415) = 1.69, p = 0.109, eta2 = 0.028
  amplitude_ratio: F(7, 415) = 1.93, p = 0.0628, eta2 = 0.032
variant drops 0 units with too few spikes
variant: CV and skewness averaged over trials
  MANOVA Wilks' lambda 0.740, F(42, 1927) = 3.05, p = 3.4e-10
  baseline: F(7, 415) = 2.48, p = 0.0166, eta2 = 0.040
  CV: F(7, 415) = 2.97, p = 0.00476, eta2 = 0.048
  CS: F(7, 415) = 2.02, p = 0.0511, eta2 = 0.033
  bregma: F(7, 415) = 1.08, p = 0.377, eta2 = 0.018
  half_duration: F(7, 415) = 1.69, p = 0.109, eta2 = 0.028
  amplitude_ratio: F(7, 415) = 1.93, p = 0.0628, eta2 = 0.032
cube CV against CV recomputed from spike times, max |difference| over 423 units: 1.9984014443252818e-14

Result: reproduced. Baseline rate, CV and skewness differ between clusters and location, half duration and amplitude ratio do not (p values above). With CV and skewness averaged over trials, skewness is no longer significant (p = 0.051).

k1-k3-low-baseline¶

Units of clusters k1 and k3 had lower baseline firing rates than all other clusters.

In [13]:
low = char.cluster.isin(["k1", "k3"])
t_res = stats.ttest_ind(char.baseline[low], char.baseline[~low])
print(f"k1 + k3: n = {low.sum()}, mean {char.baseline[low].mean():.2f} Hz; others n = {(~low).sum()}, "
      f"mean {char.baseline[~low].mean():.2f} Hz; t({len(char) - 2}) = {t_res.statistic:.2f}, p = {t_res.pvalue:.3g}")
print("Welch variant p =", stats.ttest_ind(char.baseline[low], char.baseline[~low], equal_var=False).pvalue)
print(char.groupby("cluster").baseline.agg(["mean", "median", "count"]).round(2).T)
k1 + k3: n = 51, mean 9.70 Hz; others n = 372, mean 17.35 Hz; t(421) = -3.28, p = 0.00114
Welch variant p = 0.00012587794099600644
cluster     k1     k2     k3     k4     k5     k6     k7     k8
mean      9.76  17.57   9.58  18.32  13.24  18.90  16.12  19.59
median    7.00  13.19   2.19  14.62   8.88  11.88  11.59  13.19
count    33.00  59.00  18.00  63.00  58.00  61.00  64.00  67.00

Result: reproduced. k1 and k3 units have the lower baseline rate, and the t test is significant (numbers above).

table1-cue-interaction¶

Every cluster showed a significant trial type x interval interaction for cue firing.

Per cluster, the 56 250-ms bins from 2 s before cue onset to the end of the delay (bins 73-128, as the code's ANOVA data), danger, uncertainty and safety; repeated measures with trial type and interval within units, uncorrected (Greenhouse-Geisser as a variant).

In [14]:
def cue_anova_table(mm, label):
    rows = []
    for k in rrf.CLUSTERS:
        sel = cl == k
        y = np.stack([mm[t][rrf.CUE_ANOVA][:, sel] for t in "DUS"], axis=0).transpose(2, 0, 1)
        a = rrf.mixed_anova(y)["w1 x w2"]
        rows.append((k, sel.sum(), f"F({a[1]}, {a[2]}) = {a[0]:.2f}", a[3], round(a[4], 3), round(a[5], 3), a[6]))
    tab = pd.DataFrame(rows, columns=["cluster", "n", "interaction", "p", "partial eta2", "GG eps", "GG p"])
    print(label); print(tab.to_string(index=False))
    return tab

t1cue = cue_anova_table(m250, "code normalization")
print("clusters with p < 0.05:", int((t1cue.p < 0.05).sum()), "of 8")
for nm in ("z-a", "z-b"):
    tv = cue_anova_table(NORMS[nm], nm)
    print(nm, "clusters with p < 0.05:", int((tv.p < 0.05).sum()))
code normalization
cluster  n         interaction             p  partial eta2  GG eps         GG p
     k1 33 F(110, 3520) = 4.00  5.931866e-38         0.111   0.158 1.168862e-07
     k2 59 F(110, 6380) = 3.54  1.382318e-31         0.058   0.249 2.367178e-09
     k3 18 F(110, 1870) = 4.91  5.574636e-49         0.224   0.088 4.562796e-06
     k4 63 F(110, 6820) = 8.09 2.858135e-113         0.115   0.263 1.428089e-31
     k5 58 F(110, 6270) = 6.66  1.816162e-86         0.105   0.241 1.492913e-22
     k6 61 F(110, 6600) = 7.34  3.751086e-99         0.109   0.274 7.536582e-29
     k7 64 F(110, 6930) = 4.63  2.417002e-50         0.069   0.248 4.453217e-14
     k8 67 F(110, 7260) = 6.56  2.325226e-85         0.090   0.289 2.609509e-26
clusters with p < 0.05: 8 of 8
z-a
cluster  n         interaction             p  partial eta2  GG eps         GG p
     k1 33 F(110, 3520) = 3.90  2.473411e-36         0.109   0.160 1.874178e-07
     k2 59 F(110, 6380) = 3.46  2.796657e-30         0.056   0.242 8.013114e-09
     k3 18 F(110, 1870) = 4.68  1.576012e-45         0.216   0.091 6.811163e-06
     k4 63 F(110, 6820) = 7.93 1.870210e-110         0.113   0.261 1.475300e-30
     k5 58 F(110, 6270) = 6.57  1.046625e-84         0.103   0.250 6.785837e-23
     k6 61 F(110, 6600) = 7.13  1.968936e-95         0.106   0.275 6.218919e-28
     k7 64 F(110, 6930) = 4.52  2.791201e-48         0.067   0.247 1.524233e-13
     k8 67 F(110, 7260) = 6.42  1.088695e-82         0.089   0.285 3.465672e-25
z-a clusters with p < 0.05: 8
z-b
cluster  n         interaction             p  partial eta2  GG eps         GG p
     k1 33 F(110, 3520) = 3.94  6.424276e-37         0.110   0.157 1.778791e-07
     k2 59 F(110, 6380) = 3.44  5.868730e-30         0.056   0.243 8.639384e-09
     k3 18 F(110, 1870) = 4.63  8.100077e-45         0.214   0.092 6.793230e-06
     k4 63 F(110, 6820) = 7.72 1.910670e-106         0.111   0.256 5.308129e-29
     k5 58 F(110, 6270) = 6.51  1.222734e-83         0.102   0.255 4.544278e-23
     k6 61 F(110, 6600) = 7.15  9.790893e-96         0.106   0.274 5.681379e-28
     k7 64 F(110, 6930) = 4.51  3.708412e-48         0.067   0.250 1.204697e-13
     k8 67 F(110, 7260) = 6.44  3.437718e-83         0.089   0.285 2.475234e-25
z-b clusters with p < 0.05: 8

Result: reproduced. The trial type x interval interaction is significant in all eight clusters, with or without the Greenhouse-Geisser correction and under each normalization. Table 1 prints no degrees of freedom; the claims file infers 110 and 3520 for k1 from the printed partial eta squared, and the k1 test here has these df and partial eta squared 0.111.

fig3b-excitatory-clusters and fig3d-inhibitory-clusters¶

Clusters k1, k3, k5 and k7 show excitatory firing to danger and uncertainty; k1 fires most to danger at cue onset with lower, similar firing to uncertainty and safety; k3 (whole cue and delay), k5 (late cue and delay) and k7 (delay) fully differentiate danger > uncertainty > safety.

Clusters k2, k4, k6 and k8 show sustained inhibition through the cue and delay; k2 is inhibited to uncertainty only, k4 equally to danger and uncertainty, k6 most to danger, less to uncertainty, with excitation to safety, and k8 to danger only.

Per unit, mean normalized firing to each cue in the cluster's Figure 3 interval (the code's bins: k1 81-84, k5 101-128, k7 121-128, others 81-128); per-unit differences danger - uncertainty and uncertainty - safety with studentized bootstrap CIs (Table S1).

In [15]:
TABLE_S1 = {  # mean, CI low, CI high, tolerance (claims file)
    "k1": [(0.51, 0.30, 0.74, 0.23), (0.25, -0.11, 0.59, 0.36)],
    "k3": [(0.73, 0.37, 0.95, 0.36), (0.62, 0.38, 0.80, 0.24)],
    "k5": [(0.33, 0.20, 0.45, 0.13), (0.35, 0.24, 0.44, 0.11)],
    "k7": [(0.21, 0.08, 0.33, 0.13), (0.27, 0.17, 0.37, 0.10)],
    "k2": [(0.27, 0.20, 0.33, 0.07), (-0.30, -0.37, -0.23, 0.07)],
    "k4": [(0.01, -0.05, 0.07, 0.06), (-0.50, -0.56, -0.44, 0.06)],
    "k6": [(-0.23, -0.30, -0.15, 0.08), (-0.37, -0.44, -0.29, 0.08)],
    "k8": [(-0.45, -0.51, -0.38, 0.07), (0.06, -0.01, 0.13, 0.07)],
}

def table_s1(clusters, mm, gen, label):
    rows = []
    for k in clusters:
        sel = cl == k
        per = {t: np.nanmean(mm[t][rrf.FIG3_INTERVAL[k]][:, sel], axis=0) for t in "DUS"}
        for nm, d, ref in (("D-U", per["D"] - per["U"], TABLE_S1[k][0]), ("U-S", per["U"] - per["S"], TABLE_S1[k][1])):
            ci = rrf.boot_ci(d, gen)
            paper_sign = rrf.ci_sign((ref[0], ref[1], ref[2]))
            rows.append((k, nm, round(ci[0], 3), round(ci[1], 3), round(ci[2], 3), ref[0], f"[{ref[1]}, {ref[2]}]",
                         rrf.ci_sign(ci) == paper_sign, abs(ci[0] - ref[0]) <= ref[3]))
    tab = pd.DataFrame(rows, columns=["cluster", "diff", "mean", "low", "high", "paper mean", "paper CI",
                                      "CI agrees", "mean within tol"])
    print(label); print(tab.to_string(index=False))
    return tab
In [16]:
g = seeded("fig3b-excitatory-clusters")
s1_exc = table_s1(("k1", "k3", "k5", "k7"), m250, g, "code normalization")
print("CIs agreeing:", int(s1_exc["CI agrees"].sum()), "of 8; means within tolerance:", int(s1_exc["mean within tol"].sum()), "of 8")
print("clusters with both CIs agreeing:", int(s1_exc.groupby("cluster")["CI agrees"].all().sum()), "of 4")
for nm in ("z-a", "z-b"):
    tv = table_s1(("k1", "k3", "k5", "k7"), NORMS[nm], seeded("fig3b-excitatory-clusters"), nm)
    print(nm, "CIs agreeing", int(tv["CI agrees"].sum()), "means within", int(tv["mean within tol"].sum()))
for k in ("k1", "k3", "k5", "k7"):
    pr = rrf.cluster_profile(m250, cl == k)
    print(k, "mean D, U, S in its interval:", np.round([np.nanmean(m250[t][rrf.FIG3_INTERVAL[k]][:, cl == k]) for t in "DUS"], 3))
code normalization
cluster diff  mean    low  high  paper mean      paper CI  CI agrees  mean within tol
     k1  D-U 0.514  0.320 0.718        0.51   [0.3, 0.74]       True             True
     k1  U-S 0.252 -0.075 0.594        0.25 [-0.11, 0.59]       True             True
     k3  D-U 0.737  0.530 1.057        0.73  [0.37, 0.95]       True             True
     k3  U-S 0.616  0.421 0.854        0.62   [0.38, 0.8]       True             True
     k5  D-U 0.327  0.213 0.456        0.33   [0.2, 0.45]       True             True
     k5  U-S 0.348  0.263 0.451        0.35  [0.24, 0.44]       True             True
     k7  D-U 0.209  0.095 0.332        0.21  [0.08, 0.33]       True             True
     k7  U-S 0.271  0.168 0.370        0.27  [0.17, 0.37]       True             True
CIs agreeing: 8 of 8; means within tolerance: 8 of 8
clusters with both CIs agreeing: 4 of 4
z-a
cluster diff  mean    low  high  paper mean      paper CI  CI agrees  mean within tol
     k1  D-U 0.918  0.587 1.274        0.51   [0.3, 0.74]       True            False
     k1  U-S 0.419 -0.136 1.012        0.25 [-0.11, 0.59]       True             True
     k3  D-U 1.072  0.779 1.406        0.73  [0.37, 0.95]       True             True
     k3  U-S 0.893  0.642 1.211        0.62   [0.38, 0.8]       True            False
     k5  D-U 0.591  0.388 0.804        0.33   [0.2, 0.45]       True            False
     k5  U-S 0.617  0.462 0.791        0.35  [0.24, 0.44]       True            False
     k7  D-U 0.367  0.174 0.583        0.21  [0.08, 0.33]       True            False
     k7  U-S 0.475  0.293 0.642        0.27  [0.17, 0.37]       True            False
z-a CIs agreeing 8 means within 2
z-b
cluster diff  mean    low  high  paper mean      paper CI  CI agrees  mean within tol
     k1  D-U 1.031  0.657 1.425        0.51   [0.3, 0.74]       True            False
     k1  U-S 0.519 -0.131 1.206        0.25 [-0.11, 0.59]       True             True
     k3  D-U 1.134  0.833 1.443        0.73  [0.37, 0.95]       True            False
     k3  U-S 0.956  0.684 1.294        0.62   [0.38, 0.8]       True            False
     k5  D-U 0.671  0.439 0.909        0.33   [0.2, 0.45]       True            False
     k5  U-S 0.707  0.531 0.906        0.35  [0.24, 0.44]       True            False
     k7  D-U 0.424  0.195 0.666        0.21  [0.08, 0.33]       True            False
     k7  U-S 0.543  0.340 0.725        0.27  [0.17, 0.37]       True            False
z-b CIs agreeing 8 means within 1
k1 mean D, U, S in its interval: [1.498 0.984 0.732]
k3 mean D, U, S in its interval: [ 1.234  0.497 -0.119]
k5 mean D, U, S in its interval: [ 0.538  0.212 -0.136]
k7 mean D, U, S in its interval: [ 0.207 -0.002 -0.274]

Result: reproduced. With the code's normalization all eight CIs agree with Table S1 on excluding zero and on sign (k1's uncertainty - safety includes zero, as in the paper; the other seven exclude zero, positive), and all eight means are within tolerance.

In [17]:
g = seeded("fig3d-inhibitory-clusters")
s1_inh = table_s1(("k2", "k4", "k6", "k8"), m250, g, "code normalization")
print("CIs agreeing:", int(s1_inh["CI agrees"].sum()), "of 8; means within tolerance:", int(s1_inh["mean within tol"].sum()), "of 8")
print("clusters with both CIs agreeing:", int(s1_inh.groupby("cluster")["CI agrees"].all().sum()), "of 4")
for nm in ("z-a", "z-b"):
    tv = table_s1(("k2", "k4", "k6", "k8"), NORMS[nm], seeded("fig3d-inhibitory-clusters"), nm)
    print(nm, "CIs agreeing", int(tv["CI agrees"].sum()), "means within", int(tv["mean within tol"].sum()))
for k in ("k2", "k4", "k6", "k8"):
    print(k, "mean D, U, S in 0-12 s:", np.round([np.nanmean(m250[t][rrf.FIG3_INTERVAL[k]][:, cl == k]) for t in "DUS"], 3))
code normalization
cluster diff   mean    low   high  paper mean       paper CI  CI agrees  mean within tol
     k2  D-U  0.266  0.201  0.330        0.27    [0.2, 0.33]       True             True
     k2  U-S -0.299 -0.359 -0.228       -0.30 [-0.37, -0.23]       True             True
     k4  D-U  0.006 -0.060  0.061        0.01  [-0.05, 0.07]       True             True
     k4  U-S -0.504 -0.570 -0.445       -0.50 [-0.56, -0.44]       True             True
     k6  D-U -0.231 -0.318 -0.156       -0.23  [-0.3, -0.15]       True             True
     k6  U-S -0.368 -0.434 -0.302       -0.37 [-0.44, -0.29]       True             True
     k8  D-U -0.449 -0.510 -0.385       -0.45 [-0.51, -0.38]       True             True
     k8  U-S  0.063 -0.002  0.131        0.06  [-0.01, 0.13]       True             True
CIs agreeing: 8 of 8; means within tolerance: 8 of 8
clusters with both CIs agreeing: 4 of 4
z-a
cluster diff   mean    low   high  paper mean       paper CI  CI agrees  mean within tol
     k2  D-U  0.485  0.365  0.603        0.27    [0.2, 0.33]       True            False
     k2  U-S -0.553 -0.669 -0.421       -0.30 [-0.37, -0.23]       True            False
     k4  D-U  0.010 -0.108  0.108        0.01  [-0.05, 0.07]       True             True
     k4  U-S -0.895 -1.009 -0.790       -0.50 [-0.56, -0.44]       True            False
     k6  D-U -0.424 -0.567 -0.291       -0.23  [-0.3, -0.15]       True            False
     k6  U-S -0.655 -0.772 -0.536       -0.37 [-0.44, -0.29]       True            False
     k8  D-U -0.813 -0.920 -0.702       -0.45 [-0.51, -0.38]       True            False
     k8  U-S  0.108 -0.011  0.232        0.06  [-0.01, 0.13]       True             True
z-a CIs agreeing 8 means within 2
z-b
cluster diff   mean    low   high  paper mean       paper CI  CI agrees  mean within tol
     k2  D-U  0.567  0.432  0.699        0.27    [0.2, 0.33]       True            False
     k2  U-S -0.655 -0.782 -0.507       -0.30 [-0.37, -0.23]       True            False
     k4  D-U  0.016 -0.117  0.134        0.01  [-0.05, 0.07]       True             True
     k4  U-S -1.054 -1.171 -0.938       -0.50 [-0.56, -0.44]       True            False
     k6  D-U -0.469 -0.630 -0.320       -0.23  [-0.3, -0.15]       True            False
     k6  U-S -0.766 -0.909 -0.630       -0.37 [-0.44, -0.29]       True            False
     k8  D-U -0.935 -1.059 -0.806       -0.45 [-0.51, -0.38]       True            False
     k8  U-S  0.127 -0.012  0.270        0.06  [-0.01, 0.13]       True             True
z-b CIs agreeing 8 means within 2
k2 mean D, U, S in 0-12 s: [ 0.011 -0.255  0.044]
k4 mean D, U, S in 0-12 s: [-0.319 -0.324  0.18 ]
k6 mean D, U, S in 0-12 s: [-0.356 -0.125  0.243]
k8 mean D, U, S in 0-12 s: [-0.477 -0.028 -0.091]

Result: reproduced. All eight CIs agree with Table S1 and all eight means are within tolerance (numbers above).

figs4-onset-and-ramp¶

From cue onset to delay, k1 firing decreases for all three cues (phasic onset firing), k5 firing increases for danger and uncertainty (ramping), and k2 firing increases for danger.

Per unit and cue, delay (bins 121-128) minus onset (bins 81-84), as the code's tempDiff.

In [18]:
g = seeded("figs4-onset-and-ramp")
S4 = {("k1", "D"): (-1.32, 0.35, -1), ("k1", "U"): (-0.95, 0.32, -1), ("k1", "S"): (-0.52, 0.32, -1),
      ("k5", "D"): (0.50, 0.18, 1), ("k5", "U"): (0.23, 0.12, 1), ("k2", "D"): (0.18, 0.13, 1)}
rows = []
for k in rrf.CLUSTERS:
    for t in "DUS":
        d = np.nanmean(m250[t][rrf.DELAY][:, cl == k], 0) - np.nanmean(m250[t][rrf.ONSET][:, cl == k], 0)
        ci = rrf.boot_ci(d, g)
        ref = S4.get((k, t))
        rows.append((k, t, round(ci[0], 3), round(ci[1], 3), round(ci[2], 3), rrf.ci_sign(ci),
                     ref[0] if ref else None, (rrf.ci_sign(ci) == ref[2]) if ref else None,
                     (abs(ci[0] - ref[0]) <= ref[1]) if ref else None))
s4 = pd.DataFrame(rows, columns=["cluster", "cue", "mean", "low", "high", "CI sign", "paper mean", "CI agrees", "within tol"])
print(s4.to_string(index=False))
claimed = s4.dropna(subset=["paper mean"])
print("claimed CIs with the paper's sign:", int(claimed["CI agrees"].astype(bool).sum()), "of 6; means within tolerance:",
      int(claimed["within tol"].astype(bool).sum()), "of 6")
for nm in ("z-a", "z-b"):
    gv = seeded("figs4-onset-and-ramp")
    agree = within_ = 0
    for (k, t), ref in S4.items():
        mm = NORMS[nm]
        d = np.nanmean(mm[t][rrf.DELAY][:, cl == k], 0) - np.nanmean(mm[t][rrf.ONSET][:, cl == k], 0)
        ci = rrf.boot_ci(d, gv)
        agree += rrf.ci_sign(ci) == ref[2]; within_ += abs(ci[0] - ref[0]) <= ref[1]
    print(f"{nm}: claimed CIs with the paper's sign {agree} of 6; means within tolerance {within_} of 6")
cluster cue   mean    low   high  CI sign  paper mean CI agrees within tol
     k1   D -1.323 -1.674 -1.005       -1       -1.32      True       True
     k1   U -0.945 -1.303 -0.669       -1       -0.95      True       True
     k1   S -0.519 -0.842 -0.300       -1       -0.52      True       True
     k2   D  0.179  0.055  0.302        1        0.18      True       True
     k2   U  0.042 -0.043  0.125        0         NaN      None       None
     k2   S  0.054 -0.062  0.178        0         NaN      None       None
     k3   D -0.274 -0.728  0.084        0         NaN      None       None
     k3   U -0.116 -0.741  0.319        0         NaN      None       None
     k3   S -0.229 -0.544  0.021        0         NaN      None       None
     k4   D  0.001 -0.098  0.094        0         NaN      None       None
     k4   U -0.090 -0.167 -0.010       -1         NaN      None       None
     k4   S  0.088 -0.053  0.214        0         NaN      None       None
     k5   D  0.492  0.304  0.677        1        0.50      True       True
     k5   U  0.230  0.107  0.334        1        0.23      True       True
     k5   S -0.045 -0.140  0.061        0         NaN      None       None
     k6   D -0.070 -0.236  0.065        0         NaN      None       None
     k6   U -0.140 -0.295 -0.033       -1         NaN      None       None
     k6   S  0.012 -0.120  0.154        0         NaN      None       None
     k7   D  0.147 -0.041  0.312        0         NaN      None       None
     k7   U -0.003 -0.108  0.093        0         NaN      None       None
     k7   S -0.049 -0.158  0.057        0         NaN      None       None
     k8   D  0.088 -0.020  0.197        0         NaN      None       None
     k8   U  0.012 -0.081  0.103        0         NaN      None       None
     k8   S  0.003 -0.108  0.092        0         NaN      None       None
claimed CIs with the paper's sign: 6 of 6; means within tolerance: 6 of 6
z-a: claimed CIs with the paper's sign 6 of 6; means within tolerance 0 of 6
z-b: claimed CIs with the paper's sign 6 of 6; means within tolerance 0 of 6

Result: reproduced. The six claimed changes have CIs that exclude zero with the paper's sign and means within tolerance (table above); the other cues and clusters are listed for comparison with Figure S4.

fig4abc-threat-bias¶

Except for k2, each cluster's uncertainty firing has the direction and time course of its danger firing at lower magnitude, and safety firing tends to oppose danger firing; k4 and k6 are inhibited to danger but excited to safety, k3 and k5 the reverse.

In [19]:
rows = []
for k in rrf.CLUSTERS:
    dus = [np.nanmean(m250[t][rrf.FIG3_INTERVAL[k]][:, cl == k]) for t in "DUS"]
    s5 = {p: np.round([np.nanmean(m250[t][sl][:, cl == k]) for t in "DUS"], 2)
          for p, sl in (("onset", rrf.ONSET), ("late", rrf.LATE), ("delay", rrf.DELAY))}
    rows.append((k, *np.round(dus, 3), np.sign(dus[1]) == np.sign(dus[0]) and abs(dus[1]) < abs(dus[0]),
                 np.sign(dus[2]) != np.sign(dus[0]), s5["onset"], s5["late"], s5["delay"]))
bias = pd.DataFrame(rows, columns=["cluster", "D", "U", "S", "U like D, smaller", "S opposes D",
                                   "onset D,U,S", "late D,U,S", "delay D,U,S"])
print(bias.to_string(index=False))
b = bias.set_index("cluster")
part1 = bool(b.loc["k4", "D"] < 0 < b.loc["k4", "S"] and b.loc["k6", "D"] < 0 < b.loc["k6", "S"] and
             b.loc["k3", "D"] > 0 > b.loc["k3", "S"] and b.loc["k5", "D"] > 0 > b.loc["k5", "S"])
part2 = int(b.drop("k2")["U like D, smaller"].sum())
print("(1) k4, k6 danger < 0 < safety and k3, k5 danger > 0 > safety:", part1)
print("(2) clusters other than k2 with uncertainty of danger's sign and smaller:", part2, "of 7")
print("safety opposes danger in", int(b["S opposes D"].sum()), "of 8 clusters")
for nm in ("z-a", "z-b"):
    mm = NORMS[nm]
    bb = {k: [np.nanmean(mm[t][rrf.FIG3_INTERVAL[k]][:, cl == k]) for t in "DUS"] for k in rrf.CLUSTERS}
    p1 = bool(bb["k4"][0] < 0 < bb["k4"][2] and bb["k6"][0] < 0 < bb["k6"][2] and bb["k3"][0] > 0 > bb["k3"][2]
              and bb["k5"][0] > 0 > bb["k5"][2])
    p2 = sum(np.sign(bb[k][1]) == np.sign(bb[k][0]) and abs(bb[k][1]) < abs(bb[k][0]) for k in rrf.CLUSTERS if k != "k2")
    print(f"{nm}: part (1) {p1}; part (2) {p2} of 7")
cluster      D      U      S  U like D, smaller  S opposes D           onset D,U,S            late D,U,S           delay D,U,S
     k1  1.498  0.984  0.732               True        False     [1.5, 0.98, 0.73]    [0.13, 0.14, 0.23]    [0.17, 0.04, 0.21]
     k2  0.011 -0.255  0.044              False        False [-0.05, -0.22, -0.03]   [0.03, -0.27, 0.07]   [0.13, -0.18, 0.03]
     k3  1.234  0.497 -0.119               True         True     [1.28, 0.61, 0.1]    [1.38, 0.5, -0.14]    [1.0, 0.49, -0.13]
     k4 -0.319 -0.324  0.180              False         True  [-0.25, -0.25, 0.06]  [-0.31, -0.35, 0.22]  [-0.24, -0.34, 0.15]
     k5  0.538  0.212 -0.136               True         True   [0.08, 0.04, -0.09]   [0.52, 0.19, -0.13]   [0.57, 0.27, -0.14]
     k6 -0.356 -0.125  0.243               True         True   [-0.21, -0.03, 0.2]  [-0.38, -0.16, 0.27]  [-0.28, -0.17, 0.21]
     k7  0.207 -0.002 -0.274              False         True    [0.06, 0.0, -0.22]  [0.05, -0.09, -0.29]   [0.21, -0.0, -0.27]
     k8 -0.477 -0.028 -0.091               True        False [-0.43, -0.05, -0.14] [-0.48, -0.03, -0.08] [-0.35, -0.04, -0.14]
(1) k4, k6 danger < 0 < safety and k3, k5 danger > 0 > safety: True
(2) clusters other than k2 with uncertainty of danger's sign and smaller: 5 of 7
safety opposes danger in 5 of 8 clusters
z-a: part (1) True; part (2) 5 of 7
z-b: part (1) True; part (2) 5 of 7

Result: partially reproduced. Part (1) holds: k4 and k6 are inhibited to danger and excited to safety, k3 and k5 the reverse. Part (2) holds in five of the seven clusters other than k2, one short of the six the criterion asks: in k4 uncertainty inhibition equals danger inhibition (-0.324 against -0.319, as the paper itself reports k4 as equal), and in k7 mean uncertainty firing over the delay is about zero (-0.002 against danger 0.207). Safety firing has the opposite sign to danger in five of eight clusters.

fig4def-danger-uncertainty-correlation, fig4ghi-danger-safety-correlation, fig4-correlations-differ¶

Across all cue-responsive units, danger and uncertainty firing are positively related at cue onset (R2 = 0.48), late cue (R2 = 0.21) and delay (R2 = 0.21).

Danger and safety firing are positively related at cue onset (R2 = 0.14) but negatively related in the late cue (R2 = 0.03) and delay (R2 = 0.02).

The danger-uncertainty and danger-safety correlations differ from one another in each period (Z = 7.69 onset, 8.94 late cue, 8.20 delay).

Per unit, mean normalized firing in the first 1 s of the cue, the last 5 s and the 2-s delay (the code's bins); Pearson correlation over the 423 units (corr in rrfAnalysis.m). Meng's Z uses the uncertainty-safety correlation of the same units as the correlation between the two predictors.

In [20]:
PERIODS = {"onset": rrf.ONSET, "late cue": rrf.LATE, "delay": rrf.DELAY}

def correlations(mm):
    rows = []
    for p, sl in PERIODS.items():
        D, U, S = (np.nanmean(mm[t][sl], 0) for t in "DUS")
        rdu, pdu = stats.pearsonr(D, U)
        rds, pds = stats.pearsonr(D, S)
        rus = stats.pearsonr(U, S)[0]
        zm, pm = rrf.meng_z(rdu, rds, rus, len(D))
        rows.append((p, rdu, rdu ** 2, pdu, rds, rds ** 2, pds, rus, zm, pm))
    return pd.DataFrame(rows, columns=["period", "r DU", "R2 DU", "p DU", "r DS", "R2 DS", "p DS", "r US", "Meng Z", "Meng p"])

corr_tabs = {nm: correlations(mm) for nm, mm in NORMS.items()}
for nm, tab in corr_tabs.items():
    print(nm); print(tab.to_string(index=False, float_format=lambda v: f"{v:.3g}"))
code
  period  r DU  R2 DU     p DU   r DS  R2 DS     p DS   r US  Meng Z   Meng p
   onset 0.695  0.483 3.25e-62  0.378  0.143 7.98e-16  0.406    7.69 1.44e-14
late cue 0.463  0.214 8.23e-24 -0.183 0.0337 0.000148  -0.18    8.95 3.64e-19
   delay 0.458   0.21 2.46e-23 -0.129 0.0167  0.00771 -0.168     8.2 2.33e-16
z-a
  period  r DU  R2 DU     p DU   r DS  R2 DS     p DS   r US  Meng Z   Meng p
   onset 0.672  0.451 7.32e-57  0.379  0.144 6.93e-16  0.389    6.92 4.53e-12
late cue 0.432  0.187 1.11e-20 -0.149 0.0222  0.00213 -0.136    8.16 3.43e-16
   delay  0.44  0.194 1.68e-21 -0.103 0.0106   0.0345 -0.129    7.69 1.42e-14
z-b
  period  r DU  R2 DU     p DU   r DS  R2 DS     p DS   r US  Meng Z   Meng p
   onset 0.672  0.451  7.4e-57  0.349  0.122 1.56e-13  0.374    7.45 9.41e-14
late cue 0.417  0.174 3.26e-19 -0.243  0.059 4.21e-07 -0.157    9.12 7.72e-20
   delay 0.424  0.179 7.63e-20 -0.166 0.0277 0.000585 -0.143    8.23  1.8e-16
In [21]:
exp_du = {"onset": (0.48, 0.048), "late cue": (0.21, 0.021), "delay": (0.21, 0.021)}
for nm, tab in corr_tabs.items():
    ok = [(r["r DU"] > 0 and r["p DU"] < 0.05, abs(r["R2 DU"] - exp_du[r["period"]][0]) <= exp_du[r["period"]][1])
          for _, r in tab.iterrows()]
    print(f"{nm}: R2 {np.round(tab['R2 DU'].to_numpy(), 3)}; positive and significant {[a for a, _ in ok]}; "
          f"within tolerance {[b for _, b in ok]}")
code: R2 [0.483 0.214 0.21 ]; positive and significant [True, True, True]; within tolerance [True, True, True]
z-a: R2 [0.451 0.187 0.194]; positive and significant [True, True, True]; within tolerance [True, False, True]
z-b: R2 [0.451 0.174 0.179]; positive and significant [True, True, True]; within tolerance [True, False, False]

Result: reproduced. Under the code's normalization the three correlations are positive and significant with R2 0.483, 0.214 and 0.210, all within tolerance of 0.48, 0.21 and 0.21. The Methods' normalizations give positive, significant correlations with R2 printed above.

In [22]:
exp_ds = {"onset": (0.14, 0.014, 1), "late cue": (0.03, 0.005, -1), "delay": (0.02, 0.005, -1)}
for nm, tab in corr_tabs.items():
    ok = [(np.sign(r["r DS"]) == exp_ds[r["period"]][2] and r["p DS"] < 0.05,
           abs(r["R2 DS"] - exp_ds[r["period"]][0]) <= exp_ds[r["period"]][1]) for _, r in tab.iterrows()]
    print(f"{nm}: r {np.round(tab['r DS'].to_numpy(), 3)}, R2 {np.round(tab['R2 DS'].to_numpy(), 4)}, "
          f"p {np.array([f'{v:.2g}' for v in tab['p DS']])}; sign and significance {[a for a, _ in ok]}; "
          f"within tolerance {[b for _, b in ok]}")
code: r [ 0.378 -0.183 -0.129], R2 [0.143  0.0337 0.0167], p ['8e-16' '0.00015' '0.0077']; sign and significance [True, True, True]; within tolerance [True, True, True]
z-a: r [ 0.379 -0.149 -0.103], R2 [0.1435 0.0222 0.0106], p ['6.9e-16' '0.0021' '0.034']; sign and significance [True, True, True]; within tolerance [True, False, False]
z-b: r [ 0.349 -0.243 -0.166], R2 [0.1215 0.059  0.0277], p ['1.6e-13' '4.2e-07' '0.00059']; sign and significance [True, True, True]; within tolerance [False, False, False]

Result: reproduced. Under the code's normalization danger and safety firing are positively correlated at onset and negatively in the late cue and delay, all with p < 0.05, and the three R2 are within tolerance (numbers above).

In [23]:
exp_z = {"onset": 7.69, "late cue": 8.94, "delay": 8.20}
for nm, tab in corr_tabs.items():
    print(f"{nm}: Z {np.round(tab['Meng Z'].to_numpy(), 2)} (expected 7.69, 8.94, 8.20 +/- 10%); p "
          f"{np.array([f'{v:.2g}' for v in tab['Meng p']])}; within tolerance "
          f"{[abs(z_ - exp_z[p]) <= 0.1 * exp_z[p] for p, z_ in zip(tab['period'], tab['Meng Z'])]}")
code: Z [7.69 8.95 8.2 ] (expected 7.69, 8.94, 8.20 +/- 10%); p ['1.4e-14' '3.6e-19' '2.3e-16']; within tolerance [True, True, True]
z-a: Z [6.92 8.16 7.69] (expected 7.69, 8.94, 8.20 +/- 10%); p ['4.5e-12' '3.4e-16' '1.4e-14']; within tolerance [False, True, True]
z-b: Z [7.45 9.12 8.23] (expected 7.69, 8.94, 8.20 +/- 10%); p ['9.4e-14' '7.7e-20' '1.8e-16']; within tolerance [True, True, True]

Result: reproduced. Meng's Z under the code's normalization is within 10% of the paper's value in all three periods, with p < 0.05 (numbers above).

Single-unit regression (Figure 5)¶

Per unit and 1-s bin from 2 s before cue onset to the end of the delay (14 bins, the code's columns 19-32 of the 1-s z-scores), the 16 trials' normalized firing regressed on a constant, the cue's threat probability (danger 1, safety 0, uncertainty set to 0, 0.125, ... 1) and the trial's suppression ratio for the whole cue (fear output), with MATLAB regress's handling of rank deficiency. Variants: (t-b) trial firing z-scored over the unit's 16 trials in each bin (from the differential rates); (t-a) tuning curves from the 10 cue bins in place of the cluster periods.

In [24]:
z1_trials = cube["fire.z.s1.interval"][:, 18:32, :][:, :, R]                 # (16, 14, 423)
d1 = cube["fire.diff.s1.interval"][:, 18:32, :][:, :, R].astype(float)
sd1 = d1.std(0, ddof=1, keepdims=True)
z1_trials_tb = np.where(sd1 > 0, (d1 - d1.mean(0, keepdims=True)) / np.where(sd1 > 0, sd1, 1), 0.0)
fear = cube["cer.cue"][:, R]

def regressions(ztr):
    tp = np.zeros((len(R), 9, 14)); fo = np.zeros((len(R), 9, 14)); deficient = np.zeros(len(R), bool)
    for u in range(len(R)):
        for a, val in enumerate(rrf.ASSIGNMENTS):
            prob = np.r_[np.ones(4), np.full(8, val), np.zeros(4)]
            X = np.column_stack([np.ones(16), prob, fear[:, u]])
            b, rank = rrf.regress_betas(ztr[:, :, u], X)
            tp[u, a], fo[u, a] = b[1], b[2]
            deficient[u] |= rank < 3
    return tp, fo, deficient

tp_beta, fo_beta, deficient = regressions(z1_trials)
tp_beta_tb, fo_beta_tb, _ = regressions(z1_trials_tb)
print("units with a rank-deficient regression (constant suppression ratio over trials):", int(deficient.sum()),
      "; clusters", collections.Counter(cl[deficient]))
print("beta ranges: threat probability", np.round([tp_beta.min(), tp_beta.max()], 2),
      "fear output", np.round([fo_beta.min(), fo_beta.max()], 2))
SEVEN = [k for k in rrf.CLUSTERS if k != "k2"]

def tuning(tp, cols_by_cluster):
    curves, per_unit = {}, {}
    for k in SEVEN:
        sel = cl == k
        v = tp[sel][:, :, cols_by_cluster[k]].mean(2)
        if k in rrf.INVERTED:
            v = -v
        per_unit[k] = v
        curves[k] = v.mean(0)
    return curves, per_unit

TEN_CUE = {k: slice(2, 12) for k in SEVEN}
tune_main = tuning(tp_beta, rrf.TUNE_COLS)
tune_variants = {"t-a cue bins": tuning(tp_beta, TEN_CUE), "t-b trial z": tuning(tp_beta_tb, rrf.TUNE_COLS),
                 "t-a and t-b": tuning(tp_beta_tb, TEN_CUE)}
peaks = pd.DataFrame({nm: {k: rrf.ASSIGNMENTS[int(np.argmax(c[k]))] for k in SEVEN}
                      for nm, (c, _) in {"code periods, code z": tune_main, **tune_variants}.items()})
peaks["paper"] = pd.Series(rrf.PAPER_PEAK)
print(peaks)
print(pd.DataFrame(tune_main[0], index=rrf.ASSIGNMENTS).round(3).T)
units with a rank-deficient regression (constant suppression ratio over trials): 0 ; clusters Counter()
beta ranges: threat probability [-10.88   8.  ] fear output [-7.54  9.27]
    code periods, code z  t-a cue bins  t-b trial z  t-a and t-b  paper
k1                 0.375         0.750        0.250        0.750  0.375
k3                 0.375         0.375        0.375        0.375  0.375
k4                 0.875         0.875        0.875        0.875  0.875
k5                 0.375         0.500        0.375        0.500  0.375
k6                 0.625         0.625        0.625        0.625  0.625
k7                 0.500         0.625        0.500        0.625  0.500
k8                 0.250         0.250        0.250        0.250  0.250
    0.000  0.125  0.250  0.375  0.500  0.625  0.750  0.875  1.000
k1  0.631  0.718  0.791  0.823  0.789  0.700  0.581  0.444  0.311
k3  0.964  1.123  1.265  1.346  1.330  1.221  1.049  0.838  0.620
k4 -0.053  0.023  0.132  0.264  0.388  0.471  0.508  0.515  0.499
k5  0.404  0.488  0.566  0.614  0.604  0.536  0.437  0.353  0.305
k6  0.237  0.323  0.421  0.511  0.570  0.580  0.541  0.465  0.414
k7  0.313  0.398  0.491  0.569  0.603  0.576  0.506  0.423  0.342
k8  0.396  0.416  0.418  0.389  0.328  0.250  0.179  0.123 -0.012

fig5a-tuning-peaks-exaggerated¶

Threat tuning curves of k1, k3 and k5 peak at an uncertainty assignment of 0.375 and k7 at 0.500, above the actual shock probability of 0.250 (exaggerated threat probability signaling).

In [25]:
exc = ["k1", "k3", "k5", "k7"]
print(peaks.loc[exc])
for col in peaks.columns[:-1]:
    print(f"{col}: all four match {bool((peaks.loc[exc, col] == peaks.loc[exc, 'paper']).all())}; "
          f"all above 0.25 {bool((peaks.loc[exc, col] > 0.25).all())}")
fig, ax = plt.subplots(figsize=(4, 3))
for k in SEVEN:
    ax.plot(rrf.ASSIGNMENTS, tune_main[0][k], label=k)
ax.set_xlabel("uncertainty assignment"); ax.set_ylabel("threat probability beta"); ax.legend(fontsize=6)
plt.show()
print("plotted range:", round(min(v.min() for v in tune_main[0].values()), 3), "to",
      round(max(v.max() for v in tune_main[0].values()), 3))
    code periods, code z  t-a cue bins  t-b trial z  t-a and t-b  paper
k1                 0.375         0.750        0.250        0.750  0.375
k3                 0.375         0.375        0.375        0.375  0.375
k5                 0.375         0.500        0.375        0.500  0.375
k7                 0.500         0.625        0.500        0.625  0.500
code periods, code z: all four match True; all above 0.25 True
t-a cue bins: all four match False; all above 0.25 True
t-b trial z: all four match False; all above 0.25 False
t-a and t-b: all four match False; all above 0.25 True
No description has been provided for this image
plotted range: -0.053 to 1.346

Result: reproduced. With the code's periods and normalization the tuning curves peak at 0.375 for k1, k3 and k5 and at 0.500 for k7, the paper's four values. The readings the code does not use give other peaks for k1, k5 or k7 (table above): the cue-bin reading (t-a) moves k1 to 0.750, k5 to 0.500 and k7 to 0.625, and the trial z-score reading (t-b) moves k1 to 0.250.

fig5a-tuning-peaks-inhibited¶

Among the cue-inhibited clusters, k4 (peak 0.875) and k6 (0.625) show even greater exaggeration of threat probability, while k8 peaks at the actual probability, 0.250, flattening toward 0.000.

In [26]:
inh = ["k4", "k6", "k8"]
print(peaks.loc[inh])
for col in peaks.columns[:-1]:
    print(f"{col}: all three match {bool((peaks.loc[inh, col] == peaks.loc[inh, 'paper']).all())}")
print("k8 curve:", np.round(tune_main[0]["k8"], 3))
    code periods, code z  t-a cue bins  t-b trial z  t-a and t-b  paper
k4                 0.875         0.875        0.875        0.875  0.875
k6                 0.625         0.625        0.625        0.625  0.625
k8                 0.250         0.250        0.250        0.250  0.250
code periods, code z: all three match True
t-a cue bins: all three match True
t-b trial z: all three match True
t-a and t-b: all three match True
k8 curve: [ 0.396  0.416  0.418  0.389  0.328  0.25   0.179  0.123 -0.012]

Result: reproduced. k4 peaks at 0.875, k6 at 0.625 and k8 at 0.250 under every reading, and the k8 curve falls to -0.012 at an assignment of 1.

fig5a-tuning-anova¶

The tuning curves differ between clusters (main effect of cluster and cluster x assignment interaction) and show a main effect of assignment.

In [27]:
for nm, (_, per_unit) in {"code periods, code z": tune_main, **tune_variants}.items():
    y = np.concatenate([per_unit[k] for k in SEVEN])
    grp = np.concatenate([[k] * len(per_unit[k]) for k in SEVEN])
    a = rrf.mixed_anova(y, grp)
    print(nm, f"(n = {len(y)})")
    for eff, lab_ in (("group", "cluster"), ("w1", "assignment"), ("w1 x group", "cluster x assignment")):
        F, df1, df2, p, eta = a[eff][:5]
        print(f"  {lab_}: F({df1}, {df2}) = {F:.2f}, p = {p:.3g}, partial eta2 = {eta:.3f}, GG p = {a[eff][6]:.3g}")
    F, df1, df2, p = rrf.mixed_anova(y, grp, type3=False)["w1"][:4]
    print(f"  assignment, weighted (not type III): F({df1}, {df2}) = {F:.2f}, p = {p:.3g}")
code periods, code z (n = 364)
  cluster: F(6, 357) = 4.14, p = 0.000488, partial eta2 = 0.065, GG p = 0.000488
  assignment: F(8, 2856) = 24.84, p = 2.67e-37, partial eta2 = 0.065, GG p = 2.22e-09
  cluster x assignment: F(48, 2856) = 7.22, p = 1.16e-43, partial eta2 = 0.108, GG p = 1.93e-10
  assignment, weighted (not type III): F(8, 2856) = 21.87, p = 1.31e-32
t-a cue bins (n = 364)
  cluster: F(6, 357) = 8.73, p = 7.01e-09, partial eta2 = 0.128, GG p = 7.01e-09
  assignment: F(8, 2856) = 22.09, p = 5.77e-33, partial eta2 = 0.058, GG p = 8.92e-09
  cluster x assignment: F(48, 2856) = 9.83, p = 8.34e-65, partial eta2 = 0.142, GG p = 2.26e-15
  assignment, weighted (not type III): F(8, 2856) = 21.75, p = 2.04e-32
t-b trial z (n = 364)
  cluster: F(6, 357) = 2.75, p = 0.0126, partial eta2 = 0.044, GG p = 0.0126
  assignment: F(8, 2856) = 21.28, p = 1.11e-31, partial eta2 = 0.056, GG p = 4.63e-08
  cluster x assignment: F(48, 2856) = 9.14, p = 3.5e-59, partial eta2 = 0.133, GG p = 2.48e-13
  assignment, weighted (not type III): F(8, 2856) = 21.11, p = 2.1e-31
t-a and t-b (n = 364)
  cluster: F(6, 357) = 5.93, p = 6.42e-06, partial eta2 = 0.091, GG p = 6.42e-06
  assignment: F(8, 2856) = 19.45, p = 8.89e-29, partial eta2 = 0.052, GG p = 7.87e-08
  cluster x assignment: F(48, 2856) = 10.08, p = 7.56e-67, partial eta2 = 0.145, GG p = 9.72e-16
  assignment, weighted (not type III): F(8, 2856) = 22.26, p = 3.08e-33

Result: reproduced. Main effect of cluster F(6, 357) = 4.14, p = 0.00049; of assignment F(8, 2856) = 24.84, p = 2.7e-37; cluster x assignment F(48, 2856) = 7.22, p = 1.2e-43, the paper's values. All three effects are significant under every reading.

fig5e-peak-probability-over-fear-output¶

With peak threat probability and fear output as regressors, neither is signaled before the cue; peak threat probability is signaled from cue onset through the delay, fear output in every bin but the first 1 s of the cue, and peak threat probability signaling exceeds fear output signaling in every cue and delay bin.

Each cluster's regression at the paper's peak assignment, in the 14 bins; for k4, k6 and k8 both betas multiplied by -1, as the code does (reading s-a, sign-inverted, settled by the code; the betas left as computed are a variant). The ANOVA has regressor and bin within units and cluster between.

In [28]:
BIN_NAMES = ["pre1", "pre2"] + [f"cue{i}" for i in range(1, 11)] + ["delay1", "delay2"]

def peak_betas(tp, fo, peaks_by_cluster, invert=True):
    rows_tp, rows_fo, grp = [], [], []
    for k in SEVEN:
        a = int(round(peaks_by_cluster[k] / 0.125))
        sign = -1.0 if (invert and k in rrf.INVERTED) else 1.0
        rows_tp.append(sign * tp[cl == k, a]); rows_fo.append(sign * fo[cl == k, a]); grp += [k] * (cl == k).sum()
    return np.concatenate(rows_tp), np.concatenate(rows_fo), np.array(grp)

def table_s2(TP, FO, gen):
    rows = []
    for b_, nm in enumerate(BIN_NAMES):
        c1, c2, c3 = rrf.boot_ci(TP[:, b_], gen), rrf.boot_ci(FO[:, b_], gen), rrf.boot_ci(TP[:, b_] - FO[:, b_], gen)
        rows.append((nm, *np.round(c1, 3), *np.round(c2, 3), *np.round(c3, 3)))
    return pd.DataFrame(rows, columns=["bin", "TP", "TP lo", "TP hi", "FO", "FO lo", "FO hi", "diff", "diff lo", "diff hi"])

S2_TP = [0.02, -0.02, 0.46, 0.45, 0.43, 0.38, 0.46, 0.50, 0.56, 0.55, 0.55, 0.52, 0.44, 0.49]
S2_TP_TOL = [0.05, 0.05, 0.12, 0.1, 0.1, 0.09, 0.09, 0.11, 0.11, 0.11, 0.11, 0.1, 0.1, 0.1]
S2_FO = [-0.01, 0.01, 0.06, 0.12, 0.14, 0.18, 0.18, 0.17, 0.10, 0.13, 0.20, 0.16, 0.17, 0.14]
S2_FO_TOL = [0.04, 0.04, 0.08, 0.09, 0.08, 0.09, 0.08, 0.09, 0.09, 0.12, 0.09, 0.1, 0.09, 0.1]

def judge_s2(tab):
    tp_inc = (tab["TP lo"] <= 0) & (tab["TP hi"] >= 0)
    fo_inc = (tab["FO lo"] <= 0) & (tab["FO hi"] >= 0)
    pattern = {
        "pre bins: both include zero": bool(tp_inc[:2].all() and fo_inc[:2].all()),
        "TP excludes zero (above) in all 12 cue and delay bins": int((tab["TP lo"][2:] > 0).sum()),
        "FO above zero in cue2..delay2 (11 bins)": int((tab["FO lo"][3:] > 0).sum()),
        "FO includes zero in cue1": bool(fo_inc[2]),
        "TP - FO above zero (12 bins)": int((tab["diff lo"][2:] > 0).sum()),
    }
    means = int(sum(abs(tab["TP"][i] - S2_TP[i]) <= S2_TP_TOL[i] for i in range(14)) +
                sum(abs(tab["FO"][i] - S2_FO[i]) <= S2_FO_TOL[i] for i in range(14)))
    return pattern, means

def regressor_anova(TP, FO, grp):
    y = np.stack([TP, FO], axis=1)            # units x regressor x bin
    return rrf.mixed_anova(y, grp)

def show_anova(a, keys):
    for eff, lab_ in keys:
        F, df1, df2, p, eta = a[eff][:5]
        print(f"  {lab_}: F({df1}, {df2}) = {F:.2f}, p = {p:.3g}, partial eta2 = {eta:.3f}, GG p = {a[eff][6]:.3g}")
In [29]:
g = seeded("fig5e-peak-probability-over-fear-output")
TP, FO, grp = peak_betas(tp_beta, fo_beta, rrf.PAPER_PEAK)
print("units", len(TP), "in", len(SEVEN), "clusters")
s2 = table_s2(TP, FO, g)
print(s2.to_string(index=False))
pat5e, means5e = judge_s2(s2)
print(pat5e, "; means within tolerance:", means5e, "of 28")
a5 = regressor_anova(TP, FO, grp)
print("ANOVA, regressor and bin within units, cluster between:")
show_anova(a5, (("w1", "regressor"), ("w1 x w2", "regressor x bin"), ("w2", "bin"), ("group", "cluster"),
                ("w1 x group", "regressor x cluster"), ("w1 x w2 x group", "regressor x bin x cluster")))
# Variants: betas not sign-inverted (s-a), and the trial z-scores of reading t-b
for label, (tp_, fo_, inv_) in {"not inverted": (tp_beta, fo_beta, False),
                                "t-b trial z": (tp_beta_tb, fo_beta_tb, True)}.items():
    TPv, FOv, grpv = peak_betas(tp_, fo_, rrf.PAPER_PEAK, invert=inv_)
    tv = table_s2(TPv, FOv, seeded("fig5e-peak-probability-over-fear-output"))
    pv, mv = judge_s2(tv)
    av = regressor_anova(TPv, FOv, grpv)
    print(label, pv, "means within", mv,
          f"regressor F = {av['w1'][0]:.2f} p = {av['w1'][3]:.3g}; regressor x bin F = {av['w1 x w2'][0]:.2f} p = {av['w1 x w2'][3]:.3g}")
units 364 in 7 clusters
   bin     TP  TP lo  TP hi     FO  FO lo  FO hi   diff  diff lo  diff hi
  pre1  0.024 -0.021  0.070 -0.012 -0.055  0.030  0.036   -0.045    0.114
  pre2 -0.024 -0.071  0.023  0.012 -0.029  0.056 -0.036   -0.123    0.046
  cue1  0.461  0.362  0.566  0.063 -0.013  0.137  0.398    0.242    0.554
  cue2  0.451  0.358  0.543  0.122  0.034  0.206  0.328    0.176    0.487
  cue3  0.427  0.325  0.520  0.139  0.052  0.226  0.289    0.134    0.439
  cue4  0.382  0.290  0.475  0.183  0.112  0.264  0.199    0.042    0.346
  cue5  0.465  0.380  0.547  0.183  0.112  0.271  0.282    0.130    0.425
  cue6  0.505  0.416  0.603  0.170  0.085  0.253  0.335    0.154    0.505
  cue7  0.555  0.455  0.660  0.106  0.023  0.188  0.449    0.282    0.628
  cue8  0.550  0.446  0.660  0.135  0.038  0.223  0.415    0.232    0.601
  cue9  0.552  0.453  0.651  0.202  0.120  0.280  0.351    0.171    0.521
 cue10  0.519  0.416  0.614  0.160  0.068  0.246  0.359    0.183    0.523
delay1  0.436  0.339  0.541  0.166  0.077  0.249  0.270    0.095    0.439
delay2  0.488  0.373  0.598  0.137  0.052  0.224  0.350    0.177    0.523
{'pre bins: both include zero': True, 'TP excludes zero (above) in all 12 cue and delay bins': 12, 'FO above zero in cue2..delay2 (11 bins)': 11, 'FO includes zero in cue1': True, 'TP - FO above zero (12 bins)': 12} ; means within tolerance: 28 of 28
ANOVA, regressor and bin within units, cluster between:
  regressor: F(1, 357) = 31.40, p = 4.2e-08, partial eta2 = 0.081, GG p = 4.2e-08
  regressor x bin: F(13, 4641) = 4.63, p = 5.58e-08, partial eta2 = 0.013, GG p = 9.28e-07
  bin: F(13, 4641) = 56.97, p = 1.28e-138, partial eta2 = 0.138, GG p = 3.65e-102
  cluster: F(6, 357) = 38.29, p = 7.74e-36, partial eta2 = 0.392, GG p = 7.74e-36
  regressor x cluster: F(6, 357) = 2.40, p = 0.0273, partial eta2 = 0.039, GG p = 0.0273
  regressor x bin x cluster: F(78, 4641) = 1.10, p = 0.251, partial eta2 = 0.018, GG p = 0.27
not inverted {'pre bins: both include zero': True, 'TP excludes zero (above) in all 12 cue and delay bins': 0, 'FO above zero in cue2..delay2 (11 bins)': 0, 'FO includes zero in cue1': True, 'TP - FO above zero (12 bins)': 0} means within 6 regressor F = 2.17 p = 0.142; regressor x bin F = 1.07 p = 0.378
t-b trial z {'pre bins: both include zero': True, 'TP excludes zero (above) in all 12 cue and delay bins': 12, 'FO above zero in cue2..delay2 (11 bins)': 11, 'FO includes zero in cue1': True, 'TP - FO above zero (12 bins)': 12} means within 28 regressor F = 28.27 p = 1.86e-07; regressor x bin F = 3.67 p = 7.76e-06

Result: reproduced. The CI pattern of Table S2 is found in full: neither beta excludes zero before the cue, the peak threat probability beta is above zero in all 12 cue and delay bins, the fear output beta in all of them but the first cue bin, and the difference is above zero in all 12; all 28 means are within tolerance. The regressor main effect (F(1, 357) = 31.40, p = 4.2e-8) and the regressor x bin interaction (F(13, 4641) = 4.63, p = 5.6e-8) are significant. The error df are 357, where the paper's 355 imply two units fewer (see table-s3-cluster-regression). With the betas left as computed (not sign-inverted) the pattern is not found, which confirms that the paper's Table S2 uses the code's inversion.

fig5-regressor-cluster¶

Signaling varied somewhat between clusters (regressor x cluster interaction) with no regressor x cluster x bin interaction.

In [30]:
show_anova(a5, (("w1 x group", "regressor x cluster"), ("w1 x w2 x group", "regressor x bin x cluster")))
for label, (tp_, fo_, inv_) in {"not inverted": (tp_beta, fo_beta, False),
                                "t-b trial z": (tp_beta_tb, fo_beta_tb, True)}.items():
    av = regressor_anova(*peak_betas(tp_, fo_, rrf.PAPER_PEAK, invert=inv_))
    print(label); show_anova(av, (("w1 x group", "regressor x cluster"), ("w1 x w2 x group", "regressor x bin x cluster")))
  regressor x cluster: F(6, 357) = 2.40, p = 0.0273, partial eta2 = 0.039, GG p = 0.0273
  regressor x bin x cluster: F(78, 4641) = 1.10, p = 0.251, partial eta2 = 0.018, GG p = 0.27
not inverted
  regressor x cluster: F(6, 357) = 7.90, p = 5.21e-08, partial eta2 = 0.117, GG p = 5.21e-08
  regressor x bin x cluster: F(78, 4641) = 1.81, p = 2.16e-05, partial eta2 = 0.029, GG p = 0.000123
t-b trial z
  regressor x cluster: F(6, 357) = 2.17, p = 0.045, partial eta2 = 0.035, GG p = 0.045
  regressor x bin x cluster: F(78, 4641) = 0.97, p = 0.566, partial eta2 = 0.016, GG p = 0.544

Result: reproduced. Regressor x cluster F(6, 357) = 2.40, p = 0.027 (paper 2.15, p = 0.048), and no regressor x cluster x bin interaction, F(78, 4641) = 1.10, p = 0.25 (paper 1.06, p = 0.33).

table-s3-cluster-regression¶

Within clusters, peak threat probability exceeds fear output (main effect of regressor) in k3, k4, k6, k7 and k8 but not in k1 or k5, and only k7 shows a regressor x bin interaction.

In [31]:
S3_MAIN = {"k1": False, "k3": True, "k4": True, "k5": False, "k6": True, "k7": True, "k8": True}
S3_INT = {k: k == "k7" for k in SEVEN}
rows = []
for k in SEVEN:
    sel = grp == k
    a = rrf.mixed_anova(np.stack([TP[sel], FO[sel]], axis=1))
    larger = TP[sel].mean() > FO[sel].mean()
    rows.append((k, sel.sum(), round(a["w1"][0], 2), a["w1"][3], larger, S3_MAIN[k], round(a["w1 x w2"][0], 2),
                 a["w1 x w2"][3], S3_INT[k]))
s3 = pd.DataFrame(rows, columns=["cluster", "n", "regressor F", "p", "TP larger", "paper sig", "reg x bin F", "p int", "paper int sig"])
s3["main agrees"] = ((s3.p < 0.05) & s3["TP larger"]) == s3["paper sig"]
s3["int agrees"] = (s3["p int"] < 0.05) == s3["paper int sig"]
print(s3.to_string(index=False, float_format=lambda v: f"{v:.3g}"))
print("clusters agreeing on both terms:", int((s3["main agrees"] & s3["int agrees"]).sum()), "of 7")

# The paper's ANOVA has 355 error df (362 units), two fewer than the 364 units here. For each
# cluster, the single unit whose removal brings the regressor F closest to Table S3's value:
S3_F = {"k1": 0.44, "k3": 9.35, "k4": 6.72, "k5": 2.02, "k6": 6.28, "k7": 16.89, "k8": 4.29}
drop_rows = []
names7 = np.concatenate([names[R][cl == k] for k in SEVEN])     # unit names in the order of TP, FO
for k in SEVEN:
    idx_k = np.flatnonzero(grp == k)
    full = rrf.mixed_anova(np.stack([TP[idx_k], FO[idx_k]], 1))["w1"][0]
    best = None
    for j in idx_k:
        keep = np.setdiff1d(idx_k, [j])
        a = rrf.mixed_anova(np.stack([TP[keep], FO[keep]], 1))
        cand = (abs(a["w1"][0] - S3_F[k]), j, a["w1"][0], a["w1 x w2"][3])
        best = cand if best is None or cand[0] < best[0] else best
    drop_rows.append((k, round(full, 2), S3_F[k], names7[best[1]],
                      round(best[2], 2), round(best[3], 3)))
print(pd.DataFrame(drop_rows, columns=["cluster", "F all units", "Table S3 F", "best unit to drop",
                                       "F without it", "interaction p without it"]).to_string(index=False))

# How specific is the match? Every k3 and k5 unit, removed alone
for k, f_t in (("k3", 9.35), ("k5", 2.02)):
    idx_k = np.flatnonzero(grp == k)
    res = []
    for j in idx_k:
        keep = np.setdiff1d(idx_k, [j])
        a = rrf.mixed_anova(np.stack([TP[keep], FO[keep]], 1))
        res.append((names7[j], a["w1"][0], a["w1 x w2"][3]))
    res = pd.DataFrame(res, columns=["unit", "F", "interaction p"])
    print(f"{k}: {len(res)} units; removal gives F within 0.05 of {f_t} for {int(((res.F - f_t).abs() <= 0.05).sum())}, "
          f"an interaction p >= 0.05 for {int((res['interaction p'] >= 0.05).sum())}; F range {res.F.min():.2f} to {res.F.max():.2f}")

# Table S3's partial eta squared against the number of k3 units: eta2 = F df1 / (F df1 + df2)
for n_k3 in (18, 17):
    print(f"k3 with {n_k3} units: main effect eta2 {9.35 / (9.35 + (n_k3 - 1)):.3f} (Table S3 0.37), "
          f"interaction eta2 {1.58 * 13 / (1.58 * 13 + 13 * (n_k3 - 1)):.3f} (Table S3 0.09)")

# The pooled ANOVA of Figure 5E without the two units (362 units, 355 error df)
drop2 = ~np.isin(names7, ["rb06032120epr25bSPK11b", "rb12030520epr25bSPK13a"])
a362 = regressor_anova(TP[drop2], FO[drop2], grp[drop2])
print(f"without the two units ({int(drop2.sum())} units); paper: regressor F(1, 355) = 28.57, regressor x bin "
      "F(13, 4615) = 4.13, regressor x cluster F(6, 355) = 2.15 (p = 0.048), three-way F(78, 4615) = 1.06 (p = 0.33)")
show_anova(a362, (("w1", "regressor"), ("w1 x w2", "regressor x bin"), ("w1 x group", "regressor x cluster"),
                  ("w1 x w2 x group", "regressor x bin x cluster")))
cluster  n  regressor F        p  TP larger  paper sig  reg x bin F    p int  paper int sig  main agrees  int agrees
     k1 33         0.44    0.513      False      False         1.66   0.0662          False         True        True
     k3 18         11.5  0.00345       True       True         1.78   0.0467          False         True       False
     k4 63         6.72   0.0119       True       True         0.97     0.48          False         True        True
     k5 58         2.19    0.145       True      False         0.72    0.741          False         True        True
     k6 61         6.28   0.0149       True       True          1.6   0.0795          False         True        True
     k7 64         16.9 0.000116       True       True         3.01 0.000239           True         True        True
     k8 67         4.29   0.0424       True       True         1.21     0.27          False         True        True
clusters agreeing on both terms: 6 of 7
cluster  F all units  Table S3 F      best unit to drop  F without it  interaction p without it
     k1         0.44        0.44 rb03090418epr25aSPK09a          0.43                     0.065
     k3        11.52        9.35 rb06032120epr25bSPK11b          9.35                     0.092
     k4         6.72        6.72 rb01090318epr25aSPK12b          6.73                     0.494
     k5         2.19        2.02 rb12030520epr25bSPK13a          2.02                     0.787
     k6         6.28        6.28 rb01092018epr25aSPK05a          6.28                     0.086
     k7        16.89       16.89 rb03091018epr25aSPK09a         16.86                     0.000
     k8         4.29        4.29 rb12030420epr25bSPK15c          4.28                     0.245
k3: 18 units; removal gives F within 0.05 of 9.35 for 4, an interaction p >= 0.05 for 10; F range 9.35 to 18.75
k5: 58 units; removal gives F within 0.05 of 2.02 for 8, an interaction p >= 0.05 for 58; F range 1.55 to 3.41
k3 with 18 units: main effect eta2 0.355 (Table S3 0.37), interaction eta2 0.085 (Table S3 0.09)
k3 with 17 units: main effect eta2 0.369 (Table S3 0.37), interaction eta2 0.090 (Table S3 0.09)
without the two units (362 units); paper: regressor F(1, 355) = 28.57, regressor x bin F(13, 4615) = 4.13, regressor x cluster F(6, 355) = 2.15 (p = 0.048), three-way F(78, 4615) = 1.06 (p = 0.33)
  regressor: F(1, 355) = 28.72, p = 1.51e-07, partial eta2 = 0.075, GG p = 1.51e-07
  regressor x bin: F(13, 4615) = 4.34, p = 2.55e-07, partial eta2 = 0.012, GG p = 3.28e-06
  regressor x cluster: F(6, 355) = 2.16, p = 0.0461, partial eta2 = 0.035, GG p = 0.0461
  regressor x bin x cluster: F(78, 4615) = 1.08, p = 0.303, partial eta2 = 0.018, GG p = 0.318

Result: partially reproduced. Six of the seven clusters agree with Table S3 on both terms. The regressor main effect is significant, with peak probability larger, in exactly k3, k4, k6, k7 and k8; but k3 also has a regressor x bin interaction (p = 0.047, paper 0.09), so the interaction is not in k7 only. The paper's df imply two units fewer than here. Table S3's partial eta squared for k3 (0.37 and 0.09) fits 17 units (0.369, 0.090) better than 18 (0.355, 0.085), so one k3 unit may have been left out, but the data do not say which: four k3 units give Table S3's F when removed, and removing any of 10 of the 18 makes the k3 interaction non-significant. Without the two closest candidates, the pooled ANOVA gives regressor F(1, 355) = 28.72 and regressor x bin F(13, 4615) = 4.34, near the paper's 28.57 and 4.13 but not equal. The claims file asks for all units, and with all units the k3 interaction is significant.

fig5f-fear-output-vs-peak-probability¶

Across units there is a continuous negative relationship between fear output and peak threat probability betas (R2 = 0.43), with signaling biased toward peak threat probability, so the two are not signaled by distinct populations.

Per unit, the mean of each beta over the code's columns 3-14 (cue and delay, 12 bins; the code's Figure 5F scatter); variants (f-a) the 10 cue bins and (f-b) all 14 bins.

In [32]:
S6_R2 = {"k1": 0.64, "k3": 0.46, "k4": 0.55, "k5": 0.65, "k6": 0.55, "k7": 0.58, "k8": 0.64}
for label, sl in (("code: cue and delay (12 bins)", slice(2, 14)), ("f-a: 10 cue bins", slice(2, 12)),
                  ("f-b: all 14 bins", slice(0, 14))):
    a_, b_ = TP[:, sl].mean(1), FO[:, sl].mean(1)
    r, p = stats.pearsonr(a_, b_)
    per = {k: round(stats.pearsonr(a_[grp == k], b_[grp == k])[0] ** 2, 2) for k in SEVEN}
    print(f"{label}: r = {r:.3f}, R2 = {r * r:.3f}, p = {p:.3g}; mean TP {a_.mean():.3f}, FO {b_.mean():.3f}; "
          f"units with TP > FO {np.mean(a_ > b_):.2f}")
    print("   per-cluster R2", per, "Figure S6", S6_R2)
a_, b_ = TP[:, 2:14].mean(1), FO[:, 2:14].mean(1)
fig, ax = plt.subplots(figsize=(3.5, 3.5))
ax.scatter(a_, b_, s=6)
ax.set_xlabel("peak threat probability beta"); ax.set_ylabel("fear output beta")
plt.show()
print("plotted ranges: TP", np.round([a_.min(), a_.max()], 2), "FO", np.round([b_.min(), b_.max()], 2))
code: cue and delay (12 bins): r = -0.656, R2 = 0.430, p = 4.18e-46; mean TP 0.483, FO 0.147; units with TP > FO 0.63
   per-cluster R2 {'k1': np.float64(0.64), 'k3': np.float64(0.46), 'k4': np.float64(0.55), 'k5': np.float64(0.65), 'k6': np.float64(0.55), 'k7': np.float64(0.58), 'k8': np.float64(0.64)} Figure S6 {'k1': 0.64, 'k3': 0.46, 'k4': 0.55, 'k5': 0.65, 'k6': 0.55, 'k7': 0.58, 'k8': 0.64}
f-a: 10 cue bins: r = -0.648, R2 = 0.419, p = 1.2e-44; mean TP 0.487, FO 0.146; units with TP > FO 0.63
   per-cluster R2 {'k1': np.float64(0.64), 'k3': np.float64(0.52), 'k4': np.float64(0.55), 'k5': np.float64(0.65), 'k6': np.float64(0.55), 'k7': np.float64(0.59), 'k8': np.float64(0.64)} Figure S6 {'k1': 0.64, 'k3': 0.46, 'k4': 0.55, 'k5': 0.65, 'k6': 0.55, 'k7': 0.58, 'k8': 0.64}
f-b: all 14 bins: r = -0.656, R2 = 0.430, p = 4.24e-46; mean TP 0.414, FO 0.126; units with TP > FO 0.63
   per-cluster R2 {'k1': np.float64(0.64), 'k3': np.float64(0.47), 'k4': np.float64(0.55), 'k5': np.float64(0.65), 'k6': np.float64(0.55), 'k7': np.float64(0.58), 'k8': np.float64(0.64)} Figure S6 {'k1': 0.64, 'k3': 0.46, 'k4': 0.55, 'k5': 0.65, 'k6': 0.55, 'k7': 0.58, 'k8': 0.64}
No description has been provided for this image
plotted ranges: TP [-1.58  2.38] FO [-1.37  1.94]

Result: reproduced. r = -0.656, R2 = 0.430, p = 4.2e-46 over 364 units, the paper's R2, and the per-cluster R2 equal those of Figure S6. The mean peak probability beta (0.483) is above the mean fear output beta (0.147), with 63% of units above the diagonal. The f-a and f-b readings give R2 0.419 and 0.430.

table1-outcome-anova¶

Every cluster showed differential firing after shock delivery or omission, a main effect of trial type and/or a trial type x interval interaction.

Per cluster, the 70 250-ms bins of the 17.5 s after shock offset (the code's bins 131-200), for danger, uncertainty shock, uncertainty omission and safety; repeated measures with trial type and interval within units.

In [33]:
T1_OUT = {"k1": (True, True), "k2": (True, True), "k3": (True, False), "k4": (True, True),
          "k5": (True, True), "k6": (False, True), "k7": (True, True), "k8": (True, True)}   # (interaction, main)

def outcome_anova(mm, label):
    rows = []
    for k in rrf.CLUSTERS:
        sel = cl == k
        y = np.stack([mm[t][rrf.OUTCOME][:, sel] for t in ("D", "US", "UO", "S")], axis=0).transpose(2, 0, 1)
        a = rrf.mixed_anova(y)
        rows.append((k, sel.sum(), round(a["w1 x w2"][0], 2), a["w1 x w2"][3], a["w1 x w2"][6],
                     round(a["w1"][0], 2), a["w1"][3], a["w1"][6]))
    tab = pd.DataFrame(rows, columns=["cluster", "n", "interaction F", "p int", "GG p int", "type F", "p type", "GG p type"])
    tab["matches"] = [((r["p int"] < 0.05) == T1_OUT[r["cluster"]][0]) + ((r["p type"] < 0.05) == T1_OUT[r["cluster"]][1])
                      for _, r in tab.iterrows()]
    tab["any effect"] = (tab["p int"] < 0.05) | (tab["p type"] < 0.05)
    print(label); print(tab.to_string(index=False, float_format=lambda v: f"{v:.3g}"))
    print("  clusters with an effect:", int(tab["any effect"].sum()), "of 8; tests matching Table 1:",
          int(tab["matches"].sum()), "of 16")
    return tab

t1out = outcome_anova(m250, "code normalization")
for nm in ("z-a", "z-b"):
    outcome_anova(NORMS[nm], nm)
code normalization
cluster  n  interaction F    p int  GG p int  type F   p type  GG p type  matches  any effect
     k1 33           1.21   0.0212     0.225    2.98   0.0351     0.0384        2        True
     k2 59           2.12 2.21e-18  9.95e-05    56.6 1.37e-25   2.92e-24        2        True
     k3 18            1.2   0.0322     0.284    2.12     0.11      0.115        2        True
     k4 63           1.85 2.72e-12   0.00132    47.5 7.76e-23   4.79e-21        2        True
     k5 58           2.62 6.98e-31  3.31e-07     3.9  0.00999     0.0161        2        True
     k6 61           1.11    0.142       0.3    48.8 3.88e-23   1.41e-18        2        True
     k7 64           3.84 5.58e-67  3.19e-13    94.8 1.73e-37   2.38e-34        2        True
     k8 67           2.18 1.09e-19  2.62e-05    47.2 4.47e-23   8.82e-20        2        True
  clusters with an effect: 8 of 8; tests matching Table 1: 16 of 16
z-a
cluster  n  interaction F    p int  GG p int  type F   p type  GG p type  matches  any effect
     k1 33           1.18   0.0428     0.257    3.05   0.0323     0.0354        2        True
     k2 59            2.1  7.5e-18   0.00011    56.3 1.76e-25   1.13e-24        2        True
     k3 18           1.15   0.0794     0.325    2.06    0.118      0.126        1       False
     k4 63           1.82 9.52e-12   0.00153    50.7 5.32e-24   3.07e-22        2        True
     k5 58           2.58 1.09e-29  5.31e-07    3.76   0.0119     0.0175        2        True
     k6 61           1.14   0.0779      0.25      52 3.09e-24   2.38e-20        2        True
     k7 64           3.68 5.33e-62  1.88e-12    97.5 3.57e-38   2.63e-34        2        True
     k8 67           2.18 7.76e-20  2.83e-05    49.1 8.79e-24   3.06e-21        2        True
  clusters with an effect: 7 of 8; tests matching Table 1: 15 of 16
z-b
cluster  n  interaction F    p int  GG p int  type F   p type  GG p type  matches  any effect
     k1 33           1.17   0.0536      0.27    2.91   0.0386     0.0429        1        True
     k2 59           2.17  2.2e-19  6.67e-05    58.2 4.24e-26   1.44e-24        2        True
     k3 18           1.12    0.114     0.343    1.99    0.127      0.135        1       False
     k4 63            1.8 2.85e-11   0.00224    50.7 5.51e-24   4.77e-22        2        True
     k5 58           2.52 2.69e-28  1.11e-06    3.84   0.0107     0.0167        2        True
     k6 61           1.12    0.118     0.283    45.2 8.03e-22   2.98e-16        2        True
     k7 64           3.71 4.73e-63   2.4e-12    92.8 5.96e-37   3.25e-31        2        True
     k8 67           2.14 1.03e-18  4.67e-05    49.2 8.22e-24   1.05e-20        2        True
  clusters with an effect: 7 of 8; tests matching Table 1: 14 of 16

Result: reproduced. Under the code's normalization every cluster has at least one effect and the pattern of significance matches Table 1 in all 16 tests (k3 interaction only, k6 main effect only, both in the others). With the Greenhouse-Geisser correction the interaction of k1 and k3 is no longer significant (p = 0.23 and 0.28); the Methods' normalizations leave k3 without an effect (z-a 15 of 16, z-b 14 of 16 tests match).

Outcome firing (Figure 6, Table S4)¶

The shared method of the fig6 claims: per unit, mean normalized firing per trial type in the cluster's gray-box interval of Figure 6 (claims file: 0 to 8 s after shock offset for k1, k3, k5 and k6, 250-ms bins 131-162; the whole 17.5 s for k2, k4, k7 and k8, bins 131-200); studentized bootstrap CIs per cluster of each trial type and of the differences uncertainty shock - danger, uncertainty omission - safety and danger - safety. The code holds no Table S4 computation; its outcome windows are the first 2 s (bins 131-138) and the last 10 s (bins 161-200), shown as variants. The next cell scans every window that starts at shock offset for the one whose four trial-type means come closest to Table S4: for k1, k3, k5 and k6 it is 0 to 4 s, not the 0 to 8 s of the gray boxes, so 0 to 4 s is shown as a variant too. The code does not draw the gray boxes; its traces (printed in the code section) put 0 s at shock offset, with ticks every 2 s, so the boxes' 8 s is 8 s after shock offset.

In [34]:
TYPES = ("D", "US", "UO", "S")
DIFFS = (("US-D", "US", "D"), ("UO-S", "UO", "S"), ("D-S", "D", "S"))
TABLE_S4 = {  # mean, tolerance per trial type (claims file)
    "k1": [(0.19, 0.18), (0.20, 0.17), (-0.02, 0.12), (0.15, 0.10)],
    "k2": [(0.33, 0.05), (-0.18, 0.07), (-0.05, 0.053), (0.06, 0.05)],
    "k3": [(0.07, 0.27), (-0.03, 0.21), (0.20, 0.23), (-0.18, 0.11)],
    "k4": [(0.19, 0.06), (0.25, 0.06), (-0.16, 0.04), (0.20, 0.05)],
    "k5": [(0.04, 0.11), (-0.05, 0.11), (0.25, 0.08), (-0.07, 0.067)],
    "k6": [(-0.17, 0.09), (-0.32, 0.10), (0.02, 0.07), (0.26, 0.07)],
    "k7": [(0.29, 0.06), (0.42, 0.08), (0.08, 0.05), (-0.28, 0.06)],
    "k8": [(-0.11, 0.06), (0.32, 0.07), (0.18, 0.04), (-0.02, 0.04)],
}
PAPER_PATTERN = {  # CI sign of D, US, UO, S, then US-D, UO-S, D-S (claims file criteria)
    "k1": (1, 1, 0, 1, 0, -1, 0), "k2": (1, -1, 0, 1, -1, -1, 1), "k3": (0, 0, 0, -1, 0, 1, 0),
    "k4": (1, 1, -1, 1, 0, -1, 0), "k5": (0, 0, 1, -1, 0, 1, 0), "k6": (-1, -1, 0, 1, -1, -1, -1),
    "k7": (1, 1, 1, -1, 1, 1, 1), "k8": (-1, 1, 1, 0, 1, 1, -1),
}

def outcome_cis(k, mm, window, gen):
    sel = cl == k
    per = {t: np.nanmean(mm[t][window][:, sel], 0) for t in TYPES}
    cis = {t: rrf.boot_ci(per[t], gen) for t in TYPES}
    for nm, a, b in DIFFS:
        cis[nm] = rrf.boot_ci(per[a] - per[b], gen)
    return cis

def fig6_table(k, gen, mm=None, window=None):
    mm = m250 if mm is None else mm
    window = rrf.FIG6_WINDOW[k] if window is None else window
    cis = outcome_cis(k, mm, window, gen)
    rows = []
    for j, key in enumerate(TYPES + tuple(d[0] for d in DIFFS)):
        ci = cis[key]
        ref = TABLE_S4[k][j] if j < 4 else None
        rows.append((key, round(ci[0], 3), round(ci[1], 3), round(ci[2], 3), rrf.ci_sign(ci), PAPER_PATTERN[k][j],
                     rrf.ci_sign(ci) == PAPER_PATTERN[k][j], ref[0] if ref else np.nan,
                     bool(abs(ci[0] - ref[0]) <= ref[1]) if ref else np.nan))
    tab = pd.DataFrame(rows, columns=["measure", "mean", "low", "high", "CI sign", "paper sign", "agrees",
                                      "Table S4 mean", "within tol"])
    return tab

def fig6_report(k, claim):
    tab = fig6_table(k, seeded(claim))
    print(f"{k}, window {rrf.FIG6_WINDOW[k]}, n = {(cl == k).sum()}")
    print(tab.to_string(index=False))
    print(f"  CIs agreeing: {int(tab.agrees.sum())} of 7; means within tolerance: {int(tab['within tol'].iloc[:4].sum())} of 4")
    for label, win in (("other window: first 2 s", rrf.b250(131, 138)), ("other window: last 10 s", rrf.b250(161, 200)),
                       ("other window: 0-8 s" if rrf.FIG6_WINDOW[k] == rrf.OUTCOME else "other window: 17.5 s",
                        rrf.OUTCOME_0_8 if rrf.FIG6_WINDOW[k] == rrf.OUTCOME else rrf.OUTCOME)):
        tv = fig6_table(k, seeded(claim), window=win)
        print(f"  {label}: means {dict(zip(tv.measure, tv['mean']))}; CIs agreeing {int(tv.agrees.sum())} of 7")
    if rrf.FIG6_WINDOW[k] == rrf.OUTCOME_0_8:
        tv = fig6_table(k, seeded(claim), window=rrf.b250(131, 146))
        print(f"  variant window 0-4 s after shock offset: means {dict(zip(tv.measure, tv['mean']))}; CIs agreeing "
              f"{int(tv.agrees.sum())} of 7; means within tolerance {int(tv['within tol'].iloc[:4].sum())} of 4")
    for nm in ("z-a", "z-b"):
        tv = fig6_table(k, seeded(claim), mm=NORMS[nm])
        print(f"  {nm}: CIs agreeing {int(tv.agrees.sum())} of 7, means within {int(tv['within tol'].iloc[:4].sum())} of 4; "
              f"means {dict(zip(TYPES, tv['mean'].iloc[:4]))}")
    return tab
In [35]:
# Which window starting at shock offset reproduces the Table S4 means? (largest absolute difference
# over the four trial types)
scan = []
for k in rrf.CLUSTERS:
    ref = np.array([m for m, _ in TABLE_S4[k]])
    best = min(((np.abs(np.array([np.nanmean(m250[t][130:b][:, cl == k]) for t in TYPES]) - ref).max(), (b - 130) / 4)
                for b in range(134, 201)), key=lambda x: x[0])
    v8 = np.abs(np.array([np.nanmean(m250[t][rrf.OUTCOME_0_8][:, cl == k]) for t in TYPES]) - ref).max()
    v17 = np.abs(np.array([np.nanmean(m250[t][rrf.OUTCOME][:, cl == k]) for t in TYPES]) - ref).max()
    scan.append((k, best[1], round(best[0], 4), round(v8, 3), round(v17, 3)))
print(pd.DataFrame(scan, columns=["cluster", "best window end (s)", "max |diff| there", "max |diff| 0-8 s",
                                  "max |diff| 0-17.5 s"]).to_string(index=False))
cluster  best window end (s)  max |diff| there  max |diff| 0-8 s  max |diff| 0-17.5 s
     k1                 4.00            0.0077             0.147                0.226
     k2                17.25            0.0033             0.081                0.004
     k3                 4.00            0.0059             0.127                0.264
     k4                16.50            0.0044             0.077                0.005
     k5                 4.00            0.0030             0.094                0.208
     k6                 3.75            0.0031             0.041                0.085
     k7                17.50            0.0035             0.170                0.003
     k8                17.50            0.0058             0.083                0.006

Bootstrap CIs over 20 draws and with MATLAB's nested standard errors¶

Several CIs end within 0.01 of zero, where one random draw decides whether they exclude it. Every CI that a criterion judges (behavior, Table S1, Figure S4, Table S2 and Table S4) is redrawn here with 20 seeds, with the main reading's standard errors (s / sqrt(n)) and with the nested bootstrap that MATLAB's bootci(..., 'type', 'student') uses when no StdErr is given (100 samples per standard error; MATLAB documentation, NBootStd). For the outcomes, each CI is judged by the sign it gives in most of the 20 draws; the per-claim sections show the single draw of their own seed.

In [36]:
# Every bootstrap CI a criterion judges, with the paper's sign (+1 above zero, -1 below, 0 includes
# zero), redrawn with 20 seeds, with standard errors s / sqrt(n) (main reading) and with bootci's
# default nested bootstrap (100 samples per standard error).
ci_tests = []          # (claim, label, values, paper sign)
y_beh = per_rat_mean[["D", "U", "S"]].to_numpy()
for nm, d in (("D-U", y_beh[:, 0] - y_beh[:, 1]), ("U-S", y_beh[:, 1] - y_beh[:, 2]), ("D-S", y_beh[:, 0] - y_beh[:, 2])):
    ci_tests.append(("behavior-discrimination", nm, d, 1))
for k in rrf.CLUSTERS:
    claim = "fig3b-excitatory-clusters" if k in ("k1", "k3", "k5", "k7") else "fig3d-inhibitory-clusters"
    per = {t: np.nanmean(m250[t][rrf.FIG3_INTERVAL[k]][:, cl == k], axis=0) for t in "DUS"}
    for j, (nm, d) in enumerate((("D-U", per["D"] - per["U"]), ("U-S", per["U"] - per["S"]))):
        ref = TABLE_S1[k][j]
        ci_tests.append((claim, f"{k} {nm}", d, rrf.ci_sign(ref[:3])))
for (k, t), ref in S4.items():
    d = np.nanmean(m250[t][rrf.DELAY][:, cl == k], 0) - np.nanmean(m250[t][rrf.ONSET][:, cl == k], 0)
    ci_tests.append(("figs4-onset-and-ramp", f"{k} {t} delay-onset", d, ref[2]))
for b_, nm in enumerate(BIN_NAMES):
    ci_tests.append(("fig5e-peak-probability-over-fear-output", f"TP {nm}", TP[:, b_], 0 if b_ < 2 else 1))
    ci_tests.append(("fig5e-peak-probability-over-fear-output", f"FO {nm}", FO[:, b_], 0 if b_ < 3 else 1))
    if b_ >= 2:
        ci_tests.append(("fig5e-peak-probability-over-fear-output", f"TP-FO {nm}", TP[:, b_] - FO[:, b_], 1))
FIG6_CLAIM = {"k1": "fig6a-k1-shock", "k2": "fig6b-k2-anti-ppe", "k3": "fig6c-k3-continued-threat",
              "k4": "fig6de-k4-k5-persistent-threat", "k5": "fig6de-k4-k5-persistent-threat",
              "k6": "fig6f-k6-ppe-then-valence", "k7": "fig6g-k7-valence-then-ppe", "k8": "fig6h-k8-ppe-then-unsigned"}
for k in rrf.CLUSTERS:
    per = {t: np.nanmean(m250[t][rrf.FIG6_WINDOW[k]][:, cl == k], 0) for t in TYPES}
    vals = [per[t] for t in TYPES] + [per[a] - per[b] for _, a, b in DIFFS]
    for j, (key, v) in enumerate(zip(TYPES + tuple(d[0] for d in DIFFS), vals)):
        ci_tests.append((FIG6_CLAIM[k], f"{k} {key}", v, PAPER_PATTERN[k][j]))

N_SEEDS = 20
stab_rows = []
for claim, label, v, sign in ci_tests:
    row = [claim, label, sign]
    for nbs in (0, 100):
        gs = [np.random.default_rng([s, nbs]) for s in range(N_SEEDS)]
        cis = np.array([rrf.boot_ci(v, gg, n_boot_std=nbs) for gg in gs])
        row += [float(np.mean([rrf.ci_sign(c) == sign for c in cis])), cis[:, 1].min(), cis[:, 2].max()]
    stab_rows.append(row)
stab = pd.DataFrame(stab_rows, columns=["claim", "CI", "paper sign", "agree s/sqrt(n)", "min low", "max high",
                                        "agree nested", "min low n", "max high n"])
print(len(stab), "CIs;", int(((stab["agree s/sqrt(n)"] < 1) | (stab["agree nested"] < 1)).sum()),
      "do not agree with the paper's sign in all 20 draws under both standard errors:")
print(stab[(stab["agree s/sqrt(n)"] < 1) | (stab["agree nested"] < 1)].to_string(index=False, float_format=lambda x: f"{x:.3f}"))

# The rule used for the outcomes: a CI is judged by the sign it gives in most of the 20 draws
# (standard errors s / sqrt(n)); the per-claim counts under it
stab["agrees (majority of draws)"] = stab["agree s/sqrt(n)"] > 0.5
stab["agrees (majority, nested)"] = stab["agree nested"] > 0.5
print(stab.groupby("claim", sort=False)[["agrees (majority of draws)", "agrees (majority, nested)"]].agg(["sum", "count"]))
121 CIs; 8 do not agree with the paper's sign in all 20 draws under both standard errors:
                         claim     CI  paper sign  agree s/sqrt(n)  min low  max high  agree nested  min low n  max high n
     fig3d-inhibitory-clusters k8 U-S           0            0.550   -0.008     0.140         0.550     -0.013       0.140
                fig6a-k1-shock   k1 D           1            0.000   -0.043     0.219         0.000     -0.059       0.237
                fig6a-k1-shock  k1 US           1            0.000   -0.088     0.184         0.000     -0.087       0.200
                fig6a-k1-shock  k1 UO           0            1.000   -0.201     0.012         0.950     -0.205       0.032
             fig6b-k2-anti-ppe  k2 UO           0            0.050   -0.094     0.001         0.200     -0.101       0.006
fig6de-k4-k5-persistent-threat  k5 US           0            1.000   -0.161     0.018         0.950     -0.172       0.029
     fig6f-k6-ppe-then-valence  k6 UO           0            0.100   -0.001     0.102         0.200     -0.005       0.107
    fig6h-k8-ppe-then-unsigned k8 D-S          -1            1.000   -0.167    -0.003         0.900     -0.172       0.004
                                        agrees (majority of draws)       agrees (majority, nested)      
                                                               sum count                       sum count
claim                                                                                                   
behavior-discrimination                                          3     3                         3     3
fig3b-excitatory-clusters                                        8     8                         8     8
fig3d-inhibitory-clusters                                        8     8                         8     8
figs4-onset-and-ramp                                             6     6                         6     6
fig5e-peak-probability-over-fear-output                         40    40                        40    40
fig6a-k1-shock                                                   5     7                         5     7
fig6b-k2-anti-ppe                                                6     7                         6     7
fig6c-k3-continued-threat                                        7     7                         7     7
fig6de-k4-k5-persistent-threat                                  14    14                        14    14
fig6f-k6-ppe-then-valence                                        6     7                         6     7
fig6g-k7-valence-then-ppe                                        7     7                         7     7
fig6h-k8-ppe-then-unsigned                                       7     7                         7     7

Result. Of the 121 CIs, 8 do not give the paper's sign in every draw (table above), and the majority sign is the same with either standard error. One of them changes a count against the single draws of the claim sections: the k6 uncertainty omission CI (fig6f) excludes zero in 18 of 20 draws, where the paper's includes it. The k8 uncertainty - safety CI (fig3d) includes zero, as the paper's does, in 11 of 20 draws and in the claim's own draw, so its count does not change. The k2 omission CI (fig6b) excludes zero in 19 of 20 draws, so it disagrees with the paper's as in that claim's own draw. The claims file does not say how to judge a CI that changes sign between draws; the majority rule is this attempt's convention, applied to every judged CI.

fig6a-k1-shock¶

k1 units are generally shock responsive, with equivalent, transient firing after danger and uncertainty shock.

In [37]:
f6 = {}
f6["k1"] = fig6_report("k1", "fig6a-k1-shock")
k1, window slice(130, 162, None), n = 33
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D  0.085 -0.032  0.205        0           1   False           0.19       True
     US  0.053 -0.080  0.184        0           1   False           0.20       True
     UO -0.081 -0.198  0.008        0           0    True          -0.02       True
      S  0.093  0.023  0.164        1           1    True           0.15       True
   US-D -0.032 -0.190  0.122        0           0    True            NaN        NaN
   UO-S -0.174 -0.316 -0.044       -1          -1    True            NaN        NaN
    D-S -0.008 -0.168  0.135        0           0    True            NaN        NaN
  CIs agreeing: 5 of 7; means within tolerance: 4 of 4
  other window: first 2 s: means {'D': 0.338, 'US': 0.306, 'UO': 0.028, 'S': 0.154, 'US-D': -0.031, 'UO-S': -0.126, 'D-S': 0.184}; CIs agreeing 6 of 7
  other window: last 10 s: means {'D': -0.13, 'US': -0.051, 'UO': -0.184, 'S': 0.02, 'US-D': 0.079, 'UO-S': -0.204, 'D-S': -0.15}; CIs agreeing 2 of 7
  other window: 17.5 s: means {'D': -0.036, 'US': -0.002, 'UO': -0.137, 'S': 0.055, 'US-D': 0.034, 'UO-S': -0.192, 'D-S': -0.091}; CIs agreeing 3 of 7
  variant window 0-4 s after shock offset: means {'D': 0.191, 'US': 0.208, 'UO': -0.012, 'S': 0.147, 'US-D': 0.017, 'UO-S': -0.16, 'D-S': 0.043}; CIs agreeing 7 of 7; means within tolerance 4 of 4
  z-a: CIs agreeing 4 of 7, means within 3 of 4; means {'D': 0.116, 'US': 0.075, 'UO': -0.166, 'S': 0.134}
  z-b: CIs agreeing 4 of 7, means within 3 of 4; means {'D': 0.132, 'US': 0.093, 'UO': -0.192, 'S': 0.138}

Result: not reproduced. In the claims file's window, 0 to 8 s after shock offset, the danger and uncertainty shock CIs include zero (means 0.085 and 0.053), where the paper's are above zero; five of seven CIs agree and the four means are within the (wide) tolerances. The criterion's fallback needs both shock CIs above zero, so the claim is not reproduced in this window. In the window that reproduces Table S4's means, 0 to 4 s after shock offset, all seven CIs agree and the four means are within tolerance (0.191, 0.208, -0.012, 0.147): the result depends on which window the paper analysed (see the window scan above).

fig6b-k2-anti-ppe¶

k2 units fire most to the predicted shock on danger trials and are inhibited by the surprising shock on uncertainty trials, an anti-positive prediction error signal.

In [38]:
f6["k2"] = fig6_report("k2", "fig6b-k2-anti-ppe")
maj = stab[stab.claim == "fig6b-k2-anti-ppe"]
print("over 20 draws:", maj[["CI", "paper sign", "agree s/sqrt(n)", "agree nested"]].to_string(index=False))
print("CIs agreeing in most of the 20 draws:", int(maj["agrees (majority of draws)"].sum()), "of", len(maj))
k2, window slice(130, 200, None), n = 59
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D  0.331  0.278  0.379        1           1    True           0.33       True
     US -0.178 -0.237 -0.119       -1          -1    True          -0.18       True
     UO -0.046 -0.093 -0.005       -1           0   False          -0.05       True
      S  0.061  0.013  0.110        1           1    True           0.06       True
   US-D -0.509 -0.597 -0.418       -1          -1    True            NaN        NaN
   UO-S -0.108 -0.195 -0.029       -1          -1    True            NaN        NaN
    D-S  0.269  0.187  0.344        1           1    True            NaN        NaN
  CIs agreeing: 6 of 7; means within tolerance: 4 of 4
  other window: first 2 s: means {'D': 0.463, 'US': -0.086, 'UO': -0.143, 'S': 0.037, 'US-D': -0.549, 'UO-S': -0.179, 'D-S': 0.426}; CIs agreeing 4 of 7
  other window: last 10 s: means {'D': 0.264, 'US': -0.196, 'UO': -0.026, 'S': 0.066, 'US-D': -0.46, 'UO-S': -0.092, 'D-S': 0.198}; CIs agreeing 7 of 7
  other window: 0-8 s: means {'D': 0.411, 'US': -0.158, 'UO': -0.07, 'S': 0.052, 'US-D': -0.569, 'UO-S': -0.122, 'D-S': 0.358}; CIs agreeing 5 of 7
  z-a: CIs agreeing 7 of 7, means within 1 of 4; means {'D': 0.62, 'US': -0.286, 'UO': -0.065, 'S': 0.142}
  z-b: CIs agreeing 5 of 7, means within 1 of 4; means {'D': 0.619, 'US': -0.47, 'UO': -0.178, 'S': 0.05}
over 20 draws:      CI  paper sign  agree s/sqrt(n)  agree nested
   k2 D           1             1.00           1.0
  k2 US          -1             1.00           1.0
  k2 UO           0             0.05           0.2
   k2 S           1             1.00           1.0
k2 US-D          -1             1.00           1.0
k2 UO-S          -1             1.00           1.0
 k2 D-S           1             1.00           1.0
CIs agreeing in most of the 20 draws: 6 of 7

Result: partially reproduced. Danger is above zero, uncertainty shock below zero, and shock - danger below zero, with all four means within tolerance; six of seven CIs agree. The omission CI ends just below zero (-0.093 to -0.005), where the paper's just includes it (-0.09 to 0.003). Over 20 draws it agrees with the paper's in 5% (1 of 20) with s / sqrt(n) and in 20% with the nested standard errors, so six of seven CIs agree under the majority rule too.

fig6c-k3-continued-threat¶

k3 units sharply reduce firing after shock but sustain excitation after omission on uncertainty trials, a continued threat signal.

In [39]:
f6["k3"] = fig6_report("k3", "fig6c-k3-continued-threat")
k3, window slice(130, 162, None), n = 18
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D  0.014 -0.151  0.217        0           0    True           0.07       True
     US -0.073 -0.185  0.104        0           0    True          -0.03       True
     UO  0.073 -0.076  0.258        0           0    True           0.20       True
      S -0.187 -0.273 -0.101       -1          -1    True          -0.18       True
   US-D -0.087 -0.357  0.089        0           0    True            NaN        NaN
   UO-S  0.260  0.073  0.505        1           1    True            NaN        NaN
    D-S  0.201 -0.003  0.453        0           0    True            NaN        NaN
  CIs agreeing: 7 of 7; means within tolerance: 4 of 4
  other window: first 2 s: means {'D': 0.176, 'US': 0.09, 'UO': 0.267, 'S': -0.167, 'US-D': -0.086, 'UO-S': 0.434, 'D-S': 0.343}; CIs agreeing 6 of 7
  other window: last 10 s: means {'D': -0.045, 'US': -0.107, 'UO': -0.178, 'S': -0.25, 'US-D': -0.061, 'UO-S': 0.072, 'D-S': 0.205}; CIs agreeing 4 of 7
  other window: 17.5 s: means {'D': -0.019, 'US': -0.094, 'UO': -0.064, 'S': -0.224, 'US-D': -0.075, 'UO-S': 0.16, 'D-S': 0.205}; CIs agreeing 6 of 7
  variant window 0-4 s after shock offset: means {'D': 0.064, 'US': -0.029, 'UO': 0.2, 'S': -0.184, 'US-D': -0.093, 'UO-S': 0.384, 'D-S': 0.248}; CIs agreeing 6 of 7; means within tolerance 4 of 4
  z-a: CIs agreeing 7 of 7, means within 4 of 4; means {'D': 0.007, 'US': -0.106, 'UO': 0.094, 'S': -0.286}
  z-b: CIs agreeing 7 of 7, means within 3 of 4; means {'D': -0.001, 'US': -0.124, 'UO': 0.092, 'S': -0.31}

Result: reproduced. All seven CIs agree with the paper's pattern and the four means are within tolerance in the 0 to 8 s window; in the 0 to 4 s window six of seven agree and the four means are within 0.01 of Table S4's.

fig6de-k4-k5-persistent-threat¶

k4 units sustain inhibition and k5 units sustain excitation on uncertainty omission trials, persistent threat signaling through opposite firing directions.

In [40]:
f6["k4"] = fig6_report("k4", "fig6de-k4-k5-persistent-threat")
f6["k5"] = fig6_report("k5", "fig6de-k4-k5-persistent-threat")
k4, window slice(130, 200, None), n = 63
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D  0.192  0.137  0.245        1           1    True           0.19       True
     US  0.248  0.193  0.304        1           1    True           0.25       True
     UO -0.158 -0.196 -0.122       -1          -1    True          -0.16       True
      S  0.195  0.150  0.241        1           1    True           0.20       True
   US-D  0.056 -0.023  0.140        0           0    True            NaN        NaN
   UO-S -0.353 -0.425 -0.292       -1          -1    True            NaN        NaN
    D-S -0.003 -0.084  0.082        0           0    True            NaN        NaN
  CIs agreeing: 7 of 7; means within tolerance: 4 of 4
  other window: first 2 s: means {'D': 0.284, 'US': 0.376, 'UO': -0.281, 'S': 0.216, 'US-D': 0.091, 'UO-S': -0.497, 'D-S': 0.068}; CIs agreeing 7 of 7
  other window: last 10 s: means {'D': 0.144, 'US': 0.181, 'UO': -0.117, 'S': 0.18, 'US-D': 0.037, 'UO-S': -0.297, 'D-S': -0.036}; CIs agreeing 7 of 7
  other window: 0-8 s: means {'D': 0.255, 'US': 0.327, 'UO': -0.209, 'S': 0.212, 'US-D': 0.072, 'UO-S': -0.421, 'D-S': 0.043}; CIs agreeing 7 of 7
  z-a: CIs agreeing 7 of 7, means within 0 of 4; means {'D': 0.28, 'US': 0.38, 'UO': -0.35, 'S': 0.277}
  z-b: CIs agreeing 7 of 7, means within 0 of 4; means {'D': 0.336, 'US': 0.474, 'UO': -0.411, 'S': 0.332}
k5, window slice(130, 162, None), n = 58
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D -0.025 -0.101  0.044        0           0    True           0.04       True
     US -0.070 -0.159  0.009        0           0    True          -0.05       True
     UO  0.156  0.097  0.219        1           1    True           0.25      False
      S -0.098 -0.141 -0.053       -1          -1    True          -0.07       True
   US-D -0.046 -0.181  0.077        0           0    True            NaN        NaN
   UO-S  0.254  0.181  0.336        1           1    True            NaN        NaN
    D-S  0.074 -0.018  0.170        0           0    True            NaN        NaN
  CIs agreeing: 7 of 7; means within tolerance: 3 of 4
  other window: first 2 s: means {'D': 0.175, 'US': 0.026, 'UO': 0.299, 'S': -0.091, 'US-D': -0.149, 'UO-S': 0.39, 'D-S': 0.266}; CIs agreeing 5 of 7
  other window: last 10 s: means {'D': -0.052, 'US': -0.054, 'UO': -0.053, 'S': -0.124, 'US-D': -0.002, 'UO-S': 0.07, 'D-S': 0.072}; CIs agreeing 6 of 7
  other window: 17.5 s: means {'D': -0.039, 'US': -0.062, 'UO': 0.042, 'S': -0.113, 'US-D': -0.023, 'UO-S': 0.155, 'D-S': 0.074}; CIs agreeing 7 of 7
  variant window 0-4 s after shock offset: means {'D': 0.041, 'US': -0.053, 'UO': 0.248, 'S': -0.07, 'US-D': -0.094, 'UO-S': 0.317, 'D-S': 0.11}; CIs agreeing 6 of 7; means within tolerance 4 of 4
  z-a: CIs agreeing 7 of 7, means within 3 of 4; means {'D': -0.032, 'US': -0.097, 'UO': 0.296, 'S': -0.157}
  z-b: CIs agreeing 7 of 7, means within 2 of 4; means {'D': -0.04, 'US': -0.126, 'UO': 0.334, 'S': -0.185}

Result: partially reproduced. All CIs of both clusters agree with the paper's pattern, and the four k4 means are within tolerance; the k5 omission mean in the 0 to 8 s window is 0.156 against 0.25 +/- 0.08, so not every mean is within tolerance. In the 0 to 4 s window the k5 means are within tolerance (omission 0.248) and six of seven k5 CIs agree.

fig6f-k6-ppe-then-valence¶

k6 units show early positive prediction error through firing decreases (more inhibition after uncertainty shock than danger shock), giving way to a sustained valence signal with most firing to safety, little after omission and sustained inhibition after danger and uncertainty shock.

In [41]:
f6["k6"] = fig6_report("k6", "fig6f-k6-ppe-then-valence")
print("k6 means over the whole 17.5 s:", dict(zip(TYPES, [round(float(np.nanmean(m250[t][rrf.OUTCOME][:, cl == "k6"])), 3) for t in TYPES])))
maj = stab[stab.claim == "fig6f-k6-ppe-then-valence"]
print("over 20 draws:", maj[["CI", "paper sign", "agree s/sqrt(n)", "agree nested"]].to_string(index=False))
print("CIs agreeing in most of the 20 draws:", int(maj["agrees (majority of draws)"].sum()), "of", len(maj))
t6 = f6["k6"].set_index("measure")
print("partial condition: shock - danger below zero in", f"{maj.set_index('CI').loc['k6 US-D', 'agree s/sqrt(n)']:.0%}",
      "of draws; safety the largest mean:", bool(t6.loc["S", "mean"] == t6.loc[list(TYPES), "mean"].max()))
k6, window slice(130, 162, None), n = 61
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D -0.147 -0.212 -0.080       -1          -1    True          -0.17       True
     US -0.279 -0.379 -0.210       -1          -1    True          -0.32       True
     UO  0.050 -0.000  0.099        0           0    True           0.02       True
      S  0.253  0.205  0.295        1           1    True           0.26       True
   US-D -0.132 -0.247 -0.027       -1          -1    True            NaN        NaN
   UO-S -0.203 -0.267 -0.137       -1          -1    True            NaN        NaN
    D-S -0.400 -0.489 -0.319       -1          -1    True            NaN        NaN
  CIs agreeing: 7 of 7; means within tolerance: 4 of 4
  other window: first 2 s: means {'D': -0.134, 'US': -0.364, 'UO': 0.014, 'S': 0.274, 'US-D': -0.229, 'UO-S': -0.261, 'D-S': -0.409}; CIs agreeing 7 of 7
  other window: last 10 s: means {'D': -0.137, 'US': -0.198, 'UO': 0.056, 'S': 0.244, 'US-D': -0.061, 'UO-S': -0.187, 'D-S': -0.381}; CIs agreeing 5 of 7
  other window: 17.5 s: means {'D': -0.141, 'US': -0.235, 'UO': 0.051, 'S': 0.247, 'US-D': -0.094, 'UO-S': -0.195, 'D-S': -0.388}; CIs agreeing 5 of 7
  variant window 0-4 s after shock offset: means {'D': -0.166, 'US': -0.324, 'UO': 0.018, 'S': 0.259, 'US-D': -0.158, 'UO-S': -0.241, 'D-S': -0.425}; CIs agreeing 7 of 7; means within tolerance 4 of 4
  z-a: CIs agreeing 6 of 7, means within 1 of 4; means {'D': -0.219, 'US': -0.426, 'UO': 0.147, 'S': 0.516}
  z-b: CIs agreeing 7 of 7, means within 0 of 4; means {'D': -0.313, 'US': -0.62, 'UO': 0.093, 'S': 0.503}
k6 means over the whole 17.5 s: {'D': -0.141, 'US': -0.235, 'UO': 0.051, 'S': 0.247}
over 20 draws:      CI  paper sign  agree s/sqrt(n)  agree nested
   k6 D          -1              1.0           1.0
  k6 US          -1              1.0           1.0
  k6 UO           0              0.1           0.2
   k6 S           1              1.0           1.0
k6 US-D          -1              1.0           1.0
k6 UO-S          -1              1.0           1.0
 k6 D-S          -1              1.0           1.0
CIs agreeing in most of the 20 draws: 6 of 7
partial condition: shock - danger below zero in 100% of draws; safety the largest mean: True

Result: partially reproduced. In this claim's own draw all seven CIs agree and the four means are within tolerance, but the omission CI's lower bound is -0.000. Over 20 draws the omission CI includes zero, as the paper's does, in only 10% (20% with the nested standard errors), so under the majority rule (this attempt's convention, not the claims file's) six of seven CIs agree. The partial condition holds: shock - danger is below zero in every draw and safety has the largest mean. Over the whole 17.5 s safety still has the largest mean (0.247) and danger and shock stay below zero.

fig6g-k7-valence-then-ppe¶

k7 units show initial valence signaling (danger shock = uncertainty shock > omission > safety) giving way to positive prediction error (uncertainty shock > danger shock), and sustain inhibition to safety through the outcome period.

In [42]:
f6["k7"] = fig6_report("k7", "fig6g-k7-valence-then-ppe")
k7, window slice(130, 200, None), n = 64
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D  0.290  0.237  0.340        1           1    True           0.29       True
     US  0.423  0.344  0.499        1           1    True           0.42       True
     UO  0.079  0.029  0.131        1           1    True           0.08       True
      S -0.278 -0.330 -0.230       -1          -1    True          -0.28       True
   US-D  0.133  0.038  0.216        1           1    True            NaN        NaN
   UO-S  0.357  0.274  0.434        1           1    True            NaN        NaN
    D-S  0.569  0.484  0.653        1           1    True            NaN        NaN
  CIs agreeing: 7 of 7; means within tolerance: 4 of 4
  other window: first 2 s: means {'D': 0.704, 'US': 0.843, 'UO': 0.077, 'S': -0.289, 'US-D': 0.138, 'UO-S': 0.366, 'D-S': 0.994}; CIs agreeing 5 of 7
  other window: last 10 s: means {'D': 0.151, 'US': 0.31, 'UO': 0.052, 'S': -0.276, 'US-D': 0.159, 'UO-S': 0.328, 'D-S': 0.427}; CIs agreeing 6 of 7
  other window: 0-8 s: means {'D': 0.46, 'US': 0.558, 'UO': 0.115, 'S': -0.282, 'US-D': 0.098, 'UO-S': 0.397, 'D-S': 0.742}; CIs agreeing 6 of 7
  z-a: CIs agreeing 6 of 7, means within 1 of 4; means {'D': 0.459, 'US': 0.678, 'UO': 0.098, 'S': -0.532}
  z-b: CIs agreeing 7 of 7, means within 0 of 4; means {'D': 0.61, 'US': 0.896, 'UO': 0.188, 'S': -0.516}

Result: reproduced. All seven CIs agree and the four means equal Table S4's to two decimals (0.290, 0.423, 0.079, -0.278). Under z-a and z-b the CIs agree in 6 and 7 of 7, and all four means are larger in absolute value than Table S4's (printed above).

fig6h-k8-ppe-then-unsigned¶

k8 units show early positive prediction error (uncertainty shock > danger shock) giving way to an unsigned prediction error, with equal firing increases on uncertainty shock and omission trials exceeding those for danger and safety.

In [43]:
f6["k8"] = fig6_report("k8", "fig6h-k8-ppe-then-unsigned")
k8, window slice(130, 200, None), n = 67
measure   mean    low   high  CI sign  paper sign  agrees  Table S4 mean within tol
      D -0.107 -0.169 -0.051       -1          -1    True          -0.11       True
     US  0.326  0.257  0.392        1           1    True           0.32       True
     UO  0.178  0.144  0.216        1           1    True           0.18       True
      S -0.020 -0.062  0.021        0           0    True          -0.02       True
   US-D  0.432  0.336  0.530        1           1    True            NaN        NaN
   UO-S  0.198  0.136  0.265        1           1    True            NaN        NaN
    D-S -0.087 -0.155 -0.013       -1          -1    True            NaN        NaN
  CIs agreeing: 7 of 7; means within tolerance: 4 of 4
  other window: first 2 s: means {'D': 0.057, 'US': 0.494, 'UO': 0.121, 'S': -0.084, 'US-D': 0.437, 'UO-S': 0.204, 'D-S': 0.14}; CIs agreeing 4 of 7
  other window: last 10 s: means {'D': -0.135, 'US': 0.263, 'UO': 0.15, 'S': 0.004, 'US-D': 0.399, 'UO-S': 0.146, 'D-S': -0.14}; CIs agreeing 7 of 7
  other window: 0-8 s: means {'D': -0.071, 'US': 0.403, 'UO': 0.212, 'S': -0.046, 'US-D': 0.473, 'UO-S': 0.258, 'D-S': -0.025}; CIs agreeing 5 of 7
  z-a: CIs agreeing 7 of 7, means within 1 of 4; means {'D': -0.212, 'US': 0.563, 'UO': 0.309, 'S': -0.057}
  z-b: CIs agreeing 7 of 7, means within 1 of 4; means {'D': -0.133, 'US': 0.774, 'UO': 0.457, 'S': 0.044}

Result: reproduced. All seven CIs agree and the four means equal Table S4's to two decimals (-0.107, 0.326, 0.178, -0.020).

Summary¶

Claim Outcome
units-and-sessions reproduced
cue-responsive-units reproduced
behavior-discrimination reproduced
kmeans-elbow reproduced (resting on an assumption)
kmeans-clusters reproduced (resting on an assumption)
cluster-firing-characteristics reproduced (resting on an assumption)
k1-k3-low-baseline reproduced (resting on an assumption)
table1-cue-interaction reproduced (resting on an assumption)
fig3b-excitatory-clusters reproduced (resting on an assumption)
fig3d-inhibitory-clusters reproduced (resting on an assumption)
figs4-onset-and-ramp reproduced (resting on an assumption)
fig4abc-threat-bias partially reproduced (resting on an assumption)
fig4def-danger-uncertainty-correlation reproduced (resting on an assumption)
fig4ghi-danger-safety-correlation reproduced (resting on an assumption)
fig4-correlations-differ reproduced (resting on an assumption)
fig5a-tuning-peaks-exaggerated reproduced (resting on an assumption)
fig5a-tuning-peaks-inhibited reproduced (resting on an assumption)
fig5a-tuning-anova reproduced (resting on an assumption)
fig5e-peak-probability-over-fear-output reproduced (resting on an assumption)
fig5-regressor-cluster reproduced (resting on an assumption)
table-s3-cluster-regression partially reproduced (resting on an assumption)
fig5f-fear-output-vs-peak-probability reproduced (resting on an assumption)
table1-outcome-anova reproduced (resting on an assumption)
fig6a-k1-shock not reproduced (resting on an assumption)
fig6b-k2-anti-ppe partially reproduced (resting on an assumption)
fig6c-k3-continued-threat reproduced (resting on an assumption)
fig6de-k4-k5-persistent-threat partially reproduced (resting on an assumption)
fig6f-k6-ppe-then-valence partially reproduced (resting on an assumption)
fig6g-k7-valence-then-ppe reproduced (resting on an assumption)
fig6h-k8-ppe-then-unsigned reproduced (resting on an assumption)

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.

How the analysis differs from the paper's. The data set includes the paper's MATLAB code, and the analysis follows it wherever the claims file left a reading open: the trial-level z-scores the code computes (the Methods describe z-scoring trial-type means; the claims file's readings z-a and z-b of the Methods are shown as variants, under which the code's k-means run no longer gives the paper's clusters; every claim that uses normalized firing or the clusters is therefore marked as resting on the assumption that the code is what the paper did), the code's k-means matrix (outcome epochs from 13 s after cue onset) and its single k-means run, reproduced outside MATLAB so that the cluster sizes are the paper's (there is no label file to check membership), the cluster-specific tuning periods, and the sign inversion of k4, k6 and k8. Statistics are recomputed in Python: repeated-measures ANOVAs from sums of squares (type III for the within effect of the mixed designs, as SPSS), studentized bootstrap CIs with 1,000 resamples and standard errors s / sqrt(n), where MATLAB's bootci estimates them by a nested bootstrap; each CI is judged by the sign it gives in most of 20 draws (this attempt's convention; the claims file sets none), which changes fig6f-k6-ppe-then-valence from the single draw's 7 of 7 to 6 of 7. Meng's Z. The outcome windows of Figure 6 are those the claims file reads from the gray boxes; for k1, k3, k5 and k6 Table S4's values come from 0 to 4 s, not 0 to 8 s.

What was found about the data set. It holds every unit, session and rat the paper reports, and the authors' derived file (cube.mat) agrees exactly with the spike and event times of the unit files. Most counts, F values and correlations of the paper that depend only on the data and the code were recovered to the printed digits; some were not (Table 1 cue F for k4, 8.09 against 7.93; Table 1 outcome F for k1, k4 and k7; regressor x cluster F, 2.40 against 2.15; Table S3 for k3 and k5). Not stated in the data set's description: the recordings cover only 20 s before to about 33.5 s after each cue (recording paused between trials); the event channel names (only in code comments); the cluster labels (fixed only by the code's k-means run) and the electrode locations (a table in the code). The description calls wave a mean waveform per trial type (it is one per unit) and poke.base a 2-s baseline (it is 20 s). The paper's Figure 5E and Table S3 ANOVAs leave out two units that the paper does not name.