Reproducing Hazon et al. (2022) from CRCNS hc-30: position decoding¶

Paper. Hazon O, Minces VH, Tomàs DP, Ganguli S, Schnitzer MJ, Jercog PE (2022). Noise correlations in neural ensemble activity limit the accuracy of hippocampal spatial representations. Nature Communications 13, 4276. doi:10.1038/s41467-022-31254-y

Dataset. CRCNS hc-30, Jercog P and Schnitzer M (2022), "Functional calcium imaging recordings of hippocampal area CA1 from mice performing a linear track task", doi:10.6080/K0GH9G5X. One file, hc-30/live/event_traces.mat (142,350,100 bytes), streamed from the public S3 bucket crcnsarchive into memory.

Version. CRCNS data sets are not versioned, so the version is recorded as unversioned (docs/archives.md). The paper cites no version; the only one published is the one in the bucket (data descriptor version 0.6, July 8, 2022, the initial version), which matches the claims file's description (110 sessions with mouse name, session ID, sparse event array and position). The MD5 sum from the data set's checksums.md5, which the next cell checks against the streamed bytes, is fe0f5dd2fca6d64dbf0cd3f35e31e1f0 (event_traces.mat); the descriptor PDF is 320d157fbcc43be385485cc186842636.

Text the claims were written from. The version of record (PMC9314334) with its Methods and Supplementary Information; the paper's code, github.com/approbatory/ML-project at commit 2057af9facfd3035c573e1254bdc32ed4781ba60, was read for method details (claims/hazon-2022.yaml). Method details taken by this attempt cite the passage or code file in hc30.py.

Data. 110 sessions of 12 mice with an event-onset array (frames x neurons) and the position in camera pixels. There are no cell positions, no frame times and no trial table; trials, bins and the event trace are built here from the Methods and the code (hc30.py).

Claim Status
fig2d-rms-error-ensemble-vs-shuffled tested
fig2cd-shuffle-better-in-all-bins tested
fig2ef-imse-saturates-with-correlations tested
suppl7b-initial-slope-lower-with-correlations tested
saturation-ensemble-size tested
suppl11b-i0-vs-single-cell-snr tested
suppl11c-asymptotic-imse-vs-asymptotic-snr tested
suppl8-task-performance-and-accuracy tested
suppl6-twenty-bins-near-optimal tested
suppl9-fit-recovers-saturation tested (simulation, data elsewhere)

The other claims are in reproduce_hazon_2022.ipynb; reproduce_hazon_2022_fitcheck.ipynb repeats the IMSE fits with the paper's 80 subsets on steps of 10 for 16 sessions. The decoders are the heavy part: this notebook takes about 66 minutes on 4 CPUs (4 worker processes), with fewer repetitions than the paper's 80 (stated at each claim).

In [1]:
import os
for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ[_v] = "1"  # one thread per process; the decoders run in 4 processes
import multiprocessing as mp
import resource
import time

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

import hc30

T0 = time.time()
sessions, md5, load_s = hc30.load_sessions()
print(f"streamed and parsed event_traces.mat in {load_s:.0f} s; md5 {md5} "
      f"({'matches' if md5 == hc30.MD5 else 'DIFFERS FROM'} checksums.md5)")

# Settings of this notebook (the paper's values in brackets)
REPS_FULL = 10   # repetitions with all neurons [80]
REPS_SUB = 4     # neuron subsets per ensemble size [80]
SIZES = [1] + list(range(25, 500, 25))  # below the session's count, plus all neurons [1, 10, 20, ...]
BIN_COUNTS = [10, 15, 20, 25, 30, 40]  # Supplementary Figure 6 [not stated]
REPS_BINS = 2    # [80]
C_SVM = 1.0      # assumed; see hc30.OvOLinearSVM
streamed and parsed event_traces.mat in 5 s; md5 fe0f5dd2fca6d64dbf0cd3f35e31e1f0 (matches checksums.md5)

Data check¶

In [2]:
rows, TENS = [], []
for i, s in enumerate(sessions):
    T, d, tr = hc30.session_tensor(s)
    TENS.append((T, d))
    perf, n_slow, n_turn = hc30.performance(s["position"], tr)
    rows.append(dict(i=i, mouse=s["mouse"], session=s["session_id"], neurons=T.shape[0],
                     right=int((d == 1).sum()), left=int((d == -1).sum()), performance=perf,
                     slow_errors=n_slow, turn_errors=n_turn))
info = pd.DataFrame(rows)
info["min_trials"] = info[["right", "left"]].min(axis=1)
info["large"] = (info.neurons > 200) & (info.min_trials > 30)
LARGE = info.index[info.large].values
print(f"sessions {len(info)}, mice {info.mouse.nunique()}, neurons {info.neurons.sum()}, "
      f"large-data sessions {len(LARGE)} from {info.loc[LARGE, 'mouse'].nunique()} mice")
print("trials per direction used by the decoder (smaller of the two): median %d, range %d to %d"
      % (info.min_trials.median(), info.min_trials.min(), info.min_trials.max()))
info["clock_err_cm"] = [hc30.clock_check(s, 0) for s in sessions]
MISALIGNED = info.index[info.clock_err_cm > 12].values
print("sessions whose event trace does not track position at lag 0 (quick decoder error > 12 cm,"
      " first notebook):", info.loc[MISALIGNED, ["mouse", "session", "clock_err_cm"]].round(1)
      .values.tolist())
print("performance: median %.3f, range %.3f to %.3f; slow errors median %d, turn-around errors "
      "median %d" % (info.performance.median(), info.performance.min(), info.performance.max(),
                     info.slow_errors.median(), info.turn_errors.median()))
sessions 110, mice 12, neurons 27898, large-data sessions 73 from 10 mice
trials per direction used by the decoder (smaller of the two): median 92, range 31 to 187
sessions whose event trace does not track position at lag 0 (quick decoder error > 12 cm, first notebook): [['Mouse2012', '141832', 29.3], ['Mouse2026', '115639', 14.7], ['Mouse2011', '105556', 44.0], ['Mouse2011', '104511', 43.9], ['Mouse2011', '142436', 29.4], ['Mouse2021', '132808', 15.3]]
performance: median 0.830, range 0.404 to 0.989; slow errors median 24, turn-around errors median 12
In [3]:
# Cost estimate before the full run: one repetition on the first session of each mouse.
t = time.time()
probe = info.groupby("mouse").i.first().values
for i in probe:
    T, d = TENS[i]
    hc30.decode_full(T, d, seed=0, reps=1, C=C_SVM)
per_rep = (time.time() - t) / len(probe)
n_sizes = sum(sum(1 for s in SIZES if s < n) for n in info.neurons)
est = per_rep * (len(info) * REPS_FULL + 0.6 * n_sizes * REPS_SUB) / 4 / 60
print(f"{per_rep:.2f} s per repetition (both conditions, all neurons); {len(info) * REPS_FULL} "
      f"full-ensemble repetitions and {n_sizes * REPS_SUB} subset repetitions; a rough lower "
      f"bound of {est:.0f} min on 4 processes (the preparatory run took about three times this)")
0.95 s per repetition (both conditions, all neurons); 1100 full-ensemble repetitions and 4668 subset repetitions; a rough lower bound of 15 min on 4 processes (the preparatory run took about three times this)

Decoding runs¶

Every session: REPS_FULL repetitions with all neurons, and REPS_SUB subsets at each ensemble size below the session's neuron count. Each session has its own seed.

In [4]:
def job(i):
    T, d = TENS[i]
    full = hc30.decode_full(T, d, seed=20000 + i, reps=REPS_FULL, C=C_SVM)
    sizes = [s for s in SIZES if s < T.shape[0]]
    iu, is_ = hc30.decode_series(T, d, seed=30000 + i, sizes=sizes, reps=REPS_SUB, C=C_SVM)
    full["sizes"] = np.array(sizes + [T.shape[0]])
    full["imse_u"] = np.r_[iu, np.mean(1 / np.array(full["mse_u"]))]
    full["imse_s"] = np.r_[is_, np.mean(1 / np.array(full["mse_s"]))]
    return full

