Reproducing Hazon et al. (2022) from CRCNS hc-30: tensor, noise and signal analyses¶

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 Notebook Status
data-sessions-and-neurons this one tested
single-cell-variability this one tested
suppl-table1-place-field-properties this one tested
fig1d-noise-correlation-by-field-distance this one tested
noise-correlation-not-physical-distance none blocked, data_missing: no cell positions in the file
position-measurement-noise this one tested
fig3cd-signal-and-noise-growth this one tested
suppl10-asymptotic-snr-lower-with-correlations this one tested
fig3f-signal-slope-beginning-vs-end this one tested
fig3g-noise-slope-decreases-over-run this one tested
fig3h-snr-higher-at-run-end this one tested
fig4a-snr-along-noise-pcs-peaks-at-6 this one tested
fig4b-correlations-increase-noise-signal-overlap this one tested
fig4c-overlap-predicts-asymptotic-snr this one tested
fig5f-pf-width-variance-vs-nsv this one tested
fig5hi-nsv-predicts-noise-correlation-effect this one tested
suppl-table2-nsv-best-predictor this one tested
pf-width-variance-not-predictive this one tested
fig5cd-synthetic-narrow-widths-broader-nsv this one tested (simulation, data elsewhere)
fig2d, fig2cd, fig2ef, suppl7b, saturation, suppl11b, suppl11c, suppl8, suppl6, suppl9 decoding notebook tested there

Run time about 6 minutes on 4 CPUs (4 worker processes).

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 analyses run in 4 processes
import collections
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)")
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))
    p = s["position"]
    ev = s["events"]
    rows.append(dict(i=i, mouse=s["mouse"], session=s["session_id"], frames=ev.shape[0],
                     minutes=ev.shape[0] / hc30.FS / 60, neurons=ev.shape[1],
                     right=int((d == 1).sum()), left=int((d == -1).sum()),
                     fast_runs=tr["n_fast_runs"], regular=tr["n_regular"],
                     cm_per_px=tr["cpp"], p5=tr["lo"], p95=tr["hi"], pmin=p.min(), pmax=p.max(),
                     n_neg=int((p < 0).sum()), events=ev.nnz,
                     ev_min=ev.data.min(), ev_max=ev.data.max(),
                     jitter=hc30.jitter(p, tr)))
info = pd.DataFrame(rows)
info["min_trials"] = info[["right", "left"]].min(axis=1)
info["large"] = (info.neurons > 200) & (info.min_trials > 30)
pd.set_option("display.width", 200)
print("sessions", len(info), "mice", info.mouse.nunique())
print(info.groupby("mouse").agg(sessions=("session", "size"), neurons=("neurons", "sum"),
                                large=("large", "sum"), trials_med=("min_trials", "median")))
print(info[["frames", "minutes", "neurons", "right", "left", "cm_per_px", "p5", "p95", "events",
            "ev_min", "ev_max"]].describe().round(3).T)
sessions 110 mice 12
           sessions  neurons  large  trials_med
mouse                                          
Mouse2010         4      667      0        46.5
Mouse2011        11     3340     11        48.0
Mouse2012        19     3521      4        60.0
Mouse2019         7     2062      7       130.0
Mouse2021         4     1700      4       154.5
Mouse2022         6     2030      5       146.0
Mouse2023         5      959      1        78.0
Mouse2024        14     5048     14        89.5
Mouse2025         8     1421      1       126.5
Mouse2026        13     2971     11        99.0
Mouse2028        15     3510     15       143.0
Mouse2029         4      669      0        93.0
           count        mean         std        min        25%        50%         75%          max
frames     110.0   35943.382    2826.739  24075.000  36022.750  36069.500   36133.250    55247.000
minutes    110.0      29.953       2.356     20.062     30.019     30.058      30.111       46.039
neurons    110.0     253.618      87.511    151.000    183.250    235.000     295.250      497.000
right      110.0     100.145      42.569     32.000     65.500     94.500     130.000      191.000
left       110.0      99.691      42.093     31.000     68.000     96.000     129.500      195.000
cm_per_px  110.0       0.187       0.004      0.177      0.185      0.186       0.189        0.199
p5         110.0      62.935       8.025     26.543     59.705     63.432      67.167       79.375
p95        110.0     692.995      10.175    668.969    686.879    696.376     699.876      712.999
events     110.0  109186.227  128000.668  24139.000  61634.500  80534.000  126407.250  1318158.000
ev_min     110.0       0.110       0.021      0.046      0.097      0.114       0.125        0.149
ev_max     110.0      13.531      22.042      2.887      7.447      9.120      12.485      225.317

Checks of the description against the data:

  • The data descriptor says 110 sessions, each with a frames by neurons sparse array that holds "a positive value if neuron n had a calcium event in time frame t". The cell below checks that the values are single frames (event onsets with their amplitude) and not the convolved trace the paper decodes from; the alpha convolution and normalisation of the Methods are therefore applied here (hc30.event_trace).
  • Frame rate: no sampling rate is stored; 20 Hz is from the Methods. Session lengths in minutes below are at 20 Hz; the paper and the descriptor say about 20 min.
  • Position is in camera pixels, with no unit in the file. The scale is the code's: 118 cm over the 5th to 95th percentile span.
In [3]:
runs = []
for s in sessions:
    ev = s["events"]
    for j in range(0, ev.shape[1], 25):
        c = ev[:, j].toarray().ravel() != 0
        e = np.diff(np.r_[0, c.astype(int), 0])
        runs.extend(np.where(e == -1)[0] - np.where(e == 1)[0])
runs = np.array(runs)
print(f"runs of consecutive nonzero frames, sample of neurons: {len(runs)} runs, "
      f"{np.mean(runs == 1):.3f} of length 1, max {runs.max()}")
print("events per neuron per minute, by session: median %.2f, range %.2f to %.2f" % tuple(
    np.percentile(info.events / info.neurons / info.minutes, [50, 0, 100])))
print("session with the most events per neuron per minute:",
      info.loc[(info.events / info.neurons / info.minutes).idxmax(), ["mouse", "session"]].tolist(),
      round((info.events / info.neurons / info.minutes).max(), 2))
print("minutes at 20 Hz: median %.1f, range %.1f to %.1f" % tuple(
    np.percentile(info.minutes, [50, 0, 100])))
print("sessions with negative positions:")
print(info.loc[info.n_neg > 0, ["mouse", "session", "frames", "n_neg", "pmin", "pmax"]])
print("sessions whose ID joins two recordings:",
      info.loc[info.session.str.contains("&"), ["mouse", "session", "frames"]].values.tolist())
j = int(info.index[info.session == "090858&091446"][0])
ev = sessions[j]["events"]
q = np.array_split(np.arange(ev.shape[0]), 4)
print("Mouse2024 090858&091446, events per neuron per minute in quarters of the session:",
      [round(ev[k].nnz / ev.shape[1] / (len(k) / hc30.FS / 60), 1) for k in q])
for k in info.index[info.n_neg > 0]:
    p = sessions[k]["position"]
    tr = hc30.select_trials(p)
    inside = [int((p[a:b + 1] < 0).sum()) for a, b in zip(tr["starts"], tr["ends"])]
    print(f"{info.mouse[k]} {info.session[k]}: {len(inside)} valid trials, "
          f"{sum(v > 0 for v in inside)} with negative positions ({sum(inside)} frames)"
          + (f", the first at trial {next(n for n, v in enumerate(inside) if v > 0)}"
             if any(inside) else ""))
runs of consecutive nonzero frames, sample of neurons: 494491 runs, 1.000 of length 1, max 1
events per neuron per minute, by session: median 12.04, range 6.60 to 77.59
session with the most events per neuron per minute: ['Mouse2024', '090858&091446'] 77.59
minutes at 20 Hz: median 30.1, range 20.1 to 46.0
sessions with negative positions:
        mouse        session  frames  n_neg          pmin        pmax
7   Mouse2024  090858&091446   55247    503 -1.262810e+04  728.026879
28  Mouse2028         105610   36074      6 -2.295803e+01  714.642674
51  Mouse2012         141832   35771    795 -3.655230e+07  718.150676
68  Mouse2022         093722   36374     79 -1.542819e+05  725.125592
sessions whose ID joins two recordings: [['Mouse2024', '090858&091446', 55247], ['Mouse2024', '130536&130559', 36036]]
Mouse2024 090858&091446, events per neuron per minute in quarters of the session: [38.6, 71.9, 96.9, 103.1]
Mouse2024 090858&091446: 145 valid trials, 0 with negative positions (0 frames)
Mouse2028 105610: 264 valid trials, 0 with negative positions (0 frames)
Mouse2012 141832: 100 valid trials, 0 with negative positions (0 frames)
Mouse2022 093722: 371 valid trials, 1 with negative positions (79 frames), the first at trial 0
In [4]:
# Recordings deposited more than once: compare positions of sessions with the same frame count,
# and the first 2000 frames of every pair.
dups = []
heads = [s["position"][:2000] for s in sessions]
for a in range(len(sessions)):
    for b in range(a + 1, len(sessions)):
        if np.allclose(heads[a], heads[b]) or (
                sessions[a]["events"].shape == sessions[b]["events"].shape
                and np.allclose(sessions[a]["position"], sessions[b]["position"])):
            dups.append((a, b))
print("pairs with identical positions:", dups)
same_n = collections.Counter((r.mouse, r.neurons) for r in info.itertuples())
print("sessions of one mouse with the same neuron count:",
      {k: v for k, v in same_n.items() if v > 1})
print("neurons are not matched across sessions in the file (no cell identifiers), so every "
      "analysis is per session")
pairs with identical positions: []
sessions of one mouse with the same neuron count: {('Mouse2028', 235): 2, ('Mouse2010', 167): 2, ('Mouse2012', 162): 3, ('Mouse2019', 296): 2, ('Mouse2026', 237): 2, ('Mouse2026', 235): 2, ('Mouse2029', 171): 2}
neurons are not matched across sessions in the file (no cell identifiers), so every analysis is per session
In [5]:
# Clock check: position and event traces share the frame axis (same length, by construction).
# A contrast that a lag would destroy: decode position bin from the event trace with the
# position labels shifted in time, on one session per mouse (nearest-centroid on held-out
# trials, a quick check, not the paper's decoder).
shift_check = hc30.clock_check

lag0 = np.array([shift_check(s, 0) for s in sessions])
info["clock_err_cm"] = lag0
print("lag 0, per session: mean absolute position error median %.1f cm, range %.1f to %.1f" % (
    np.median(lag0), lag0.min(), lag0.max()))
first_of_mouse = info.groupby("mouse").i.first().values
for lag_s in (2, 10):
    e = [shift_check(sessions[i], int(lag_s * hc30.FS)) for i in first_of_mouse]
    print(f"event trace shifted by {lag_s:>2} s (first session of each mouse): error {np.mean(e):.1f} cm "
          f"(range {min(e):.1f} to {max(e):.1f}); the same sessions at lag 0: "
          f"{np.mean(lag0[first_of_mouse]):.1f} cm")
bad = np.where(lag0 > 12)[0]
print(f"sessions with error above 12 cm at lag 0: {len(bad)}; scanning lags of -200 to +200 frames")
lag_rows = []
for i in bad:
    errs = {lag: shift_check(sessions[i], lag) for lag in range(-200, 201, 10)}
    best = min(errs, key=errs.get)
    lag_rows.append((i, info.mouse[i], info.session[i], round(lag0[i], 1), best, round(errs[best], 1)))
