Drieu, Todorova & Zugaro (2018) on CRCNS hc-18: decoding controls, other readings and bias correlations¶

Paper. C. Drieu, R. Todorova, M. Zugaro (2018), Science 362:675-679, doi:10.1126/science.aat2952; claims file claims/drieu-2018.yaml (version of record, and the author manuscript HAL hal-02330673v1 for the Methods and supplement).

Dataset. CRCNS hc-18 (doi:10.6080/K0Z899MM), unversioned (CRCNS does not version data sets); the only published copy, hc-18/live/ in the bucket crcnsarchive, which the paper cites. Streamed and reduced in memory by drieu2018.py, as in the other two notebooks.

This notebook was added after round 1 of verification. It runs the controls of figs. S7, S8 and S10, the cross-validated decoding error for fig. S9, the pairwise bias correlations of Figs. 3G and 4G on random samples of pairs, and the theta and replay decoding under the readings the decoding notebook does not run (field reading b; the whole-session threshold for candidate events). To fit the 60-minute limit it uses 100 shuffles per event (the decoding notebook 200, the paper 5000), and the replay readings are run on a random fifth of the candidate events.

claim here
figs7-control-cell-count tested
figs8-control-firing-rate tested
figs10-control-lap-variability tested
fig3g-theta-self-consistency tested on a random sample of pairs
fig4g-theta-replay-correlation-active tested on a random sample of pairs
figs9-control-decoding-quality cross-validated error shown here; tested in the decoding notebook
theta and replay claims of the decoding notebook other readings shown here; tested in the decoding notebook
In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "4")
import time, resource, gc
import numpy as np
import pandas as pd
from scipy import stats
import drieu2018 as D

T_START = time.time()
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)
NSH = 100
BIN_M = D.TRACK_M / D.NBINS
In [2]:
sums = D.checksums()
for n in [f"data/{r}.tar.gz" for r in D.RATS]:
    print(f"{sums[n]}  {n}")
