Drieu, Todorova & Zugaro (2018) on CRCNS hc-18: theta sequences and sleep replay¶

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 is hc-18/live/ in the bucket crcnsarchive, which is what the paper cites (data descriptor version 0.61); the MD5 sums of the files read are printed below. Streamed and reduced in memory by drieu2018.py, as in the first notebook.

Decoding follows the Methods (Bayesian trajectory decoding; Assessing trajectories) and the paper's scripts in the data set's code.zip (BatchSequenceReconstructNewProto.m, BatchSequenceQuadrants.m, BatchReplayReconstructNewProto.m, BatchCandidateEvents.m). The paper uses 5000 shuffles per event; this notebook uses 200 (see the deviation in the record): with about 30,000 theta cycles and 60,000 candidate events, 5000 shuffles would take about 10 hours here. 200 shuffles resolve Monte Carlo p-values to 0.005, well below the 0.05 used to call an event significant.

claim here
fig3b-average-theta-reconstruction tested
figs5b-per-rat-reconstruction tested
fig3c-theta-scores-above-chance tested
fig3c-proportion-significant-theta tested
fig3d-theta-slopes-steeper-active tested
fig3e-joint-score-slope-theta tested
fig3f-quadrant-scores tested
figs9-control-decoding-quality tested (cross-validated error in the controls notebook)
fig4b-replay-scores-vs-baseline tested
fig4c-replay-slopes-steeper-active tested
fig4d-joint-score-slope-replay tested
fig4e-replay-proportion-vs-baseline tested
fig4f-forward-replay-after-active tested
figs12-ripple-restricted tested
fig3g-theta-self-consistency, fig4g-theta-replay-correlation-active in the controls notebook
figs7-control-cell-count, figs8-control-firing-rate, figs10-control-lap-variability in the controls notebook
the travel, field, theta-LFP and sleep claims in the first notebook

Revised after round 1 of verification: the theta channel now leaves out channels with reversed theta (rat 272), and the forward-replay test (fig4f) compares forward with reverse events. Decoding under field reading (b) and the whole-session threshold, and the controls, are in reproduce_drieu_2018_controls.ipynb.

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
from statsmodels.stats.anova import AnovaRM
import drieu2018 as D

T_START = time.time()
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)
NSH = 200
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 96 s
Train-242-20140124: 214 s, peak memory 3.7 GB
Train-261-20140617: streamed in 83 s
Train-261-20140617: 185 s, peak memory 3.8 GB
Train-272-20141215: streamed in 164 s
Train-272-20141215: 308 s, peak memory 4.5 GB
Train-292-20150501: streamed in 140 s
Train-292-20150501: 236 s, peak memory 5.6 GB
Train-314-20160118: streamed in 294 s
Train-314-20160118: 492 s, peak memory 6.4 GB

Decoding theta cycles¶