print(pd.DataFrame(lag_rows, columns=["i", "mouse", "session", "error_lag0_cm", "best_lag_frames",
                                      "error_best_cm"]).to_string(index=False))
lag 0, per session: mean absolute position error median 5.6 cm, range 2.3 to 44.0
event trace shifted by  2 s (first session of each mouse): error 23.8 cm (range 18.2 to 42.7); the same sessions at lag 0: 8.4 cm
event trace shifted by 10 s (first session of each mouse): error 42.0 cm (range 38.2 to 44.5); the same sessions at lag 0: 8.4 cm
sessions with error above 12 cm at lag 0: 6; scanning lags of -200 to +200 frames
 i     mouse session  error_lag0_cm  best_lag_frames  error_best_cm
51 Mouse2012  141832           29.3              -90            5.4
73 Mouse2026  115639           14.7                0           14.7
83 Mouse2011  105556           44.0              170           37.2
84 Mouse2011  104511           43.9             -160           39.4
92 Mouse2011  142436           29.4              -80            2.8
97 Mouse2021  132808           15.3              -10           12.7
In [6]:
WORK = info.index.values
LARGE = info.index[info.large].values
ANIMALS_L = sorted(info.loc[LARGE, "mouse"].unique())
print(f"working sessions {len(WORK)}, large-data sessions {len(LARGE)} from {len(ANIMALS_L)} mice")
print("tensor values: min %.3f, max %.2f (event trace in units of its SD)" % (
    min(T.min() for T, _ in TENS), max(T.max() for T, _ in TENS)))
print(f"peak memory so far {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB, "
      f"{time.time() - T0:.0f} s")
working sessions 110, large-data sessions 73 from 10 mice
tensor values: min 0.000, max 63.69 (event trace in units of its SD)
peak memory so far 1.9 GB, 148 s

data-sessions-and-neurons¶

The analysed data are 110 sessions from 12 mice with 27,898 neurons (151 to 497 per session, median 235), selected from 239 sessions for more than 150 neurons and 30 running trials in each direction; a subset of 73 sessions from 10 mice with at least 200 neurons is the large-data set.

In [7]:
ok = (info.neurons > 150) & (info.min_trials > 30)
print("sessions meeting the working rule (>150 neurons, >30 valid trials each way):",
      int(ok.sum()), "of", len(info))
print("mice", info.mouse.nunique(), "| neurons", info.neurons.sum(), "| median",
      info.neurons.median(), "| min", info.neurons.min(), "| max", info.neurons.max())
for label, sel in (("> 200 neurons (code)", info.neurons > 200),
                   (">= 200 neurons (Methods)", info.neurons >= 200)):
    sel = sel & ok
    print(f"large-data, {label}: {int(sel.sum())} sessions from "
          f"{info.loc[sel, 'mouse'].nunique()} mice")
print("valid trials per direction (smaller of the two): median %d, range %d to %d" % (
    info.min_trials.median(), info.min_trials.min(), info.min_trials.max()))
sessions meeting the working rule (>150 neurons, >30 valid trials each way): 110 of 110
mice 12 | neurons 27898 | median 235.0 | min 151 | max 497
large-data, > 200 neurons (code): 73 sessions from 10 mice
large-data, >= 200 neurons (Methods): 74 sessions from 10 mice
valid trials per direction (smaller of the two): median 92, range 31 to 187

Result: reproduced. All 110 sessions in the file meet the working rule (more than 150 neurons and more than 30 valid trials in each direction), from 12 mice, with 27,898 neurons (median 235, 151 to 497). Under the code's rule of more than 200 neurons, 73 sessions from 10 mice are large-data sessions, as the paper says; the Methods' "at least 200" gives 74. The file holds only the 110 working sessions, so the selection from 239 sessions cannot be checked.

single-cell-variability¶

Single-neuron responses vary strongly between visits to the same bin (response variance 0.7263 +/- 0.6117), and the single-cell signal-to-noise ratio, variance between bins over variance within bins, is 0.41 +/- 0.34, pooled over 27,898 neurons.

In [8]:
sd_vals, var_vals, snr40, snr_dir = [], [], [], []
for T, d in TENS:
    per_class_sd, per_class_var, means = [], [], []
    for dirn in (1, -1):
        A = T[:, :, d == dirn]
        per_class_sd.append(A.std(axis=2, ddof=1))
        per_class_var.append(A.var(axis=2, ddof=1))
        means.append(A.mean(axis=2))
    sd = np.concatenate(per_class_sd, axis=1)
    va = np.concatenate(per_class_var, axis=1)
    mu = np.concatenate(means, axis=1)
    sd_vals.append(sd.ravel())
    var_vals.append(va.ravel())
    with np.errstate(invalid="ignore", divide="ignore"):
        snr40.append(mu.var(axis=1, ddof=1) / va.mean(axis=1))
        snr_dir.append(np.nanmean([means[k].var(axis=1, ddof=1) / per_class_var[k].mean(axis=1)
                                   for k in (0, 1)], axis=0))
sd_vals, var_vals = np.concatenate(sd_vals), np.concatenate(var_vals)
snr40, snr_dir = np.concatenate(snr40), np.concatenate(snr_dir)
print("response variability over (session, class, neuron), n =", len(sd_vals))
print(f"  SD reading (code):        mean {np.nanmean(sd_vals):.4f} +/- {np.nanstd(sd_vals):.4f}"
      "   (paper 0.7263 +/- 0.6117)")
print(f"  variance reading (text):  mean {np.nanmean(var_vals):.4f} +/- {np.nanstd(var_vals):.4f}")
print("single-cell SNR per neuron, n =", len(snr40), "(neurons with no response:",
      int(np.isnan(snr40).sum()), ")")
print(f"  40 classes together:          {np.nanmean(snr40):.3f} +/- {np.nanstd(snr40):.3f}"
      "   (paper 0.41 +/- 0.34)")
print(f"  per direction, averaged:      {np.nanmean(snr_dir):.3f} +/- {np.nanstd(snr_dir):.3f}")
print("  median, 40 classes: %.3f" % np.nanmedian(snr40))
by_mouse = pd.DataFrame({"mouse": np.repeat(info.mouse.values, info.neurons.values),
                         "snr40": snr40}).groupby("mouse").snr40.mean().round(3)