t = time.time()
with mp.get_context("fork").Pool(4) as pool:
    DEC = pool.map(job, range(len(TENS)), chunksize=1)
print(f"decoding: {(time.time() - t) / 60:.1f} min; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
decoding: 54.0 min; peak memory 1.9 GB

fig2d-rms-error-ensemble-vs-shuffled¶

The RMS decoding error with all neurons is 9.38 +/- 4.06 cm with noise correlations and 5.15 +/- 2.40 cm after trial shuffling (median +/- IQR over 110 sessions), so noise correlations impair position estimates.

In [5]:
info["rms_u"] = [np.mean(np.sqrt(r["mse_u"])) for r in DEC]
info["rms_s"] = [np.mean(np.sqrt(r["mse_s"])) for r in DEC]
for col, name in (("rms_u", "ensemble"), ("rms_s", "shuffled")):
    q1, q3 = np.percentile(info[col], [25, 75])
    print(f"{name}: median {info[col].median():.2f} cm, IQR {q3 - q1:.2f} cm "
          f"(quartiles {q1:.2f} to {q3:.2f}), range {info[col].min():.2f} to {info[col].max():.2f}")
print("ensemble error larger than shuffled in", int((info.rms_u > info.rms_s).sum()), "of",
      len(info), "sessions; Wilcoxon p = %.1e" % stats.wilcoxon(info.rms_u, info.rms_s).pvalue)
ok_clock = ~info.index.isin(MISALIGNED)
for col, name in (("rms_u", "ensemble"), ("rms_s", "shuffled")):
    q1, q3 = np.percentile(info.loc[ok_clock, col], [25, 75])
    print(f"variant without the {len(MISALIGNED)} misaligned sessions, {name}: median "
          f"{info.loc[ok_clock, col].median():.2f} cm, IQR {q3 - q1:.2f} cm")
print("spread over repetitions within a session (SD of RMS), median: ensemble %.2f, shuffled %.2f cm"
      % (np.median([np.std(np.sqrt(r["mse_u"])) for r in DEC]),
         np.median([np.std(np.sqrt(r["mse_s"])) for r in DEC])))
print(info.groupby("mouse")[["rms_u", "rms_s"]].median().round(2))
for col in ("rms_u", "rms_s"):
    k = info[col].idxmax()
    print(f"largest {col}: {info[col][k]:.2f} cm, session {k} {info.mouse[k]} {info.session[k]}"
          f"{' (misaligned)' if k in MISALIGNED else ''}")
ensemble: median 9.36 cm, IQR 3.92 cm (quartiles 7.76 to 11.67), range 4.05 to 51.88
shuffled: median 4.80 cm, IQR 1.73 cm (quartiles 4.19 to 5.92), range 2.78 to 51.69
ensemble error larger than shuffled in 109 of 110 sessions; Wilcoxon p = 9.0e-20
variant without the 6 misaligned sessions, ensemble: median 9.14 cm, IQR 3.33 cm
variant without the 6 misaligned sessions, shuffled: median 4.78 cm, IQR 1.64 cm
spread over repetitions within a session (SD of RMS), median: ensemble 0.48, shuffled 0.13 cm
           rms_u  rms_s
mouse                  
Mouse2010  12.08   6.94
Mouse2011  10.65   4.78
Mouse2012  10.53   5.81
Mouse2019   4.46   2.95
Mouse2021  14.07   5.62
Mouse2022   8.85   3.94
Mouse2023   8.25   4.91
Mouse2024   8.33   3.93
Mouse2025  11.47   6.46
Mouse2026  10.49   5.20
Mouse2028   7.73   4.34
Mouse2029   7.47   4.69
largest rms_u: 51.88 cm, session 83 Mouse2011 105556 (misaligned)
largest rms_s: 51.69 cm, session 84 Mouse2011 104511 (misaligned)

Variant: the decoder's regularisation. On the first session of each mouse, 2 repetitions with C = 0.1 and C = 10 against the main C = 1.

In [6]:
def c_variant(args):
    i, C = args
    T, d = TENS[i]
    r = hc30.decode_full(T, d, seed=40000 + i, reps=2, C=C)
    return i, C, np.mean(np.sqrt(r["mse_u"])), np.mean(np.sqrt(r["mse_s"]))

with mp.get_context("fork").Pool(4) as pool:
    CV = pool.map(c_variant, [(i, C) for i in probe for C in (0.1, 10.0)], chunksize=1)
cv = pd.DataFrame(CV, columns=["i", "C", "rms_u", "rms_s"])
cv = pd.concat([cv, pd.DataFrame({"i": probe, "C": 1.0, "rms_u": info.rms_u[probe].values,
                                  "rms_s": info.rms_s[probe].values})])
print(cv.groupby("C")[["rms_u", "rms_s"]].median().round(2))
      rms_u  rms_s
C                 
0.1    8.52   4.98
1.0    8.86   5.03
10.0   8.56   4.99

Result: reproduced, resting on the decoder's regularisation. The median RMS error with all neurons is 9.36 cm (IQR 3.92) with noise correlations and 4.80 cm (IQR 1.73) after shuffling, against 9.38 +/- 4.06 and 5.15 +/- 2.40 cm; both medians and the ensemble IQR are within tolerance, the shuffled IQR is not, and the ensemble error is larger in 109 of 110 sessions. Without the six sessions whose events do not track position the medians are 9.14 and 4.78 cm. With C = 0.1 or 10 in place of 1 the medians on 12 sessions change by less than 0.4 cm.

fig2cd-shuffle-better-in-all-bins¶

Decoding is less accurate with noise correlations than without in every spatial bin; misclassifications are typically one bin and reach up to three bins.

In [7]:
def per_bin_rms(conf):
    pos = np.arange(40) // 2
    err2 = (pos[:, None] - pos[None, :]) ** 2 * hc30.BIN_CM ** 2
    by_class = np.sqrt((conf * err2).sum(1) / conf.sum(1))
    by_pos = np.sqrt(np.array([(conf[2 * b:2 * b + 2] * err2[2 * b:2 * b + 2]).sum()
                               / conf[2 * b:2 * b + 2].sum() for b in range(20)]))
    return by_pos, by_class

Bu, Bs, Cu, Cs, accu, accs = [], [], [], [], [], []
for r in DEC:
    a, b = per_bin_rms(r["conf_u"])
    c, e = per_bin_rms(r["conf_s"])
    Bu.append(a); Cu.append(b); Bs.append(c); Cs.append(e)
    accu.append(np.diag(r["conf_u"]) / r["conf_u"].sum(1))
    accs.append(np.diag(r["conf_s"]) / r["conf_s"].sum(1))
Bu, Bs, Cu, Cs = map(np.array, (Bu, Bs, Cu, Cs))
accu, accs = np.array(accu), np.array(accs)
print("(a) 20 positions: session-mean RMS larger for the ensemble in",
      int((Bu.mean(0) > Bs.mean(0)).sum()), "of 20 bins")
print("    ensemble", np.round(Bu.mean(0), 1))
print("    shuffled", np.round(Bs.mean(0), 1))
print("(b) 40 classes: larger for the ensemble in", int((Cu.mean(0) > Cs.mean(0)).sum()), "of 40")
print("correct-class fraction, session average: higher for shuffled in",
      int((accs.mean(0) > accu.mean(0)).sum()), "of 40 classes")
ex = info.index[(info.mouse == "Mouse2022")].values
print("sessions of animal 2022:", list(ex))
for i in ex:
    print(f"  session {i} ({info.session[i]}): correct fraction higher for shuffled in "
          f"{int((accs[i] > accu[i]).sum())} of 40 classes; ties {int((accs[i] == accu[i]).sum())}")
# size of errors
for tag in ("u", "s"):
    conf = sum(r[f"conf_{tag}"] for r in DEC)
    pos = np.arange(40) // 2
    dist = np.abs(pos[:, None] - pos[None, :])
    mis = conf * (dist > 0)
    hist = np.bincount(dist.ravel(), weights=mis.ravel(), minlength=20)
    frac = hist / hist.sum()
    cum = np.cumsum(frac[1:] * 1.0)
    med = int(np.searchsorted(cum, 0.5) + 1)
    largest = int(np.max(np.where(frac >= 0.01)[0]))
    print(f"{'ensemble' if tag == 'u' else 'shuffled'}: misclassified samples {int(hist.sum())}; "
          f"median error {med} bin(s); largest error with >= 1% of them {largest} bins; "
          f"fractions at 1..4 bins {np.round(frac[1:5], 3)}")
fig, ax = plt.subplots(figsize=(5, 3))
x = np.arange(20) + 1
for B, lab in ((Bu, "ensemble"), (Bs, "shuffled")):
    m = B.mean(0)
    ci = 1.96 * B.std(0, ddof=1) / np.sqrt(len(B))
    ax.plot(x, m, label=lab)
    ax.fill_between(x, m - ci, m + ci, alpha=0.3)
ax.set_xlabel("spatial bin"); ax.set_ylabel("RMS error (cm)"); ax.legend()
plt.show()
print("plotted range %.1f to %.1f cm" % (min(Bu.mean(0).min(), Bs.mean(0).min()),
                                       max(Bu.mean(0).max(), Bs.mean(0).max())))
(a) 20 positions: session-mean RMS larger for the ensemble in 20 of 20 bins
    ensemble [12.6  9.2  9.8 10.5 10.8 11.1 11.1 11.  11.1 11.3 11.3 11.2 11.3 11.5
 11.4 11.3 11.1 11.   9.9 12.3]
    shuffled [3.4 3.6 4.7 5.5 6.  6.4 6.7 6.9 7.1 7.2 7.2 7.2 7.1 7.  6.9 6.6 6.  5.3
 4.2 3.6]
(b) 40 classes: larger for the ensemble in 40 of 40
correct-class fraction, session average: higher for shuffled in 40 of 40 classes
sessions of animal 2022: [np.int64(64), np.int64(65), np.int64(66), np.int64(67), np.int64(68), np.int64(69)]
  session 64 (083627): correct fraction higher for shuffled in 39 of 40 classes; ties 0
  session 65 (111200): correct fraction higher for shuffled in 40 of 40 classes; ties 0
  session 66 (140317): correct fraction higher for shuffled in 40 of 40 classes; ties 0
  session 67 (100439): correct fraction higher for shuffled in 40 of 40 classes; ties 0
  session 68 (093722): correct fraction higher for shuffled in 40 of 40 classes; ties 0
  session 69 (082741): correct fraction higher for shuffled in 40 of 40 classes; ties 0
ensemble: misclassified samples 2064265; median error 1 bin(s); largest error with >= 1% of them 5 bins; fractions at 1..4 bins [0.706 0.167 0.048 0.019]
shuffled: misclassified samples 1730916; median error 1 bin(s); largest error with >= 1% of them 3 bins; fractions at 1..4 bins [0.814 0.136 0.024 0.007]
No description has been provided for this image
plotted range 3.4 to 12.6 cm

Result: reproduced. The session-mean RMS error is larger for the ensemble than for the shuffled data in 20 of 20 positions and 40 of 40 classes, and the correct-class fraction averaged over sessions is higher for the shuffled data in 40 of 40 classes (39 to 40 of 40 in each session of animal 2022). Misclassifications are most often one bin (median 1 bin, 70.6% of errors); errors of up to 5 bins each hold at least 1% of the misclassified samples with correlations, and up to 3 bins without.

fig2ef-imse-saturates-with-correlations¶

With noise correlations the decoding accuracy (IMSE) approaches a bound as ensembles grow, while without them it keeps increasing; the asymptotic IMSE (I0 N) and the saturation size N are larger for the shuffled data.

In [8]:
fits = []
for i, r in enumerate(DEC):
    I0, N, I0c, Nc = hc30.fit_imse(r["sizes"], r["imse_u"])
    I0s, Ns, I0sc, Nsc = hc30.fit_imse(r["sizes"], r["imse_s"])
    fits.append(dict(I0=I0, N=N, I0N=I0 * N, I0_ci=I0c, N_ci=Nc, I0s=I0s, Ns=Ns, I0Ns=I0s * Ns,
                     I0s_ci=I0sc, Ns_ci=Nsc))
F = pd.DataFrame(fits)
info = pd.concat([info, F], axis=1)
print("fits failed: unshuffled", int(F.N.isna().sum()), "shuffled", int(F.Ns.isna().sum()))
print("negative or absurd fits (N < 0 or N > 1e6): unshuffled", int(((F.N < 0) | (F.N > 1e6)).sum()),
      "shuffled", int(((F.Ns < 0) | (F.Ns > 1e6)).sum()))
print(F[["I0", "N", "I0N", "I0s", "Ns", "I0Ns"]].describe().round(5).T)

def two_tests(df, label):
    a = stats.wilcoxon(df.I0N, df.I0Ns)
    b = stats.wilcoxon(df.N, df.Ns)
    print(f"{label}: I0 N shuffled higher in {int((df.I0Ns > df.I0N).sum())} of {len(df)}, "
          f"p = {a.pvalue:.2e}; N shuffled higher in {int((df.Ns > df.N).sum())} of {len(df)}, "
          f"p = {b.pvalue:.2e}")

ok = F.notna().all(axis=1)
two_tests(info[ok], "110 sessions")
pm = info[ok].groupby("mouse")[["I0N", "I0Ns", "N", "Ns"]].mean()
two_tests(pm, "12 per-animal means")
print("animals with higher mean I0 N for shuffled:", int((pm.I0Ns > pm.I0N).sum()), "of", len(pm))
print(pm.round(4))
# saturation: does unshuffled IMSE at the largest size fall short of the fitted asymptote?
frac_u = [r["imse_u"][-1] / (f["I0N"]) for r, f in zip(DEC, fits)]
frac_s = [r["imse_s"][-1] / (f["I0Ns"]) for r, f in zip(DEC, fits)]
print(f"IMSE at all neurons as a fraction of the fitted asymptote: median unshuffled "
      f"{np.nanmedian(frac_u):.2f}, shuffled {np.nanmedian(frac_s):.2f}")
def fit_r2(sizes, y, I0, N):
    f = I0 * sizes / (1 + sizes / N)
    return 1 - np.sum((y - f) ** 2) / np.sum((y - y.mean()) ** 2)

info["r2_u"] = [fit_r2(r["sizes"], r["imse_u"], f["I0"], f["N"]) for r, f in zip(DEC, fits)]
info["r2_s"] = [fit_r2(r["sizes"], r["imse_s"], f["I0s"], f["Ns"]) for r, f in zip(DEC, fits)]
print("R^2 of the fitted curve to the IMSE points: unshuffled median %.3f (min %.3f), shuffled "
      "median %.3f (min %.3f)" % (info.r2_u.median(), info.r2_u.min(), info.r2_s.median(), info.r2_s.min()))
degen = info.index[(F.N < 0) | (F.N > 1e6) | info.index.isin(MISALIGNED)]
print("degenerate unshuffled fits and misaligned sessions, IMSE points (x 1000) against the "
      "fitted curve:")
for i in degen:
    r, f = DEC[i], fits[i]
    print(f"  session {i} {info.mouse[i]} {info.session[i]}: I0 = {f['I0']:.4g}, N = {f['N']:.4g}, "
          f"R^2 = {info.r2_u[i]:.3f}{' (misaligned)' if i in MISALIGNED else ''}")
    print("    n    ", " ".join(f"{v:6d}" for v in r["sizes"]))
    print("    IMSE ", " ".join(f"{1000 * v:6.2f}" for v in r["imse_u"]))
    print("    fit  ", " ".join(f"{1000 * f['I0'] * v / (1 + v / f['N']):6.2f}" for v in r["sizes"]))
fig, ax = plt.subplots(figsize=(5, 3))
k = int(info.neurons.idxmax())
ax.plot(DEC[k]["sizes"], DEC[k]["imse_u"], "o-", label="ensemble")
ax.plot(DEC[k]["sizes"], DEC[k]["imse_s"], "o-", label="shuffled")
ax.set_xlabel("neurons"); ax.set_ylabel("IMSE (1/cm^2)"); ax.legend(); ax.set_title(f"session {k}")
plt.show()
print("plotted IMSE range %.4f to %.4f" % (min(DEC[k]["imse_u"].min(), DEC[k]["imse_s"].min()),
                                          max(DEC[k]["imse_u"].max(), DEC[k]["imse_s"].max())))
fits failed: unshuffled 0 shuffled 0
negative or absurd fits (N < 0 or N > 1e6): unshuffled 7 shuffled 78
      count          mean           std        min         25%           50%  \
I0    110.0  2.366700e+00  2.482063e+01   -0.00004     0.00007  1.000000e-04   
N     110.0  7.288763e+08  4.358813e+09   -8.95071   176.16180  2.593199e+02   
I0N   110.0  6.159450e+04  3.547809e+05    0.00033     0.01567  2.572000e-02   
I0s   110.0  3.633490e+00  3.810635e+01   -0.00004     0.00013  1.900000e-04   
Ns    110.0  1.048436e+10  1.247516e+10 -940.14641  1733.88585  5.804274e+09   
I0Ns  110.0  1.616333e+06  2.068786e+06   -0.23136     0.53176  8.503641e+05   

               75%           max  
I0    1.400000e-04  2.603211e+02  
N     3.872169e+02  3.641488e+10  
I0N   4.559000e-02  2.779397e+06  
I0s   2.300000e-04  3.996630e+02  
Ns    1.807468e+10  5.757651e+10  
I0Ns  2.618906e+06  1.008943e+07  
110 sessions: I0 N shuffled higher in 97 of 110, p = 3.65e-17; N shuffled higher in 94 of 110, p = 5.36e-15
12 per-animal means: I0 N shuffled higher in 12 of 12, p = 4.88e-04; N shuffled higher in 11 of 12, p = 1.46e-03
animals with higher mean I0 N for shuffled: 12 of 12
                   I0N          I0Ns             N            Ns
mouse                                                           
Mouse2010  511458.8581  2.225585e+06  6.660226e+09  1.803643e+10
Mouse2011       0.0237  2.610989e+06  3.701130e+02  1.718073e+10
Mouse2012       0.0202  1.525975e+06  2.103004e+02  9.305803e+09
Mouse2019       0.0934  7.523000e-01  2.931638e+02  1.805352e+03
Mouse2021       0.0165  9.790788e+05  2.194027e+02  1.803937e+10
Mouse2022       0.0289  1.075137e+06  2.439011e+02  5.742322e+09
Mouse2023       0.0464  2.908100e+06  4.323742e+02  1.459506e+10
Mouse2024       0.0321  3.750559e+05  2.944998e+02  2.769378e+09
Mouse2025       0.0160  1.346871e+06  2.217188e+02  1.198402e+10
Mouse2026  213799.7739  3.128013e+06  2.801145e+09  2.045053e+10
Mouse2028    4400.2284  1.787486e+06  6.716478e+07  8.464438e+09
Mouse2029  471039.2294  6.925133e+05  4.028279e+09  2.070514e+09
IMSE at all neurons as a fraction of the fitted asymptote: median unshuffled 0.49, shuffled 0.00
R^2 of the fitted curve to the IMSE points: unshuffled median 0.986 (min -27.473), shuffled median 0.987 (min -125.441)
degenerate unshuffled fits and misaligned sessions, IMSE points (x 1000) against the fitted curve:
  session 19 Mouse2028 192709: I0 = 6.551e-05, N = 1.007e+09, R^2 = 0.988
    n          1     25     50     75    100    125    150    175    200    225    238
    IMSE    0.34   1.52   2.81   4.65   5.74   8.45  11.15  11.12  13.46  14.06  15.76
    fit     0.07   1.64   3.28   4.91   6.55   8.19   9.83  11.46  13.10  14.74  15.59
  session 34 Mouse2010 000156: I0 = 4.054e-05, N = 1.649e+09, R^2 = 0.987
    n          1     25     50     75    100    125    150    175    182
    IMSE    0.41   1.17   2.18   2.75   3.86   4.81   6.38   7.47   7.11
    fit     0.04   1.01   2.03   3.04   4.05   5.07   6.08   7.09   7.38
  session 37 Mouse2010 121404: I0 = 7.919e-05, N = 2.499e+10, R^2 = 0.994
    n          1     25     50     75    100    125    150    151
    IMSE    0.36   1.81   3.68   5.54   7.58  10.47  12.10  11.81
    fit     0.08   1.98   3.96   5.94   7.92   9.90  11.88  11.96
  session 51 Mouse2012 141832: I0 = 0.0005954, N = 0.846, R^2 = 0.954 (misaligned)
    n          1     25     50     75    100    125    150    175    200    216
    IMSE    0.28   0.47   0.47   0.49   0.51   0.50   0.50   0.51   0.53   0.52
    fit     0.27   0.49   0.50   0.50   0.50   0.50   0.50   0.50   0.50   0.50
  session 73 Mouse2026 115639: I0 = 0.0005223, N = 2.605, R^2 = 0.882 (misaligned)
    n          1     25     50     75    100    125    150    175    200    225    237
    IMSE    0.46   1.13   1.13   1.23   1.22   1.40   1.35   1.40   1.42   1.44   1.46
    fit     0.38   1.23   1.29   1.31   1.33   1.33   1.34   1.34   1.34   1.34   1.35
  session 77 Mouse2026 095846: I0 = 7.633e-05, N = 3.641e+10, R^2 = 0.968
    n          1     25     50     75    100    125    150    175    200    225    250    272
    IMSE    0.38   1.70   2.79   4.22   6.08   7.32  11.22  11.96  16.06  19.51  19.05  21.51
    fit     0.08   1.91   3.82   5.72   7.63   9.54  11.45  13.36  15.27  17.17  19.08  20.76
  session 83 Mouse2011 105556: I0 = 260.3, N = 1.538e-06, R^2 = -0.000 (misaligned)
    n          1     25     50     75    100    125    150    175    200    225    230
    IMSE    0.61   0.39   0.39   0.39   0.38   0.37   0.39   0.37   0.37   0.37   0.37
    fit     0.40   0.40   0.40   0.40   0.40   0.40   0.40   0.40   0.40   0.40   0.40
  session 84 Mouse2011 104511: I0 = -3.662e-05, N = -8.951, R^2 = -27.473 (misaligned)
    n          1     25     50     75    100    125    150    175    200    204
    IMSE    0.49   0.41   0.39   0.38   0.39   0.39   0.39   0.38   0.37   0.39
    fit    -0.04   0.51   0.40   0.37   0.36   0.35   0.35   0.35   0.34   0.34
  session 92 Mouse2011 142436: I0 = 0.002343, N = 0.2172, R^2 = 0.709 (misaligned)
    n          1     25     50     75    100    125    150    175    200    225    250    275    300    325    350    375    400    425    436
    IMSE    0.42   0.52   0.51   0.52   0.52   0.51   0.49   0.52   0.49   0.50   0.55   0.50   0.50   0.49   0.51   0.51   0.50   0.50   0.50
    fit     0.42   0.50   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51   0.51
  session 97 Mouse2021 132808: I0 = 3.011e-05, N = 53.18, R^2 = 0.849 (misaligned)
    n          1     25     50     75    100    125    150    175    200    225    250    275    300    325    350    375    400    425    430
    IMSE    0.44   0.64   0.84   0.95   0.97   1.06   1.07   1.16   1.20   1.25   1.31   1.35   1.38   1.35   1.43   1.46   1.45   1.51   1.46
    fit     0.03   0.51   0.78   0.94   1.05   1.12   1.18   1.23   1.26   1.29   1.32   1.34   1.36   1.38   1.39   1.40   1.41   1.42   1.42
  session 106 Mouse2029 094956: I0 = 0.0001201, N = 1.281e+10, R^2 = 0.988
    n          1     25     50     75    100    125    150    171
    IMSE    0.39   2.26   4.91   8.20  13.47  14.70  18.18  20.55
    fit     0.12   3.00   6.01   9.01  12.01  15.01  18.02  20.54
  session 109 Mouse2029 152034: I0 = 0.0001046, N = 3.303e+09, R^2 = 0.986
    n          1     25     50     75    100    125    150    174
    IMSE    0.42   2.28   4.65   8.06   9.71  13.53  17.07  17.22
    fit     0.10   2.61   5.23   7.84  10.46  13.07  15.69  18.20
/home/runner/work/encore/encore/entries/hazon-2022/hc30.py:297: OptimizeWarning: Covariance of the parameters could not be estimated
  p, cov = curve_fit(f, np.asarray(n, float), np.asarray(imse, float), p0=[1.0, 100.0],
No description has been provided for this image
plotted IMSE range 0.0004 to 0.1028

Result: reproduced. Over 110 sessions the fitted asymptotic IMSE (I0 N) is higher for the shuffled data in 97 sessions (Wilcoxon p = 3.6e-17) and N in 94 (p = 5.4e-15); over the 12 per- animal means p = 4.9e-04 and 1.5e-03, and the mean I0 N is higher for the shuffled data in 12 of 12 animals. At all neurons the unshuffled IMSE reaches a median 0.49 of its fitted asymptote, the shuffled IMSE a negligible fraction: the shuffled curves are close to straight lines, and 78 of their fits give N above 1e6, while 7 unshuffled fits are degenerate too. The fitted curves follow the points closely in most sessions (median R squared 0.986 unshuffled, 0.987 shuffled). Of the 7 degenerate unshuffled fits, 6 are near-linear curves (N above 1e9, R squared 0.968 to 0.994) and one is a session whose events do not track position (session 84, a flat IMSE). The cell also prints the other misaligned sessions: 51, 83 and 92 have flat IMSE curves like 84, and 73 and 97 rise slowly to 1.46 (x 1e-3 per cm^2) with all neurons, with fitted N of 2.6 and 53.

suppl7b-initial-slope-lower-with-correlations¶

The initial slope I0 of the IMSE curve differs significantly between unshuffled and shuffled data across all sessions, which the paper attributes to an artifactual sublinear growth of accuracy at small ensemble sizes.

In [9]:
w = stats.wilcoxon(info.I0[ok], info.I0s[ok])
print(f"I0 median unshuffled {info.I0[ok].median():.5f}, shuffled {info.I0s[ok].median():.5f}; "
      f"shuffled higher in {int((info.I0s[ok] > info.I0[ok]).sum())} of {int(ok.sum())}; "
      f"Wilcoxon p = {w.pvalue:.2e}")
I0 median unshuffled 0.00010, shuffled 0.00019; shuffled higher in 102 of 110; Wilcoxon p = 9.76e-16

Result: reproduced. I0 differs between unshuffled and shuffled data (Wilcoxon p = 9.8e-16 over 110 sessions); it is lower with correlations (median 0.00010 against 0.00019, shuffled higher in 102 sessions).

saturation-ensemble-size¶

Spatial accuracy approaches saturation (fitted slope 5% of I0) at 346 to 1402 neurons across animals, and reaches 95% of the asymptotic IMSE at 1894 to 7671 neurons.

In [10]:
def gmean(x):
    x = np.asarray(x, float)
    x = x[np.isfinite(x) & (x > 0)]
    return np.exp(np.log(x).mean())

for name, sel in (("(a) 73 large-data sessions", info.large & ok), ("(b) 110 working sessions", ok)):
    g = info[sel].groupby("mouse").N.apply(gmean)
    lo, hi = g.min(), g.max()
    print(f"{name}: {len(g)} mice; geometric-mean N {lo:.0f} to {hi:.0f}; 5% slope at "
          f"{lo * (np.sqrt(20) - 1):.0f} to {hi * (np.sqrt(20) - 1):.0f} neurons; 95% of asymptote "
          f"at {19 * lo:.0f} to {19 * hi:.0f}")
    print("   per mouse N:", g.round(0).to_dict())
print("sessions with N <= 0 left out of the geometric means:", int((info.N[ok] <= 0).sum()))
good_fit = ok & (info.N > 0) & (info.N < 1e6) & ~info.index.isin(MISALIGNED)
g = info[good_fit & info.large].groupby("mouse").N.apply(gmean)
print(f"variant, large-data sessions without the misaligned sessions and without fits with N "
      f"outside 0 to 1e6 ({int((good_fit & info.large).sum())} sessions): geometric-mean N "
      f"{g.min():.0f} to {g.max():.0f}; 5% slope at {g.min() * (np.sqrt(20) - 1):.0f} to "
      f"{g.max() * (np.sqrt(20) - 1):.0f}; 19 N {19 * g.min():.0f} to {19 * g.max():.0f}")
print("   per mouse N:", g.round(0).to_dict())
nodeg = ok & (info.N > 0) & (info.N < 1e6)
g2 = info[nodeg & info.large].groupby("mouse").N.apply(gmean)
print(f"reading (a) without only the fits with N outside 0 to 1e6 (misaligned sessions kept, "
      f"{int((nodeg & info.large).sum())} sessions): geometric-mean N {g2.min():.0f} to {g2.max():.0f}; "
      f"5% slope at {g2.min() * (np.sqrt(20) - 1):.0f} to {g2.max() * (np.sqrt(20) - 1):.0f}")
print("   per mouse N:", g2.round(0).to_dict())
(a) 73 large-data sessions: 10 mice; geometric-mean N 30 to 886; 5% slope at 105 to 3076 neurons; 95% of asymptote at 575 to 16830
   per mouse N: {'Mouse2011': 30.0, 'Mouse2012': 63.0, 'Mouse2019': 272.0, 'Mouse2021': 176.0, 'Mouse2022': 207.0, 'Mouse2023': 716.0, 'Mouse2024': 224.0, 'Mouse2025': 345.0, 'Mouse2026': 859.0, 'Mouse2028': 886.0}
(b) 110 working sessions: 12 mice; geometric-mean N 30 to 1416527; 5% slope at 105 to 4918374 neurons; 95% of asymptote at 575 to 26914009
   per mouse N: {'Mouse2010': 1416527.0, 'Mouse2011': 30.0, 'Mouse2012': 137.0, 'Mouse2019': 272.0, 'Mouse2021': 176.0, 'Mouse2022': 216.0, 'Mouse2023': 408.0, 'Mouse2024': 224.0, 'Mouse2025': 208.0, 'Mouse2026': 645.0, 'Mouse2028': 886.0, 'Mouse2029': 1168532.0}
sessions with N <= 0 left out of the geometric means: 1
variant, large-data sessions without the misaligned sessions and without fits with N outside 0 to 1e6 (65 sessions): geometric-mean N 207 to 716; 5% slope at 717 to 2487; 19 N 3925 to 13610
   per mouse N: {'Mouse2011': 458.0, 'Mouse2012': 268.0, 'Mouse2019': 272.0, 'Mouse2021': 263.0, 'Mouse2022': 207.0, 'Mouse2023': 716.0, 'Mouse2024': 224.0, 'Mouse2025': 345.0, 'Mouse2026': 232.0, 'Mouse2028': 327.0}
reading (a) without only the fits with N outside 0 to 1e6 (misaligned sessions kept, 70 sessions): geometric-mean N 30 to 716; 5% slope at 105 to 2487
   per mouse N: {'Mouse2011': 30.0, 'Mouse2012': 63.0, 'Mouse2019': 272.0, 'Mouse2021': 176.0, 'Mouse2022': 207.0, 'Mouse2023': 716.0, 'Mouse2024': 224.0, 'Mouse2025': 345.0, 'Mouse2026': 148.0, 'Mouse2028': 327.0}

Result: not reproduced. Under reading (a), 73 large-data sessions, the geometric mean of N per animal spans 30 to 886, so the 5% slope is reached at 105 to 3,076 neurons and 95% of the asymptote at 575 to 16,830, against 346 to 1,402 and 1,894 to 7,671; both bounds are outside tolerance. The lowest animal (2011, N = 30) includes the sessions whose events do not track position, and the highest (2028, N = 886) includes the near-linear fit of session 19 (N = 1.0e9); the cell also prints reading (a) without the fits with N outside 0 to 1e6. Reading (b), 110 sessions, gives a far wider range, from degenerate fits in animals 2010 and 2029. Without the misaligned sessions and the degenerate fits (65 sessions) the 5% slope is reached at 717 to 2,487 neurons, set by Mouse2022 and Mouse2023, still outside tolerance. The fit-check notebook repeats the fits with more subsets: without misaligned sessions the per-animal N of Mouse2011 and Mouse2012 changes from 458 to 490 and from 268 to 231 with 80 subsets, and Mouse2023's one session from 716 to 474 with 40 subsets (a 5% slope at 1,646 neurons, still above tolerance). Mouse2022 was not repeated. On 9 sessions there, the paper's loss-weighted decoding gives a median 0.71 of this decoder's N. For the animals checked the reduced repetitions do not explain the failure, but whether the paper's decoder gives the paper's range was not tested.

Asymptotic SNR of the large-data sessions (as in the first notebook)¶

The same function, seeds and settings as the first notebook (20 subsets per size), so the values are the same.

In [11]:
def _sn(i):
    T, d = TENS[i]
    sizes, P, M = hc30.signal_noise_series(T, d, seed=1000 + i, n_subsets=20)
    sig, _ = hc30.slope_with_se(sizes, M[0])
    noi, _ = hc30.slope_with_se(sizes, M[1])
    return sig / noi

t = time.time()
with mp.get_context("fork").Pool(4) as pool:
    asnr = pool.map(_sn, list(LARGE), chunksize=1)
info.loc[LARGE, "asnr"] = asnr
print(f"asymptotic SNR of {len(LARGE)} sessions in {time.time() - t:.0f} s; median {np.median(asnr):.3f}")
asymptotic SNR of 73 sessions in 261 s; median 2.156

suppl11b-i0-vs-single-cell-snr¶

Across mice, the initial slope I0 of the IMSE curve correlates with the average single-cell SNR (r squared 0.73, p < 0.01).

In [12]:
scs = np.array([hc30.single_cell_snr(*TENS[i]) for i in LARGE])
L = info.loc[LARGE].copy()
L["scs_main"], L["scs_mean"], L["scs_median"] = scs[:, 0], scs[:, 1], scs[:, 2]
ag = L.groupby("mouse").mean(numeric_only=True)
for col in ("scs_main", "scs_mean", "scs_median"):
    r, p = stats.pearsonr(ag[col], ag.I0)
    print(f"{col}: across {len(ag)} mice r = {r:.3f}, r^2 = {r * r:.3f}, p = {p:.4f}")
print(ag[["I0", "scs_main", "scs_mean"]].round(5))
Lg = L[good_fit[LARGE].values]
agg_ = Lg.groupby("mouse").mean(numeric_only=True)
r, p = stats.pearsonr(agg_.scs_main, agg_.I0)
print(f"variant without misaligned sessions and fits with N outside 0 to 1e6 ({len(Lg)} sessions):"
      f" r = {r:.3f}, r^2 = {r * r:.3f}, p = {p:.4f}")
/home/runner/work/encore/encore/entries/hazon-2022/hc30.py:638: RuntimeWarning: Mean of empty slice
  np.nanmean(np.nanmean(np.where(np.isfinite(ratio), ratio, np.nan), axis=1)),
/home/runner/work/encore/encore/entries/hazon-2022/hc30.py:639: RuntimeWarning: All-NaN slice encountered
  np.nanmean(np.nanmedian(np.where(np.isfinite(ratio), ratio, np.nan), axis=1)))
scs_main: across 10 mice r = -0.071, r^2 = 0.005, p = 0.8444
scs_mean: across 10 mice r = -0.114, r^2 = 0.013, p = 0.7542
scs_median: across 10 mice r = -0.016, r^2 = 0.000, p = 0.9650
                 I0  scs_main  scs_mean
mouse                                  
Mouse2011  23.66581   0.01240   0.04897
Mouse2012   0.00021   0.01208   0.04363
Mouse2019   0.00031   0.02442   0.08778
Mouse2021   0.00006   0.00659   0.03149
Mouse2022   0.00012   0.01158   0.05244
Mouse2023   0.00008   0.01664   0.05664
Mouse2024   0.00011   0.01319   0.05925
Mouse2025   0.00005   0.01352   0.05620
Mouse2026   0.00012   0.00997   0.04514
Mouse2028   0.00013   0.01307   0.05522
variant without misaligned sessions and fits with N outside 0 to 1e6 (65 sessions): r = 0.750, r^2 = 0.562, p = 0.0125

Result: partially reproduced, resting on leaving out failed fits. On all 73 sessions I0 does not correlate with the single-cell SNR across the 10 mice under any reading (r = -0.071, -0.114 and -0.016), because the per-mouse mean I0 of animal 2011 is 23.7 while the other animals are between 0.00005 and 0.00031. That mean comes from sessions whose events do not track position: their IMSE is flat and the fit has no meaning (in the fit-check notebook sessions 83 and 84 give I0 = 241 and 231 with 80 subsets; with 4, 260 and a negative N). Leaving out the misaligned sessions and the fits with N outside 0 to 1e6 (65 sessions) gives r = 0.750, r squared 0.562, p = 0.0125: positive and below 0.05, but not below 0.01, and r squared is outside 0.73 +/- 0.073.

suppl11c-asymptotic-imse-vs-asymptotic-snr¶

Across mice, the fitted asymptotic IMSE (I0 N) correlates with the asymptotic SNR (r squared 0.88).

In [13]:
Lok = L[np.isfinite(L.I0N)]
ag = Lok.groupby("mouse")[["I0N", "asnr"]].mean()
r, p = stats.pearsonr(ag.I0N, ag.asnr)
print(f"linear: across {len(ag)} mice r = {r:.3f}, r^2 = {r * r:.3f}, p = {p:.2e}")
agl = Lok.assign(lI=np.log10(Lok.I0N.where(Lok.I0N > 0)), la=np.log10(Lok.asnr)).groupby("mouse")[["lI", "la"]].mean()
r, p = stats.pearsonr(agl.lI, agl.la)
print(f"log10:  across {len(agl)} mice r = {r:.3f}, r^2 = {r * r:.3f}, p = {p:.2e}")
r, p = stats.pearsonr(Lok.I0N, Lok.asnr)
print(f"across {len(Lok)} sessions, linear r = {r:.3f}, p = {p:.2e}")
Lg = L[good_fit[LARGE].values]
agg_ = Lg.groupby("mouse")[["I0N", "asnr"]].mean()
r, p = stats.pearsonr(agg_.I0N, agg_.asnr)
print(f"variant, linear, without misaligned sessions and fits with N outside 0 to 1e6 "
      f"({len(Lg)} sessions): r = {r:.3f}, r^2 = {r * r:.3f}, p = {p:.2e}")
linear: across 10 mice r = 0.039, r^2 = 0.001, p = 9.16e-01
log10:  across 10 mice r = 0.894, r^2 = 0.800, p = 4.80e-04
across 73 sessions, linear r = 0.018, p = 8.78e-01
variant, linear, without misaligned sessions and fits with N outside 0 to 1e6 (65 sessions): r = 0.919, r^2 = 0.845, p = 1.69e-04

Result: reproduced, on the log scale. On the log scale the per-mouse I0 N and asymptotic SNR give r = 0.894, r squared 0.800 and p = 4.8e-04, within tolerance of 0.88 and below 0.001. On the linear scale r = 0.039, because a few degenerate fits with very large I0 N dominate the per- mouse means.

suppl8-task-performance-and-accuracy¶

Task performance correlates with the number of trials (r 0.85) and with asymptotic decoding accuracy (r 0.52); the number of trials correlates weakly with accuracy (r 0.34), and a path analysis shows performance predicts accuracy while trial number does not.

In [14]:
import statsmodels.api as sm

L["n_trials"] = L.right + L.left
Lp = L[np.isfinite(L.I0N) & (L.I0N > 0)].copy()
Lp["log_I0N"] = np.log10(Lp.I0N)
print(f"{len(Lp)} sessions (of {len(L)}) with a positive I0 N")
r, p = stats.pearsonr(Lp.performance, Lp.n_trials)
print(f"performance vs trials: r = {r:.3f}, p = {p:.1e}")
for acc in ("log_I0N", "I0N"):
    r1, p1 = stats.pearsonr(Lp[acc], Lp.n_trials)
    r2, p2 = stats.pearsonr(Lp[acc], Lp.performance)
    print(f"{acc}: vs trials r = {r1:.3f} (p {p1:.1e}); vs performance r = {r2:.3f} (p {p2:.1e})")
X = sm.add_constant(Lp[["n_trials", "performance"]])
mod = sm.OLS(Lp.log_I0N, X).fit()
print("path model, log10 I0 N ~ trials + performance:")
print(mod.summary2().tables[1][["Coef.", "Std.Err.", "P>|t|"]].round(5))
print("performance range %.3f to %.3f; trials %d to %d" % (Lp.performance.min(), Lp.performance.max(),
                                                           Lp.n_trials.min(), Lp.n_trials.max()))
Lv = Lp[good_fit[Lp.index].values]
print(f"\nvariant without the misaligned sessions and fits with N outside 0 to 1e6 ({len(Lv)} sessions):")
r, p = stats.pearsonr(Lv.performance, Lv.n_trials)
print(f"performance vs trials: r = {r:.3f}, p = {p:.1e}")
for acc in ("log_I0N", "I0N"):
    r1, p1 = stats.pearsonr(Lv[acc], Lv.n_trials)
    r2, p2 = stats.pearsonr(Lv[acc], Lv.performance)
    print(f"{acc}: vs trials r = {r1:.3f} (p {p1:.1e}); vs performance r = {r2:.3f} (p {p2:.1e})")
mod_v = sm.OLS(Lv.log_I0N, sm.add_constant(Lv[["n_trials", "performance"]])).fit()
print("path model, log10 I0 N ~ trials + performance:")
print(mod_v.summary2().tables[1][["Coef.", "Std.Err.", "P>|t|"]].round(5))
73 sessions (of 73) with a positive I0 N
performance vs trials: r = 0.847, p = 3.8e-21
log_I0N: vs trials r = -0.054 (p 6.5e-01); vs performance r = 0.189 (p 1.1e-01)
I0N: vs trials r = -0.127 (p 2.8e-01); vs performance r = -0.012 (p 9.2e-01)
path model, log10 I0 N ~ trials + performance:
               Coef.  Std.Err.    P>|t|
const       -4.86213   0.94237  0.00000
n_trials    -0.01143   0.00304  0.00035
performance  7.17702   1.74260  0.00010
performance range 0.404 to 0.989; trials 66 to 382

variant without the misaligned sessions and fits with N outside 0 to 1e6 (65 sessions):
performance vs trials: r = 0.853, p = 1.9e-19
log_I0N: vs trials r = 0.231 (p 6.4e-02); vs performance r = 0.362 (p 3.1e-03)
I0N: vs trials r = 0.157 (p 2.1e-01); vs performance r = 0.275 (p 2.7e-02)
path model, log10 I0 N ~ trials + performance:
               Coef.  Std.Err.    P>|t|
const       -2.52850   0.31445  0.00000
n_trials    -0.00124   0.00097  0.20881
performance  1.54940   0.57420  0.00897

Result: not reproduced. Performance correlates with the number of trials (r = 0.847, p = 3.8e-21), as the paper reports, but the asymptotic accuracy does not correlate with the number of trials (log10 I0 N, r = -0.054) or with performance (r = 0.189, p = 0.11), against 0.34 and 0.52. In the path model both predictors are significant (performance p = 1.0e-04, trials p = 3.5e-04, with a negative coefficient). Without the misaligned sessions and the degenerate fits (65 sessions) performance against trials gives r = 0.853, accuracy (log10 I0 N) against trials r = 0.231 (p = 0.064) and against performance r = 0.362 (p = 0.0031), and the path model gives performance p = 0.009 and trials p = 0.21, the paper's pattern; but two of the three r are outside tolerance and accuracy against trials is not significant, so this variant is not reproduced either.

suppl6-twenty-bins-near-optimal¶

Twenty spatial bins give close to the smallest decoding error relative to the continuous position (11.75 cm, 95% CI 10.33 to 13.18 cm), similar to 30 bins (11.53 cm).

In [15]:
def bins_job(args):
    i, nb = args
    try:
        a, b, drop = hc30.decode_bins(sessions[i], nb, seed=50000 + 100 * i + nb, reps=REPS_BINS,
                                      C=C_SVM)
        return i, nb, a.mean(), b.mean(), drop
    except Exception as e:
        print("failed", i, nb, repr(e))
        return i, nb, np.nan, np.nan, np.nan

t = time.time()
with mp.get_context("fork").Pool(4) as pool:
    BR = pool.map(bins_job, [(i, nb) for i in range(len(sessions)) for nb in BIN_COUNTS], chunksize=1)
print(f"bin-count variant: {(time.time() - t) / 60:.1f} min")
br = pd.DataFrame(BR, columns=["i", "bins", "centre", "class_mean", "dropped"])
print("fraction of (trial, bin) samples with no frame, mean over sessions:",
      br.groupby("bins").dropped.mean().round(4).to_dict())
print("failed (session, bins):", br[br.centre.isna()][["i", "bins"]].values.tolist())
summ = br.groupby("bins").agg(n=("centre", "count"), centre=("centre", "mean"),
                              sem_c=("centre", lambda x: x.std(ddof=1) / np.sqrt(x.count())),
                              class_mean=("class_mean", "mean"),
                              sem_m=("class_mean", lambda x: x.std(ddof=1) / np.sqrt(x.count())))
summ["ci_c"] = 1.96 * summ.sem_c
print(summ.round(3))
for col, sem in (("centre", "sem_c"), ("class_mean", "sem_m")):
    m20, s20 = summ.loc[20, col], summ.loc[20, sem]
    below = summ.index[summ[col] < m20 - s20].tolist()
    print(f"{col}: 20 bins {m20:.2f} cm, 30 bins {summ.loc[30, col]:.2f}; bin counts more than one "
          f"SEM below 20: {below}")
bin-count variant: 11.1 min
fraction of (trial, bin) samples with no frame, mean over sessions: {10: 0.0, 15: 0.0, 20: 0.0, 25: 0.0075, 30: 0.0293, 40: 0.1089}
failed (session, bins): []
        n  centre  sem_c  class_mean  sem_m   ci_c
bins                                              
10    110  11.198  1.117      11.256  1.123  2.189
15    110  11.261  0.825      11.285  0.826  1.616
20    110  11.842  0.961      11.849  0.963  1.884
25    110  11.807  0.925      11.810  0.926  1.813
30    110  11.941  0.910      11.942  0.911  1.783
40    110  12.223  0.899      12.222  0.900  1.761
centre: 20 bins 11.84 cm, 30 bins 11.94; bin counts more than one SEM below 20: []
class_mean: 20 bins 11.85 cm, 30 bins 11.94; bin counts more than one SEM below 20: []

Result: reproduced. Relative to the continuous position the mean RMS error is 11.84 cm with 20 bins and 11.94 cm with 30 bins, within tolerance of 11.75 and 11.53 cm. 10 and 15 bins give lower means (11.20 and 11.26 cm), but none is more than one SEM (0.96 cm) below 20 bins. The prediction at the class mean position gives the same values within 0.06 cm.

suppl9-fit-recovers-saturation¶

On simulated place cells with information-limiting input noise, the IMSE fit gives consistent saturation estimates N from ensembles of 500 and 2000 neurons.

A simulation of the model of the Supplementary Figure 9 legend (data: elsewhere); no dataset values are used. The legend says the decoding follows the paper's methods except for the Poisson naive Bayes model, so the simulated events are arranged as the paper's tensor: summed per run and spatial bin, 40 bin and direction classes, two halves of the runs. Choices the legend leaves open (standard choices named by the criterion): back-and-forth runs at a constant 30 cm/s over 118 cm, frames at 20 Hz, input noise drawn independently per frame, peak rate 0.05 events per frame, 20 bins.

In [16]:
rng9 = np.random.default_rng(909)
L9, FS9, SPEED = hc30.TRACK_CM, 20.0, 30.0
n_frames = int(30 * 60 * FS9)
step = SPEED / FS9
phase = (np.arange(n_frames) * step) % (2 * L9)
true_pos = np.where(phase < L9, phase, 2 * L9 - phase)
direction = np.where(phase < L9, 1, -1)
run_id = (np.arange(n_frames) * step // L9).astype(int)
noisy_pos = true_pos + rng9.normal(0, 10, n_frames)
true_bin = np.clip((true_pos / L9 * 20).astype(int), 0, 19)
cls = 2 * true_bin + (direction == -1)
sigma9 = 30 / (2 * np.sqrt(2 * np.log(2)))
key = run_id * 40 + cls
uk, inv = np.unique(key, return_inverse=True)
s_run, s_cls = uk // 40, uk % 40
s_frames = np.bincount(inv).astype(float)
n_runs = run_id.max() + 1
print(f"{n_runs} runs, {len(uk)} run-bin samples, {s_frames.mean():.1f} frames per sample")

def simulate(n_cells):
    c = rng9.uniform(0, L9, n_cells)
    Y = np.zeros((len(uk), n_cells))
    for a in range(0, n_frames, 6000):
        rate = 0.05 * np.exp(-0.5 * ((noisy_pos[a:a + 6000, None] - c[None, :]) / sigma9) ** 2)
        np.add.at(Y, inv[a:a + 6000], rng9.poisson(rate))
    return Y

def nb_imse(Y, sizes, reps):
    out = []
    for n in sizes:
        v = []
        for _ in range(reps):
            sub = rng9.choice(Y.shape[1], n, replace=False)
            first_runs = rng9.permutation(n_runs)[: n_runs // 2]
            half = np.isin(s_run, first_runs)
            mses = []
            for a, b in ((half, ~half), (~half, half)):
                Ya, Yb = Y[a][:, sub], Y[b][:, sub]
                lam = np.array([Ya[s_cls[a] == k].sum(0) / s_frames[a][s_cls[a] == k].sum()
                                for k in range(40)]) + 1e-6
                ll = Yb @ np.log(lam).T - s_frames[b][:, None] * lam.sum(1)[None, :]
                p = ll.argmax(1)
                mses.append(np.mean(((p // 2 - s_cls[b] // 2) * hc30.BIN_CM) ** 2))
            v.append(1 / np.mean(mses))
        out.append(np.mean(v))
    return np.array(out)

res9 = {}
for n_total, sizes in ((500, [1, 10, 20, 50, 100, 200, 300, 400, 500]),
                       (2000, [1, 10, 20, 50, 100, 200, 300, 400, 500, 1000, 1500, 2000])):
    Y = simulate(n_total)
    im = nb_imse(Y, sizes, reps=16)
    I0, N, I0c, Nc = hc30.fit_imse(sizes, im)
    res9[n_total] = (N, Nc)
    print(f"{n_total} neurons: IMSE {np.round(im, 4)}; fit I0 = {I0:.5f}, N = {N:.0f} +/- {Nc:.0f} (95%)")
(N1, c1), (N2, c2) = res9[500], res9[2000]
print(f"intervals overlap: {(N1 - c1) <= (N2 + c2) and (N2 - c2) <= (N1 + c1)}")
458 runs, 9153 run-bin samples, 3.9 frames per sample
500 neurons: IMSE [0.0003 0.0004 0.0007 0.0017 0.0051 0.0128 0.0166 0.0188 0.0207]; fit I0 = 0.00007, N = 704 +/- 554 (95%)
2000 neurons: IMSE [0.0005 0.0005 0.0007 0.0018 0.0055 0.013  0.0166 0.0188 0.0205 0.0246
 0.0264 0.0277]; fit I0 = 0.00010, N = 338 +/- 87 (95%)
intervals overlap: True

Result: reproduced. On the simulated ensembles the fitted N is 704 +/- 554 from 500 neurons and 338 +/- 87 from 2,000 neurons (95% intervals), and the intervals overlap. The estimate from 500 neurons is imprecise: its interval is six times wider.

Summary¶

Claim Outcome
fig2d-rms-error-ensemble-vs-shuffled reproduced (assumed: SVM regularisation)
fig2cd-shuffle-better-in-all-bins reproduced
fig2ef-imse-saturates-with-correlations reproduced
suppl7b-initial-slope-lower-with-correlations reproduced
saturation-ensemble-size not reproduced
suppl11b-i0-vs-single-cell-snr partially reproduced (assumed: failed fits left out)
suppl11c-asymptotic-imse-vs-asymptotic-snr reproduced
suppl8-task-performance-and-accuracy not reproduced
suppl6-twenty-bins-near-optimal reproduced
suppl9-fit-recovers-saturation reproduced (simulation)

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.

Differences from the paper's method: the decoder is libsvm's one-vs-one linear SVM with C = 1 and voting, not MATLAB's fitcecoc with an unregularised SpaRSA fit and loss-weighted decoding; 10 repetitions with all neurons, 4 subsets per ensemble size and sizes in steps of 25, against 80 and steps of 10; 2 repetitions per bin count. The fit-check notebook repeats the IMSE fits with the paper's 80 subsets on steps of 10 for 16 sessions of Mouse2011, Mouse2012 and Mouse2028: for the 13 sessions with two non-degenerate fits N changes by a median factor of 1.09 (0.67 to 2.02) and I0 by 0.96, and the fits that fail are those of sessions whose events do not track position, with 80 subsets as with 4. For suppl11b, leaving out those failed fits is what gives a positive correlation. saturation-ensemble-size and suppl8 fail without the misaligned sessions and degenerate fits too, so those sessions are not shown to be the reason there. Mouse2022, which sets the lower bound of the saturation range in that variant, was not refitted with more subsets, and on 9 sessions the paper's loss-weighted decoding gives a median 0.71 of this decoder's N, so these two failures may come from this attempt's decoder and repetitions and not from the data.

What was found about the dataset: see the first notebook. The sessions whose events do not track position give flat or slowly rising IMSE curves and meaningless fits, and the largest decoding error, 51.9 cm, is in one of them (Mouse2011 105556).

In [17]:
print(f"total run time {(time.time() - T0) / 60:.1f} min; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
total run time 71.5 min; peak memory 2.0 GB