4fa842b93dbf288365b3ea4aa531190f  data/Train-242-20140124.tar.gz
31f4ca8bc7b0bb1b81ea3bf63e2d8971  data/Train-261-20140617.tar.gz
939f5b02ec3e44e60b9a208a27924cd3  data/Train-272-20141215.tar.gz
6e54c694602383fc42fb5a1c35872cc4  data/Train-292-20150501.tar.gz
22ce341480a9239d20e7e7750a803f28  data/Train-314-20160118.tar.gz
In [3]:
RAT, PREP, LFPS = {}, {}, {}
for name in D.RATS:
    t = time.time()
    r = D.load_rat(name)
    P = D.prepare(r)
    LF = D.reduce_lfp(r, P)
    r["lfp_shape"] = r["lfp"]["data"].shape
    del r["lfp"]
    RAT[name], PREP[name], LFPS[name] = r, P, LF
    gc.collect()
    print(f"{name}: {time.time() - t:.0f} s, peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
Train-242-20140124: streamed in 98 s
Train-242-20140124: 215 s, peak memory 3.6 GB
Train-261-20140617: streamed in 82 s
Train-261-20140617: 184 s, peak memory 3.8 GB
Train-272-20141215: streamed in 165 s
Train-272-20141215: 310 s, peak memory 4.6 GB
Train-292-20150501: streamed in 171 s
Train-292-20150501: 266 s, peak memory 5.6 GB
Train-314-20160118: streamed in 302 s
Train-314-20160118: 502 s, peak memory 6.4 GB

Theta cycles decoded under field readings (a) and (b)¶

As in the decoding notebook (cell "Decoding theta cycles"), with 100 shuffles. Reading (a) is the decoding notebook's; it is the reference for the controls below. Reading (b) keeps place cells whose peak field spans at least 10 bins (claims file, Common methods).

In [4]:
def slope_ms(Dv, m, dur_s):
    """m/s from a line's displacement D (bins) over m windows lasting dur_s in total."""
    return Dv / (m - 1) * BIN_M / (dur_s / m)

def table(name, c, th, sc, extra=None):
    q = D.quadrant_scores(th["cent"])
    rows = []
    for e in range(len(th["mats"])):
        rows.append(dict(rat=name[6:9], cond=c, score=sc["score"][e], z=sc["z"][e], p=sc["p"][e], D=sc["D"][e],
                         dur=th["dur"][e], quad=q[e], t=th["edges"][e, 0], slope=slope_ms(sc["D"][e], 6, th["dur"][e]), **(extra or {})))
    return rows

EDGES = {(n, c): D.theta_windows(PREP[n], LFPS[n], c) for n in D.RATS for c in D.CONDS}
THC, CYR = {}, {}
for rd in ["a", "b"]:
    rows = []
    t0 = time.time()
    for k, name in enumerate(D.RATS):
        P = PREP[name]
        for j, c in enumerate(D.CONDS):
            cells = D.place_cells(P, c, rd)
            px, lam = D.train_decoder(P, c, cells, rd)
            th = D.decode_cycles(P, EDGES[(name, c)], [P["cond"][c]["cells"][i]["spk_t"] for i in cells], px, lam)
            sc = D.score_events(th["mats"], NSH, np.random.default_rng(7000 + 100 * (rd == "b") + 10 * k + j))
            THC[(rd, name, c)] = (th, sc)
            rows += table(name, c, th, sc)
    CYR[rd] = pd.DataFrame(rows)
    print(f"field reading {rd}: cycles analysed {CYR[rd].groupby('cond').size().reindex(D.CONDS).to_dict()} ({time.time() - t0:.0f} s)")
field reading a: cycles analysed {'P1': 8429, 'A': 7617, 'P2': 6998} (175 s)
field reading b: cycles analysed {'P1': 8359, 'A': 7615, 'P2': 6925} (172 s)
In [5]:
def theta_tests(CY, label):
    """The tests of fig3c, fig3d and fig3f on a table of decoded cycles."""
    g = {c: CY[CY.cond == c] for c in D.CONDS}
    sig = {c: v[v.p <= 0.05] for c, v in g.items()}
    out = dict(label=label, n=[len(v) for v in g.values()])
    out["pct_sig_pos"] = [round(100 * ((v.p <= 0.05) & (v.D > 0)).mean(), 2) for v in g.values()]
    out["z_median"] = [round(v.z.median(), 3) for v in g.values()]
    out["z_KW_P"] = f"{stats.kruskal(*[v.z for v in g.values()]).pvalue:.1e}"
    out["quad_median"] = [round(v.quad.median(), 4) for v in g.values()]
    out["quad_KW_P"] = f"{stats.kruskal(*[v.quad.dropna() for v in g.values()]).pvalue:.1e}"
    out["sig_slope_median"] = [round(v.slope.median(), 2) for v in sig.values()]
    out["sig_slope_KW_P"] = f"{stats.kruskal(*[v.slope for v in sig.values()]).pvalue:.1e}"
    for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
        out[f"KS_{a}-{b}"] = f"{stats.ks_2samp(sig[a].slope, sig[b].slope).pvalue:.1e}"
    return out

print(pd.DataFrame([theta_tests(CYR[rd], f"field reading {rd}") for rd in ["a", "b"]]).T.to_string())
print("per rat median normalized score, reading b:")
print(CYR["b"].groupby(["rat", "cond"]).z.median().unstack().reindex(columns=D.CONDS).round(3).to_string())
                                         0                         1
label                      field reading a           field reading b
n                       [8429, 7617, 6998]        [8359, 7615, 6925]
pct_sig_pos           [7.79, 12.51, 10.59]       [7.58, 12.49, 9.98]
z_median             [0.466, 0.678, 0.663]     [0.481, 0.675, 0.669]
z_KW_P                             2.2e-38                   1.9e-34
quad_median       [0.0053, 0.0503, 0.0127]  [0.0051, 0.0495, 0.0129]
quad_KW_P                          1.1e-65                   2.6e-64
sig_slope_median        [0.24, 2.41, 0.46]          [0.2, 2.5, 0.43]
sig_slope_KW_P                     3.3e-12                   2.5e-15
KS_P1-A                            4.5e-14                   6.0e-18
KS_A-P2                            7.0e-12                   4.6e-11
KS_P1-P2                           1.2e-01                   1.8e-01
per rat median normalized score, reading b:
cond     P1      A     P2
rat                      
242   0.253  0.332  0.661
261   0.512  0.646  0.573
272   0.561  0.957  0.843
292   0.514  0.474  0.580
314   0.559  0.905  0.624

Field reading (b). The theta results do not depend on the field reading: under (b) the proportions significant with positive slope are 7.58%, 12.49% and 9.98%, normalized scores differ (Kruskal-Wallis P = 1.9 x 10^-34), quadrant scores too (P = 2.6 x 10^-64), and signed slopes of significant sequences differ between Active and each passive condition (KS P = 6.0 x 10^-18 and 4.6 x 10^-11) but not between the passive conditions (P = 0.18). Reading (a), with 100 shuffles, gives the same tests as the decoding notebook but slightly different proportions (7.79%, 12.51% and 10.59% against 7.34%, 12.04% and 9.86%).

figs7-control-cell-count¶

"With Active and Passive 2 restricted to random subsets matching the Passive 1 place-cell count, theta sequences were still degraded in passive travel; slopes, normalized scores and quadrant scores still differed."

Per rat, random subsets of the Active and Passive 2 place cells (reading a) of the size of its Passive 1 set; the decoder is trained on the subset and up to 300 theta cycles are taken at random from those it decodes (Methods, control (i)). The Methods use 30 repetitions; 10 are run here, for time. Passive 1 is the reading-(a) decoding above.

In [6]:
NREP = 10
rows = []
t0 = time.time()
for k, name in enumerate(D.RATS):
    P = PREP[name]
    n1 = len(D.place_cells(P, "P1", "a"))
    for j, c in enumerate(["A", "P2"]):
        pcs = np.array(D.place_cells(P, c, "a"))
        rng = np.random.default_rng(7100 + 10 * k + j)
        for rep in range(NREP):
            cells = list(rng.choice(pcs, min(n1, len(pcs)), replace=False))
            px, lam = D.train_decoder(P, c, cells, "a")
            th = D.decode_cycles(P, EDGES[(name, c)], [P["cond"][c]["cells"][i]["spk_t"] for i in cells], px, lam)
            pick = np.sort(rng.choice(len(th["mats"]), min(300, len(th["mats"])), replace=False))
            th = dict(mats=[th["mats"][i] for i in pick], cent=th["cent"][pick], dur=th["dur"][pick], edges=th["edges"][pick])
            sc = D.score_events(th["mats"], NSH, rng)
            rows += table(name, c, th, sc, dict(rep=rep, n_cells=len(cells)))
CY7 = pd.concat([CYR["a"][CYR["a"].cond == "P1"], pd.DataFrame(rows)], ignore_index=True)
print(f"{time.time() - t0:.0f} s; cells per subset (= Passive 1 count, or all when fewer):",
      {n[6:9]: len(D.place_cells(PREP[n], "P1", "a")) for n in D.RATS})
print(pd.Series(theta_tests(CY7, "cell-count control")).to_string())
385 s; cells per subset (= Passive 1 count, or all when fewer): {'242': 31, '261': 14, '272': 67, '292': 25, '314': 70}
label                    cell-count control
n                      [8429, 15000, 15000]
pct_sig_pos            [7.79, 11.61, 10.37]
z_median              [0.466, 0.643, 0.659]
z_KW_P                              5.5e-34
quad_median         [0.0053, 0.0457, 0.013]
quad_KW_P                           2.1e-96
sig_slope_median         [0.24, 2.37, 0.45]
sig_slope_KW_P                      2.3e-17
KS_P1-A                             3.8e-17
KS_A-P2                             3.9e-24
KS_P1-P2                            4.9e-03
In [7]:
def criterion_check(CY, thr_pair=0.05, label=""):
    """The parts of the figs7, figs8 and figs10 criteria on a table of decoded cycles: the Active effects (slopes of
    significant cycles, KS against each passive condition with Active steeper; normalized and quadrant scores,
    Kruskal-Wallis with Active highest, and post hoc rank-sum tests of Active against each passive condition,
    Bonferroni x3), and the passive-pair slope test. Prints the largest P of the Active effects, so that the bound
    they reach (10^-6, 0.001 or neither) can be read, and whether Active is steepest and highest."""
    g = {c: CY[CY.cond == c] for c in D.CONDS}
    sig = {c: v[v.p <= 0.05].slope for c, v in g.items()}
    ps, order = {}, {}
    for a in ["P1", "P2"]:
        ps[f"slope KS A vs {a}"] = stats.ks_2samp(sig["A"], sig[a]).pvalue
    order["slope: Active steepest (median)"] = sig["A"].median() > max(sig["P1"].median(), sig["P2"].median())
    for col, nm in [("z", "normalized score"), ("quad", "quadrant score")]:
        v = {c: x[col].dropna() for c, x in g.items()}
        ps[f"{nm} KW"] = stats.kruskal(*v.values()).pvalue
        for a in ["P1", "P2"]:
            ps[f"{nm} rank-sum A vs {a} (Bonferroni x3)"] = min(1, 3 * stats.mannwhitneyu(v["A"], v[a]).pvalue)
        order[f"{nm}: Active highest (median)"] = v["A"].median() > max(v["P1"].median(), v["P2"].median())
    for k, p in ps.items():
        print(f"   {k}: P = {p:.1e}")
    for k, o in order.items():
        print(f"   {k}: {o}")
    worst = max(ps.values())
    pp = stats.ks_2samp(sig["P1"], sig["P2"]).pvalue
    print(f"   {label}largest P of the Active effects {worst:.1e}: below 10^-6 {worst < 1e-6}, below 0.001 {worst < 1e-3}; "
          f"Active steepest and highest in every part {all(order.values())}; passive-pair slope KS P = {pp:.1e} (> {thr_pair}: {pp > thr_pair})")

print("figs7, cell-count control:")
criterion_check(CY7)
figs7, cell-count control:
   slope KS A vs P1: P = 3.8e-17
   slope KS A vs P2: P = 3.9e-24
   normalized score KW: P = 5.5e-34
   normalized score rank-sum A vs P1 (Bonferroni x3): P = 1.0e-29
   normalized score rank-sum A vs P2 (Bonferroni x3): P = 1.0e+00
   quadrant score KW: P = 2.1e-96
   quadrant score rank-sum A vs P1 (Bonferroni x3): P = 3.6e-76
   quadrant score rank-sum A vs P2 (Bonferroni x3): P = 1.2e-63
   slope: Active steepest (median): True
   normalized score: Active highest (median): False
   quadrant score: Active highest (median): True
   largest P of the Active effects 1.0e+00: below 10^-6 False, below 0.001 False; Active steepest and highest in every part False; passive-pair slope KS P = 4.9e-03 (> 0.05: False)

Result: not reproduced. With Active and Passive 2 restricted to subsets of the Passive 1 size, significant slopes still differ between Active and each passive condition (KS P = 3.8 x 10^-17 and 3.9 x 10^-24; medians 0.24, 2.37 and 0.45 m/s), and quadrant scores still differ (Kruskal-Wallis P = 2.1 x 10^-96, Active highest, median 0.0457). Normalized scores differ (P = 5.5 x 10^-34) but Passive 2 (median 0.659) is above Active (0.643), and Passive 1 differs from Passive 2 (P = 0.0049), where the claim needs P > 0.05. Post hoc, Active does not exceed Passive 2 in normalized scores (Bonferroni P = 1.0). The Active effects do not hold even at 0.001, which neither clause of the criterion covers (changed from partially reproduced after round 3 of verification). Ten subsets per rat were run, not 30.

figs8-control-firing-rate¶

"With Active and Passive 2 spikes downsampled to match the Passive 1 median firing rate, theta sequences were still degraded in passive travel."

Per rat, a random 10% of the spikes of the most active Active (or Passive 2) place cell is removed, repeatedly, until the median rate of the condition's place cells is below the Passive 1 median (Methods, control (ii)). The decoder is trained on the downsampled spikes. Reading (a): the rate is the mean rate over the travel's moving periods; reading (b): the peak of the firing curve.

In [8]:
def cell_rates(P, c, cells, spikes, reading):
    if reading == "a":
        dur = P["cond"][c]["n_occ"] / D.POS_FS
        return np.array([len(s) / dur for s in spikes])
    px, lam = D.train_on(P, c, cells, lambda t: np.ones(len(t), bool), spikes=spikes)
    return lam.max(1)

R8, rows8 = {}, []
t0 = time.time()
for reading in ["a", "b"]:
    rows = []
    for k, name in enumerate(D.RATS):
        P = PREP[name]
        rng = np.random.default_rng(7200 + 100 * (reading == "b") + k)
        c1 = D.place_cells(P, "P1", "a")
        m1 = np.median(cell_rates(P, "P1", c1, [P["cond"]["P1"]["cells"][i]["spk_t"] for i in c1], reading))
        for c in ["P1", "A", "P2"]:
            cells = D.place_cells(P, c, "a")
            spikes = [P["cond"][c]["cells"][i]["spk_t"].copy() for i in cells]
            r = cell_rates(P, c, cells, spikes, reading)
            if c != "P1":
                while np.median(r) >= m1:
                    i = int(np.argmax(r))
                    s = spikes[i]
                    spikes[i] = np.sort(rng.choice(s, int(np.floor(0.9 * len(s))), replace=False))
                    r[i] = cell_rates(P, c, [cells[i]], [spikes[i]], reading)[0]
            for x in r:
                rows8.append(dict(reading=reading, rat=name[6:9], cond=c, rate=x))
            if c == "P1":
                rows += [d for d in table(name, c, *THC[("a", name, c)])]
                continue
            px, lam = D.train_on(P, c, cells, lambda t: np.ones(len(t), bool), spikes=spikes)
            th = D.decode_cycles(P, EDGES[(name, c)], spikes, px, lam)
            sc = D.score_events(th["mats"], NSH, rng)
            rows += table(name, c, th, sc)
    R8[reading] = pd.DataFrame(rows)
RT8 = pd.DataFrame(rows8)
print(f"{time.time() - t0:.0f} s")
for reading in ["a", "b"]:
    rt = RT8[RT8.reading == reading]
    g = [rt[rt.cond == c].rate.values for c in D.CONDS]
    print(f"rate reading {reading}: place-cell rate after downsampling (Hz), mean {[round(v.mean(), 3) for v in g]}, median {[round(np.median(v), 3) for v in g]}; "
          f"KW P = {stats.kruskal(*g).pvalue:.2f}; expected means 0.905, 0.933, 0.829 (+/- 0.145, 0.083, 0.13)")
    print(pd.Series(theta_tests(R8[reading], f"firing-rate control, reading {reading}")).to_string())
176 s
rate reading a: place-cell rate after downsampling (Hz), mean [np.float64(1.94), np.float64(1.191), np.float64(1.212)], median [np.float64(1.143), np.float64(0.92), np.float64(0.883)]; KW P = 0.02; expected means 0.905, 0.933, 0.829 (+/- 0.145, 0.083, 0.13)
label               firing-rate control, reading a
n                               [8429, 5644, 6771]
pct_sig_pos                     [7.79, 8.98, 8.17]
z_median                     [0.466, 0.481, 0.546]
z_KW_P                                     4.8e-03
quad_median               [0.0053, 0.0407, 0.0113]
quad_KW_P                                  1.9e-30
sig_slope_median                [0.24, 1.56, 0.36]
sig_slope_KW_P                             5.7e-07
KS_P1-A                                    7.3e-09
KS_A-P2                                    2.9e-07
KS_P1-P2                                   8.7e-01
rate reading b: place-cell rate after downsampling (Hz), mean [np.float64(3.758), np.float64(2.358), np.float64(2.467)], median [np.float64(2.511), np.float64(2.378), np.float64(2.294)]; KW P = 0.03; expected means 0.905, 0.933, 0.829 (+/- 0.145, 0.083, 0.13)
label               firing-rate control, reading b
n                               [8429, 5367, 5865]
pct_sig_pos                     [7.79, 6.67, 7.25]
z_median                     [0.466, 0.396, 0.481]
z_KW_P                                     4.3e-09
quad_median                 [0.0053, 0.03, 0.0092]
quad_KW_P                                  3.3e-19
sig_slope_median                [0.24, 1.19, 0.39]
sig_slope_KW_P                             3.6e-02
KS_P1-A                                    3.0e-05
KS_A-P2                                    7.5e-03
KS_P1-P2                                   2.3e-01
In [9]:
for reading in ["a", "b"]:
    print(f"figs8, firing-rate control, rate reading {reading}:")
    criterion_check(R8[reading], 0.1)
figs8, firing-rate control, rate reading a:
   slope KS A vs P1: P = 7.3e-09
   slope KS A vs P2: P = 2.9e-07
   normalized score KW: P = 4.8e-03
   normalized score rank-sum A vs P1 (Bonferroni x3): P = 1.0e+00
   normalized score rank-sum A vs P2 (Bonferroni x3): P = 3.1e-02
   quadrant score KW: P = 1.9e-30
   quadrant score rank-sum A vs P1 (Bonferroni x3): P = 9.3e-31
   quadrant score rank-sum A vs P2 (Bonferroni x3): P = 4.2e-16
   slope: Active steepest (median): True
   normalized score: Active highest (median): False
   quadrant score: Active highest (median): True
   largest P of the Active effects 1.0e+00: below 10^-6 False, below 0.001 False; Active steepest and highest in every part False; passive-pair slope KS P = 8.7e-01 (> 0.1: True)
figs8, firing-rate control, rate reading b:
   slope KS A vs P1: P = 3.0e-05
   slope KS A vs P2: P = 7.5e-03
   normalized score KW: P = 4.3e-09
   normalized score rank-sum A vs P1 (Bonferroni x3): P = 5.8e-08
   normalized score rank-sum A vs P2 (Bonferroni x3): P = 2.6e-07
   quadrant score KW: P = 3.3e-19
   quadrant score rank-sum A vs P1 (Bonferroni x3): P = 2.6e-19
   quadrant score rank-sum A vs P2 (Bonferroni x3): P = 2.0e-10
   slope: Active steepest (median): True
   normalized score: Active highest (median): False
   quadrant score: Active highest (median): True
   largest P of the Active effects 7.5e-03: below 10^-6 False, below 0.001 False; Active steepest and highest in every part False; passive-pair slope KS P = 2.3e-01 (> 0.1: True)

Result: not reproduced. Under rate reading (a), after downsampling the median rates are 1.14, 0.92 and 0.88 Hz (means 1.94, 1.19 and 1.21 Hz, outside the expected 0.905, 0.933 and 0.829) and still differ (Kruskal-Wallis P = 0.02). Significant slopes still differ between Active and each passive condition (KS P = 7.3 x 10^-9 and 2.9 x 10^-7) and not between the passive ones (P = 0.87); quadrant scores differ (P = 1.9 x 10^-30, Active highest); normalized scores differ only at P = 0.0048, with Passive 2 highest. Post hoc, Active does not exceed Passive 1 in normalized scores (P = 1.0). Reading (b), the peak rate, is weaker: slopes KS P = 3.0 x 10^-5 and 0.0075, and Active has the lowest normalized scores (median 0.396). The Active effects do not hold at 0.001 under either reading, and the rates still differ (changed from partially reproduced after round 3 of verification).

figs10-control-lap-variability¶

"With the decoder retrained on each lap, theta sequences were still degraded in passive travel."

Laps are completed turns of the unwrapped linear position from the start of each travel. Reading (a): each lap's theta cycles are decoded with firing curves and occupancy from that lap; reading (b): from the other laps of the same travel (claims file).

In [10]:
R10 = {}
t0 = time.time()
for reading in ["a", "b"]:
    rows = []
    for k, name in enumerate(D.RATS):
        P = PREP[name]
        for j, c in enumerate(D.CONDS):
            rng = np.random.default_rng(7300 + 100 * (reading == "b") + 10 * k + j)
            cells = D.place_cells(P, c, "a")
            spikes = [P["cond"][c]["cells"][i]["spk_t"] for i in cells]
            E = EDGES[(name, c)]
            lap_e = D.laps_of(P, c, E[:, 0]) if len(E) else np.zeros(0, int)
            mats, cent, dur, edges = [], [], [], []
            for lap in np.unique(lap_e):
                keep = (lambda t, lap=lap: D.laps_of(P, c, t) == lap) if reading == "a" else (lambda t, lap=lap: D.laps_of(P, c, t) != lap)
                px, lam = D.train_on(P, c, cells, keep)
                th = D.decode_cycles(P, E[lap_e == lap], spikes, px, lam)
                mats += th["mats"]; cent.append(th["cent"]); dur.append(th["dur"]); edges.append(th["edges"])
            th = dict(mats=mats, cent=np.concatenate(cent), dur=np.concatenate(dur), edges=np.concatenate(edges))
            sc = D.score_events(th["mats"], NSH, rng)
            rows += table(name, c, th, sc)
    R10[reading] = pd.DataFrame(rows)
    print(f"lap reading {reading}: {time.time() - t0:.0f} s")
    print(pd.Series(theta_tests(R10[reading], f"lap-by-lap control, reading {reading}")).to_string())
lap reading a: 247 s
label               lap-by-lap control, reading a
n                              [8429, 7617, 6998]
pct_sig_pos                 [16.62, 21.91, 20.02]
z_median                    [1.022, 1.193, 1.207]
z_KW_P                                    1.4e-20
quad_median              [0.0162, 0.0516, 0.0245]
quad_KW_P                                 3.6e-25
sig_slope_median               [0.22, 0.64, 0.24]
sig_slope_KW_P                            1.3e-07
KS_P1-A                                   1.4e-08
KS_A-P2                                   5.1e-06
KS_P1-P2                                  7.8e-01
lap reading b: 496 s
label               lap-by-lap control, reading b
n                              [8429, 7617, 6998]
pct_sig_pos                    [7.75, 11.86, 9.8]
z_median                    [0.447, 0.659, 0.632]
z_KW_P                                    1.9e-35
quad_median              [0.0046, 0.0499, 0.0118]
quad_KW_P                                 3.5e-64
sig_slope_median               [0.41, 2.44, 0.44]
sig_slope_KW_P                            1.1e-10
KS_P1-A                                   4.1e-12
KS_A-P2                                   2.5e-12
KS_P1-P2                                  9.0e-01
In [11]:
for reading in ["a", "b"]:
    print(f"figs10, lap-by-lap control, reading {reading}:")
    criterion_check(R10[reading])
figs10, lap-by-lap control, reading a:
   slope KS A vs P1: P = 1.4e-08
   slope KS A vs P2: P = 5.1e-06
   normalized score KW: P = 1.4e-20
   normalized score rank-sum A vs P1 (Bonferroni x3): P = 1.9e-15
   normalized score rank-sum A vs P2 (Bonferroni x3): P = 1.0e+00
   quadrant score KW: P = 3.6e-25
   quadrant score rank-sum A vs P1 (Bonferroni x3): P = 6.9e-24
   quadrant score rank-sum A vs P2 (Bonferroni x3): P = 5.8e-14
   slope: Active steepest (median): True
   normalized score: Active highest (median): False
   quadrant score: Active highest (median): True
   largest P of the Active effects 1.0e+00: below 10^-6 False, below 0.001 False; Active steepest and highest in every part False; passive-pair slope KS P = 7.8e-01 (> 0.05: True)
figs10, lap-by-lap control, reading b:
   slope KS A vs P1: P = 4.1e-12
   slope KS A vs P2: P = 2.5e-12
   normalized score KW: P = 1.9e-35
   normalized score rank-sum A vs P1 (Bonferroni x3): P = 4.5e-30
   normalized score rank-sum A vs P2 (Bonferroni x3): P = 5.5e-01
   quadrant score KW: P = 3.5e-64
   quadrant score rank-sum A vs P1 (Bonferroni x3): P = 3.6e-61
   quadrant score rank-sum A vs P2 (Bonferroni x3): P = 8.1e-34
   slope: Active steepest (median): True
   normalized score: Active highest (median): True
   quadrant score: Active highest (median): True
   largest P of the Active effects 5.5e-01: below 10^-6 False, below 0.001 False; Active steepest and highest in every part True; passive-pair slope KS P = 9.0e-01 (> 0.05: True)

Result: not reproduced, resting on an assumption. Under reading (a), each lap decoded with its own firing curves as the text and BatchSequenceReconstructLapByLap.m do, slopes differ between Active and Passive 1 (KS P = 1.4 x 10^-8) and Passive 2 (P = 5.1 x 10^-6, above 10^-6), not between the passive conditions (P = 0.78); quadrant scores differ (P = 3.6 x 10^-25, Active highest); normalized scores differ (P = 1.4 x 10^-20) but Passive 2 (1.207) is above Active (1.193). Under reading (b), the other laps, every test the criterion names holds, which would be reproduced: KS P = 4.1 x 10^-12 and 2.5 x 10^-12, passive pair P = 0.90, normalized scores P = 1.9 x 10^-35 with Active highest, quadrant scores P = 3.5 x 10^-64, and a post hoc test outside the criterion finds that Active does not differ from Passive 2 in normalized scores (P = 0.55; under reading a P = 1.0). Under the assumed reading (a) the Active effects do not hold at 0.001, so the outcome depends on that reading (changed from partially reproduced after round 3 of verification).

figs9-control-decoding-quality: cross-validated error¶

The decoding notebook measures the error in 500-ms bins with the decoder trained on the whole travel, including the bin decoded. Here each lap is decoded with the decoder trained on the other laps, and the restriction of fig. S9 (the highest-error passive bins dropped until the median is below the Active median) is repeated on these errors. Theta-cycle measures are those of reading (a) above.

In [12]:
ERRCV, keep_bins = {}, {}
for name in D.RATS:
    P = PREP[name]
    ok = np.isfinite(P["lin_unw"])
    tt, lu = P["t"][ok], P["lin_unw"][ok]
    for c in D.CONDS:
        cells = D.place_cells(P, c, "a")
        spikes = [P["cond"][c]["cells"][i]["spk_t"] for i in cells]
        starts = []
        for a, b in P["mov"]:
            lo, hi = max(a, P["ep"]["travel"][c][0]), min(b, P["ep"]["travel"][c][1])
            if hi - lo >= 0.5:
                starts.append(np.arange(lo, hi - 0.5 + 1e-9, 0.5))
        starts = np.concatenate(starts) if starts else np.zeros(0)
        lap_s = D.laps_of(P, c, starts + 0.25)
        cnt = np.array([np.histogram(st, np.c_[starts, starts + 0.5].ravel())[0][::2] for st in spikes])
        err = {}
        for kind in ["in-sample", "cross-validated"]:
            e = np.full(len(starts), np.nan)
            for lap in np.unique(lap_s):
                m = lap_s == lap
                keep = (lambda t: np.ones(len(t), bool)) if kind == "in-sample" else (lambda t, lap=lap: D.laps_of(P, c, t) != lap)
                px, lam = D.train_on(P, c, cells, keep)
                post = D.decode(cnt[:, m], np.full(m.sum(), 0.5), px, lam)
                dec = (np.nanargmax(np.nan_to_num(post, nan=-1), 1) + 0.5) / D.NBINS
                act = np.mod(np.interp(starts[m] + 0.25, tt, lu), 1)
                ee = np.abs((dec - act + 0.5) % 1 - 0.5) * D.TRACK_M
                ee[np.isnan(post[:, 0])] = np.nan
                e[m] = ee
            err[kind] = e
        ERRCV[(name, c)] = (starts, err)
print("median decoding error (m), in-sample and cross-validated (other laps):")
print(pd.DataFrame({(n[6:9], c): {k: round(np.nanmedian(v), 3) for k, v in ERRCV[(n, c)][1].items()} for n in D.RATS for c in D.CONDS}).T.unstack().round(3).to_string())
for name in D.RATS:
    medA = np.nanmedian(ERRCV[(name, "A")][1]["cross-validated"])
    for c in D.CONDS:
        starts, err = ERRCV[(name, c)][0], ERRCV[(name, c)][1]["cross-validated"]
        kept = np.isfinite(err)
        if c != "A":
            order = np.argsort(-np.nan_to_num(err, nan=-1))
            k = 0
            while np.median(err[kept]) >= medA and kept.sum() > 1:
                kept[order[k]] = False
                k += 1
        keep_bins[(name, c)] = (starts[kept], err[kept])
errs = {c: np.concatenate([keep_bins[(n, c)][1] for n in D.RATS]) for c in D.CONDS}
print("cross-validated error after restriction, mean +/- s.e.m. (m):", {c: f"{errs[c].mean():.3f} +/- {stats.sem(errs[c]):.3f}" for c in D.CONDS},
      " expected 0.802, 0.80, 0.802 (+/-0.018, 0.023, 0.014)")
rows = []
CYa = CYR["a"]
for name in D.RATS:
    for c in D.CONDS:
        starts = keep_bins[(name, c)][0]
        sub = CYa[(CYa.rat == name[6:9]) & (CYa.cond == c)]
        j = np.searchsorted(starts, sub.t.values, side="right") - 1
        inbin = (j >= 0) & (sub.t.values < starts[np.clip(j, 0, None)] + 0.5) if len(starts) else np.zeros(len(sub), bool)
        rows.append(sub[inbin])
CY9 = pd.concat(rows)
print("cycles kept:", CY9.groupby("cond").size().reindex(D.CONDS).to_dict())
print(pd.Series(theta_tests(CY9, "decoding-quality control, cross-validated error")).to_string())
median decoding error (m), in-sample and cross-validated (other laps):
    in-sample               cross-validated              
            A     P1     P2               A     P1     P2
242     0.402  0.931  0.760           0.559  1.160  0.931
261     0.276  0.923  0.618           0.334  0.986  0.707
272     0.141  0.815  0.316           0.306  1.130  0.580
292     0.479  0.601  0.387           0.560  0.744  0.533
314     0.115  0.535  0.225           0.264  0.907  0.474
cross-validated error after restriction, mean +/- s.e.m. (m): {'P1': '0.487 +/- 0.008', 'A': '0.627 +/- 0.011', 'P2': '0.525 +/- 0.009'}  expected 0.802, 0.80, 0.802 (+/-0.018, 0.023, 0.014)
cycles kept: {'P1': 4332, 'A': 7617, 'P2': 5422}
label               decoding-quality control, cross-validated error
n                                                [4332, 7617, 5422]
pct_sig_pos                                    [8.31, 12.51, 10.99]
z_median                                      [0.494, 0.678, 0.681]
z_KW_P                                                      3.7e-21
quad_median                                [0.0061, 0.0503, 0.0159]
quad_KW_P                                                   3.9e-45
sig_slope_median                                 [0.41, 2.41, 0.48]
sig_slope_KW_P                                              2.1e-08
KS_P1-A                                                     1.1e-07
KS_A-P2                                                     6.2e-09
KS_P1-P2                                                    4.9e-01

Cross-validated error (figs9-control-decoding-quality). Decoded with the other laps' firing curves, errors rise (per-rat medians 0.264 to 1.160 m against 0.115 to 0.931 m in-sample; pooled means after restriction 0.487, 0.627 and 0.525 m, still below the expected 0.80 m), and the restriction gives the same results as the in-sample errors of the decoding notebook: slopes differ (KS P = 1.1 x 10^-7 and 6.2 x 10^-9; passive pair P = 0.49), quadrant scores differ (P = 3.9 x 10^-45) and normalized scores still differ (P = 3.7 x 10^-21).

Pairwise bias correlations (fig3g, fig4g)¶

Bias matrices and their cosine over the cells active in both sequences, at least three common cells, surrogates shuffling the spike order of the second sequence (Methods, Pairwise bias correlations; claims file, Common methods). A pair is significant when its correlation is positive and at or above 95% of 200 surrogates (c > 0 & p < 0.05 in script_BatchBiasMatrixCosines_helper.m). As in BatchBiasMatrixCosines.m (restrict2placeFields), travel spikes are those of place cells inside their peak field. Sequences: theta cycles decoded under reading (a) above, with at least three active place cells; reading (a) every such cycle, reading (b) only cycles with a significant trajectory score. Candidate events are those of the decoding notebook (place cells of the travel, threshold over SWS, at least 60 ms and three active cells). Every pair cannot be run here (about 10^7 theta pairs and 5 x 10^7 theta-event pairs); per rat and comparison, 3000 pairs with at least three common cells are drawn at random.

In [13]:
NSUR, NPAIR = 200, 3000

def theta_seqs(name, c, only_sig):
    P = PREP[name]
    cells = D.place_cells(P, c, "a")
    spk, ids = [], []
    for k, i in enumerate(cells):
        cell = P["cond"][c]["cells"][i]
        fld = cell["readings"]["a"]["fields"][0]
        inf = fld[np.minimum((cell["spk_lin"] * D.NBINS).astype(int), D.NBINS - 1)]
        spk.append(cell["spk_t"][inf]); ids.append(np.full(inf.sum(), i))
    spk, ids = np.concatenate(spk), np.concatenate(ids)
    o = np.argsort(spk); spk, ids = spk[o], ids[o]
    th, sc = THC[("a", name, c)]
    out, when = [], []
    for e, pv in zip(th["edges"], sc["p"]):
        if only_sig and pv > 0.05:
            continue
        a, b = np.searchsorted(spk, [e[0], e[-1]])
        if len(np.unique(ids[a:b])) >= 3:
            out.append(ids[a:b]); when.append(e[0])
    return out, np.array(when)

def event_seqs(name, c, sleep):
    P, LF = PREP[name], LFPS[name]
    cells = D.place_cells(P, c, "a")
    times = [RAT[name]["units"][i]["times"] for i in cells]
    spk = np.concatenate(times); ids = np.concatenate([np.full(len(t), i) for t, i in zip(times, cells)])
    o = np.argsort(spk); spk, ids = spk[o], ids[o]
    sl = LF["sleep"][sleep]
    ev = D.candidate_events(spk, sl["interval"], sl["sws"], norm="sws")
    out = []
    for a, pk, b in ev:
        if b - a < 0.06:
            continue
        i, j = np.searchsorted(spk, [a, b])
        if len(np.unique(ids[i:j])) >= 3:
            out.append(ids[i:j])
    return out

def pairs(A, B, same, rng):
    """Up to NPAIR random pairs (k, l), one sequence from A and one from B (k != l when
    same), with at least three common cells; returns correlations, surrogate P, mid-P and the null flag (helper)."""
    res = []
    if not A or not B:
        return np.zeros((0, 4))
    for _ in range(40):
        ks, ls = rng.integers(0, len(A), 4 * NPAIR), rng.integers(0, len(B), 4 * NPAIR)
        for k, l in zip(ks, ls):
            if same and k == l:
                continue
            r = D.bias_correlation(A[k], B[l], NSUR, rng)
            if r is not None and np.isfinite(r[0]):
                res.append(r)
            if len(res) >= NPAIR:
                return np.array(res)
    return np.array(res).reshape(-1, 4)

t0 = time.time()
TSEQ = {(rd, n, c): theta_seqs(n, c, rd == "b") for rd in ["a", "b"] for n in D.RATS for c in D.CONDS}
print("theta sequences with >= 3 active place cells (in-field spikes), reading a:",
      pd.DataFrame({n[6:9]: {c: len(TSEQ[("a", n, c)][0]) for c in D.CONDS} for n in D.RATS}).T.to_string())
theta sequences with >= 3 active place cells (in-field spikes), reading a:        P1     A    P2
242  1624   878  1308
261   648   525   184
272  2274  1640  1601
292   717  1700  1206
314  1700  1880  1568
In [14]:
def prop_test(k1, n1, k2, n2):
    p = (k1 + k2) / (n1 + n2)
    z = (k1 / n1 - k2 / n2) / np.sqrt(p * (1 - p) * (1 / n1 + 1 / n2))
    return z, 2 * stats.norm.sf(abs(z))

G3 = {}
for rd in ["a", "b"]:
    rows = []
    for k, name in enumerate(D.RATS):
        for j, c in enumerate(D.CONDS):
            rng = np.random.default_rng(7400 + 100 * (rd == "b") + 10 * k + j)
            r = pairs(TSEQ[(rd, name, c)][0], TSEQ[(rd, name, c)][0], True, rng)
            rows += [dict(rat=name[6:9], cond=c, rho=x, p=pv, p_mid=pm, null_sig=ns) for x, pv, pm, ns in r]
    G3[rd] = pd.DataFrame(rows)
    G = G3[rd]
    G["sig"] = (G.rho > 0) & (G.p < 0.05)
    g = {c: G[G.cond == c] for c in D.CONDS}
    print(f"sequence reading {rd}: pairs {[len(v) for v in g.values()]}; mean correlation {[round(v.rho.mean(), 4) for v in g.values()]}; "
          f"KW P = {stats.kruskal(*[v.rho for v in g.values()]).pvalue:.1e}")
    print(f"   proportion significant {[f'{v.sig.sum()}/{len(v)} = {v.sig.mean():.3f}' for v in g.values()]} (chance about 0.05)")
    for a, b in [("A", "P1"), ("A", "P2"), ("P2", "P1")]:
        z, p = prop_test(g[a].sig.sum(), len(g[a]), g[b].sig.sum(), len(g[b]))
        print(f"   binomial proportion test {a} vs {b}: z = {z:.2f}, P = {p:.1e}")
    w = stats.wilcoxon(g["P1"].rho)
    print(f"   Passive 1 mean correlation {g['P1'].rho.mean():.4f}, signed-rank against 0 P = {w.pvalue:.2f}")
    print("   per rat proportion significant:", G.groupby(["rat", "cond"]).sig.mean().unstack().reindex(columns=D.CONDS).round(3).to_dict("index"))
print(f"{time.time() - t0:.0f} s")
sequence reading a: pairs [15000, 15000, 15000]; mean correlation [np.float64(0.0207), np.float64(0.0119), np.float64(0.0158)]; KW P = 4.0e-01
   proportion significant ['624/15000 = 0.042', '568/15000 = 0.038', '595/15000 = 0.040'] (chance about 0.05)
   binomial proportion test A vs P1: z = -1.66, P = 9.8e-02
   binomial proportion test A vs P2: z = -0.81, P = 4.2e-01
   binomial proportion test P2 vs P1: z = -0.85, P = 4.0e-01
   Passive 1 mean correlation 0.0207, signed-rank against 0 P = 0.00
   per rat proportion significant: {'242': {'P1': 0.035, 'A': 0.039, 'P2': 0.033}, '261': {'P1': 0.031, 'A': 0.028, 'P2': 0.041}, '272': {'P1': 0.044, 'A': 0.043, 'P2': 0.046}, '292': {'P1': 0.055, 'A': 0.048, 'P2': 0.044}, '314': {'P1': 0.043, 'A': 0.031, 'P2': 0.035}}
sequence reading b: pairs [15000, 15000, 15000]; mean correlation [np.float64(0.0158), np.float64(0.0486), np.float64(0.0212)]; KW P = 2.2e-06
   proportion significant ['603/15000 = 0.040', '811/15000 = 0.054', '716/15000 = 0.048'] (chance about 0.05)
   binomial proportion test A vs P1: z = 5.67, P = 1.5e-08
   binomial proportion test A vs P2: z = 2.50, P = 1.3e-02
   binomial proportion test P2 vs P1: z = 3.18, P = 1.5e-03
   Passive 1 mean correlation 0.0158, signed-rank against 0 P = 0.00
   per rat proportion significant: {'242': {'P1': 0.03, 'A': 0.051, 'P2': 0.047}, '261': {'P1': 0.035, 'A': 0.067, 'P2': 0.042}, '272': {'P1': 0.042, 'A': 0.052, 'P2': 0.049}, '292': {'P1': 0.047, 'A': 0.056, 'P2': 0.06}, '314': {'P1': 0.046, 'A': 0.044, 'P2': 0.04}}
50 s

Result: not reproduced. With every analysed theta cycle as a sequence (reading a, as BatchBiasMatrixCosines.m takes every theta cycle with three active cells), the proportions of significantly correlated pairs are 4.1%, 3.8% and 4.0%, below the 5% chance level, and do not differ (binomial P = 0.091 to 0.50; Kruskal-Wallis of correlations P = 0.38). With significant sequences only (reading b) the order is as the paper's (4.0%, 5.4% and 4.8%), Active above Passive 1 (P = 5.6 x 10^-8) and Passive 2 above Passive 1 (P = 0.0023), but Active above Passive 2 only at P = 0.016, and the Kruskal-Wallis gives P = 1.7 x 10^-6. The Passive 1 mean correlation is 0.021 (signed-rank P < 0.005). Pairs are a random sample of 3000 per rat and condition; the 20-bin matrices are not computed.

In [15]:
ESEQ = {}
for name in D.RATS:
    for c, s in [("P1", "S1"), ("A", "SA"), ("P2", "S2")]:
        ESEQ[(name, c, "post")] = event_seqs(name, c, s)
        ESEQ[(name, c, "base")] = event_seqs(name, c, "SB")
print("candidate events with >= 3 active place cells (post / baseline):",
      {n[6:9]: {c: (len(ESEQ[(n, c, "post")]), len(ESEQ[(n, c, "base")])) for c in D.CONDS} for n in D.RATS})
G4 = {}
for rd in ["a", "b"]:
    rows = []
    for k, name in enumerate(D.RATS):
        for j, c in enumerate(D.CONDS):
            for kind in ["post", "base"]:
                rng = np.random.default_rng(7500 + 100 * (rd == "b") + 10 * k + j + 5 * (kind == "base"))
                r = pairs(TSEQ[(rd, name, c)][0], ESEQ[(name, c, kind)], False, rng)
                rows += [dict(rat=name[6:9], cond=c, kind=kind, rho=x, p=pv, p_mid=pm, null_sig=ns) for x, pv, pm, ns in r]
    G = pd.DataFrame(rows)
    G["sig"] = (G.rho > 0) & (G.p < 0.05)
    G4[rd] = G
    print(f"sequence reading {rd}:")
    for c in D.CONDS:
        po, ba = G[(G.cond == c) & (G.kind == "post")], G[(G.cond == c) & (G.kind == "base")]
        z, p = prop_test(po.sig.sum(), len(po), ba.sig.sum(), len(ba))
        print(f"   {c} theta with post-sleep: {po.sig.sum()}/{len(po)} = {po.sig.mean():.3f} significant, mean correlation {po.rho.mean():.4f}; "
              f"with baseline: {ba.sig.sum()}/{len(ba)} = {ba.sig.mean():.3f}, mean {ba.rho.mean():.4f}; binomial z = {z:.2f}, P = {p:.1e}")
    post = G[G.kind == "post"]
    print(f"   KW of theta-post correlations across conditions: P = {stats.kruskal(*[post[post.cond == c].rho for c in D.CONDS]).pvalue:.1e}")
    print("   per rat, proportion significant post / baseline:",
          G.groupby(["rat", "cond", "kind"]).sig.mean().unstack([1, 2]).round(3).to_string())
print(f"{time.time() - t0:.0f} s")
candidate events with >= 3 active place cells (post / baseline): {'242': {'P1': (1564, 1709), 'A': (1574, 1651), 'P2': (435, 1650)}, '261': {'P1': (1677, 1086), 'A': (1161, 950), 'P2': (1134, 993)}, '272': {'P1': (1120, 408), 'A': (636, 405), 'P2': (1222, 430)}, '292': {'P1': (1783, 1901), 'A': (1172, 1933), 'P2': (1471, 1911)}, '314': {'P1': (636, 847), 'A': (1641, 814), 'P2': (1182, 813)}}
sequence reading a:
   P1 theta with post-sleep: 622/15000 = 0.041 significant, mean correlation -0.0001; with baseline: 666/15000 = 0.044, mean -0.0067; binomial z = -1.25, P = 2.1e-01
   A theta with post-sleep: 611/15000 = 0.041 significant, mean correlation -0.0057; with baseline: 649/15000 = 0.043, mean -0.0011; binomial z = -1.09, P = 2.7e-01
   P2 theta with post-sleep: 607/15000 = 0.040 significant, mean correlation -0.0011; with baseline: 659/15000 = 0.044, mean 0.0049; binomial z = -1.49, P = 1.4e-01
   KW of theta-post correlations across conditions: P = 6.6e-01
   per rat, proportion significant post / baseline: cond      A            P1            P2       
kind   base   post   base   post   base   post
rat                                           
242   0.037  0.046  0.037  0.041  0.039  0.039
261   0.029  0.026  0.029  0.031  0.036  0.029
272   0.046  0.044  0.046  0.040  0.043  0.047
292   0.062  0.045  0.061  0.052  0.054  0.044
314   0.043  0.042  0.049  0.044  0.049  0.044
sequence reading b:
   P1 theta with post-sleep: 714/15000 = 0.048 significant, mean correlation 0.0048; with baseline: 651/15000 = 0.043, mean 0.0025; binomial z = 1.75, P = 8.1e-02
   A theta with post-sleep: 667/15000 = 0.044 significant, mean correlation 0.0056; with baseline: 685/15000 = 0.046, mean 0.0026; binomial z = -0.50, P = 6.2e-01
   P2 theta with post-sleep: 670/15000 = 0.045 significant, mean correlation 0.0048; with baseline: 596/15000 = 0.040, mean -0.0040; binomial z = 2.13, P = 3.4e-02
   KW of theta-post correlations across conditions: P = 9.9e-01
   per rat, proportion significant post / baseline: cond      A            P1            P2       
kind   base   post   base   post   base   post
rat                                           
242   0.041  0.053  0.043  0.055  0.037  0.050
261   0.026  0.026  0.027  0.028  0.031  0.032
272   0.055  0.042  0.038  0.043  0.044  0.049
292   0.054  0.057  0.063  0.063  0.044  0.046
314   0.052  0.044  0.046  0.049  0.042  0.046
168 s

Result: not reproduced. Active theta sequences are not more often correlated with candidate events of the sleep that followed than with baseline events: 4.1% against 4.3% (reading a, P = 0.25) and 4.5% against 4.5% (reading b, P = 0.70). No condition's post-sleep pairs exceed its baseline pairs under reading (a) (P = 0.16 to 0.25); under reading (b) Passive 2 does (4.5% against 3.9%, P = 0.021). Mean correlations do not differ across conditions (Kruskal-Wallis P = 0.64 and 0.99).

In [16]:
# The surrogate test counts surrogates at or above the observed correlation. With few spikes the spike-order
# shuffles take few distinct values (3 cells with one spike each: 6 orders), so p cannot fall below 0.05 for
# many pairs and the share of significant pairs under no consistency is below 5%. Two checks, on the same pairs:
# the mid-p (ties counted half), and the chance level of the procedure itself, the share of pairs whose first
# surrogate, tested against the other surrogates in the same way, comes out significant.
for lab, GG, key in [("fig3g, theta with theta", G3, None), ("fig4g, theta with candidate events", G4, "kind")]:
    for rd in ["a", "b"]:
        G = GG[rd]
        by = ["cond"] if key is None else ["cond", key]
        t = G.groupby(by).apply(lambda g: pd.Series(dict(
            pairs=len(g), pct_sig=round(100 * g.sig.mean(), 2), pct_sig_midp=round(100 * ((g.rho > 0) & (g.p_mid < 0.05)).mean(), 2),
            pct_sig_null=round(100 * g.null_sig.mean(), 2))), include_groups=False)
        print(f"{lab}, sequence reading {rd}:")
        print(t.to_string())
        if key is None:
            g = {c: G[G.cond == c] for c in D.CONDS}
            sm = {c: (v.rho > 0) & (v.p_mid < 0.05) for c, v in g.items()}
            for a, b in [("A", "P1"), ("A", "P2"), ("P2", "P1")]:
                z, p = prop_test(sm[a].sum(), len(sm[a]), sm[b].sum(), len(sm[b]))
                print(f"   mid-p: binomial proportion test {a} vs {b}: z = {z:.2f}, P = {p:.1e}")
            for c in D.CONDS:
                z, p = prop_test(g[c].sig.sum(), len(g[c]), int(g[c].null_sig.sum()), len(g[c]))
                print(f"   {c}: significant pairs against the procedure's chance level: z = {z:.2f}, P = {p:.1e}")
        else:
            for c in D.CONDS:
                po, ba = G[(G.cond == c) & (G[key] == "post")], G[(G.cond == c) & (G[key] == "base")]
                mp, mb = (po.rho > 0) & (po.p_mid < 0.05), (ba.rho > 0) & (ba.p_mid < 0.05)
                z, p = prop_test(mp.sum(), len(mp), mb.sum(), len(mb))
                print(f"   mid-p: {c} theta with post-sleep {mp.mean():.3f} against baseline {mb.mean():.3f}: z = {z:.2f}, P = {p:.1e}")
fig3g, theta with theta, sequence reading a:
        pairs  pct_sig  pct_sig_midp  pct_sig_null
cond                                              
A     15000.0     3.79          5.13          3.25
P1    15000.0     4.16          5.95          3.13
P2    15000.0     3.97          5.81          2.93
   mid-p: binomial proportion test A vs P1: z = -3.13, P = 1.8e-03
   mid-p: binomial proportion test A vs P2: z = -2.59, P = 9.6e-03
   mid-p: binomial proportion test P2 vs P1: z = -0.54, P = 5.9e-01
   P1: significant pairs against the procedure's chance level: z = 4.78, P = 1.8e-06
   A: significant pairs against the procedure's chance level: z = 2.54, P = 1.1e-02
   P2: significant pairs against the procedure's chance level: z = 4.90, P = 9.4e-07
fig3g, theta with theta, sequence reading b:
        pairs  pct_sig  pct_sig_midp  pct_sig_null
cond                                              
A     15000.0     5.41          6.65          3.59
P1    15000.0     4.02          5.57          3.19
P2    15000.0     4.77          6.08          3.20
   mid-p: binomial proportion test A vs P1: z = 3.88, P = 1.0e-04
   mid-p: binomial proportion test A vs P2: z = 2.01, P = 4.4e-02
   mid-p: binomial proportion test P2 vs P1: z = 1.87, P = 6.1e-02
   P1: significant pairs against the procedure's chance level: z = 3.84, P = 1.2e-04
   A: significant pairs against the procedure's chance level: z = 7.61, P = 2.8e-14
   P2: significant pairs against the procedure's chance level: z = 6.96, P = 3.3e-12
fig4g, theta with candidate events, sequence reading a:
             pairs  pct_sig  pct_sig_midp  pct_sig_null
cond kind                                              
A    base  15000.0     4.33          5.47          3.55
     post  15000.0     4.07          5.20          3.46
P1   base  15000.0     4.44          5.41          3.51
     post  15000.0     4.15          5.37          3.40
P2   base  15000.0     4.39          5.52          3.44
     post  15000.0     4.05          5.35          3.41
   mid-p: P1 theta with post-sleep 0.054 against baseline 0.054: z = -0.18, P = 8.6e-01
   mid-p: A theta with post-sleep 0.052 against baseline 0.055: z = -1.03, P = 3.0e-01
   mid-p: P2 theta with post-sleep 0.054 against baseline 0.055: z = -0.64, P = 5.2e-01
fig4g, theta with candidate events, sequence reading b:
             pairs  pct_sig  pct_sig_midp  pct_sig_null
cond kind                                              
A    base  15000.0     4.57          5.65          3.42
     post  15000.0     4.45          5.37          3.82
P1   base  15000.0     4.34          5.47          3.85
     post  15000.0     4.76          5.90          3.29
P2   base  15000.0     3.97          5.35          3.37
     post  15000.0     4.47          5.58          3.34
   mid-p: P1 theta with post-sleep 0.059 against baseline 0.055: z = 1.62, P = 1.1e-01
   mid-p: A theta with post-sleep 0.054 against baseline 0.056: z = -1.04, P = 3.0e-01
   mid-p: P2 theta with post-sleep 0.056 against baseline 0.053: z = 0.89, P = 3.7e-01

Surrogate resolution. The procedure's own chance level, from the first surrogate tested against the others, is 2.9% to 3.6% for theta pairs and 3.3% to 3.9% for theta-event pairs, below 5%. Against it, the reading (a) proportions of fig3g are above chance in every condition (P = 2.3 x 10^-6, 0.016 and 7.0 x 10^-7 for Passive 1, Active and Passive 2), with Active lowest. With the mid-p, reading (a) gives 5.95%, 5.11% and 5.83%, Active below Passive 1 (P = 0.0015); reading (b) gives 5.59%, 6.63% and 6.07%, Active above Passive 1 (P = 1.7 x 10^-4) and Passive 2 (P = 0.044), Passive 2 against Passive 1 P = 0.080. For fig4g, post-sleep pairs do not exceed baseline pairs with the mid-p (P = 0.28 to 0.86 under reading a, 0.13 to 0.34 under b). Neither outcome changes.

Replay under the other readings, on a random fifth of the candidate events¶

The decoding notebook decodes every candidate event under field reading (a) with the threshold over SWS. Here a random fifth of the post-sleep and baseline events is decoded under (i) field reading (b), threshold over SWS, and (ii) field reading (a), threshold over the whole sleep session (claims file, Common methods, candidate events, reading b), with 100 shuffles. The measures of fig4b (scores relative to baseline), fig4c (slopes) and fig4e (proportion significant against baseline) are shown.

In [17]:
SLEEP_OF = {"P1": "S1", "A": "SA", "P2": "S2"}
t0 = time.time()
RV = {}
for vi, (rd, norm) in enumerate([("b", "sws"), ("a", "all")]):
    rows = []
    for k, name in enumerate(D.RATS):
        P, LF = PREP[name], LFPS[name]
        for j, c in enumerate(D.CONDS):
            cells = D.place_cells(P, c, rd)
            px, lam = D.train_decoder(P, c, cells, rd)
            spikes = [RAT[name]["units"][i]["times"] for i in cells]
            allspk = np.sort(np.concatenate(spikes))
            for kind, s in [("post", SLEEP_OF[c]), ("base", "SB")]:
                rng = np.random.default_rng(7600 + 1000 * vi + 100 * k + 10 * j + (kind == "base"))
                sl = LF["sleep"][s]
                ev = D.candidate_events(allspk, sl["interval"], sl["sws"], norm=norm)
                ev = ev[np.sort(rng.choice(len(ev), len(ev) // 5, replace=False))] if len(ev) else ev
                mats, keep = D.replay_matrices(ev, spikes, px, lam)
                sc = D.score_events(mats, NSH, rng)
                for e in range(len(mats)):
                    m = len(mats[e])
                    rows.append(dict(rat=name[6:9], cond=c, kind=kind, score=sc["score"][e], p=sc["p"][e], D=sc["D"][e],
                                     slope=sc["D"][e] / (m - 1) * BIN_M / 0.02))
    E = pd.DataFrame(rows)
    E["rel"] = np.nan
    for (rat, c), sub in E.groupby(["rat", "cond"]):
        q1, med, q3 = np.percentile(sub[sub.kind == "base"].score, [25, 50, 75])
        E.loc[sub.index, "rel"] = (sub.score - med) / (q3 - q1)
    RV[(rd, norm)] = E
    print(f"field reading {rd}, threshold over {norm} ({time.time() - t0:.0f} s): decoded events (post / baseline)",
          {c: (int(((E.cond == c) & (E.kind == "post")).sum()), int(((E.cond == c) & (E.kind == "base")).sum())) for c in D.CONDS})
    for c in D.CONDS:
        po, ba = E[(E.cond == c) & (E.kind == "post")], E[(E.cond == c) & (E.kind == "base")]
        w = stats.wilcoxon(po.rel)
        z, p = prop_test((po.p <= 0.05).sum(), len(po), (ba.p <= 0.05).sum(), len(ba))
        print(f"   after {c}: score relative to baseline median {po.rel.median():.3f}, signed-rank P = {w.pvalue:.1e}; "
              f"significant {100 * (po.p <= 0.05).mean():.2f}% vs baseline {100 * (ba.p <= 0.05).mean():.2f}%, binomial z = {z:.2f}, P = {p:.1e}")
    sig = E[(E.kind == "post") & (E.p <= 0.05)]
    g = {c: np.abs(sig[sig.cond == c].slope.values) for c in D.CONDS}
    print(f"   significant post events, median |slope| (m/s) {[round(np.median(v), 2) for v in g.values()]}; KW P = {stats.kruskal(*g.values()).pvalue:.1e}; "
          + "; ".join(f"KS {a}-{b} P = {stats.ks_2samp(g[a], g[b]).pvalue:.1e}" for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]))
field reading b, threshold over sws (134 s): decoded events (post / baseline) {'P1': (1304, 1138), 'A': (1218, 1105), 'P2': (1066, 1091)}
   after P1: score relative to baseline median 0.071, signed-rank P = 2.4e-11; significant 15.72% vs baseline 14.59%, binomial z = 0.78, P = 4.4e-01
   after A: score relative to baseline median 0.269, signed-rank P = 2.2e-42; significant 18.06% vs baseline 13.94%, binomial z = 2.70, P = 6.9e-03
   after P2: score relative to baseline median 0.054, signed-rank P = 1.8e-08; significant 15.10% vs baseline 16.32%, binomial z = -0.77, P = 4.4e-01
   significant post events, median |slope| (m/s) [np.float64(2.74), np.float64(4.89), np.float64(6.93)]; KW P = 4.4e-03; KS P1-A P = 3.1e-02; KS A-P2 P = 2.4e-01; KS P1-P2 P = 2.8e-04
field reading a, threshold over all (263 s): decoded events (post / baseline) {'P1': (1187, 1042), 'A': (1198, 1036), 'P2': (1104, 1008)}
   after P1: score relative to baseline median -0.026, signed-rank P = 3.0e-01; significant 15.00% vs baseline 12.96%, binomial z = 1.38, P = 1.7e-01
   after A: score relative to baseline median 0.220, signed-rank P = 5.0e-38; significant 16.19% vs baseline 12.64%, binomial z = 2.37, P = 1.8e-02
   after P2: score relative to baseline median -0.078, signed-rank P = 2.8e-01; significant 13.95% vs baseline 15.08%, binomial z = -0.74, P = 4.6e-01
   significant post events, median |slope| (m/s) [np.float64(2.7), np.float64(6.76), np.float64(7.1)]; KW P = 2.3e-04; KS P1-A P = 2.3e-04; KS A-P2 P = 3.2e-01; KS P1-P2 P = 3.1e-04

Other readings of replay. On a random fifth of the events, field reading (b) improves scores after every travel (medians 0.071, 0.269 and 0.054, signed-rank P = 2.4 x 10^-11, 2.2 x 10^-42 and 1.8 x 10^-8), increases significant events only after Active (18.06% against 13.94%, P = 0.0069; after Passive 2 P = 0.44), and does not separate absolute slopes after Active from after Passive 2 (KS P = 0.24). The whole-session threshold improves scores only after Active (median 0.220), increases significant events only after Active (P = 0.018), and does not separate the slopes after Active and Passive 2 (P = 0.32). Neither reading changes the outcomes of fig4b, fig4c or fig4e.

Summary¶

claim outcome
figs7-control-cell-count not reproduced
figs8-control-firing-rate not reproduced
figs10-control-lap-variability not reproduced (assumed own-lap reading; the other-laps reading passes)
fig3g-theta-self-consistency not reproduced
fig4g-theta-replay-correlation-active not reproduced

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. 100 shuffles per event (the paper 5000), 10 cell subsets per rat for fig. S7 (the paper 30), and random samples of 3000 sequence pairs per rat and comparison for the bias correlations, for time. Place cells are those of field reading (a).

About the dataset. The theta-sequence differences between Active and the passive travels survive the cell-count, firing-rate, lap-by-lap and decoding-error controls in slopes and quadrant scores (except slopes under the peak-rate reading of the firing-rate control, Active against Passive 2 P = 0.0075), but not in normalized scores: Active does not exceed Passive 2 in post hoc tests of the cell-count, firing-rate and lap-by-lap controls, and in the decoding-error control Passive 2's median (0.681) is above Active's (0.678). Under sequence reading (a), pairwise bias correlations show no more self-consistency in Active than in the passive travels; under reading (b) Active has the most significant pairs (5.4%), above Passive 1 at P = 5.6 x 10^-8 but above Passive 2 only at P = 0.016, and Passive 1's mean correlation is above 0 (signed-rank P < 0.005). No theta-replay correlation exceeds baseline. The surrogate test's own chance level is 2.9% to 3.9%, not 5%.

In [18]:
print(f"notebook runtime {(time.time() - T_START) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
notebook runtime 57.0 min; peak memory 6.4 GB