print("SNR (40 classes) by mouse:", by_mouse.to_dict())
/tmp/ipykernel_2549/3108183018.py:16: RuntimeWarning: Mean of empty slice
  snr_dir.append(np.nanmean([means[k].var(axis=1, ddof=1) / per_class_var[k].mean(axis=1)
response variability over (session, class, neuron), n = 1115920
  SD reading (code):        mean 0.7263 +/- 0.6117   (paper 0.7263 +/- 0.6117)
  variance reading (text):  mean 0.9016 +/- 1.5301
single-cell SNR per neuron, n = 27898 (neurons with no response: 5 )
  40 classes together:          0.437 +/- 0.464   (paper 0.41 +/- 0.34)
  per direction, averaged:      0.295 +/- 0.294
  median, 40 classes: 0.288
SNR (40 classes) by mouse: {'Mouse2010': 0.391, 'Mouse2011': 0.307, 'Mouse2012': 0.449, 'Mouse2019': 0.667, 'Mouse2021': 0.253, 'Mouse2022': 0.428, 'Mouse2023': 0.488, 'Mouse2024': 0.492, 'Mouse2025': 0.336, 'Mouse2026': 0.383, 'Mouse2028': 0.499, 'Mouse2029': 0.514}

Result: reproduced. Under the code's reading (the standard deviation over trials per neuron and class, pooled over sessions, classes and neurons) the response variability is 0.7263 +/- 0.6117, the paper's numbers to four decimals; the variance reading gives 0.9016 +/- 1.5301. The single-cell SNR with the 40 classes together is 0.437 +/- 0.464, so the mean is within 10% of 0.41 and the spread is larger than the paper's 0.34; per direction it is 0.295.

suppl-table1-place-field-properties¶

In these data the mean event rate is 0.33 +/- 0.24 Hz, the in-field and out-of-field rates 0.88 +/- 0.72 and 0.034 +/- 0.07 Hz, the maximum rate 1.4 +/- 0.72 Hz, the place-field width at half amplitude 37.8 +/- 48.5 cm, the trial-by-trial variability 1.2 +/- 0.66 and the spatial information 0.24 +/- 0.051 bits per event, similar to electrophysiological reports.

Rates use the detected events (nonzero onsets of the dataset's array). The Gaussian fit is to each direction's binned event rate (Supplementary Figure 3 legend); the readings of the criterion are computed side by side.

In [9]:
from scipy.optimize import curve_fit

def gauss(x, a, m, s, b):
    return b + a * np.exp(-0.5 * ((x - m) / s) ** 2)

xb = np.arange(20)
pf_rows = []
for si, s in enumerate(sessions):
    tr = hc30.select_trials(s["position"])
    ev = s["events"].tocsr()
    onsets = (ev != 0).astype(float)
    n_frames = ev.shape[0]
    in_trial = np.zeros(n_frames, bool)
    for a, b in zip(tr["starts"], tr["ends"]):
        in_trial[a:b + 1] = True
    total_events = np.asarray(onsets.sum(axis=0)).ravel()
    run_events = np.asarray(onsets[in_trial].sum(axis=0)).ravel()
    per_dir = {}
    cnt_both, occ_both = 0, 0
    for dirn in (1, -1):
        cnt = np.zeros((20, ev.shape[1]))
        occ = np.zeros(20)
        visit_counts = []
        for a, b, dd in zip(tr["starts"], tr["ends"], tr["direction"]):
            if dd != dirn:
                continue
            bb = tr["bins"][a:b + 1]
            c = np.zeros((20, ev.shape[1]))
            np.add.at(c, bb, onsets[a:b + 1].toarray())
            cnt += c
            occ += np.bincount(bb, minlength=20)
            visit_counts.append(c)
        rate = cnt / (occ[:, None] / hc30.FS)  # events per second, bins x neurons
        V = np.stack(visit_counts, axis=2)  # bins x neurons x visits
        per_dir[dirn] = (rate, V.var(axis=2, ddof=1).mean(axis=0))
        cnt_both, occ_both = cnt_both + cnt, occ_both + occ
    rate_both = cnt_both / (occ_both[:, None] / hc30.FS)
    T_, d_ = TENS[si]
    tbt_trace = np.mean([T_[:, :, d_ == s_].var(axis=2, ddof=1).mean(axis=1) for s_ in (1, -1)], axis=0)
    minutes = n_frames / hc30.FS / 60
    for n in range(ev.shape[1]):
        r = dict(session=si, mouse=s["mouse"],
                 rate_run=run_events[n] / (in_trial.sum() / hc30.FS),
                 rate_all=total_events[n] / (n_frames / hc30.FS),
                 active=total_events[n] / minutes * 10 > 100, tbt_trace=tbt_trace[n])
        y = rate_both[:, n]
        r["width_both"] = np.nan
        if y.max() > 0:
            try:
                fit, _ = curve_fit(gauss, xb, y, p0=[y.max() - y.min(), y.argmax(), 2.0, y.min()],
                                   maxfev=2000)
                r["width_both"] = 2 * np.sqrt(2 * np.log(2)) * abs(fit[2]) * hc30.BIN_CM
            except Exception:
                pass
        for dirn, tag in ((1, "R"), (-1, "L")):
            rate, tbt = per_dir[dirn]
            y = rate[:, n]
            r[f"max_{tag}"] = y.max()
            r[f"tbt_{tag}"] = tbt[n]
            p = y / y.sum() if y.sum() > 0 else np.full(20, np.nan)
            with np.errstate(divide="ignore", invalid="ignore"):
                plogp = np.where(p > 0, p * np.log2(p), 0.0)
            r[f"si_skaggs_{tag}"] = np.log2(20) + plogp.sum()
            r[f"si_literal_{tag}"] = -plogp.sum() / 20
            half = y > y.max() / 2
            r[f"in_b_{tag}"] = y[half].mean() if y.max() > 0 else np.nan
            r[f"out_b_{tag}"] = y[~half].mean() if (~half).any() else np.nan
            r[f"sd_{tag}"] = y.std()
            fit = (np.nan,) * 4
            if y.max() > 0:
                try:
                    fit, _ = curve_fit(gauss, xb, y, p0=[y.max() - y.min(), y.argmax(), 2.0, y.min()],
                                       maxfev=2000)
                except Exception:
                    pass
            a_, m_, s_, b_ = fit
            r[f"fit_ok_{tag}"] = np.isfinite(s_)
            width = 2 * np.sqrt(2 * np.log(2)) * abs(s_) * hc30.BIN_CM
            r[f"width_{tag}"] = width
            if np.isfinite(s_):
                inside = np.abs(xb - m_) <= np.sqrt(2 * np.log(2)) * abs(s_)
                r[f"in_a_{tag}"] = y[inside].mean() if inside.any() else np.nan
                r[f"out_a_{tag}"] = y[~inside].mean() if (~inside).any() else np.nan
            else:
                r[f"in_a_{tag}"] = r[f"out_a_{tag}"] = np.nan
        pf_rows.append(r)
pf = pd.DataFrame(pf_rows)
print("neurons", len(pf), "| Gaussian fits failed: R", int((~pf.fit_ok_R).sum()), "L",
      int((~pf.fit_ok_L).sum()))
for tag in ("R", "L"):
    pf[f"modulated_{tag}"] = pf[f"max_{tag}"] > 0.2 * pf[f"sd_{tag}"]

def both(col):
    return np.concatenate([pf[f"{col}_R"].values, pf[f"{col}_L"].values])

def mstd(x):
    x = np.asarray(x, float)
    x = x[np.isfinite(x)]
    return f"{x.mean():.3f} +/- {x.std():.3f} (n {len(x)})"

active2 = np.concatenate([pf.active.values, pf.active.values])
modul = np.concatenate([pf.modulated_R.values, pf.modulated_L.values])
w = both("width")
w_ok = np.isfinite(w) & (w < 20 * hc30.BIN_CM * 10)
print("cells with > 100 events per 10 min:", int(pf.active.sum()), "of", len(pf))
table = []
for cells, sel1, sel2 in (("all", np.ones(len(pf), bool), np.ones(2 * len(pf), bool)),
                          (">100 ev/10 min", pf.active.values, active2)):
    table += [
        ("mean rate (a) running", cells, mstd(pf.rate_run[sel1]), 0.33),
        ("mean rate (b) session", cells, mstd(pf.rate_all[sel1]), 0.33),
        ("in-field (a) fitted width", cells, mstd(both("in_a")[sel2]), 0.88),
        ("in-field (b) above half peak", cells, mstd(both("in_b")[sel2]), 0.88),
        ("out-of-field (a)", cells, mstd(both("out_a")[sel2]), 0.034),
        ("out-of-field (b)", cells, mstd(both("out_b")[sel2]), 0.034),
        ("max rate", cells, mstd(both("max")[sel2]), 1.4),
        ("PF width, fitted FWHM, cm", cells, mstd(w[sel2 & w_ok]), 37.8),
        ("PF width, modulated cells", cells, mstd(w[sel2 & w_ok & modul]), 37.8),
        ("PF width, both directions pooled", cells,
         mstd(pf.width_both[sel1 & (pf.width_both < 1180).values]), 37.8),
        ("trial-by-trial variability, counts", cells, mstd(both("tbt")[sel2]), 1.2),
        ("trial-by-trial variability, event trace", cells, mstd(pf.tbt_trace[sel1]), 1.2),
        ("spatial info, log2(20) - H(p)", cells, mstd(both("si_skaggs")[sel2]), 0.24),
        ("spatial info, footnote literal", cells, mstd(both("si_literal")[sel2]), 0.24),
    ]
tab = pd.DataFrame(table, columns=["quantity", "cells", "mean +/- SD (n)", "paper"])
tab["mean"] = tab["mean +/- SD (n)"].str.split(" ").str[0].astype(float)
tab["within 10%"] = (np.abs(tab["mean"] - tab["paper"]) <= 0.1 * tab["paper"])
print(tab.to_string())
print("widths above the cap of 200 bins (fit runaway), dropped:", int((np.isfinite(w) & ~w_ok).sum()))
print("width per direction: R", mstd(pf.width_R[np.isfinite(pf.width_R) & (pf.width_R < 1180)]),
      "| L", mstd(pf.width_L[np.isfinite(pf.width_L) & (pf.width_L < 1180)]))
print("cells passing the minimal-modulation rule (max > 0.2 SD of the tuning curve): R",
      int(pf.modulated_R.sum()), "L", int(pf.modulated_L.sum()), "of", len(pf),
      "(Supplementary Figure 2c and 2d: 27,793 of 27,898)")
w_fin = w[np.isfinite(w)]
print("fitted FWHM over both directions without any cap: median %.1f cm, mean %.1f cm (n %d); "
      "capped at the track length (118 cm): mean %.1f cm (n %d)"
      % (np.median(w_fin), w_fin.mean(), len(w_fin), w_fin[w_fin <= hc30.TRACK_CM].mean(),
         int((w_fin <= hc30.TRACK_CM).sum())))
print("mean running rate by mouse:", pf.groupby("mouse").rate_run.mean().round(3).to_dict())
/tmp/ipykernel_2549/4035699871.py:72: OptimizeWarning: Covariance of the parameters could not be estimated
  fit, _ = curve_fit(gauss, xb, y, p0=[y.max() - y.min(), y.argmax(), 2.0, y.min()],
/tmp/ipykernel_2549/4035699871.py:50: OptimizeWarning: Covariance of the parameters could not be estimated
  fit, _ = curve_fit(gauss, xb, y, p0=[y.max() - y.min(), y.argmax(), 2.0, y.min()],
neurons 27898 | Gaussian fits failed: R 1536 L 1411
cells with > 100 events per 10 min: 18290 of 27898
                                   quantity           cells              mean +/- SD (n)   paper    mean  within 10%
0                     mean rate (a) running             all    0.293 +/- 0.189 (n 27898)   0.330   0.293       False
1                     mean rate (b) session             all    0.230 +/- 0.166 (n 27898)   0.330   0.230       False
2                 in-field (a) fitted width             all    1.165 +/- 0.818 (n 41411)   0.880   1.165       False
3              in-field (b) above half peak             all    1.042 +/- 0.762 (n 55485)   0.880   1.042       False
4                          out-of-field (a)             all    0.199 +/- 0.190 (n 52605)   0.034   0.199       False
5                          out-of-field (b)             all    0.153 +/- 0.148 (n 55792)   0.034   0.153       False
6                                  max rate             all    1.248 +/- 0.878 (n 55796)   1.400   1.248       False
7                 PF width, fitted FWHM, cm             all  16.378 +/- 21.883 (n 52654)  37.800  16.378       False
8                 PF width, modulated cells             all  16.378 +/- 21.883 (n 52654)  37.800  16.378       False
9          PF width, both directions pooled             all  18.239 +/- 27.474 (n 26919)  37.800  18.239       False
10       trial-by-trial variability, counts             all    0.036 +/- 0.029 (n 55796)   1.200   0.036       False
11  trial-by-trial variability, event trace             all    0.902 +/- 0.546 (n 27898)   1.200   0.902       False
12            spatial info, log2(20) - H(p)             all    1.295 +/- 0.821 (n 55796)   0.240   1.295       False
13           spatial info, footnote literal             all    0.151 +/- 0.041 (n 55796)   0.240   0.151       False
14                    mean rate (a) running  >100 ev/10 min    0.362 +/- 0.192 (n 18290)   0.330   0.362        True
15                    mean rate (b) session  >100 ev/10 min    0.289 +/- 0.176 (n 18290)   0.330   0.289       False
16                in-field (a) fitted width  >100 ev/10 min    1.336 +/- 0.826 (n 27865)   0.880   1.336       False
17             in-field (b) above half peak  >100 ev/10 min    1.206 +/- 0.769 (n 36572)   0.880   1.206       False
18                         out-of-field (a)  >100 ev/10 min    0.248 +/- 0.209 (n 35047)   0.034   0.248       False
19                         out-of-field (b)  >100 ev/10 min    0.194 +/- 0.160 (n 36576)   0.034   0.194       False
20                                 max rate  >100 ev/10 min    1.461 +/- 0.877 (n 36580)   1.400   1.461        True
21                PF width, fitted FWHM, cm  >100 ev/10 min  16.880 +/- 22.357 (n 35085)  37.800  16.880       False
22                PF width, modulated cells  >100 ev/10 min  16.880 +/- 22.357 (n 35085)  37.800  16.880       False
23         PF width, both directions pooled  >100 ev/10 min  18.469 +/- 28.230 (n 17763)  37.800  18.469       False
24       trial-by-trial variability, counts  >100 ev/10 min    0.043 +/- 0.031 (n 36580)   1.200   0.043       False
25  trial-by-trial variability, event trace  >100 ev/10 min    0.879 +/- 0.487 (n 18290)   1.200   0.879       False
26            spatial info, log2(20) - H(p)  >100 ev/10 min    1.063 +/- 0.628 (n 36580)   0.240   1.063       False
27           spatial info, footnote literal  >100 ev/10 min    0.163 +/- 0.031 (n 36580)   0.240   0.163       False
widths above the cap of 200 bins (fit runaway), dropped: 195
width per direction: R 16.440 +/- 23.169 (n 26268) | L 16.316 +/- 20.524 (n 26386)
cells passing the minimal-modulation rule (max > 0.2 SD of the tuning curve): R 27715 L 27770 of 27898 (Supplementary Figure 2c and 2d: 27,793 of 27,898)
fitted FWHM over both directions without any cap: median 11.5 cm, mean 37.8 cm (n 52849); capped at the track length (118 cm): mean 15.5 cm (n 52416)
mean running rate by mouse: {'Mouse2010': 0.172, 'Mouse2011': 0.248, 'Mouse2012': 0.226, 'Mouse2019': 0.44, 'Mouse2021': 0.309, 'Mouse2022': 0.39, 'Mouse2023': 0.236, 'Mouse2024': 0.328, 'Mouse2025': 0.268, 'Mouse2026': 0.236, 'Mouse2028': 0.302, 'Mouse2029': 0.289}

Result: not reproduced, resting on leaving out runaway width fits. Two of the seven values are within 10% under some reading: the mean event rate over running frames in cells with more than 100 events per 10 min (0.362 Hz against 0.33) and the maximum rate in the same cells (1.461 Hz against 1.4). In-field rates (1.04 to 1.34 Hz) and out-of-field rates (0.15 to 0.25 Hz) are outside, the fitted place-field width is 16 to 18 cm against 37.8 cm, the trial-by-trial variability is 0.04 in event counts and 0.88 to 0.90 in the event trace against 1.2, and the spatial information is 0.15 to 0.16 (footnote formula) or 1.06 to 1.30 bits (log2(20) minus the entropy) against 0.24. The widths leave out 195 fits wider than 1180 cm (ten times the track), a choice of this attempt. With no cap the mean width is 37.8 cm, within tolerance, which would make three values and a partial reproduction; that mean comes from those 195 fits, since the median is 11.5 cm and the mean capped at the track length 15.5 cm. The minimal-modulation rule keeps 27,715 and 27,770 of 27,898 cells per direction (the paper 27,793) and does not move the width.

fig1d-noise-correlation-by-field-distance¶

Noise correlations between neuron pairs depend on the distance between their place-field peaks, highest for nearby fields, and trial shuffling drastically reduces them.

In [10]:
rng_1d = np.random.default_rng(101)
per_sess = {1: [], -1: []}
pooled = {1: [np.zeros(20), np.zeros(20), np.zeros(20), np.zeros(20), np.zeros(20)],
          -1: [np.zeros(20), np.zeros(20), np.zeros(20), np.zeros(20), np.zeros(20)]}
n_pairs = 0
for T, d in TENS:
    o = hc30.noise_pairs_by_peak_distance(T, d, rng_1d)
    for dirn in (1, -1):
        dist, cu, cs = o[dirn]
        n_pairs += len(dist)
        mu_u = np.array([cu[dist == k].mean() if (dist == k).any() else np.nan for k in range(20)])
        mu_s = np.array([cs[dist == k].mean() if (dist == k).any() else np.nan for k in range(20)])
        per_sess[dirn].append((mu_u, mu_s))
        cnt = np.bincount(dist, minlength=20)
        P = pooled[dirn]
        P[0] += cnt
        P[1] += np.bincount(dist, cu, minlength=20)
        P[2] += np.bincount(dist, cu ** 2, minlength=20)
        P[3] += np.bincount(dist, cs, minlength=20)
        P[4] += np.bincount(dist, cs ** 2, minlength=20)
print("pairs counted (both directions):", n_pairs, "(legend 3,941,140)")
res1d = {}
for dirn, name in ((1, "rightward"), (-1, "leftward")):
    U = np.array([a for a, _ in per_sess[dirn]])
    Sh = np.array([b for _, b in per_sess[dirn]])
    mu_u, mu_s = np.nanmean(U, 0), np.nanmean(Sh, 0)
    ci_u = 1.96 * np.nanstd(U, 0, ddof=1) / np.sqrt(np.isfinite(U).sum(0))
    ci_s = 1.96 * np.nanstd(Sh, 0, ddof=1) / np.sqrt(np.isfinite(Sh).sum(0))
    far = np.nanmean(U[:, 10:], axis=1)
    print(f"\n{name}: mean over sessions (95% interval)")
    for k in (0, 1, 2, 3, 5, 10, 15, 19):
        print(f"  distance {k:>2}: unshuffled {mu_u[k]:.4f} +/- {ci_u[k]:.4f}   "
              f"shuffled {mu_s[k]:.5f} +/- {ci_s[k]:.5f}")
    sep = all(mu_u[k] - ci_u[k] > mu_s[k] + ci_s[k] for k in range(11))
    print(f"  distance 0 vs mean of distances >= 10: {mu_u[0]:.4f} vs {np.nanmean(mu_u[10:]):.4f}")
    print(f"  shuffled below unshuffled with non-overlapping intervals at every distance 0..10: {sep}")
    # pooled over pairs
    P = pooled[dirn]
    pm_u = P[1] / P[0]
    pm_s = P[3] / P[0]
    pse_u = np.sqrt(P[2] / P[0] - pm_u ** 2) / np.sqrt(P[0])
    pse_s = np.sqrt(P[4] / P[0] - pm_s ** 2) / np.sqrt(P[0])
    sep_p = all(pm_u[k] - 1.96 * pse_u[k] > pm_s[k] + 1.96 * pse_s[k] for k in range(11))
    print(f"  pooled pairs: distance 0 {pm_u[0]:.4f}, >= 10 {np.average(pm_u[10:], weights=P[0][10:]):.4f};"
          f" separated 0..10: {sep_p}")
    # code's joined bins (d and d+1)
    joined = [(np.nanmean(U[:, k:k + 2])) for k in range(0, 19)]
    print("  joined distances (code variant), first values:", np.round(joined[:4], 4))
    res1d[name] = (mu_u, mu_s, ci_u, ci_s)
fig, axs = plt.subplots(1, 2, figsize=(9, 3))
for ax, (name, (mu_u, mu_s, ci_u, ci_s)) in zip(axs, res1d.items()):
    x = np.arange(20)
    ax.plot(x, mu_u, label="unshuffled")
    ax.fill_between(x, mu_u - ci_u, mu_u + ci_u, alpha=0.3)
    ax.plot(x, mu_s, label="shuffled")
    ax.fill_between(x, mu_s - ci_s, mu_s + ci_s, alpha=0.3)
    ax.set_title(name)
    ax.set_xlabel("PF peak distance (bins)")
axs[0].set_ylabel("noise correlation")
axs[0].legend()
plt.show()
print("all plotted values within the axes; y range %.4f to %.4f" % (
    min(np.nanmin(v[1] - v[3]) for v in res1d.values()), max(np.nanmax(v[0] + v[2]) for v in res1d.values())))
pairs counted (both directions): 7859771 (legend 3,941,140)

rightward: mean over sessions (95% interval)
  distance  0: unshuffled 0.0386 +/- 0.0040   shuffled 0.00002 +/- 0.00011
  distance  1: unshuffled 0.0296 +/- 0.0028   shuffled 0.00002 +/- 0.00011
  distance  2: unshuffled 0.0220 +/- 0.0022   shuffled -0.00006 +/- 0.00012
  distance  3: unshuffled 0.0177 +/- 0.0021   shuffled -0.00009 +/- 0.00015
  distance  5: unshuffled 0.0130 +/- 0.0029   shuffled 0.00005 +/- 0.00016
  distance 10: unshuffled 0.0048 +/- 0.0018   shuffled -0.00007 +/- 0.00020
  distance 15: unshuffled 0.0053 +/- 0.0020   shuffled 0.00010 +/- 0.00020
  distance 19: unshuffled 0.0131 +/- 0.0020   shuffled -0.00009 +/- 0.00021
  distance 0 vs mean of distances >= 10: 0.0386 vs 0.0064
  shuffled below unshuffled with non-overlapping intervals at every distance 0..10: True
  pooled pairs: distance 0 0.0372, >= 10 0.0054; separated 0..10: True
  joined distances (code variant), first values: [0.0341 0.0258 0.0199 0.0163]

leftward: mean over sessions (95% interval)
  distance  0: unshuffled 0.0374 +/- 0.0024   shuffled 0.00011 +/- 0.00014
  distance  1: unshuffled 0.0284 +/- 0.0020   shuffled 0.00002 +/- 0.00011
  distance  2: unshuffled 0.0208 +/- 0.0018   shuffled -0.00016 +/- 0.00011
  distance  3: unshuffled 0.0154 +/- 0.0015   shuffled -0.00005 +/- 0.00014
  distance  5: unshuffled 0.0098 +/- 0.0013   shuffled -0.00009 +/- 0.00018
  distance 10: unshuffled 0.0044 +/- 0.0013   shuffled 0.00006 +/- 0.00017
  distance 15: unshuffled 0.0040 +/- 0.0017   shuffled -0.00014 +/- 0.00018
  distance 19: unshuffled 0.0145 +/- 0.0018   shuffled 0.00014 +/- 0.00018
  distance 0 vs mean of distances >= 10: 0.0374 vs 0.0058
  shuffled below unshuffled with non-overlapping intervals at every distance 0..10: True
  pooled pairs: distance 0 0.0369, >= 10 0.0053; separated 0..10: True
  joined distances (code variant), first values: [0.0329 0.0246 0.0181 0.0143]
No description has been provided for this image
all plotted values within the axes; y range -0.0003 to 0.0426

Result: reproduced. In both directions the mean noise correlation is highest for pairs with the same place-field peak (rightward 0.0386, leftward 0.0374) and lower at distances of 10 bins or more (0.0064 and 0.0058), and the shuffled means at the printed distances (within 0.0002 of zero) are below the unshuffled ones with non-overlapping 95% intervals at every distance from 0 to 10 bins. Pooling all pairs gives the same. 7,859,771 pairs are counted over both directions, against the legend's 3,941,140, which is about half and may count each pair once.

position-measurement-noise¶

Position tracking noise is small, 0.28 cm on average (0.12 to 1.0 cm across 110 sessions), far below the decoding errors.

In [11]:
j = info.jitter
print(f"jitter over {len(j)} sessions: mean {j.mean():.3f} cm, min {j.min():.3f}, max {j.max():.3f},"
      f" median {j.median():.3f}")
print("sessions above 1.1 cm:", int((j > 1.1).sum()))
print("by mouse:", info.groupby("mouse").jitter.mean().round(3).to_dict())
jitter over 110 sessions: mean 0.277 cm, min 0.118, max 1.001, median 0.235
sessions above 1.1 cm: 0
by mouse: {'Mouse2010': 0.43, 'Mouse2011': 0.429, 'Mouse2012': 0.386, 'Mouse2019': 0.185, 'Mouse2021': 0.172, 'Mouse2022': 0.164, 'Mouse2023': 0.266, 'Mouse2024': 0.227, 'Mouse2025': 0.242, 'Mouse2026': 0.26, 'Mouse2028': 0.165, 'Mouse2029': 0.366}

Result: reproduced. The jitter is 0.277 cm on average over the 110 sessions, from 0.118 to 1.001 cm, all three within tolerance of 0.28, 0.12 and 1.0 cm.

Signal and noise against ensemble size (shared by Figures 3 to 5)¶

Per session, 20 random neuron subsets per ensemble size (the paper uses 80; reduced to fit the time limit), sizes 2, 10, 20, ... all neurons, each subset with its own equalised trials and half split. Run in 4 worker processes, each session with its own seed.

In [12]:
def _sn(i):
    T, d = TENS[i]
    return hc30.signal_noise_series(T, d, seed=1000 + i, n_subsets=20)

t = time.time()
with mp.get_context("fork").Pool(4) as pool:
    SN = pool.map(_sn, range(len(TENS)))
print(f"signal and noise series: {time.time() - t:.0f} s")

sn_rows = []
for i, (sizes, P, M) in enumerate(SN):
    sig, sse = hc30.slope_with_se(sizes, M[0])
    noi, nse = hc30.slope_with_se(sizes, M[1])
    nos, sse_s = hc30.slope_with_se(sizes, M[2])
    sig_s = sig  # trial shuffling leaves the bin means, hence the signal, unchanged (code 'se')
    a, b, r2u = hc30.fit_line(sizes, M[1])
    _, _, r2s = hc30.fit_line(sizes, M[2])
    asn = sig / noi
    asn_s = sig / nos
    # delta-method 95% half-intervals of the two asymptotic SNRs
    ci = 1.96 * abs(asn) * np.sqrt((sse / sig) ** 2 + (nse / noi) ** 2)
    ci_s = 1.96 * abs(asn_s) * np.sqrt((sse / sig) ** 2 + (sse_s / nos) ** 2)
    ratio = asn / asn_s
    ci_r = 1.96 * abs(ratio) * np.sqrt((nse / noi) ** 2 + (sse_s / nos) ** 2)
    # per bin pair slopes
    pair_sig = np.array([hc30.slope_with_se(sizes, P[0][:, k])[0] for k in range(38)])
    pair_noi = np.array([hc30.slope_with_se(sizes, P[1][:, k])[0] for k in range(38)])
    sn_rows.append(dict(i=i, mouse=info.mouse[i], sig_slope=sig, noise_slope=noi,
                        noise_slope_shuf=nos, noise_r2=r2u, noise_shuf_r2=r2s,
                        asnr=asn, asnr_shuf=asn_s, asnr_ci=ci, asnr_shuf_ci=ci_s,
                        ratio=ratio, ratio_ci=ci_r, pair_sig=pair_sig, pair_noi=pair_noi))
SNR = pd.DataFrame(sn_rows)
print(SNR[["sig_slope", "noise_slope", "noise_slope_shuf", "asnr", "asnr_shuf", "ratio"]]
      .describe().round(5).T)
signal and noise series: 331 s
                  count      mean       std      min       25%       50%       75%       max
sig_slope         110.0   0.02894   0.01144  0.00002   0.02340   0.02883   0.03606   0.06130
noise_slope       110.0   0.01559   0.00529  0.00211   0.01209   0.01538   0.01817   0.03087
noise_slope_shuf  110.0   0.00136   0.00085  0.00001   0.00084   0.00121   0.00166   0.00429
asnr              110.0   1.98941   0.99913  0.00658   1.31726   1.94137   2.47430   5.10417
asnr_shuf         110.0  27.65494  19.12195  0.06749  13.69905  23.41937  33.88525  90.31145
ratio             110.0   0.08975   0.05108  0.00228   0.05539   0.08385   0.11006   0.27304

fig3cd-signal-and-noise-growth¶

The spatial signal grows linearly with ensemble size and does not change with trial shuffling, while the noise along the signal direction keeps growing linearly in the unmodified data but saturates within about 100 neurons in the shuffled data.

In [13]:
med = SNR[["sig_slope", "noise_slope", "noise_slope_shuf", "noise_r2"]].median()
# the signal measured on the shuffled test half: means are unchanged by the shuffle, check it
T, d = TENS[0]
rr = np.random.default_rng(5)
S_ = hc30.shuffle_tensor(T, d, rr)
print("largest change of a bin mean under the shuffle (session 0):",
      float(np.abs(S_.mean(axis=2) - T.mean(axis=2)).max()))
print(f"median session: signal slope {med.sig_slope:.5f}, unshuffled noise slope "
      f"{med.noise_slope:.5f} (R^2 of the line {med.noise_r2:.3f}), shuffled noise slope "
      f"{med.noise_slope_shuf:.6f}")
print("(1) shuffled signal slope / unshuffled: 1.000 (identical bin means)")
print(f"(2) unshuffled noise slope > 0 in {int((SNR.noise_slope > 0).sum())} of {len(SNR)} sessions;"
      f" R^2 >= 0.9 in {int((SNR.noise_r2 >= 0.9).sum())}; median R^2 {SNR.noise_r2.median():.3f}")
rel = SNR.noise_slope_shuf / SNR.noise_slope
print(f"(3) shuffled / unshuffled noise slope: median {rel.median():.3f}, "
      f"below 0.1 in {int((rel < 0.1).sum())} of {len(SNR)} sessions")
# example curves, median session by noise slope
k = int(SNR.noise_slope.sub(med.noise_slope).abs().idxmin())
sizes, P, M = SN[k]
fig, axs = plt.subplots(1, 2, figsize=(9, 3))
axs[0].plot(sizes, M[0]); axs[0].set_title("signal |dmu|^2"); axs[0].set_xlabel("neurons")
axs[1].plot(sizes, M[1], label="unshuffled"); axs[1].plot(sizes, M[2], label="shuffled")
axs[1].set_title("noise sigma^2"); axs[1].legend(); axs[1].set_xlabel("neurons")
plt.show()
print(f"example session {k} ({info.mouse[k]}): signal {M[0].min():.3f} to {M[0].max():.3f}, "
      f"noise {M[1].min():.3f} to {M[1].max():.3f}, shuffled noise {M[2].min():.3f} to {M[2].max():.3f}")
largest change of a bin mean under the shuffle (session 0): 6.661338147750939e-16
median session: signal slope 0.02883, unshuffled noise slope 0.01538 (R^2 of the line 0.983), shuffled noise slope 0.001206
(1) shuffled signal slope / unshuffled: 1.000 (identical bin means)
(2) unshuffled noise slope > 0 in 110 of 110 sessions; R^2 >= 0.9 in 109; median R^2 0.983
(3) shuffled / unshuffled noise slope: median 0.084, below 0.1 in 72 of 110 sessions
No description has been provided for this image
example session 22 (Mouse2028): signal 0.024 to 7.660, noise 0.856 to 5.933, shuffled noise 0.831 to 3.283

Result: reproduced. Trial shuffling leaves the bin means, and so the signal, unchanged (largest change 7e-16), so the shuffled and unshuffled signal slopes are equal. In the median session the unshuffled noise slope is 0.0154 with a line explaining 98.3% of the variance at 100 neurons or more (positive in 110 of 110 sessions), and the shuffled noise slope is 0.0012, 8.4% of the unshuffled one in the median session; it is below 10% in 72 of 110 sessions.

suppl10-asymptotic-snr-lower-with-correlations¶

Across all mice the asymptotic SNR (signal slope over noise slope) is lower in the unmodified data than in the shuffled data.

In [14]:
w_ = stats.wilcoxon(SNR.asnr, SNR.asnr_shuf)
print(f"asymptotic SNR, median unshuffled {SNR.asnr.median():.3f}, shuffled "
      f"{SNR.asnr_shuf.median():.2f}; shuffled higher in {int((SNR.asnr_shuf > SNR.asnr).sum())} "
      f"of {len(SNR)} sessions; Wilcoxon signed-rank p = {w_.pvalue:.2e}")
print("negative shuffled noise slopes (asymptotic SNR undefined or negative):",
      int((SNR.noise_slope_shuf <= 0).sum()))
pm = SNR.groupby("mouse")[["asnr", "asnr_shuf"]].median()
pm["shuf_higher"] = pm.asnr_shuf > pm.asnr
print(pm.round(3))
print("mice with higher median for shuffled:", int(pm.shuf_higher.sum()), "of", len(pm))
asymptotic SNR, median unshuffled 1.941, shuffled 23.42; shuffled higher in 110 of 110 sessions; Wilcoxon signed-rank p = 8.75e-20
negative shuffled noise slopes (asymptotic SNR undefined or negative): 0
            asnr  asnr_shuf  shuf_higher
mouse                                   
Mouse2010  1.082     12.315         True
Mouse2011  1.891     16.241         True
Mouse2012  1.472     13.684         True
Mouse2019  4.543     54.476         True
Mouse2021  0.916     29.673         True
Mouse2022  1.543     49.634         True
Mouse2023  2.201     15.057         True
Mouse2024  1.956     27.195         True
Mouse2025  1.072     11.706         True
Mouse2026  2.156     16.399         True
Mouse2028  2.447     33.599         True
Mouse2029  2.558     28.243         True
mice with higher median for shuffled: 12 of 12

Result: reproduced. The asymptotic SNR is higher for the shuffled data in 110 of 110 sessions (medians 1.94 and 23.4; Wilcoxon p = 8.8e-20) and the per-animal median is higher for the shuffled data in 12 of 12 mice.

Run position (Figures 3f to 3h)¶

Beginning of a run: the first bin pair of rightward runs and the last of leftward runs; end: the opposite pairs (the code's choice). Pairs are ordered leftward 0..18 then rightward 0..18, pair k joining bins k and k+1 in track coordinates, rightward runs going from bin 0 to 19.

In [15]:
def begin_end(arr):
    a = np.stack(arr.values)
    begin_pooled = np.concatenate([a[:, 19 + 0], a[:, 18]])  # rightward pair 0, leftward pair 18
    end_pooled = np.concatenate([a[:, 19 + 18], a[:, 0]])
    return begin_pooled, end_pooled, a[:, 19], a[:, 37]

def one_sided(x, y, alt):
    return stats.wilcoxon(x, y, alternative=alt).pvalue

subsets = {"110 working": SNR.index.values, "73 large-data": LARGE}

fig3f-signal-slope-beginning-vs-end¶

The asymptotic signal slope differs between the beginning and the end of runs, decreasing over the run as the legend states.

In [16]:
for name, idx in subsets.items():
    sub = SNR.loc[idx]
    b, e, br, er = begin_end(sub.pair_sig)
    print(f"{name}: pooled n = {len(b)}: median begin {np.median(b):.4f}, end {np.median(e):.4f}; "
          f"begin > end (legend) p = {one_sided(b, e, 'greater'):.2e}; begin < end (code) p = "
          f"{one_sided(b, e, 'less'):.2e}")
    print(f"   rightward only n = {len(br)}: begin {np.median(br):.4f}, end {np.median(er):.4f}; "
          f"greater p = {one_sided(br, er, 'greater'):.2e}; less p = {one_sided(br, er, 'less'):.2e}")
a = np.stack(SNR.pair_sig.values)
along = np.concatenate([np.median(a[:, 19:], 0), np.median(a[:, :19], 0)[::-1]])
print("median signal slope along the run, rightward pairs 0..18:", np.round(along[:19], 4))
print("                      leftward pairs, run order:", np.round(along[19:], 4))
110 working: pooled n = 220: median begin 0.2082, end 0.3126; begin > end (legend) p = 1.00e+00; begin < end (code) p = 1.12e-18
   rightward only n = 110: begin 0.2026, end 0.2995; greater p = 1.00e+00; less p = 1.75e-09
73 large-data: pooled n = 146: median begin 0.2150, end 0.3135; begin > end (legend) p = 1.00e+00; begin < end (code) p = 3.85e-15
   rightward only n = 73: begin 0.2229, end 0.2954; greater p = 1.00e+00; less p = 1.72e-05
median signal slope along the run, rightward pairs 0..18: [0.2026 0.1033 0.0551 0.0352 0.0275 0.0225 0.0211 0.019  0.018  0.0197
 0.0184 0.0186 0.0184 0.0218 0.0238 0.0302 0.0494 0.1073 0.2995]
                      leftward pairs, run order: [0.2105 0.0972 0.0472 0.0363 0.0286 0.0251 0.0218 0.0195 0.0163 0.0159
 0.0155 0.0165 0.0197 0.0231 0.0273 0.0355 0.0504 0.121  0.3193]

Result: reproduced, resting on the code's direction of the test. The signal slope differs strongly between the beginning and the end of runs, and it is larger at the end (pooled medians 0.208 at the beginning and 0.313 at the end). The code's test (beginning lower) gives p = 1.1e-18 for 110 sessions, as the code printed (2.19e-18), and p = 1.8e-09 for rightward runs alone. The legend's test (beginning greater) gives p = 1.00 under every reading, so the legend's "decreases" does not hold; the criterion records an outcome that holds only in the code's direction as resting on that reading.

fig3g-noise-slope-decreases-over-run¶

The asymptotic noise slope decreases monotonically and significantly from the beginning to the end of runs.

In [17]:
for name, idx in subsets.items():
    sub = SNR.loc[idx]
    b, e, br, er = begin_end(sub.pair_noi)
    print(f"{name}: pooled n = {len(b)}: median begin {np.median(b):.5f}, end {np.median(e):.5f}; "
          f"begin > end p = {one_sided(b, e, 'greater'):.2e} (other direction "
          f"{one_sided(b, e, 'less'):.2e})")
a = np.stack(SNR.pair_noi.values)
print("median noise slope along the run, rightward:", np.round(np.median(a[:, 19:], 0), 5))
print("median noise slope along the run, leftward (run order):", np.round(np.median(a[:, :19], 0)[::-1], 5))
110 working: pooled n = 220: median begin 0.01752, end 0.01163; begin > end p = 1.91e-09 (other direction 1.00e+00)
73 large-data: pooled n = 146: median begin 0.01644, end 0.01044; begin > end p = 1.24e-10 (other direction 1.00e+00)
median noise slope along the run, rightward: [0.01744 0.01562 0.0155  0.01409 0.01539 0.01349 0.01125 0.01205 0.01323
 0.01282 0.01245 0.01198 0.01261 0.01294 0.01348 0.01208 0.01151 0.01168
 0.01069]
median noise slope along the run, leftward (run order): [0.01846 0.01663 0.01449 0.0154  0.01432 0.01486 0.01273 0.01201 0.01224
 0.013   0.01286 0.012   0.01256 0.01369 0.01394 0.01356 0.01143 0.01141
 0.01281]

Result: reproduced. The noise slope is larger at the beginning than at the end of runs (pooled medians 0.0175 and 0.0116), one-tailed p = 1.9e-09 over 110 sessions (code printed 7.7e-10) and 1.2e-10 over the 73 large-data sessions. The medians along the run fall from 0.0174 to 0.0107 (rightward) with ups and downs; monotonic decrease is not tested.

fig3h-snr-higher-at-run-end¶

The asymptotic SNR (signal slope over noise slope) is significantly higher at the end of runs than at their start.

In [18]:
for name, idx in subsets.items():
    sub = SNR.loc[idx]
    ratio_pairs = pd.Series([s / n for s, n in zip(sub.pair_sig, sub.pair_noi)], index=sub.index)
    b, e, br, er = begin_end(ratio_pairs)
    print(f"{name}: pooled n = {len(b)}: median begin {np.median(b):.3f}, end {np.median(e):.3f}; "
          f"begin < end p = {one_sided(b, e, 'less'):.2e}")
    print(f"   rightward only: begin {np.median(br):.3f}, end {np.median(er):.3f}; "
          f"begin < end p = {one_sided(br, er, 'less'):.2e}")
110 working: pooled n = 220: median begin 11.694, end 25.149; begin < end p = 2.80e-26
   rightward only: begin 12.274, end 27.556; begin < end p = 9.39e-17
73 large-data: pooled n = 146: median begin 12.672, end 30.465; begin < end p = 5.73e-21
   rightward only: begin 12.959, end 30.746; begin < end p = 2.06e-11

Result: reproduced. The asymptotic SNR per bin pair is lower at the beginning than at the end of runs (pooled medians 11.7 and 25.1), one-tailed p = 2.8e-26 over 110 sessions (code printed 2.4e-29), and p = 9.4e-17 for rightward runs alone.

fig4a-snr-along-noise-pcs-peaks-at-6¶

Along the eigenvectors of the noise covariance, each component's SNR contribution rises to a maximum at the sixth component, and the first six carry only a small part of the total, so spatial information is spread over many dimensions.

100 random half splits per bin pair, as in the code.

In [19]:
N_SPLITS_4A = 100

def eigen_snr(i):
    rng = np.random.default_rng(4000 + i)
    T, d = TENS[i]
    h = min((d == 1).sum(), (d == -1).sum())
    X = np.concatenate([T[:, :, d == 1][:, :, :h], T[:, :, d == -1][:, :, :h]], axis=1)
    N, K, Tn = X.shape
    t2 = Tn // 2
    nd = t2 - 1
    out = np.zeros((38, nd))
    for pi, b in enumerate(list(range(19)) + list(range(20, 39))):
        Xa, Xb = X[:, b, :], X[:, b + 1, :]
        acc = np.zeros(nd)
        for _ in range(N_SPLITS_4A):
            perm = rng.permutation(Tn)
            p1, p2 = perm[:t2], perm[t2:2 * t2]
            V, _ = hc30.pca_dirs(Xa[:, p1])
            V = V[:, :nd]
            pa, pb = Xa[:, p2].T @ V, Xb[:, p2].T @ V
            acc += (pa.mean(0) - pb.mean(0)) ** 2 / ((pa.var(0, ddof=1) + pb.var(0, ddof=1)) / 2)
        out[pi] = acc / N_SPLITS_4A
    return np.median(out, axis=0)

t = time.time()
with mp.get_context("fork").Pool(4) as pool:
    EIG = pool.map(eigen_snr, list(LARGE))
print(f"eigen-SNR: {time.time() - t:.0f} s, components per session {min(map(len, EIG))} to "
      f"{max(map(len, EIG))}")
L = min(map(len, EIG))
E = np.array([e[:L] for e in EIG])
curve = E.mean(axis=0)
peak = int(np.argmax(curve)) + 1
share6 = curve[:6].sum() / curve.sum()
print(f"peak of the session-mean curve at component {peak}; first 10 values:", np.round(curve[:10], 4))
print(f"share of the first six in the sum over the {L} components common to all sessions: {share6:.3f}")
full_share = [e[:6].sum() / e.sum() for e in EIG]
print(f"share of the first six per session over all its components: median {np.median(full_share):.3f}")
per_sess_peak = np.array([int(np.argmax(e)) + 1 for e in EIG])
print("per-session peak component: median", np.median(per_sess_peak), "counts",
      dict(collections.Counter(per_sess_peak)))
mice_curves = pd.DataFrame(E, index=info.mouse[LARGE].values).groupby(level=0).mean()
print("per-mouse peak:", {m: int(np.argmax(r.values)) + 1 for m, r in mice_curves.iterrows()})
eigen-SNR: 145 s, components per session 14 to 92
peak of the session-mean curve at component 7; first 10 values: [0.0197 0.0364 0.0505 0.0609 0.0689 0.0719 0.073  0.072  0.0709 0.0693]
share of the first six in the sum over the 14 components common to all sessions: 0.358
share of the first six per session over all its components: median 0.103
per-session peak component: median 8.0 counts {np.int64(5): 8, np.int64(7): 11, np.int64(6): 9, np.int64(13): 3, np.int64(8): 6, np.int64(10): 2, np.int64(15): 2, np.int64(18): 2, np.int64(9): 6, np.int64(3): 1, np.int64(12): 4, np.int64(11): 1, np.int64(4): 6, np.int64(23): 2, np.int64(19): 1, np.int64(16): 2, np.int64(14): 3, np.int64(17): 1, np.int64(2): 1, np.int64(24): 1, np.int64(30): 1}
per-mouse peak: {'Mouse2011': 5, 'Mouse2012': 4, 'Mouse2019': 7, 'Mouse2021': 8, 'Mouse2022': 13, 'Mouse2023': 5, 'Mouse2024': 6, 'Mouse2025': 5, 'Mouse2026': 9, 'Mouse2028': 8}

Result: partially reproduced. The session-mean SNR along the noise components rises to its maximum at the seventh component (0.0730), with the sixth close (0.0719), against the paper's sixth; per-mouse peaks range from the 4th to the 13th. The first six carry 0.358 of the sum over the 14 components that all sessions have and a median 0.103 of each session's own sum, less than half under both.

fig4b-correlations-increase-noise-signal-overlap¶

Noise correlations increase the overlap (squared cosine) between the noise principal directions and the signal direction compared with shuffled data.

In [20]:
def _ovl(i):
    T, d = TENS[i]
    rows = hc30.overlap_measures(T, d, np.random.default_rng(5000 + i))
    r = {}
    for kind in ("cov", "corr"):
        r[f"area_all_{kind}"] = np.mean([x[f"{kind}_u_cos2"].sum() - x[f"{kind}_s_cos2"].sum() for x in rows])
        r[f"area_6_{kind}"] = np.mean([x[f"{kind}_u_cos2"][:6].sum() - x[f"{kind}_s_cos2"][:6].sum() for x in rows])
        r[f"ipr_cos2_{kind}"] = np.mean([x[f"{kind}_u_cos2"].sum() ** 2 / (x[f"{kind}_u_cos2"] ** 2).sum() for x in rows])
    r["pr_lambda"] = np.mean([x["cov_u_lam"].sum() ** 2 / (x["cov_u_lam"] ** 2).sum() for x in rows])
    r["nsv"] = np.mean([np.var(x["u2"]) for x in rows])
    r["var_dmu2"] = np.mean([np.var(x["dmu2"]) for x in rows])
    r["mean_dmu2"] = np.mean([np.mean(x["dmu2"]) for x in rows])
    return r

t = time.time()
with mp.get_context("fork").Pool(4) as pool:
    OV = pool.map(_ovl, list(LARGE))
OV = pd.DataFrame(OV, index=LARGE)
OV["mouse"] = info.mouse[LARGE].values
print(f"overlap measures: {time.time() - t:.0f} s")
for col in ("area_all_cov", "area_6_cov", "area_all_corr", "area_6_corr"):
    pm = OV.groupby("mouse")[col].mean()
    print(f"{col}: median session {OV[col].median():.4f}, positive in "
          f"{int((OV[col] > 0).sum())} of {len(OV)} sessions; animal means positive in "
          f"{int((pm > 0).sum())} of {len(pm)}; min animal mean {pm.min():.4f}")
overlap measures: 17 s
area_all_cov: median session 0.1188, positive in 73 of 73 sessions; animal means positive in 10 of 10; min animal mean 0.0656
area_6_cov: median session 0.1367, positive in 73 of 73 sessions; animal means positive in 10 of 10; min animal mean 0.0792
area_all_corr: median session 0.1997, positive in 73 of 73 sessions; animal means positive in 10 of 10; min animal mean 0.1525
area_6_corr: median session 0.0894, positive in 73 of 73 sessions; animal means positive in 10 of 10; min animal mean 0.0625

Result: reproduced. With all components (legend and code), the unshuffled minus shuffled sum of squared cosines is positive in 73 of 73 sessions (median 0.119) and in the means of 10 of 10 animals; up to the sixth component (Methods) and with correlation-matrix components it is also positive in every session and animal.

fig4c-overlap-predicts-asymptotic-snr¶

Across animals, the increase in noise and signal overlap caused by noise correlations is inversely correlated with the asymptotic SNR (r squared 0.50, p = 0.014), so the geometry of the noise predicts where information saturates.

In [21]:
def adj_r2(r, n):
    return 1 - (1 - r ** 2) * (n - 1) / (n - 2)

LS = SNR.loc[LARGE].copy()
for col in OV.columns:
    if col != "mouse":
        LS[col] = OV[col].values
agg = LS.groupby("mouse").mean(numeric_only=True)
for x in ("area_all_cov", "area_6_cov"):
    for y in ("asnr", "ratio"):
        r, p = stats.pearsonr(agg[x], agg[y])
        print(f"{x} vs {y} across {len(agg)} mice: r = {r:.3f}, r^2 = {r * r:.3f}, adjusted "
              f"{adj_r2(r, len(agg)):.3f}, p = {p:.4f}")
r, p = stats.pearsonr(LS.area_all_cov, LS.asnr)
print(f"across {len(LS)} sessions, area_all_cov vs asnr: r = {r:.3f}, p = {p:.2e}")
area_all_cov vs asnr across 10 mice: r = -0.743, r^2 = 0.552, adjusted 0.496, p = 0.0139
area_all_cov vs ratio across 10 mice: r = -0.304, r^2 = 0.093, adjusted -0.021, p = 0.3927
area_6_cov vs asnr across 10 mice: r = -0.441, r^2 = 0.195, adjusted 0.094, p = 0.2016
area_6_cov vs ratio across 10 mice: r = -0.301, r^2 = 0.091, adjusted -0.023, p = 0.3980
across 73 sessions, area_all_cov vs asnr: r = -0.356, p = 2.00e-03

Result: reproduced. Across the 10 mice the overlap change (all components) and the unshuffled asymptotic SNR give r = -0.743, r squared 0.552 (adjusted 0.496) and p = 0.0139, as the code printed (r = -0.744, adjusted 0.498, p = 0.0136). With the first six components (r = -0.441) or with the SNR ratio (r = -0.30) the correlation is not significant.

fig5f-pf-width-variance-vs-nsv¶

Across animals, the broader the distribution of place-field widths, the smaller the normalized signal variance (NSV) (Pearson r = -0.65, r squared 0.36, p = 0.039).

In [22]:
LS["nsv"] = [hc30.nsv(*TENS[i]) for i in LARGE]
LS["var_fwhm_cm"] = [hc30.var_fwhm_cm(*TENS[i]) for i in LARGE]
agg = LS.groupby("mouse").mean(numeric_only=True)
r, p = stats.pearsonr(agg.var_fwhm_cm, agg.nsv)
print(f"across {len(agg)} mice: Pearson r = {r:.3f}, r^2 = {r * r:.3f}, p = {p:.4f}")
r2_, p2_ = stats.pearsonr(LS.var_fwhm_cm, LS.nsv)
print(f"across {len(LS)} sessions: r = {r2_:.3f}, p = {p2_:.2e}")
print(agg[["var_fwhm_cm", "nsv"]].round(6))
print("NSV range over sessions: %.2e to %.2e; var FWHM %.0f to %.0f cm^2" % (
    LS.nsv.min(), LS.nsv.max(), LS.var_fwhm_cm.min(), LS.var_fwhm_cm.max()))
across 10 mice: Pearson r = -0.658, r^2 = 0.433, p = 0.0385
across 73 sessions: r = -0.140, p = 2.39e-01
           var_fwhm_cm       nsv
mouse                           
Mouse2011   633.744517  0.000139
Mouse2012   631.519182  0.000227
Mouse2019   623.561692  0.000129
Mouse2021   954.911355  0.000060
Mouse2022   870.371851  0.000092
Mouse2023   603.243257  0.000320
Mouse2024   603.053640  0.000149
Mouse2025   472.149931  0.000253
Mouse2026   662.846510  0.000279
Mouse2028   752.128248  0.000201
NSV range over sessions: 2.29e-05 to 4.02e-04; var FWHM 367 to 1270 cm^2

Result: reproduced. Across the 10 mice the variance of place-field widths and the NSV give r = -0.658, r squared 0.433 and p = 0.0385, within tolerance of -0.65, as the code printed (r = -0.657, p = 0.0389). Across the 73 sessions the correlation is weak (r = -0.140, p = 0.24).

fig5hi-nsv-predicts-noise-correlation-effect¶

Across animals, the NSV correlates with the ratio of asymptotic SNR with and without noise correlations (Pearson 0.83, r squared 0.65, p = 0.003); animals with a small NSV lose more information to noise correlations.

In [23]:
filt = (LS.asnr.abs() > LS.asnr_ci) & (LS.asnr_shuf.abs() > LS.asnr_shuf_ci) & (LS.ratio < 7) & (LS.noise_slope_shuf > 0)
print("sessions kept by the code's filters (values larger than their interval, ratio < 7):",
      int(filt.sum()), "of", len(LS))
for name, sub in (("no filter", LS), ("code filters", LS[filt])):
    for yname, y in (("unshuffled/shuffled", sub.ratio), ("shuffled/unshuffled", 1 / sub.ratio)):
        rs, ps = stats.pearsonr(sub.nsv, y)
        ag = pd.DataFrame({"nsv": sub.nsv, "y": y, "mouse": sub.mouse}).groupby("mouse").mean()
        ra, pa = stats.pearsonr(ag.nsv, ag.y)
        print(f"{name:12s} {yname}: sessions r = {rs:.3f} (p {ps:.2e}, n {len(sub)}); "
              f"animals r = {ra:.3f}, r^2 {ra * ra:.3f} (p {pa:.4f}, n {len(ag)})")
sessions kept by the code's filters (values larger than their interval, ratio < 7): 69 of 73
no filter    unshuffled/shuffled: sessions r = 0.716 (p 1.12e-12, n 73); animals r = 0.869, r^2 0.755 (p 0.0011, n 10)
no filter    shuffled/unshuffled: sessions r = -0.354 (p 2.10e-03, n 73); animals r = -0.620, r^2 0.384 (p 0.0561, n 10)
code filters unshuffled/shuffled: sessions r = 0.708 (p 9.93e-12, n 69); animals r = 0.872, r^2 0.760 (p 0.0010, n 10)
code filters shuffled/unshuffled: sessions r = -0.595 (p 7.04e-08, n 69); animals r = -0.826, r^2 0.683 (p 0.0032, n 10)

Result: reproduced. With the ratio unshuffled over shuffled, the NSV correlates across the 10 mice with r = 0.869 (p = 0.0011) and across the 73 sessions with r = 0.716 (p = 1.1e-12), both within tolerance of 0.83 and 0.76; with the code's filters (69 sessions) r = 0.872 and 0.708. The inverse ratio gives negative correlations, as expected.

suppl-table2-nsv-best-predictor¶

Of the variables tested, the NSV explains the effect of noise correlations on the asymptotic SNR best (highest adjusted R squared), and the result does not depend on the number of neurons or trials in a session.

In [24]:
LS["n_neurons"] = info.neurons[LARGE].values
LS["n_trials"] = (info.right + info.left)[LARGE].values
rng_t2 = np.random.default_rng(202)

def fixed_nsv(i, n=200, reps=100):
    T, d = TENS[i]
    return np.mean([hc30.nsv(T[rng_t2.choice(T.shape[0], n, replace=False)], d) for _ in range(reps)])

LS["fixed_nsv_200"] = [fixed_nsv(i) for i in LARGE]
variables = {"NSV": "nsv", "cos2 area, corr PCs": "area_all_corr", "Var((dmu_i)^2)": "var_dmu2",
             "# neurons": "n_neurons", "(sum lambda)^2 / sum lambda^2": "pr_lambda",
             "Mean((dmu_i)^2)": "mean_dmu2", "cos2 area, cov PCs": "area_all_cov",
             "Var(PF halfwidths)": "var_fwhm_cm", "IPR cos2, cov PCs": "ipr_cos2_cov",
             "# trials": "n_trials", "IPR cos2, corr PCs": "ipr_cos2_corr"}
for name, sub in (("all 73", LS), ("code filters", LS[filt])):
    out = []
    for lab, col in variables.items():
        r, p = stats.pearsonr(sub[col], sub.ratio)
        ag = sub.groupby("mouse")[[col, "ratio"]].mean()
        ra, pa = stats.pearsonr(ag[col], ag.ratio)
        out.append((lab, r, p, adj_r2(r, len(sub)), ra, pa, adj_r2(ra, len(ag))))
    tab2 = pd.DataFrame(out, columns=["variable", "r", "p", "adjR2", "r_agg", "p_agg", "adjR2_agg"])
    print(f"\n{name} (n = {len(sub)}), y = asymptotic SNR ratio unshuffled/shuffled")
    print(tab2.sort_values("adjR2", ascending=False).round(4).to_string(index=False))
r, p = stats.pearsonr(LS.fixed_nsv_200, LS.ratio)
ag = LS.groupby("mouse")[["fixed_nsv_200", "ratio"]].mean()
ra, pa = stats.pearsonr(ag.fixed_nsv_200, ag.ratio)
print(f"\nNSV at a fixed 200 neurons (100 subsets) vs ratio: sessions r = {r:.3f}, p = {p:.2e}; "
      f"animals r = {ra:.3f}, p = {pa:.4f}")
all 73 (n = 73), y = asymptotic SNR ratio unshuffled/shuffled
                     variable       r      p   adjR2   r_agg  p_agg  adjR2_agg
                          NSV  0.7156 0.0000  0.5052  0.8688 0.0011     0.7241
                    # neurons -0.4498 0.0001  0.1911 -0.6331 0.0494     0.3260
(sum lambda)^2 / sum lambda^2 -0.3016 0.0095  0.0781 -0.6720 0.0333     0.3830
          cos2 area, corr PCs -0.2938 0.0116  0.0735 -0.6541 0.0402     0.3563
               Var((dmu_i)^2)  0.2686 0.0216  0.0591  0.7255 0.0176     0.4671
           Var(PF halfwidths) -0.2402 0.0407  0.0444 -0.5712 0.0846     0.2421
           cos2 area, cov PCs -0.2351 0.0453  0.0420 -0.3043 0.3927    -0.0208
              Mean((dmu_i)^2)  0.2054 0.0813  0.0287  0.6044 0.0642     0.2859
                     # trials -0.2051 0.0817  0.0286 -0.5718 0.0842     0.2428
            IPR cos2, cov PCs -0.1878 0.1116  0.0217 -0.6052 0.0638     0.2870
           IPR cos2, corr PCs -0.0591 0.6196 -0.0105 -0.4782 0.1621     0.1323

code filters (n = 69), y = asymptotic SNR ratio unshuffled/shuffled
                     variable       r      p   adjR2   r_agg  p_agg  adjR2_agg
                          NSV  0.7083 0.0000  0.4943  0.8716 0.0010     0.7296
                    # neurons -0.4945 0.0000  0.2333 -0.6643 0.0362     0.3715
          cos2 area, corr PCs -0.3964 0.0007  0.1446 -0.6922 0.0265     0.4140
(sum lambda)^2 / sum lambda^2 -0.3543 0.0028  0.1125 -0.6950 0.0257     0.4184
                     # trials -0.3374 0.0046  0.1006 -0.6622 0.0370     0.3683
            IPR cos2, cov PCs -0.3163 0.0081  0.0866 -0.6732 0.0329     0.3848
           cos2 area, cov PCs -0.2185 0.0713  0.0335 -0.2536 0.4796    -0.0527
           Var(PF halfwidths) -0.1986 0.1018  0.0251 -0.5825 0.0772     0.2567
           IPR cos2, corr PCs -0.1922 0.1136  0.0226 -0.5782 0.0800     0.2511
               Var((dmu_i)^2)  0.1883 0.1212  0.0211  0.7182 0.0193     0.4553
              Mean((dmu_i)^2)  0.0737 0.5473 -0.0094  0.6121 0.0600     0.2965

NSV at a fixed 200 neurons (100 subsets) vs ratio: sessions r = 0.475, p = 2.18e-05; animals r = 0.730, p = 0.0166

Result: reproduced. Of the eleven variables the NSV has the highest adjusted R squared across sessions (0.505, next the number of neurons at 0.191), with and without the filters, and across animals (0.724). At a fixed 200 neurons the NSV still correlates with the ratio across sessions (r = 0.475, p = 2.2e-05) and animals (r = 0.730, p = 0.017). As in the paper's table, the number of neurons correlates with the ratio (r = -0.450, p = 1e-04) and the number of trials less (r = -0.205, p = 0.08).

pf-width-variance-not-predictive¶

The variance of place-field widths or amplitudes does not directly correlate with the effect of noise correlations on information saturation.

In [25]:
def var_amp(i):
    T, d = TENS[i]
    return np.var(np.concatenate([T[:, :, d == s].mean(axis=2).max(axis=1) for s in (1, -1)]), ddof=1)

LS["var_amp"] = [var_amp(i) for i in LARGE]
for col in ("var_fwhm_cm", "var_amp"):
    for name, sub in (("all 73", LS), ("code filters", LS[filt])):
        r, p = stats.pearsonr(sub[col], sub.ratio)
        ag = sub.groupby("mouse")[[col, "ratio"]].mean()
        ra, pa = stats.pearsonr(ag[col], ag.ratio)
        print(f"{col:12s} {name:12s}: sessions r = {r:.3f}, p = {p:.3f} (n {len(sub)}); "
              f"animals r = {ra:.3f}, p = {pa:.3f} (n {len(ag)})")
# The filter of Supplementary Table 2 drops values whose 95% interval is larger than the value. The
# intervals here are delta-method intervals from the line slopes' standard errors (z = 1.96); the
# paper's intervals are over subsets. Other interval widths, and the sessions each drops:
se_a, se_s = LS.asnr_ci / 1.96, LS.asnr_shuf_ci / 1.96
for z in (1.0, 1.645, 1.96, 2.576, 3.0):
    fz = (LS.asnr.abs() > z * se_a) & (LS.asnr_shuf.abs() > z * se_s) & (LS.ratio < 7) & (LS.noise_slope_shuf > 0)
    sub = LS[fz]
    r, p = stats.pearsonr(sub.var_fwhm_cm, sub.ratio)
    ag = sub.groupby("mouse")[["var_fwhm_cm", "ratio"]].mean()
    ra, pa = stats.pearsonr(ag.var_fwhm_cm, ag.ratio)
    print(f"interval z = {z:5.3f}: {int(fz.sum())} sessions kept; sessions r = {r:.3f}, p = {p:.3f}; "
          f"animals r = {ra:.3f}, p = {pa:.3f}; dropped {[int(k) for k in LS.index[~fz]]}")
print("sessions dropped at z = 1.96, with their ratio and var(FWHM):")
print(LS.loc[~filt, ["mouse", "ratio", "asnr", "asnr_ci", "asnr_shuf", "asnr_shuf_ci", "var_fwhm_cm"]].round(3))
# leave-one-out on the 73 sessions: how many single sessions move p across 0.05
loo = [stats.pearsonr(LS.var_fwhm_cm.drop(k), LS.ratio.drop(k))[1] for k in LS.index]
print(f"leave one session out of 73: p from {min(loo):.3f} to {max(loo):.3f}; "
      f"p >= 0.05 after dropping {sum(q >= 0.05 for q in loo)} of the 73 single sessions")
var_fwhm_cm  all 73      : sessions r = -0.240, p = 0.041 (n 73); animals r = -0.571, p = 0.085 (n 10)
var_fwhm_cm  code filters: sessions r = -0.199, p = 0.102 (n 69); animals r = -0.583, p = 0.077 (n 10)
var_amp      all 73      : sessions r = 0.327, p = 0.005 (n 73); animals r = 0.746, p = 0.013 (n 10)
var_amp      code filters: sessions r = 0.227, p = 0.061 (n 69); animals r = 0.774, p = 0.009 (n 10)
interval z = 1.000: 71 sessions kept; sessions r = -0.228, p = 0.056; animals r = -0.577, p = 0.081; dropped [84, 92]
interval z = 1.645: 70 sessions kept; sessions r = -0.201, p = 0.096; animals r = -0.581, p = 0.078; dropped [51, 84, 92]
interval z = 1.960: 69 sessions kept; sessions r = -0.199, p = 0.102; animals r = -0.583, p = 0.077; dropped [51, 83, 84, 92]
interval z = 2.576: 67 sessions kept; sessions r = -0.189, p = 0.125; animals r = -0.581, p = 0.078; dropped [20, 30, 51, 83, 84, 92]
interval z = 3.000: 63 sessions kept; sessions r = -0.189, p = 0.139; animals r = -0.571, p = 0.085; dropped [19, 20, 21, 24, 30, 51, 64, 83, 84, 92]
sessions dropped at z = 1.96, with their ratio and var(FWHM):
        mouse  ratio   asnr  asnr_ci  asnr_shuf  asnr_shuf_ci  var_fwhm_cm
51  Mouse2012  0.028  0.014    0.005      0.492         0.715     1000.774
83  Mouse2011  0.098  0.007    0.005      0.067         0.077      538.887
84  Mouse2011  0.004  0.011    0.012      2.648        76.074      425.970
92  Mouse2011  0.002  0.009    0.001      3.992        14.052     1226.423
leave one session out of 73: p from 0.014 to 0.127; p >= 0.05 after dropping 11 of the 73 single sessions

Result: reproduced, resting on the filter of Supplementary Table 2. With the table's filter (values whose confidence interval is larger than the value left out; 69 of 73 sessions with the intervals built here) the variance of place-field widths does not correlate with the asymptotic SNR ratio across sessions (r = -0.199, p = 0.102) or animals (r = -0.583, p = 0.077). The four sessions the filter drops (51, 83, 84 and 92) are four of the six whose events do not track the position. Intervals of 1 to 3 standard errors keep 63 to 71 sessions and give p = 0.056 to 0.139 across sessions and 0.077 to 0.085 across animals. Without the filter the session-level test gives r = -0.240, p = 0.041, below 0.05, and leaving out any one of 11 of the 73 sessions brings p above 0.05. The variance of place-field amplitudes, which the text also names, does correlate with the ratio across animals (r = 0.746, p = 0.013; filtered r = 0.774, p = 0.009), against the text's "or amplitudes".

fig5cd-synthetic-narrow-widths-broader-nsv¶

In synthetic Gaussian place-field populations, a narrow distribution of field widths gives a broader distribution of PF slopes, a higher NSV, than a broad width distribution, up to ten thousand neurons.

A simulation of the paper's model (data: elsewhere); no dataset values are used. Centres uniform over the 20-bin track (continuous), amplitude 1, tuning evaluated at the 20 bin centres.

In [26]:
rng_5 = np.random.default_rng(55)
centers_x = np.arange(20) + 0.5

def sim_nsv(n_cells, halfwidths):
    c = rng_5.uniform(0, 20, n_cells)
    sigma = halfwidths / np.sqrt(2 * np.log(2))  # half-width at half maximum to SD
    F = np.exp(-0.5 * ((centers_x[None, :] - c[:, None]) / sigma[:, None]) ** 2)
    D = np.diff(F, axis=1)
    U = D / np.linalg.norm(D, axis=0, keepdims=True)
    return np.var(U ** 2, axis=0)  # per bin pair

readings = {
    "legend, uniform half-widths": (lambda n: rng_5.uniform(0.2, 1.42, n), lambda n: rng_5.uniform(0.8, 2.0, n)),
    "Methods, log-normal half-widths": (lambda n: np.exp(rng_5.normal(0, np.sqrt(0.3), n)),
                                        lambda n: np.exp(rng_5.normal(0, np.sqrt(2.0), n))),
}
for name, (narrow, broad) in readings.items():
    a = np.array([sim_nsv(50, narrow(50)) for _ in range(1000)])
    b = np.array([sim_nsv(50, broad(50)) for _ in range(1000)])
    print(f"{name}, 50 cells, 1000 simulations: median NSV narrow {np.nanmedian(a):.4f}, broad "
          f"{np.nanmedian(b):.4f}; narrow higher: {np.nanmedian(a) > np.nanmedian(b)}")
    line = []
    for n in (100, 1000, 10000):
        reps = 50 if n == 10000 else 200
        a = np.nanmean([sim_nsv(n, narrow(n)).mean() for _ in range(reps)])
        b = np.nanmean([sim_nsv(n, broad(n)).mean() for _ in range(reps)])
        line.append(f"{n}: {a:.2e} vs {b:.2e}")
    print("   mean NSV narrow vs broad by ensemble size ->", "; ".join(line))
legend, uniform half-widths, 50 cells, 1000 simulations: median NSV narrow 0.0033, broad 0.0020; narrow higher: True
   mean NSV narrow vs broad by ensemble size -> 100: 9.33e-04 vs 5.44e-04; 1000: 9.16e-06 vs 5.39e-06; 10000: 9.14e-08 vs 5.40e-08
Methods, log-normal half-widths, 50 cells, 1000 simulations: median NSV narrow 0.0030, broad 0.0044; narrow higher: False
   mean NSV narrow vs broad by ensemble size -> 100: 8.53e-04 vs 1.38e-03; 1000: 8.59e-06 vs 1.42e-05; 10000: 8.58e-08 vs 1.42e-07

Result: reproduced, resting on the legend's width distributions. With the legend's uniform half-widths the median NSV is higher for the narrow distribution (0.0033 against 0.0020), and the mean NSV stays higher for it at 100, 1,000 and 10,000 neurons. With the Methods' log-normal half-widths the broad distribution has the higher NSV (0.0044 against 0.0030), at every size.

Summary¶

Claim Outcome
data-sessions-and-neurons reproduced
single-cell-variability reproduced
suppl-table1-place-field-properties not reproduced (assumed: runaway width fits left out)
fig1d-noise-correlation-by-field-distance reproduced
noise-correlation-not-physical-distance blocked: data missing (no cell positions)
position-measurement-noise reproduced
fig3cd-signal-and-noise-growth reproduced
suppl10-asymptotic-snr-lower-with-correlations reproduced
fig3f-signal-slope-beginning-vs-end reproduced (assumed: the code's direction)
fig3g-noise-slope-decreases-over-run reproduced
fig3h-snr-higher-at-run-end reproduced
fig4a-snr-along-noise-pcs-peaks-at-6 partially reproduced
fig4b-correlations-increase-noise-signal-overlap reproduced
fig4c-overlap-predicts-asymptotic-snr reproduced
fig5f-pf-width-variance-vs-nsv reproduced
fig5hi-nsv-predicts-noise-correlation-effect reproduced
suppl-table2-nsv-best-predictor reproduced
pf-width-variance-not-predictive reproduced (assumed: the filter of Supplementary Table 2)
fig5cd-synthetic-narrow-widths-broader-nsv reproduced (assumed: the legend's widths; 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: signal and noise use 20 neuron subsets per ensemble size in place of 80; the event trace is rebuilt from the deposited onsets with the Methods' alpha kernel; the place-field table rests on readings the paper leaves open. The decoding claims are in the second notebook.

What was found about the dataset: the file holds the 110 working sessions only, as event onsets (single frames with amplitudes), not the convolved trace the paper analyses. Sessions last about 30 min at 20 Hz (20 to 46), not about 20 min. Four sessions have position values far below the track (down to -3.7e7 pixels). Two session IDs join two recordings, one of them with 6 times the usual event rate. In six sessions the event trace does not track the position at lag 0: in two (Mouse2012 141832, Mouse2011 142436) it does at a lag of 80 to 90 frames, and in two (Mouse2011 105556 and 104511) at no lag within 200 frames. There are no cell positions.

In [27]:
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 14.0 min; peak memory 1.9 GB