For each rat and travel condition, the decoder is trained on that condition's place cells (field reading a of the claims file) and applied to its theta cycles, six phase windows of pi/3 per cycle. Every analysed cycle gets a trajectory score and slope against 200 shuffles, and a quadrant score.

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."""
    v_bins_per_win = Dv / (m - 1)
    return v_bins_per_win * BIN_M / (dur_s / m)

TH = {}
rows = []
t0 = time.time()
for k, name in enumerate(D.RATS):
    P, LF = PREP[name], LFPS[name]
    for j, c in enumerate(D.CONDS):
        rng = np.random.default_rng(1000 + 10 * k + j)
        th = D.decode_theta(P, LF, c)
        sc = D.score_events(th["mats"], NSH, rng)
        q = D.quadrant_scores(th["cent"])
        TH[(name, c)] = dict(th=th, sc=sc, q=q)
        mean_period = np.mean(np.diff(th["edges"][:, [0, 6]], axis=1)) if len(th["edges"]) else np.nan
        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_a=slope_ms(sc["D"][e], 6, th["dur"][e]), slope_b=slope_ms(sc["D"][e], 6, mean_period),
                             cm_per_cycle=sc["D"][e] / 5 * 6 * BIN_M * 100))
        print(f"{name[6:9]} {c}: place cells {th['n_cells']}, theta cycles {th['n_cycles_all']}, analysed {len(th['mats'])} "
              f"({time.time() - t0:.0f} s)", flush=True)
CY = pd.DataFrame(rows)
242 P1: place cells 31, theta cycles 2265, analysed 1764 (25 s)
242 A: place cells 31, theta cycles 1119, analysed 962 (38 s)
242 P2: place cells 32, theta cycles 1801, analysed 1454 (57 s)
261 P1: place cells 14, theta cycles 3226, analysed 1114 (69 s)
261 A: place cells 13, theta cycles 2350, analysed 874 (79 s)
261 P2: place cells 14, theta cycles 2352, analysed 510 (84 s)
272 P1: place cells 67, theta cycles 2466, analysed 2300 (119 s)
272 A: place cells 63, theta cycles 1741, analysed 1640 (144 s)
272 P2: place cells 71, theta cycles 1737, analysed 1617 (169 s)
292 P1: place cells 25, theta cycles 2289, analysed 1537 (187 s)
292 A: place cells 24, theta cycles 2693, analysed 2256 (214 s)
292 P2: place cells 28, theta cycles 2264, analysed 1816 (235 s)
314 P1: place cells 70, theta cycles 1737, analysed 1714 (261 s)
314 A: place cells 72, theta cycles 1894, analysed 1885 (290 s)
314 P2: place cells 83, theta cycles 1637, analysed 1601 (314 s)
In [5]:
print("Analysed theta cycles per rat and condition:")
print(CY.groupby(["rat", "cond"]).size().unstack().reindex(columns=D.CONDS).to_string())
print("Cycle duration (s): ", CY.dur.describe().round(3).to_dict())
print("Trajectory score range", CY.score.min().round(3), CY.score.max().round(3), "; Monte Carlo p range", CY.p.min(), CY.p.max())
print("Quadrant score range", np.nanmin(CY.quad).round(3), np.nanmax(CY.quad).round(3), "; NaN quadrant scores", int(CY.quad.isna().sum()))
Analysed theta cycles per rat and condition:
cond    P1     A    P2
rat                   
242   1764   962  1454
261   1114   874   510
272   2300  1640  1617
292   1537  2256  1816
314   1714  1885  1601
Cycle duration (s):  {'count': 23044.0, 'mean': 0.135, 'std': 0.014, 'min': 0.071, '25%': 0.127, '50%': 0.135, '75%': 0.142, 'max': 0.194}
Trajectory score range 0.171 0.996 ; Monte Carlo p range 0.0 1.0
Quadrant score range -0.962 0.947 ; NaN quadrant scores 0

fig3b-average-theta-reconstruction¶

Averaged over all theta cycles of all rats, the reconstruction of position across theta phase had trajectory score 0.17 and slope 6 cm/cycle in Passive 1, 0.23 and 48 cm/cycle in Active, and 0.19 and 21 cm/cycle in Passive 2.

Decoded probabilities centred on the animal's position, averaged over all analysed cycles of all rats, then scored. The slope is the best line's displacement over the six windows, in cm per cycle (displacement per window times 6).

In [6]:
AVG = {}
rng = np.random.default_rng(2001)
for c in D.CONDS:
    allc = np.concatenate([TH[(n, c)]["th"]["cent"] for n in D.RATS])
    avg = np.nanmean(allc, 0)
    o = D.score_events([avg], 10, rng)
    AVG[c] = dict(score=o["score"][0], cm=o["D"][0] / 5 * 6 * BIN_M * 100, n=len(allc))
exp = {"P1": (0.17, 6), "A": (0.23, 48), "P2": (0.19, 21)}
tolr = {"P1": (0.017, 3), "A": (0.023, 4.8), "P2": (0.019, 3)}
for c in D.CONDS:
    a = AVG[c]
    print(f"{c}: cycles {a['n']}, score {a['score']:.3f} (expected {exp[c][0]} +/- {tolr[c][0]}), slope {a['cm']:.1f} cm/cycle "
          f"(expected {exp[c][1]} +/- {tolr[c][1]})")
P1: cycles 8429, score 0.178 (expected 0.17 +/- 0.017), slope 17.3 cm/cycle (expected 6 +/- 3)
A: cycles 7617, score 0.249 (expected 0.23 +/- 0.023), slope 60.5 cm/cycle (expected 48 +/- 4.8)
P2: cycles 6998, score 0.205 (expected 0.19 +/- 0.019), slope 20.2 cm/cycle (expected 21 +/- 3)

Result: partially reproduced. The scores 0.178, 0.249 and 0.205 are within tolerance and Active has the highest score and slope, but two slopes are outside tolerance: 17.3 cm/cycle in Passive 1 against 6 +/- 3, and 60.5 in Active against 48 +/- 4.8; Passive 2 (20.2 against 21 +/- 3) is within.

figs5b-per-rat-reconstruction¶

Across the five rats, the trajectory scores, slopes and quadrant scores of the average theta reconstructions differed between conditions (repeated-measures ANOVA, P = 0.008, 0.007 and 0.004), higher in Active.

In [7]:
rows = []
rng = np.random.default_rng(2002)
for name in D.RATS:
    for c in D.CONDS:
        cent = TH[(name, c)]["th"]["cent"]
        avg = np.nanmean(cent, 0)
        o = D.score_events([avg], 10, rng)
        q = D.quadrant_scores(avg[None])[0]
        rows.append(dict(rat=name[6:9], cond=c, score=o["score"][0], slope=o["D"][0] / 5 * 6 * BIN_M * 100, quad=q))
PR = pd.DataFrame(rows)
print(PR.round(3).pivot(index="rat", columns="cond").to_string())
for col in ["score", "slope", "quad"]:
    res = AnovaRM(PR, col, "rat", within=["cond"]).fit().anova_table
    print(f"{col}: means {PR.groupby('cond')[col].mean().reindex(D.CONDS).round(3).to_dict()}; RM-ANOVA F = {res['F Value'].iloc[0]:.2f}, P = {res['Pr > F'].iloc[0]:.4f}")
      score                slope                 quad              
cond      A     P1     P2      A     P1     P2      A     P1     P2
rat                                                                
242   0.196  0.170  0.175  63.36  14.40   5.76  0.030  0.007  0.007
261   0.305  0.176  0.211  63.36   5.76  48.96  0.112  0.012  0.021
272   0.271  0.175  0.209  51.84   8.64   5.76  0.051  0.004  0.013
292   0.203  0.188  0.209  74.88  46.08  31.68  0.048  0.014  0.032
314   0.280  0.180  0.219  60.48  31.68  20.16  0.104  0.012  0.024
score: means {'P1': 0.178, 'A': 0.251, 'P2': 0.205}; RM-ANOVA F = 9.69, P = 0.0073
slope: means {'P1': 21.312, 'A': 62.784, 'P2': 22.464}; RM-ANOVA F = 17.01, P = 0.0013
quad: means {'P1': 0.01, 'A': 0.069, 'P2': 0.019}; RM-ANOVA F = 12.60, P = 0.0034

Result: reproduced. Over rats, the score (P = 0.0073), slope (P = 0.0013) and quadrant score (P = 0.0034) all differ by RM-ANOVA, with the Active mean highest for each (0.251, 62.8 cm/cycle, 0.069). Every rat now has its highest slope and quadrant score in Active; rat 272 did not before its theta channel was corrected.

fig3c-theta-scores-above-chance¶

Normalized trajectory scores of theta sequences were better than chance in all three conditions, and differed between conditions (Kruskal-Wallis, P < 10^-23).

In [8]:
g = {c: CY[CY.cond == c].z.values for c in D.CONDS}
for c in D.CONDS:
    w = stats.wilcoxon(g[c])
    print(f"{c}: n {len(g[c])}, median normalized score {np.median(g[c]):.3f}, signed-rank vs 0 P = {w.pvalue:.1e}")
h, p = stats.kruskal(*g.values())
print(f"KW H = {h:.1f}, P = {p:.1e}")
for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
    pp = stats.mannwhitneyu(g[a], g[b]).pvalue
    print(f"   rank-sum {a} vs {b}: P (Bonferroni x3) = {min(1, 3 * pp):.1e}; medians {np.median(g[a]):.3f} vs {np.median(g[b]):.3f}")
print("per rat median normalized score:")
print(CY.groupby(["rat", "cond"]).z.median().unstack().reindex(columns=D.CONDS).round(3).to_string())
P1: n 8429, median normalized score 0.471, signed-rank vs 0 P = 8.3e-245
A: n 7617, median normalized score 0.667, signed-rank vs 0 P = 0.0e+00
P2: n 6998, median normalized score 0.660, signed-rank vs 0 P = 0.0e+00
KW H = 169.1, P = 1.9e-37
   rank-sum P1 vs A: P (Bonferroni x3) = 7.8e-32; medians 0.471 vs 0.667
   rank-sum A vs P2: P (Bonferroni x3) = 4.9e-01; medians 0.667 vs 0.660
   rank-sum P1 vs P2: P (Bonferroni x3) = 3.4e-24; medians 0.471 vs 0.660
per rat median normalized score:
cond     P1      A     P2
rat                      
242   0.240  0.339  0.657
261   0.507  0.662  0.563
272   0.521  0.963  0.848
292   0.509  0.475  0.585
314   0.560  0.909  0.618

Result: reproduced. Median normalized scores (0.471, 0.667 and 0.660) are above 0 in every condition (signed-rank P = 8.3 x 10^-245 and below), and differ across conditions (Kruskal-Wallis P = 1.9 x 10^-37); Passive 1 is below Active and Passive 2 (Bonferroni P = 7.8 x 10^-32 and 3.4 x 10^-24), and Active does not differ from Passive 2 (P = 0.49).

fig3c-proportion-significant-theta¶

The proportion of significant theta sequences (significant score, positive slope) was 7.95% in Passive 1, 13.61% in Active and 9.05% in Passive 2, each above shuffled control, and Active exceeded both passive conditions.

Shuffled control: for each shuffle j, every event's j-th shuffled score is tested against its other shuffles with the same rule (p <= 0.05, and positive slope); the 200 shuffled proportions give the Monte Carlo test.

In [9]:
def shuffled_props(keys, slope_rule):
    out = []
    for j in range(NSH):
        k_sig, n = 0, 0
        for key in keys:
            sc = TH[key]["sc"] if key in TH else REP[key]["sc"]
            if len(sc["score"]) == 0:
                continue
            sh = sc["sh_score"]
            pj = (np.sum(sh > sh[:, j:j + 1], 1)) / (NSH - 1)
            ok = pj <= 0.05
            if slope_rule == "pos":
                ok &= sc["sh_D"][:, j] > 0
            k_sig += ok.sum()
            n += len(sh)
        out.append(k_sig / n)
    return np.array(out)

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))
In [10]:
SIGTH = {}
for rule, lab in [("pos", "significant and positive slope"), ("any", "significant, any slope")]:
    print(lab)
    for c in D.CONDS:
        sub = CY[CY.cond == c]
        sig = (sub.p <= 0.05) & ((sub.D > 0) if rule == "pos" else True)
        shp = shuffled_props([(n, c) for n in D.RATS], rule)
        SIGTH[(c, rule)] = (int(sig.sum()), len(sub))
        print(f"   {c}: {sig.sum()}/{len(sub)} = {100 * sig.mean():.2f}%; shuffled control mean {100 * shp.mean():.2f}% (max {100 * shp.max():.2f}%), "
              f"Monte Carlo P = {np.mean(shp >= sig.mean()):.3f}")
    for a, b in [("A", "P1"), ("A", "P2"), ("P1", "P2")]:
        z, p = prop_test(*SIGTH[(a, rule)], *SIGTH[(b, rule)])
        print(f"   binomial proportion test {a} vs {b}: z = {z:.2f}, P = {p:.1e}")
print("expected: 7.95, 13.61, 9.05 (positive slope); 14.66, 20.20, 16.37 (any slope); tolerance 10%")
print("per rat, % significant with positive slope:")
print((CY.assign(s=(CY.p <= 0.05) & (CY.D > 0)).groupby(["rat", "cond"]).s.mean().unstack().reindex(columns=D.CONDS) * 100).round(2).to_string())
significant and positive slope
   P1: 619/8429 = 7.34%; shuffled control mean 2.50% (max 2.95%), Monte Carlo P = 0.000
   A: 917/7617 = 12.04%; shuffled control mean 2.51% (max 3.09%), Monte Carlo P = 0.000
   P2: 690/6998 = 9.86%; shuffled control mean 2.49% (max 3.07%), Monte Carlo P = 0.000
   binomial proportion test A vs P1: z = 10.09, P = 5.8e-24
   binomial proportion test A vs P2: z = 4.21, P = 2.6e-05
   binomial proportion test P1 vs P2: z = -5.58, P = 2.4e-08
significant, any slope
   P1: 1204/8429 = 14.28%; shuffled control mean 5.03% (max 5.68%), Monte Carlo P = 0.000
   A: 1435/7617 = 18.84%; shuffled control mean 5.02% (max 5.67%), Monte Carlo P = 0.000
   P2: 1230/6998 = 17.58%; shuffled control mean 5.02% (max 5.67%), Monte Carlo P = 0.000
   binomial proportion test A vs P1: z = 7.77, P = 7.6e-15
   binomial proportion test A vs P2: z = 1.98, P = 4.8e-02
   binomial proportion test P1 vs P2: z = -5.58, P = 2.3e-08
expected: 7.95, 13.61, 9.05 (positive slope); 14.66, 20.20, 16.37 (any slope); tolerance 10%
per rat, % significant with positive slope:
cond    P1      A     P2
rat                     
242   4.76   7.59   8.46
261   6.82  11.21   9.80
272   9.52  15.00  11.56
292   6.77   6.21   8.92
314   7.93  19.10  10.49

Result: partially reproduced. With the slope rule the proportions are 7.34%, 12.04% and 9.86%; without it 14.28%, 18.84% and 17.58%. Five of six are within tolerance (Active with the slope rule, 12.04% against 13.61 +/- 1.36%, is not). All exceed the shuffled control (about 2.5% and 5%, Monte Carlo P < 0.005). Active exceeds Passive 1 (P = 5.8 x 10^-24) and Passive 2 (P = 2.6 x 10^-5) at P < 0.001, and Passive 2 exceeds Passive 1 (P = 2.4 x 10^-8).

fig3d-theta-slopes-steeper-active¶

Slopes of significant theta sequences were steeper during active travel than in either passive condition, while the two passive conditions did not differ.

In [11]:
sig = CY[CY.p <= 0.05]
for col in ["slope_a", "slope_b"]:
    for kind in ["signed", "absolute"]:
        g = {c: (sig[sig.cond == c][col].values if kind == "signed" else np.abs(sig[sig.cond == c][col].values)) for c in D.CONDS}
        h, p = stats.kruskal(*g.values())
        print(f"{col} ({kind}): n {[len(v) for v in g.values()]}, median (m/s) {[round(np.median(v), 2) for v in g.values()]}; KW P = {p:.1e}")
        for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
            ks = stats.ks_2samp(g[a], g[b])
            print(f"   KS {a} vs {b}: D = {ks.statistic:.3f}, P = {ks.pvalue:.1e}")
print("slope_a range (m/s):", sig.slope_a.min().round(1), sig.slope_a.max().round(1))
slope_a (signed): n [1204, 1435, 1230], median (m/s) [np.float64(0.23), np.float64(2.44), np.float64(0.44)]; KW P = 1.1e-13
   KS P1 vs A: D = 0.165, P = 4.4e-16
   KS A vs P2: D = 0.143, P = 2.4e-12
   KS P1 vs P2: D = 0.047, P = 1.3e-01
slope_a (absolute): n [1204, 1435, 1230], median (m/s) [np.float64(4.69), np.float64(6.9), np.float64(5.44)]; KW P = 9.1e-05
   KS P1 vs A: D = 0.108, P = 4.6e-07
   KS A vs P2: D = 0.088, P = 7.0e-05
   KS P1 vs P2: D = 0.042, P = 2.3e-01
slope_b (signed): n [1204, 1435, 1230], median (m/s) [np.float64(0.22), np.float64(2.46), np.float64(0.44)]; KW P = 9.7e-14
   KS P1 vs A: D = 0.167, P = 1.7e-16
   KS A vs P2: D = 0.145, P = 1.2e-12
   KS P1 vs P2: D = 0.047, P = 1.3e-01
slope_b (absolute): n [1204, 1435, 1230], median (m/s) [np.float64(4.83), np.float64(6.98), np.float64(5.16)]; KW P = 1.4e-04
   KS P1 vs A: D = 0.114, P = 7.9e-08
   KS A vs P2: D = 0.090, P = 4.0e-05
   KS P1 vs P2: D = 0.043, P = 1.9e-01
slope_a range (m/s): -72.4 72.0

Result: reproduced. Signed slopes of significant sequences (conversion reading a): medians 0.23, 2.44 and 0.44 m/s; KS Active against Passive 1 P = 4.4 x 10^-16 and against Passive 2 P = 2.4 x 10^-12, both below 10^-6, and Passive 1 against Passive 2 P = 0.13. Reading (b) gives the same (1.7 x 10^-16, 1.2 x 10^-12, 0.13). Absolute slopes give P = 4.6 x 10^-7 and 7.0 x 10^-5 for the Active comparisons.

fig3e-joint-score-slope-theta¶

Joint analysis of trajectory scores and slopes showed a much greater proportion of high-score, high-slope theta sequences during active travel.

Z-proportions (Methods, Z-proportions): the score-slope matrix of event proportions, each cell z-scored against the same cell of the shuffled matrices (here 200, one per shuffle index). Grid 0.05 score by 3 m/s slope, and half and double. High-value region (criterion): score above the 95th percentile of the pooled shuffled scores and slope above 3 m/s. Slopes with reading (a).

In [12]:
def zprop(scores, slopes, sh_scores, sh_slopes, ds, dv, region):
    se = np.arange(0, 1.0001 + ds, ds)
    ve = np.arange(-60, 60 + dv, dv)
    H = np.histogram2d(scores, np.clip(slopes, -59.9, 59.9), [se, ve])[0] / len(scores)
    Hs = np.array([np.histogram2d(sh_scores[:, j], np.clip(sh_slopes[:, j], -59.9, 59.9), [se, ve])[0] / len(scores) for j in range(sh_scores.shape[1])])
    with np.errstate(invalid="ignore", divide="ignore"):
        Z = (H - Hs.mean(0)) / Hs.std(0)
    sc_c = (se[:-1] + se[1:]) / 2
    v_c = (ve[:-1] + ve[1:]) / 2
    reg = region(sc_c[:, None], v_c[None, :])
    Zr = np.where(reg & np.isfinite(Z) & (Z > 0), Z, 0).sum()
    return Zr

def theta_shuffled_slopes(key):
    th, sc = TH[key]["th"], TH[key]["sc"]
    return slope_ms(sc["sh_D"], 6, th["dur"][:, None])
In [13]:
shs_all = np.concatenate([TH[k]["sc"]["sh_score"].ravel() for k in TH])
thr95 = np.percentile(shs_all, 95)
print(f"95th percentile of pooled shuffled theta scores: {thr95:.3f}")
region = lambda s, v: (s > thr95) & (v > 3)
for ds, dv in [(0.05, 3), (0.025, 1.5), (0.1, 6)]:
    zr = {}
    for c in D.CONDS:
        keys = [(n, c) for n in D.RATS]
        sc = np.concatenate([TH[k]["sc"]["score"] for k in keys])
        sl = np.concatenate([CY[(CY.rat == k[0][6:9]) & (CY.cond == c)].slope_a.values for k in keys])
        shs = np.concatenate([TH[k]["sc"]["sh_score"] for k in keys])
        shv = np.concatenate([theta_shuffled_slopes(k) for k in keys])
        zr[c] = zprop(sc, sl, shs, shv, ds, dv, region)
    print(f"grid {ds} x {dv} m/s: summed positive z-proportion in the high-value region {dict((c, round(v, 1)) for c, v in zr.items())}")
cnt = {}
for c in D.CONDS:
    sub = CY[CY.cond == c]
    k = int(((sub.score > thr95) & (sub.slope_a > 3)).sum())
    cnt[c] = (k, len(sub))
    print(f"{c}: events in region {k}/{len(sub)} = {100 * k / len(sub):.2f}%")
for a in ["P1", "P2"]:
    z, p = prop_test(*cnt["A"], *cnt[a])
    print(f"   binomial proportion test A vs {a}: z = {z:.2f}, P = {p:.1e}")
95th percentile of pooled shuffled theta scores: 0.401
grid 0.05 x 3 m/s: summed positive z-proportion in the high-value region {'P1': np.float64(37.3), 'A': np.float64(351.0), 'P2': np.float64(129.6)}
grid 0.025 x 1.5 m/s: summed positive z-proportion in the high-value region {'P1': np.float64(71.9), 'A': np.float64(696.9), 'P2': np.float64(274.4)}
grid 0.1 x 6 m/s: summed positive z-proportion in the high-value region {'P1': np.float64(6.1), 'A': np.float64(108.5), 'P2': np.float64(40.8)}
P1: events in region 23/8429 = 0.27%
A: events in region 740/7617 = 9.72%
P2: events in region 206/6998 = 2.94%
   binomial proportion test A vs P1: z = 28.07, P = 2.6e-173
   binomial proportion test A vs P2: z = 16.62, P = 5.0e-62

Result: reproduced, resting on the claims file's region. The summed positive z-proportion in the high-value region (score above 0.401, slope above 3 m/s) is 37.3, 351.0 and 129.6 on the 0.05 by 3 m/s grid, and largest in Active on the half and double grids too. 0.27%, 9.72% and 2.94% of events fall in the region; Active exceeds both passive conditions (binomial P = 2.6 x 10^-173 and 5.0 x 10^-62).

fig3f-quadrant-scores¶

Quadrant scores of theta cycles were greater during active travel, remained very low in passive travel, and were higher in Passive 2 than in Passive 1 (Kruskal-Wallis, P < 10^-24).

In [14]:
g = {c: CY[CY.cond == c].quad.dropna().values for c in D.CONDS}
h, p = stats.kruskal(*g.values())
print(f"n {[len(v) for v in g.values()]}; median quadrant score {[round(np.median(v), 4) for v in g.values()]}; mean {[round(np.mean(v), 4) for v in g.values()]}; KW P = {p:.1e}")
for a, b in [("A", "P1"), ("A", "P2"), ("P2", "P1")]:
    pp = stats.mannwhitneyu(g[a], g[b]).pvalue
    print(f"   rank-sum {a} vs {b}: P (Bonferroni x3) = {min(1, 3 * pp):.1e}; median {np.median(g[a]):.4f} vs {np.median(g[b]):.4f}")
print(CY.groupby(["rat", "cond"]).quad.median().unstack().reindex(columns=D.CONDS).round(4).to_string())
n [8429, 7617, 6998]; median quadrant score [np.float64(0.0053), np.float64(0.0503), np.float64(0.0127)]; mean [np.float64(0.0086), np.float64(0.063), np.float64(0.018)]; KW P = 1.1e-65
   rank-sum A vs P1: P (Bonferroni x3) = 9.4e-63; median 0.0503 vs 0.0053
   rank-sum A vs P2: P (Bonferroni x3) = 2.8e-34; median 0.0503 vs 0.0127
   rank-sum P2 vs P1: P (Bonferroni x3) = 3.1e-03; median 0.0127 vs 0.0053
cond      P1       A      P2
rat                         
242   0.0033  0.0218  0.0055
261   0.0089  0.0969  0.0141
272   0.0034  0.0379  0.0061
292   0.0069  0.0430  0.0251
314   0.0096  0.0821  0.0149

Result: reproduced. Kruskal-Wallis gives P = 1.1 x 10^-65; Active is above Passive 1 and Passive 2 (Bonferroni P = 9.4 x 10^-63 and 2.8 x 10^-34), and Passive 2 above Passive 1 (P = 0.0031). Active has the highest median quadrant score in every rat.

Theta polarity in rats 292 and 314¶

In rats 292 and 314, recorded at 20 kHz, the pyramidal cells' spikes fall at -5 to -51 deg of the theta channel's phase (0 at peaks) on every channel, against -67 to -175 deg and 149 to 168 deg in the other rats (travel/sleep notebook, data check), which fits an inverted signal polarity. The data set does not say, so the analyses above keep the recorded sign. Inverting the sign shifts the theta cycles, and so the six phase windows, by half a cycle. Below, the theta cycles of these two rats are decoded again with the theta LFP inverted, and the tests of fig3c, fig3d and fig3f are repeated with them in place of the recorded-sign cycles (200 shuffles, other seeds).

In [15]:
rows = []
t0 = time.time()
for k, name in enumerate(D.RATS):
    if name[6:9] not in ("292", "314"):
        continue
    P, LF = PREP[name], LFPS[name]
    LFi = dict(LF, travel={c: dict(v, a=-v["a"]) for c, v in LF["travel"].items()})
    for j, c in enumerate(D.CONDS):
        rng = np.random.default_rng(1500 + 10 * k + j)
        th = D.decode_theta(P, LFi, c)
        sc = D.score_events(th["mats"], NSH, rng)
        q = D.quadrant_scores(th["cent"])
        for e in range(len(th["mats"])):
            rows.append(dict(rat=name[6:9], cond=c, z=sc["z"][e], p=sc["p"][e], D=sc["D"][e], quad=q[e],
                             slope_a=slope_ms(sc["D"][e], 6, th["dur"][e])))
CYI = pd.DataFrame(rows)
print(f"{time.time() - t0:.0f} s")
inv = CYI.assign(sign="inverted")
rec = CY[CY.rat.isin(["292", "314"])][inv.columns.drop("sign")].assign(sign="recorded")
both = pd.concat([rec, inv])
print("rats 292 and 314, per rat and condition: cycles, median normalized score, median quadrant score, % significant with positive slope,")
print("median signed slope of significant cycles (m/s), recorded sign and inverted:")
summ = both.groupby(["rat", "sign", "cond"]).apply(lambda g: pd.Series(dict(
    n=len(g), z=round(g.z.median(), 3), quad=round(g.quad.median(), 4), pct_sig_pos=round(100 * ((g.p <= 0.05) & (g.D > 0)).mean(), 2),
    sig_slope=round(g[g.p <= 0.05].slope_a.median(), 2))), include_groups=False)
print(summ.unstack("cond").to_string())
ALT = pd.concat([CY[~CY.rat.isin(["292", "314"])][inv.columns.drop("sign")], CYI])
for lab, T in [("recorded sign (as above)", CY), ("rats 292 and 314 inverted", ALT)]:
    g = {c: T[T.cond == c] for c in D.CONDS}
    sig = {c: v[v.p <= 0.05].slope_a for c, v in g.items()}
    print(f"--- all rats, {lab}: cycles {[len(v) for v in g.values()]}")
    print(f"   % significant with positive slope {[round(100 * ((v.p <= 0.05) & (v.D > 0)).mean(), 2) for v in g.values()]}")
    print(f"   normalized score medians {[round(v.z.median(), 3) for v in g.values()]}; KW P = {stats.kruskal(*[v.z for v in g.values()]).pvalue:.1e}")
    print(f"   quadrant score medians {[round(v.quad.median(), 4) for v in g.values()]}; KW P = {stats.kruskal(*[v.quad.dropna() for v in g.values()]).pvalue:.1e}")
    for b in ["P1", "P2"]:
        print(f"      quadrant rank-sum A vs {b}: P (Bonferroni x3) = {min(1, 3 * stats.mannwhitneyu(g['A'].quad.dropna(), g[b].quad.dropna()).pvalue):.1e}")
    print(f"   significant signed slopes, medians {[round(v.median(), 2) for v in sig.values()]} m/s")
    for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
        print(f"      KS {a} vs {b}: P = {stats.ks_2samp(sig[a], sig[b]).pvalue:.1e}")
144 s
rats 292 and 314, per rat and condition: cycles, median normalized score, median quadrant score, % significant with positive slope,
median signed slope of significant cycles (m/s), recorded sign and inverted:
                   n                      z                  quad                 pct_sig_pos              sig_slope            
cond               A      P1      P2      A     P1     P2       A      P1      P2           A    P1     P2         A    P1    P2
rat sign                                                                                                                        
292 inverted  2272.0  1512.0  1779.0  0.410  0.418  0.571 -0.0545 -0.0130 -0.0283        5.99  5.89   5.62      0.00  0.08 -0.52
    recorded  2256.0  1537.0  1816.0  0.475  0.509  0.585  0.0430  0.0069  0.0251        6.21  6.77   8.92      0.33  0.00  1.20
314 inverted  1837.0  1779.0  1607.0  0.795  0.523  0.603 -0.1000 -0.0119 -0.0248       10.67  7.53   8.46     -0.43  0.62  0.21
    recorded  1885.0  1714.0  1601.0  0.909  0.560  0.618  0.0821  0.0096  0.0149       19.10  7.93  10.49      4.38  0.82  0.86
--- all rats, recorded sign (as above): cycles [8429, 7617, 6998]
   % significant with positive slope [np.float64(7.34), np.float64(12.04), np.float64(9.86)]
   normalized score medians [np.float64(0.471), np.float64(0.667), np.float64(0.66)]; KW P = 1.9e-37
   quadrant score medians [np.float64(0.0053), np.float64(0.0503), np.float64(0.0127)]; KW P = 1.1e-65
      quadrant rank-sum A vs P1: P (Bonferroni x3) = 9.4e-63
      quadrant rank-sum A vs P2: P (Bonferroni x3) = 2.8e-34
   significant signed slopes, medians [np.float64(0.23), np.float64(2.44), np.float64(0.44)] m/s
      KS P1 vs A: P = 4.4e-16
      KS A vs P2: P = 2.4e-12
      KS P1 vs P2: P = 1.3e-01
--- all rats, rats 292 and 314 inverted: cycles [8469, 7585, 6967]
   % significant with positive slope [np.float64(7.11), np.float64(9.87), np.float64(8.55)]
   normalized score medians [np.float64(0.443), np.float64(0.655), np.float64(0.643)]; KW P = 7.8e-37
   quadrant score medians [np.float64(-0.0), np.float64(-0.0147), np.float64(-0.0051)]; KW P = 3.1e-08
      quadrant rank-sum A vs P1: P (Bonferroni x3) = 1.6e-08
      quadrant rank-sum A vs P2: P (Bonferroni x3) = 2.0e-02
   significant signed slopes, medians [np.float64(0.22), np.float64(0.45), np.float64(0.22)] m/s
      KS P1 vs A: P = 7.3e-02
      KS A vs P2: P = 5.2e-04
      KS P1 vs P2: P = 3.2e-01

Theta polarity. With the LFP of rats 292 and 314 inverted, their quadrant scores turn negative in every condition (Active -0.0545 and -0.100 against 0.043 and 0.082 with the recorded sign), so their decoded sequences run backward within the cycle, and their Active slopes of significant cycles drop to 0.00 and -0.43 m/s (0.33 and 4.38 recorded). Pooled over rats, the quadrant score medians become -0.000, -0.015 and -0.005, with Active lowest (Kruskal-Wallis P = 3.1 x 10^-8), and significant slopes of Active against Passive 1 give KS P = 0.073 (Passive 2 P = 5.2 x 10^-4). Normalized scores still differ (P = 7.8 x 10^-37). The fig3d and fig3f outcomes therefore rest on the recorded sign, which this attempt keeps since neither the data set nor the paper says the signal is inverted.

figs9-control-decoding-quality¶

With passive-travel theta cycles restricted to low decoding-error periods matching Active, slopes and quadrant scores still differed between conditions, while normalized scores no longer did (Kruskal-Wallis, P > 0.05).

Per rat and condition, positions decoded in 500-ms bins of moving travel with the condition's decoder; error = circular distance (m) between the decoded maximum and the actual position. In Passive 1 and Passive 2, the highest-error bin is dropped repeatedly until the median error is below the Active median (criterion's reading). Theta cycles starting in kept bins are kept.

In [16]:
ERR = {}
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]
    meds = {}
    for c in D.CONDS:
        cells = D.place_cells(P, c, "a")
        px, lam = D.train_decoder(P, c, cells)
        edges = []
        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:
                edges.append(np.arange(lo, hi - 0.5 + 1e-9, 0.5))
        starts = np.concatenate(edges) if edges else np.zeros(0)
        cnt = np.array([[np.sum((st >= s) & (st < s + 0.5)) for s in starts] for st in [P["cond"][c]["cells"][i]["spk_t"] for i in cells]])
        post = D.decode(cnt, np.full(len(starts), 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 + 0.25, tt, lu), 1)
        err = np.abs((dec - act + 0.5) % 1 - 0.5) * D.TRACK_M
        err[np.isnan(post[:, 0])] = np.nan
        ERR[(name, c)] = (starts, err)
        meds[c] = np.nanmedian(err)
    for c in D.CONDS:
        starts, err = ERR[(name, c)]
        kept = np.isfinite(err)
        if c != "A":
            order = np.argsort(-np.nan_to_num(err, nan=-1))
            k = 0
            while np.median(err[kept]) >= meds["A"] and kept.sum() > 1:
                kept[order[k]] = False
                k += 1
        keep_bins[(name, c)] = (starts[kept], err[kept])
    print(name[6:9], "median error (m) before:", {c: round(meds[c], 3) for c in D.CONDS},
          "after:", {c: round(np.median(keep_bins[(name, c)][1]), 3) for c in D.CONDS},
          "bins kept:", {c: f"{len(keep_bins[(name, c)][0])}/{np.isfinite(ERR[(name, c)][1]).sum()}" for c in D.CONDS})
rows = []
for name in D.RATS:
    for c in D.CONDS:
        starts = keep_bins[(name, c)][0]
        sub = CY[(CY.rat == name[6:9]) & (CY.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)
errs = {c: np.concatenate([keep_bins[(n, c)][1] for n in D.RATS]) for c in D.CONDS}
print("pooled 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)")
print("pooled median error after restriction (m):", {c: round(np.median(errs[c]), 3) for c in D.CONDS})
print("cycles kept:", CY9.groupby("cond").size().reindex(D.CONDS).to_dict(), "of", CY.groupby("cond").size().reindex(D.CONDS).to_dict())
s9 = CY9[CY9.p <= 0.05]
g = {c: s9[s9.cond == c].slope_a.values for c in D.CONDS}
print(f"significant slopes (m/s, reading a): n {[len(v) for v in g.values()]}, medians {[round(np.median(v), 2) for v in g.values()]}; KW P = {stats.kruskal(*g.values()).pvalue:.1e}")
for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
    print(f"   KS {a} vs {b}: P = {stats.ks_2samp(g[a], g[b]).pvalue:.1e}")
gz = {c: CY9[CY9.cond == c].z.values for c in D.CONDS}
print(f"normalized score medians {[round(np.median(v), 3) for v in gz.values()]}; KW P = {stats.kruskal(*gz.values()).pvalue:.1e}")
gq = {c: CY9[CY9.cond == c].quad.dropna().values for c in D.CONDS}
print(f"quadrant score medians {[round(np.median(v), 4) for v in gq.values()]}; KW P = {stats.kruskal(*gq.values()).pvalue:.1e}")
for a in ["P1", "P2"]:
    print(f"   quadrant rank-sum A vs {a}: P (Bonferroni x3) = {min(1, 3 * stats.mannwhitneyu(gq['A'], gq[a]).pvalue):.1e}")
242 median error (m) before: {'P1': np.float64(0.931), 'A': np.float64(0.402), 'P2': np.float64(0.76)} after: {'P1': np.float64(0.402), 'A': np.float64(0.402), 'P2': np.float64(0.401)} bins kept: {'P1': '699/1075', 'A': '666/666', 'P2': '642/881'}
261 median error (m) before: {'P1': np.float64(0.923), 'A': np.float64(0.276), 'P2': np.float64(0.618)} after: {'P1': np.float64(0.275), 'A': np.float64(0.276), 'P2': np.float64(0.275)} bins kept: {'P1': '499/1080', 'A': '715/715', 'P2': '526/825'}
272 median error (m) before: {'P1': np.float64(0.815), 'A': np.float64(0.141), 'P2': np.float64(0.316)} after: {'P1': np.float64(0.141), 'A': np.float64(0.141), 'P2': np.float64(0.141)} bins kept: {'P1': '417/896', 'A': '696/696', 'P2': '540/688'}
292 median error (m) before: {'P1': np.float64(0.601), 'A': np.float64(0.479), 'P2': np.float64(0.387)} after: {'P1': np.float64(0.479), 'A': np.float64(0.479), 'P2': np.float64(0.387)} bins kept: {'P1': '636/725', 'A': '800/800', 'P2': '713/713'}
314 median error (m) before: {'P1': np.float64(0.535), 'A': np.float64(0.115), 'P2': np.float64(0.225)} after: {'P1': np.float64(0.115), 'A': np.float64(0.115), 'P2': np.float64(0.115)} bins kept: {'P1': '569/970', 'A': '849/849', 'P2': '731/946'}
pooled error after restriction, mean +/- s.e.m. (m): {'P1': '0.414 +/- 0.008', 'A': '0.537 +/- 0.011', 'P2': '0.434 +/- 0.009'}  expected 0.802, 0.80, 0.802 (+/-0.018, 0.023, 0.014)
pooled median error after restriction (m): {'P1': np.float64(0.26), 'A': np.float64(0.259), 'P2': np.float64(0.241)}
cycles kept: {'P1': 5071, 'A': 7617, 'P2': 5788} of {'P1': 8429, 'A': 7617, 'P2': 6998}
significant slopes (m/s, reading a): n [765, 1435, 1058], medians [np.float64(0.28), np.float64(2.44), np.float64(0.59)]; KW P = 4.0e-10
   KS P1 vs A: P = 7.7e-10
   KS A vs P2: P = 1.3e-09
   KS P1 vs P2: P = 1.9e-01
normalized score medians [np.float64(0.512), np.float64(0.667), np.float64(0.687)]; KW P = 7.8e-22
quadrant score medians [np.float64(0.0057), np.float64(0.0503), np.float64(0.0145)]; KW P = 1.8e-51
   quadrant rank-sum A vs P1: P (Bonferroni x3) = 1.7e-45
   quadrant rank-sum A vs P2: P (Bonferroni x3) = 3.8e-28

Result: partially reproduced. After the restriction the median 500-ms error equals Active's in four rats (in rat 292 Passive 2's median, 0.387 m, was already below Active's 0.479 m), and the pooled mean errors are 0.414, 0.537 and 0.434 m, far from the expected 0.80 m. On the kept cycles significant slopes still differ (KS Active against Passive 1 P = 7.7 x 10^-10, against Passive 2 P = 1.3 x 10^-9; passive pair P = 0.19) and quadrant scores too (Kruskal-Wallis P = 1.8 x 10^-51), but normalized scores still differ (P = 7.8 x 10^-22), where the paper finds no difference. The errors here are in-sample; the controls notebook repeats the restriction with errors from decoders trained on the other laps and finds the same.

Replay: candidate events in sleep¶

Candidate events in SWS of each post-travel sleep, from the place cells of the preceding travel (field reading a; threshold mean and s.d. over SWS, as BatchCandidateEvents.m), and in baseline sleep from the same place cells; both decoded with that travel's decoder in 20-ms windows and scored against 200 shuffles.

In [17]:
SLEEP_OF = {"P1": "S1", "A": "SA", "P2": "S2"}
REP = {}
rows = []
t0 = time.time()
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, "a")
        px, lam = D.train_decoder(P, c, cells)
        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")]:
            sl = LF["sleep"][s]
            ev = D.candidate_events(allspk, sl["interval"], sl["sws"], norm="sws")
            mats, keep = D.replay_matrices(ev, spikes, px, lam)
            rng = np.random.default_rng(5000 + 100 * k + 10 * j + (kind == "base"))
            sc = D.score_events(mats, NSH, rng)
            REP[(name, c, kind)] = dict(sc=sc, ev=ev[keep], n_candidates=len(ev))
            rip = sl["ripples"]
            for e in range(len(mats)):
                a, pk, b = ev[keep[e]]
                m = len(mats[e])
                ov = np.any((rip[:, 0] <= b) & (rip[:, 2] >= a)) if len(rip) else False
                pin = np.any((rip[:, 0] <= pk) & (rip[:, 2] >= pk)) if len(rip) else False
                rows.append(dict(rat=name[6:9], cond=c, kind=kind, score=sc["score"][e], z=sc["z"][e], p=sc["p"][e], D=sc["D"][e],
                                 m=m, slope=sc["D"][e] / (m - 1) * BIN_M / 0.02, rip_overlap=ov, rip_peak=pin))
        print(f"{name[6:9]} {c}: place cells {len(cells)}; post events {REP[(name, c, 'post')]['n_candidates']} -> {len(REP[(name, c, 'post')]['sc']['score'])} decoded; "
              f"baseline {REP[(name, c, 'base')]['n_candidates']} -> {len(REP[(name, c, 'base')]['sc']['score'])} ({time.time() - t0:.0f} s)", flush=True)
EV = pd.DataFrame(rows)
# score relative to baseline, per rat and decoder (Methods, Assessing trajectories, paragraph 3)
EV["rel"] = np.nan
for (rat, c), sub in EV.groupby(["rat", "cond"]):
    b = sub[sub.kind == "base"].score
    q1, med, q3 = np.percentile(b, [25, 50, 75])
    EV.loc[sub.index, "rel"] = (sub.score - med) / (q3 - q1)
242 P1: place cells 31; post events 1938 -> 1556 decoded; baseline 2156 -> 1694 (77 s)
242 A: place cells 31; post events 1911 -> 1564 decoded; baseline 2127 -> 1626 (152 s)
242 P2: place cells 32; post events 539 -> 434 decoded; baseline 2105 -> 1633 (202 s)
261 P1: place cells 14; post events 3690 -> 1527 decoded; baseline 2176 -> 1018 (237 s)
261 A: place cells 13; post events 2521 -> 1054 decoded; baseline 2507 -> 857 (264 s)
261 P2: place cells 14; post events 2176 -> 1055 decoded; baseline 2034 -> 917 (292 s)
272 P1: place cells 67; post events 1259 -> 1120 decoded; baseline 466 -> 408 (346 s)
272 A: place cells 63; post events 740 -> 636 decoded; baseline 483 -> 405 (381 s)
272 P2: place cells 71; post events 1362 -> 1221 decoded; baseline 497 -> 430 (439 s)
292 P1: place cells 25; post events 2944 -> 1751 decoded; baseline 3115 -> 1843 (515 s)
292 A: place cells 24; post events 1886 -> 1141 decoded; baseline 3336 -> 1880 (576 s)
292 P2: place cells 28; post events 2395 -> 1418 decoded; baseline 3100 -> 1868 (645 s)
314 P1: place cells 70; post events 834 -> 634 decoded; baseline 1132 -> 847 (699 s)
314 A: place cells 72; post events 2188 -> 1638 decoded; baseline 1081 -> 813 (790 s)
314 P2: place cells 83; post events 1550 -> 1182 decoded; baseline 1082 -> 812 (867 s)
In [18]:
print("Decoded candidate events per rat, decoder and sleep (post / baseline):")
print(EV.groupby(["rat", "cond", "kind"]).size().unstack([1, 2]).to_string())
print("windows per event:", EV.m.describe().round(1).to_dict())
print("fraction of events overlapping a ripple:", EV.groupby("kind").rip_overlap.mean().round(3).to_dict())
Decoded candidate events per rat, decoder and sleep (post / baseline):
cond     A          P1          P2      
kind  base  post  base  post  base  post
rat                                     
242   1626  1564  1694  1556  1633   434
261    857  1054  1018  1527   917  1055
272    405   636   408  1120   430  1221
292   1880  1141  1843  1751  1868  1418
314    813  1638   847   634   812  1182
windows per event: {'count': 34982.0, 'mean': 5.1, 'std': 2.5, 'min': 3.0, '25%': 3.0, '50%': 4.0, '75%': 6.0, 'max': 24.0}
fraction of events overlapping a ripple: {'base': 0.427, 'post': 0.44}

fig4b-replay-scores-vs-baseline¶

Replay trajectory scores, relative to baseline sleep, were improved only in sleep after Active and after Passive 2 (Kruskal-Wallis, P < 10^-17).

In [19]:
def fig4b(E, label):
    post = E[E.kind == "post"]
    g = {c: post[post.cond == c].rel.values for c in D.CONDS}
    print(label)
    for c in D.CONDS:
        w = stats.wilcoxon(g[c])
        print(f"   sleep after {c}: n {len(g[c])}, median score relative to baseline {np.median(g[c]):.3f}, signed-rank vs 0 P = {w.pvalue:.1e}")
    print(f"   KW P = {stats.kruskal(*g.values()).pvalue:.1e}")
    for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
        print(f"   rank-sum {a} vs {b}: P (Bonferroni x3) = {min(1, 3 * stats.mannwhitneyu(g[a], g[b]).pvalue):.1e}")
    print("   per rat median:", post.groupby(["rat", "cond"]).rel.median().unstack().reindex(columns=D.CONDS).round(3).to_dict("index"))
In [20]:
fig4b(EV, "all decoded candidate events")
all decoded candidate events
   sleep after P1: n 6588, median score relative to baseline -0.003, signed-rank vs 0 P = 4.7e-10
   sleep after A: n 6033, median score relative to baseline 0.261, signed-rank vs 0 P = 1.6e-209
   sleep after P2: n 5310, median score relative to baseline -0.043, signed-rank vs 0 P = 2.6e-04
   KW P = 1.0e-111
   rank-sum P1 vs A: P (Bonferroni x3) = 1.2e-84
   rank-sum A vs P2: P (Bonferroni x3) = 2.5e-84
   rank-sum P1 vs P2: P (Bonferroni x3) = 5.3e-01
   per rat median: {'242': {'P1': 0.264, 'A': 0.469, 'P2': 0.783}, '261': {'P1': -0.102, 'A': 0.523, 'P2': -0.065}, '272': {'P1': -0.33, 'A': -0.025, 'P2': -0.138}, '292': {'P1': 0.004, 'A': 0.133, 'P2': -0.277}, '314': {'P1': 0.059, 'A': 0.194, 'P2': 0.175}}

Result: partially reproduced. Relative to baseline, scores are improved after Active (median 0.261, signed-rank P = 1.6 x 10^-209). After Passive 1 the median is -0.003 and after Passive 2 -0.043, neither above 0. Kruskal-Wallis P = 1.0 x 10^-111. After Active alone the scores are improved, which the criterion calls partial; the paper also finds an improvement after Passive 2.

fig4c-replay-slopes-steeper-active¶

Replay slopes were steeper in sleep after Active than after either passive travel, while sleep after Passive 1 and Passive 2 did not differ.

In [21]:
def fig4c(E, label):
    post = E[E.kind == "post"]
    for sel, lab in [(post, "all events"), (post[post.p <= 0.05], "significant events")]:
        g = {c: np.abs(sel[sel.cond == c].slope.values) for c in D.CONDS}
        gs = {c: sel[sel.cond == c].slope.values for c in D.CONDS}
        print(f"{label}, {lab}: n {[len(v) for v in g.values()]}, median |slope| (m/s) {[round(np.median(v), 2) for v in g.values()]}; "
              f"KW P = {stats.kruskal(*g.values()).pvalue:.1e}")
        for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
            print(f"   KS signed slopes {a} vs {b}: P = {stats.ks_2samp(gs[a], gs[b]).pvalue:.1e}; KS |slopes| P = {stats.ks_2samp(g[a], g[b]).pvalue:.1e}")
In [22]:
fig4c(EV, "all decoded")
all decoded, all events: n [6588, 6033, 5310], median |slope| (m/s) [np.float64(24.6), np.float64(23.6), np.float64(24.6)]; KW P = 5.0e-02
   KS signed slopes P1 vs A: P = 8.2e-04; KS |slopes| P = 7.1e-09
   KS signed slopes A vs P2: P = 3.7e-01; KS |slopes| P = 9.1e-02
   KS signed slopes P1 vs P2: P = 2.2e-02; KS |slopes| P = 7.6e-05
all decoded, significant events: n [894, 948, 674], median |slope| (m/s) [np.float64(2.82), np.float64(5.87), np.float64(5.2)]; KW P = 6.1e-07
   KS signed slopes P1 vs A: P = 1.1e-06; KS |slopes| P = 3.2e-09
   KS signed slopes A vs P2: P = 1.0e-04; KS |slopes| P = 1.9e-01
   KS signed slopes P1 vs P2: P = 9.3e-03; KS |slopes| P = 1.0e-04

Result: not reproduced. On significant events, absolute slopes are steepest after Active (medians 2.82, 5.87 and 5.20 m/s), but the Kruskal-Wallis gives P = 6.1 x 10^-7, not below 10^-10, and after Active does not differ from after Passive 2 (KS P = 0.19), while the passive pair does (P = 1.0 x 10^-4). On all events the Kruskal-Wallis gives P = 0.050.

fig4d-joint-score-slope-replay¶

Joint analysis of replay trajectory scores and slopes showed a much greater proportion of high-score, high-slope events in sleep after Active.

As fig3e, on post-travel events, with |slope| above 3 m/s. The proportion ratio of fig. S13D is shown as the ratio of the post-sleep proportion in the region to the baseline one.

In [23]:
shr = np.concatenate([REP[k]["sc"]["sh_score"].ravel() for k in REP if k[2] == "post" and len(REP[k]["sc"]["score"])])
thr95r = np.percentile(shr, 95)
print(f"95th percentile of pooled shuffled replay scores: {thr95r:.3f}")
regr = lambda s, v: (s > thr95r) & (np.abs(v) > 3)
for ds, dv in [(0.05, 3), (0.025, 1.5), (0.1, 6)]:
    zr = {}
    for c in D.CONDS:
        keys = [(n, c, "post") for n in D.RATS if len(REP[(n, c, "post")]["sc"]["score"])]
        sc = np.concatenate([REP[k]["sc"]["score"] for k in keys])
        ms = np.concatenate([REP[k]["sc"]["m"] for k in keys])
        sl = np.concatenate([REP[k]["sc"]["D"] for k in keys]) / (ms - 1) * BIN_M / 0.02
        shs = np.concatenate([REP[k]["sc"]["sh_score"] for k in keys])
        shv = np.concatenate([REP[k]["sc"]["sh_D"] for k in keys]) / (ms[:, None] - 1) * BIN_M / 0.02
        zr[c] = zprop(sc, sl, shs, shv, ds, dv, regr)
    print(f"grid {ds} x {dv} m/s: summed positive z-proportion in the high-value region, sleep after {dict((c, round(v, 1)) for c, v in zr.items())}")
cnt = {}
for c in D.CONDS:
    for kind in ["post", "base"]:
        sub = EV[(EV.cond == c) & (EV.kind == kind)]
        cnt[(c, kind)] = (int(((sub.score > thr95r) & (sub.slope.abs() > 3)).sum()), len(sub))
    k, n = cnt[(c, "post")]
    kb, nb = cnt[(c, "base")]
    print(f"after {c}: in region {k}/{n} = {100 * k / n:.2f}%; baseline {kb}/{nb} = {100 * kb / nb:.2f}%; proportion ratio {(k / n) / (kb / nb):.2f}")
for a in ["P1", "P2"]:
    z, p = prop_test(*cnt[("A", "post")], *cnt[(a, "post")])
    print(f"   binomial proportion test after A vs after {a}: z = {z:.2f}, P = {p:.1e}")
95th percentile of pooled shuffled replay scores: 0.505
grid 0.05 x 3 m/s: summed positive z-proportion in the high-value region, sleep after {'P1': np.float64(99.8), 'A': np.float64(317.9), 'P2': np.float64(117.1)}
grid 0.025 x 1.5 m/s: summed positive z-proportion in the high-value region, sleep after {'P1': np.float64(183.3), 'A': np.float64(746.4), 'P2': np.float64(276.3)}
grid 0.1 x 6 m/s: summed positive z-proportion in the high-value region, sleep after {'P1': np.float64(41.5), 'A': np.float64(104.3), 'P2': np.float64(36.4)}
after P1: in region 49/6588 = 0.74%; baseline 28/5810 = 0.48%; proportion ratio 1.54
after A: in region 664/6033 = 11.01%; baseline 268/5581 = 4.80%; proportion ratio 2.29
after P2: in region 190/5310 = 3.58%; baseline 157/5660 = 2.77%; proportion ratio 1.29
   binomial proportion test after A vs after P1: z = 24.94, P = 2.5e-137
   binomial proportion test after A vs after P2: z = 14.96, P = 1.3e-50

Result: reproduced, resting on the claims file's region. The summed positive z-proportion in the high-value region is 99.8, 317.9 and 117.1 after Passive 1, Active and Passive 2 on the 0.05 by 3 m/s grid, and largest after Active on all three grids. 0.74%, 11.01% and 3.58% of events are in the region; after Active exceeds both (P = 2.5 x 10^-137 and 1.3 x 10^-50).

fig4e-replay-proportion-vs-baseline¶

Relative to baseline sleep, the proportion of significant replay events was not increased after Passive 1, was boosted after Active, and was intermediate but significantly increased after Passive 2.

In [24]:
def fig4e(E, label):
    print(label)
    for rule in ["a", "b"]:
        for c in D.CONDS:
            po = E[(E.cond == c) & (E.kind == "post")]
            ba = E[(E.cond == c) & (E.kind == "base")]
            sp = (po.p <= 0.05) & ((po.D > 0) if rule == "b" else True)
            sb = (ba.p <= 0.05) & ((ba.D > 0) if rule == "b" else True)
            z, p = prop_test(sp.sum(), len(po), sb.sum(), len(ba))
            print(f"   reading {rule}, after {c}: {sp.sum()}/{len(po)} = {100 * sp.mean():.2f}% vs baseline {sb.sum()}/{len(ba)} = {100 * sb.mean():.2f}%; "
                  f"ratio {sp.mean() / sb.mean():.2f}; binomial z = {z:.2f}, P = {p:.1e}")
In [25]:
fig4e(EV, "all decoded candidate events")
print("per rat, % significant (reading a), post / baseline:")
print((EV.assign(s=EV.p <= 0.05).groupby(["rat", "cond", "kind"]).s.mean().unstack([1, 2]) * 100).round(1).to_string())
all decoded candidate events
   reading a, after P1: 894/6588 = 13.57% vs baseline 750/5810 = 12.91%; ratio 1.05; binomial z = 1.08, P = 2.8e-01
   reading a, after A: 948/6033 = 15.71% vs baseline 716/5581 = 12.83%; ratio 1.22; binomial z = 4.43, P = 9.3e-06
   reading a, after P2: 674/5310 = 12.69% vs baseline 828/5660 = 14.63%; ratio 0.87; binomial z = -2.95, P = 3.2e-03
   reading b, after P1: 426/6588 = 6.47% vs baseline 351/5810 = 6.04%; ratio 1.07; binomial z = 0.97, P = 3.3e-01
   reading b, after A: 517/6033 = 8.57% vs baseline 352/5581 = 6.31%; ratio 1.36; binomial z = 4.63, P = 3.7e-06
   reading b, after P2: 305/5310 = 5.74% vs baseline 400/5660 = 7.07%; ratio 0.81; binomial z = -2.82, P = 4.7e-03
per rat, % significant (reading a), post / baseline:
cond     A          P1          P2      
kind  base  post  base  post  base  post
rat                                     
242   16.1  23.3  12.2  16.7  15.2  19.4
261   10.2  10.8  12.0  13.1  14.1  13.3
272   15.8  11.2  18.1  15.3  20.2  15.2
292   11.7  14.5  12.5  11.0  14.7   9.7
314   10.2  14.2  13.7  11.2  11.0  10.7

Result: not reproduced. Relative to baseline, significant events are not increased after Passive 1 (13.57% against 12.91%, P = 0.28), increased after Active (15.71% against 12.83%, P = 9.3 x 10^-6), and decreased after Passive 2 (12.69% against 14.63%, P = 0.0032), where the claim needs an increase after Passive 2 at P < 0.01.

fig4f-forward-replay-after-active¶

Forward and reverse replay events were equally common in sleep after passive travel, while sleep after Active held more forward than reverse events.

In [26]:
def fig4f(E, label):
    print(label)
    for c in D.CONDS:
        po = E[(E.cond == c) & (E.kind == "post") & (E.p <= 0.05)]
        ba = E[(E.cond == c) & (E.kind == "base") & (E.p <= 0.05)]
        fw, rv, n = int((po.D > 0).sum()), int((po.D < 0).sum()), len(po)
        # (a) forward against reverse: exact binomial test of forward among events with a
        # direction (zero-slope events left out; corrected after round 1 of verification)
        pa = stats.binomtest(fw, fw + rv, 0.5).pvalue
        fb, rb = int((ba.D > 0).sum()), int((ba.D < 0).sum())
        zb, pb = prop_test(fw, fw + rv, fb, fb + rb)
        print(f"   after {c}: forward {fw}, reverse {rv}, zero {n - fw - rv}, of {n} significant; forward / (forward + reverse) {fw / (fw + rv):.3f}; "
              f"(a) exact binomial against 0.5: P = {pa:.1e}; (b) against baseline {fb}/{fb + rb} = {fb / max(fb + rb, 1):.3f}: z = {zb:.2f}, P = {pb:.1e}")
In [27]:
fig4f(EV, "all decoded candidate events")
all decoded candidate events
   after P1: forward 426, reverse 404, zero 64, of 894 significant; forward / (forward + reverse) 0.513; (a) exact binomial against 0.5: P = 4.7e-01; (b) against baseline 351/706 = 0.497: z = 0.63, P = 5.3e-01
   after A: forward 517, reverse 401, zero 30, of 948 significant; forward / (forward + reverse) 0.563; (a) exact binomial against 0.5: P = 1.4e-04; (b) against baseline 352/702 = 0.501: z = 2.47, P = 1.4e-02
   after P2: forward 305, reverse 342, zero 27, of 674 significant; forward / (forward + reverse) 0.471; (a) exact binomial against 0.5: P = 1.6e-01; (b) against baseline 400/802 = 0.499: z = -1.04, P = 3.0e-01

Result: reproduced. Among significant events with a direction, after Active 517 are forward and 401 reverse (0.563, exact binomial P = 1.4 x 10^-4); after Passive 1, 426 against 404 (P = 0.47); after Passive 2, 305 against 342 (P = 0.16). Against baseline's forward proportion (reading b) after Active gives P = 0.014.

figs12-ripple-restricted¶

Restricting candidate events to ripples left the replay results unchanged; scores relative to baseline, slopes, the boost after Active and the forward bias after Active all held.

Readings: (a) events that overlap a detected ripple; (b) events whose peak falls inside a ripple. Scores relative to baseline recomputed on the restricted baseline events.

In [28]:
for col, lab in [("rip_overlap", "reading (a), any overlap with a ripple"), ("rip_peak", "reading (b), event peak inside a ripple")]:
    E = EV[EV[col]].copy()
    for (rat, c), sub in E.groupby(["rat", "cond"]):
        b = sub[sub.kind == "base"].score
        q1, med, q3 = np.percentile(b, [25, 50, 75])
        E.loc[sub.index, "rel"] = (sub.score - med) / (q3 - q1)
    print("=" * 20, lab, "; events kept", len(E), "of", len(EV))
    fig4b(E, lab)
    fig4c(E, lab)
    fig4e(E, lab)
    fig4f(E, lab)
==================== reading (a), any overlap with a ripple ; events kept 15171 of 34982
reading (a), any overlap with a ripple
   sleep after P1: n 2987, median score relative to baseline -0.012, signed-rank vs 0 P = 1.6e-05
   sleep after A: n 2669, median score relative to baseline 0.384, signed-rank vs 0 P = 5.9e-146
   sleep after P2: n 2237, median score relative to baseline -0.054, signed-rank vs 0 P = 9.3e-02
   KW P = 3.4e-90
   rank-sum P1 vs A: P (Bonferroni x3) = 7.6e-70
   rank-sum A vs P2: P (Bonferroni x3) = 2.3e-66
   rank-sum P1 vs P2: P (Bonferroni x3) = 4.2e-01
   per rat median: {'242': {'P1': 0.314, 'A': 0.514, 'P2': 0.841}, '261': {'P1': -0.051, 'A': 0.554, 'P2': -0.052}, '272': {'P1': -0.366, 'A': -0.065, 'P2': -0.164}, '292': {'P1': -0.068, 'A': 0.262, 'P2': -0.309}, '314': {'P1': 0.116, 'A': 0.346, 'P2': 0.216}}
reading (a), any overlap with a ripple, all events: n [2987, 2669, 2237], median |slope| (m/s) [np.float64(21.8), np.float64(20.25), np.float64(21.0)]; KW P = 3.6e-01
   KS signed slopes P1 vs A: P = 1.1e-03; KS |slopes| P = 2.1e-06
   KS signed slopes A vs P2: P = 4.7e-01; KS |slopes| P = 2.1e-01
   KS signed slopes P1 vs P2: P = 7.5e-02; KS |slopes| P = 7.5e-03
reading (a), any overlap with a ripple, significant events: n [426, 480, 316], median |slope| (m/s) [np.float64(2.8), np.float64(5.94), np.float64(5.26)]; KW P = 1.9e-03
   KS signed slopes P1 vs A: P = 1.8e-03; KS |slopes| P = 3.4e-05
   KS signed slopes A vs P2: P = 3.2e-01; KS |slopes| P = 6.1e-01
   KS signed slopes P1 vs P2: P = 2.4e-01; KS |slopes| P = 5.8e-03
reading (a), any overlap with a ripple
   reading a, after P1: 426/2987 = 14.26% vs baseline 358/2561 = 13.98%; ratio 1.02; binomial z = 0.30, P = 7.6e-01
   reading a, after A: 480/2669 = 17.98% vs baseline 315/2266 = 13.90%; ratio 1.29; binomial z = 3.89, P = 1.0e-04
   reading a, after P2: 316/2237 = 14.13% vs baseline 379/2451 = 15.46%; ratio 0.91; binomial z = -1.29, P = 2.0e-01
   reading b, after P1: 205/2987 = 6.86% vs baseline 177/2561 = 6.91%; ratio 0.99; binomial z = -0.07, P = 9.4e-01
   reading b, after A: 252/2669 = 9.44% vs baseline 163/2266 = 7.19%; ratio 1.31; binomial z = 2.84, P = 4.6e-03
   reading b, after P2: 151/2237 = 6.75% vs baseline 179/2451 = 7.30%; ratio 0.92; binomial z = -0.74, P = 4.6e-01
reading (a), any overlap with a ripple
   after P1: forward 205, reverse 198, zero 23, of 426 significant; forward / (forward + reverse) 0.509; (a) exact binomial against 0.5: P = 7.7e-01; (b) against baseline 177/342 = 0.518: z = -0.24, P = 8.1e-01
   after A: forward 252, reverse 215, zero 13, of 480 significant; forward / (forward + reverse) 0.540; (a) exact binomial against 0.5: P = 9.6e-02; (b) against baseline 163/310 = 0.526: z = 0.38, P = 7.1e-01
   after P2: forward 151, reverse 154, zero 11, of 316 significant; forward / (forward + reverse) 0.495; (a) exact binomial against 0.5: P = 9.1e-01; (b) against baseline 179/365 = 0.490: z = 0.12, P = 9.0e-01
==================== reading (b), event peak inside a ripple ; events kept 8727 of 34982
reading (b), event peak inside a ripple
   sleep after P1: n 1784, median score relative to baseline -0.036, signed-rank vs 0 P = 3.0e-02
   sleep after A: n 1446, median score relative to baseline 0.322, signed-rank vs 0 P = 4.6e-61
   sleep after P2: n 1244, median score relative to baseline -0.063, signed-rank vs 0 P = 5.6e-01
   KW P = 2.5e-39
   rank-sum P1 vs A: P (Bonferroni x3) = 1.0e-31
   rank-sum A vs P2: P (Bonferroni x3) = 5.7e-29
   rank-sum P1 vs P2: P (Bonferroni x3) = 8.9e-01
   per rat median: {'242': {'P1': 0.358, 'A': 0.385, 'P2': 0.887}, '261': {'P1': -0.061, 'A': 0.598, 'P2': -0.021}, '272': {'P1': -0.418, 'A': -0.092, 'P2': -0.147}, '292': {'P1': -0.14, 'A': 0.216, 'P2': -0.337}, '314': {'P1': -0.012, 'A': 0.012, 'P2': 0.022}}
reading (b), event peak inside a ripple, all events: n [1784, 1446, 1244], median |slope| (m/s) [np.float64(23.34), np.float64(25.11), np.float64(23.7)]; KW P = 8.2e-03
   KS signed slopes P1 vs A: P = 5.1e-05; KS |slopes| P = 3.9e-05
   KS signed slopes A vs P2: P = 5.7e-01; KS |slopes| P = 6.3e-01
   KS signed slopes P1 vs P2: P = 9.7e-03; KS |slopes| P = 4.9e-03
reading (b), event peak inside a ripple, significant events: n [235, 230, 158], median |slope| (m/s) [np.float64(2.67), np.float64(6.25), np.float64(6.35)]; KW P = 1.2e-03
   KS signed slopes P1 vs A: P = 2.8e-04; KS |slopes| P = 1.3e-04
   KS signed slopes A vs P2: P = 2.3e-01; KS |slopes| P = 9.5e-01
   KS signed slopes P1 vs P2: P = 2.4e-01; KS |slopes| P = 2.4e-03
reading (b), event peak inside a ripple
   reading a, after P1: 235/1784 = 13.17% vs baseline 203/1564 = 12.98%; ratio 1.01; binomial z = 0.17, P = 8.7e-01
   reading a, after A: 230/1446 = 15.91% vs baseline 151/1245 = 12.13%; ratio 1.31; binomial z = 2.80, P = 5.1e-03
   reading a, after P2: 158/1244 = 12.70% vs baseline 209/1444 = 14.47%; ratio 0.88; binomial z = -1.33, P = 1.8e-01
   reading b, after P1: 106/1784 = 5.94% vs baseline 100/1564 = 6.39%; ratio 0.93; binomial z = -0.54, P = 5.9e-01
   reading b, after A: 125/1446 = 8.64% vs baseline 83/1245 = 6.67%; ratio 1.30; binomial z = 1.92, P = 5.5e-02
   reading b, after P2: 76/1244 = 6.11% vs baseline 89/1444 = 6.16%; ratio 0.99; binomial z = -0.06, P = 9.5e-01
reading (b), event peak inside a ripple
   after P1: forward 106, reverse 110, zero 19, of 235 significant; forward / (forward + reverse) 0.491; (a) exact binomial against 0.5: P = 8.4e-01; (b) against baseline 100/191 = 0.524: z = -0.66, P = 5.1e-01
   after A: forward 125, reverse 98, zero 7, of 230 significant; forward / (forward + reverse) 0.561; (a) exact binomial against 0.5: P = 8.1e-02; (b) against baseline 83/148 = 0.561: z = -0.01, P = 1.0e+00
   after P2: forward 76, reverse 78, zero 4, of 158 significant; forward / (forward + reverse) 0.494; (a) exact binomial against 0.5: P = 9.4e-01; (b) against baseline 89/199 = 0.447: z = 0.86, P = 3.9e-01

Result: not reproduced. On events overlapping a ripple (15171 of 34982), none of the four criteria holds: scores relative to baseline are improved after Active (median 0.384) but not after Passive 2 (-0.054, P = 0.093); significant-event slopes after Active do not differ from after Passive 2 (KS P = 0.61 for absolute slopes); significant events after Passive 2 are not above baseline (P = 0.20); forward events after Active do not exceed reverse (252 against 215, P = 0.096). Events with their peak inside a ripple give the same.

Summary¶

claim outcome
fig3b-average-theta-reconstruction partially reproduced
figs5b-per-rat-reconstruction reproduced
fig3c-theta-scores-above-chance reproduced
fig3c-proportion-significant-theta partially reproduced
fig3d-theta-slopes-steeper-active reproduced (assumed recorded LFP sign in rats 292 and 314)
fig3e-joint-score-slope-theta reproduced (claims file's region)
fig3f-quadrant-scores reproduced (assumed recorded LFP sign in rats 292 and 314)
figs9-control-decoding-quality partially reproduced
fig4b-replay-scores-vs-baseline partially reproduced
fig4c-replay-slopes-steeper-active not reproduced
fig4d-joint-score-slope-replay reproduced (claims file's region)
fig4e-replay-proportion-vs-baseline not reproduced
fig4f-forward-replay-after-active reproduced
figs12-ripple-restricted not reproduced
fig3g, fig4g, figs7, figs8, figs10 in the controls notebook

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. 200 shuffles per event instead of 5000. Place cells are those of the Methods' definition without a minimum field size, more numerous than the paper's; the theta results under field reading (b) are in the controls notebook and agree. 250 position bins as the claims file gives (the scripts default to 200). The linearization, LFP channel and theta cycles are rebuilt, since the paper's files are not in the data set; the theta channel leaves out channels with reversed theta.

About the dataset. Theta sequences are present in every rat, steepest in Active, and replay after Active is selectively improved and, on all events, forward-biased; on ripple-restricted events the forward bias is not significant (P = 0.096 and 0.081). In rats 292 and 314 the theta-sequence results depend on the sign of the LFP: inverted, their sequences run backward and the pooled Active effects on slopes and quadrant scores are lost. The Passive 2 replay increase and the steeper replay slopes after Active than after Passive 2 are not found.

In [29]:
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 46.2 min; peak memory 6.4 GB