Drieu, Todorova & Zugaro (2018) on CRCNS hc-18: travel, place fields, theta and sleep¶

Paper. C. Drieu, R. Todorova, M. Zugaro (2018), "Nested sequences of hippocampal assemblies during behavior support subsequent sleep replay", Science 362:675-679, doi:10.1126/science.aat2952. The claims file (claims/drieu-2018.yaml) was written from the version of record and the author manuscript (HAL hal-02330673v1) for the Methods and the supplement.

Dataset. CRCNS hc-18 (doi:10.6080/K0Z899MM), "Bilateral recordings from dorsal hippocampal area CA1 from rats transported on a model train and sleeping". CRCNS data sets are not versioned: the version is recorded as unversioned, and the MD5 sums of the files read (from the data set's checksums.md5) are printed below so that a later change is detectable. The files are under hc-18/live/ in the public bucket crcnsarchive; there is no other copy (no old/ folder), so this is the only version that can be pinned, and it is the one the paper's citation (data descriptor version 0.61, 2018-11-27) describes. Each rat is one tar.gz of NeuroSuite files, streamed and reduced in memory by drieu2018.py; nothing is written to disk.

This notebook tests the claims on travel, place fields, theta and sleep sessions. The decoding claims are in reproduce_drieu_2018_decoding.ipynb and reproduce_drieu_2018_controls.ipynb.

Revised after round 1 of verification: field entry for phase precession corrected; theta channels with reversed theta left out; spectrogram readings of burst frequency, 8-s spectra for theta frequency, field-size and spatial-information distributions, and the lines of the paper's scripts used, added.

claim tested here
figs1-travel-similar yes
figs2b-place-cell-count yes
fig1c-field-size-similar yes
fig1c-peak-rate-lower-passive1 yes
figs2c-track-coverage yes
fig1d-no-remapping-p1-active yes
fig1e-no-remapping-active-p2 yes
figs2d-stability-p1-p2 yes
fig2b-theta-frequency-unchanged yes
fig2b-theta-power-reduced yes
fig2b-theta-asymmetry-reduced yes
fig2cd-spike-bursts-slower yes
figs4b-proportions-oscillating-precessing yes
fig2f-phase-precession-degraded yes
figs4de-precession-range-similar yes
figs11-sleep-sessions-similar yes
all decoding claims (fig3*, figs5b, figs7 to figs10, fig4*, figs12) in the decoding notebook
In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "4")
import time, resource, gc, re
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.anova import AnovaRM
import statsmodels.formula.api as smf
import statsmodels.api as sm
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import drieu2018 as D

T_START = time.time()
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)
In [2]:
sums = D.checksums()
for n in ["code.zip"] + [f"data/{r}.tar.gz" for r in D.RATS]:
    print(f"{sums[n]}  {n}")
code = D.read_code_zip()
print(len(code), "MATLAB scripts in code.zip")
# lines of the paper's scripts that settings here are taken from (comments left out)
PATTERNS = {
    "DiscriminateUnits.m": r"nSpikesSample = |ratelim = |kmeans\(|strcmp\(rate,|halfwidth\(i,:\) =|width\(i,:\) =",
    "BatchPlaceFields.m": r"nBins = |threshold = |minSize = |maxSize = |length\(s\)<|curve = FiringCurve|sum\(field1\)>maxSize",
    "GetEventsManip1.m": r"Forward|Sleep|ConsolidateIntervals|292",
    "BatchCandidateEvents.m": r"msh = |sdsh = |swsSh = |MeanCross = |peakCross = |tooLong = ",
    "BatchSequenceReconstructNewProto.m": r"minUnitInEvent = |nShuffles = |nMinWin = |minSpikePerCycle = |FindSubcycles",
    "BatchReplayReconstructNewProto.m": r"minUnitInEvent = |nMinWin = |window = |tooShort = |SplitIntervals",
    "BatchBiasMatrixCosines.m": r"restrict2place|IsInZone|ok = sum\(count|fields\(:,NFIELDS\)==1",
    "ClusterIsolation.m": r"^n=1;|n=n\+1;|continue|lratio\(n\) =|distance\(n\) =",
}
for f, pat in PATTERNS.items():
    print(f"--- {f}")
    for k, line in enumerate(code[f].splitlines(), 1):
        if re.search(pat, line) and not line.strip().startswith("%"):
            print(f"{k:4d}: {line.strip()[:160]}")
151cb8245070619019e15750f5efe760  code.zip
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
50 MATLAB scripts in code.zip
--- DiscriminateUnits.m
  43: nSpikesSample = 800;
  45: ratelim = 'on';
  64: nSpikesSample = varargin{i+1};
  69: ratelim = varargin{i+1};
 137: halfwidth(i,:) = [id 0.00005*(indshoulder2-indtrough)/upsamp];% computes the trough to second peak width of the spike waveform
 140: width(i,:) = [id 0.00005*(indshoulder2-indshoulder1)/upsamp];% computes the width of the spike waveform
 145: idx = kmeans([halfwidth(:,2) width(:,2)],2);
 173: if strcmp(rate,'on'),
--- BatchPlaceFields.m
  23: nBins = 250;
  24: threshold = 0.3;
  25: minSize = 10;
  26: maxSize = (3/4)*nBins;
  65: if length(s)<50,
  74: curve = FiringCurve(xx,s,'nbins',nBins,'smooth',5,'type','cl','minSize',minSize,'minpeak',peakmin,'threshold',threshold);
  82: if length(s)<30,
  91: curve = FiringCurve(xx,s,'nbins',nBins,'smooth',5,'type','cl','minSize',minSize,'minpeak',peakmin,'threshold',threshold);
 112: if nFieldsCurve == 0 || sum(field1)>maxSize,
 130: if sum(field1)>maxSize,
--- GetEventsManip1.m
  15: PF = GetEvents('.*-PassiveForward');PF = [PF(1:2:end-1) PF(2:2:end)];
  16: PF = ConsolidateIntervals(PF);
  19: PAF = GetEvents('.*-PseudoActiveForward');PAF = [PAF(1:2:end-1) PAF(2:2:end)];
  20: if strcmp(sessionName, 'Train-292-20150501')
  23: PAF = ConsolidateIntervals(PAF);
  27: sleeps = GetEvents('.*-Sleep.*');sleeps = [sleeps(1:2:end-1) sleeps(2:2:end)];
  28: sleeps = ConsolidateIntervals(sleeps);
  35: quiet = ConsolidateIntervals(quiet);
--- BatchCandidateEvents.m
  65: swsSh = sh(InIntervals(times,sws));
  66: msh = mean(swsSh);
  67: sdsh = std(swsSh);
  69: startMeanCross = strfind(swsSh'>msh,[0 1])';
  70: endMeanCross = strfind(swsSh'>msh,[1 0])';
  72: startMeanCross = [1;startMeanCross];
  75: endMeanCross = [endMeanCross;length(swsSh)];
  78: peakCross = strfind(swsSh'>thresholdPeak,1);
  85: tooLong = candEventDuration>0.5;
 121: swsSh = sh(InIntervals(times,sws));
 127: msh = mean(swsSh);
 128: sdsh = std(swsSh);
 130: startMeanCross = strfind(swsSh'>msh,[0 1])';
 131: endMeanCross = strfind(swsSh'>msh,[1 0])';
 133: startMeanCross = [1;startMeanCross];
 136: endMeanCross = [endMeanCross;length(swsSh)];
 139: peakCross = strfind(swsSh'>thresholdPeak,1);
 146: tooLong = candEventDurationB>0.5;
--- BatchSequenceReconstructNewProto.m
  20: minUnitInEvent = 3;
  21: nShuffles = 5000;
  22: nMinWin = 3;
  25: minSpikePerCycle = 3;
  84: [windows,subID,cyID] = FindSubcycles(unw,6);
--- BatchReplayReconstructNewProto.m
  21: minUnitInEvent = 3;
  23: nMinWin = 3;
  25: window = 0.020; %for reconstruct positions
  26: tooShort = 3*window;
 104: [windows, ids] = SplitIntervals(candEventsTimesIntervals,'pieceSize',window);
--- BatchBiasMatrixCosines.m
   4: restrict2placeCells = true;
   5: restrict2placeFields = true;
  54: fields = fields(fields(:,NFIELDS)==1,:);
  57: if restrict2placeCells,
  64: if restrict2placeFields,
  65: in = IsInZone(spikePos(indices,:),fields(i,:));
  82: ok = sum(count>0,2)>=3;
--- ClusterIsolation.m
  41: n=1;
  66: continue
  70: continue
  78: distance(n) = sOut(nSpikesInCluster);
  86: lratio(n) = sum(1-p1)/nSpikesInElectrodeGroup;
  87: n=n+1;
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
    # share of sleep LFP samples at the 16-bit limit, on the theta channel and on any pyramidal-layer channel
    sl = np.array([P["ep"]["sleep"][s_] for s_ in D.SLEEPS])
    idx = np.concatenate([np.arange(int(a * D.LFP_FS), min(int(b * D.LFP_FS), r["lfp"]["data"].shape[1])) for a, b in sl])
    r["lfp_sat"] = dict(theta=float(np.mean(np.abs(r["lfp"]["data"][LF["theta_row"], idx]) >= 32767)),
                        any_pyr=float(np.mean((np.abs(r["lfp"]["data"][LF["pyr_rows"]][:, idx]) >= 32767).any(0))))
    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 92 s
Train-242-20140124: 208 s, peak memory 3.7 GB
Train-261-20140617: streamed in 79 s
Train-261-20140617: 180 s, peak memory 4.0 GB
Train-272-20141215: streamed in 216 s
Train-272-20141215: 360 s, peak memory 4.8 GB
Train-292-20150501: streamed in 141 s
Train-292-20150501: 237 s, peak memory 5.8 GB
Train-314-20160118: streamed in 288 s
Train-314-20160118: 486 s, peak memory 6.6 GB

Data check¶

What was loaded, per rat (one session per rat), and the checks of the description against the values.

In [4]:
rows = []
for name in D.RATS:
    r, P, LF = RAT[name], PREP[name], LFPS[name]
    m = r["meta"]
    rows.append(dict(rat=name[6:9], channels=m["nChannels"], spike_groups=len(m["groups"]), acq_Hz=m["fs"],
                     units=len(r["units"]), pyramidal=int(P["pyr"].sum()), isolated=int(P["iso"].sum()),
                     pyr_isolated=int((P["pyr"] & P["iso"]).sum()),
                     spikes_end_s=round(r["res_max_s"], 1), pos_end_s=round(len(r["pos"]) / D.POS_FS, 1),
                     lfp_end_s=round(r["lfp_shape"][1] / D.LFP_FS, 1),
                     pos_lost_pct=round(100 * np.mean(np.isnan(P["xy"][:, 0])), 1),
                     track_perimeter_cm=round(P["L"]), direction_flipped=P["flipped"],
                     theta_channel=LF["theta_channel"], pyr_layer_channels=len(LF["pyr_channels"])))
sanity = pd.DataFrame(rows)
print(sanity.to_string(index=False))
print()
print("Epochs (consolidated as GetEventsManip1.m does), minutes:")
rows = []
for name in D.RATS:
    ep = PREP[name]["ep"]
    d = {"rat": name[6:9]}
    for c in D.CONDS:
        a, b = ep["travel"][c]
        d[c] = round((b - a) / 60, 2)
    for s in D.SLEEPS:
        a, b = ep["sleep"][s]
        d[s] = round((b - a) / 60, 1)
    d["n_PF_blocks"] = len(ep["PF_blocks"]); d["n_PAF_blocks"] = len(ep["PAF_blocks"]); d["n_sleep_blocks"] = len(ep["SL_blocks"])
    rows.append(d)
print(pd.DataFrame(rows).to_string(index=False))
print()
print("Event names per rat:")
for name in D.RATS:
    print(name[6:9], sorted({n.split("-")[-1] for n, a, b in RAT[name]["events"]}))
print()
print("Position ranges (cm) and velocity during travel:")
for name in D.RATS:
    P = PREP[name]
    xy = P["xy"]
    tr = D.in_intervals(P["t"], np.array([P["ep"]["travel"][c] for c in D.CONDS]))
    print(name[6:9], "x", np.round(np.nanpercentile(xy[tr, 0], [0, 100])), "y", np.round(np.nanpercentile(xy[tr, 1], [0, 100])),
          "velocity median/95th pct (cm/s)", np.round(np.nanpercentile(P["v"][tr], [50, 95]), 1),
          "moving periods", len(P["mov"]))
print()
print("Theta phase (deg, Hilbert phase of the 6-10 Hz LFP, 0 at peaks) of the pyramidal cells' spikes on each")
print("pyramidal-layer channel, Active travel, moving periods; channels more than 90 deg from the mean of the")
print("others have reversed theta and are left out of the theta readings (helper, reduce_lfp):")
for name in D.RATS:
    LF = LFPS[name]
    ph = {RAT[name]["meta"]["groups"][k]["channels"][0]: round(v) for k, v in LF["spike_phase_by_row"].items()}
    print(f"{name[6:9]}: theta channel {LF['theta_channel']}; reversed {LF['reversed_channels']}; spike phase by channel {ph}")
rat  channels  spike_groups    acq_Hz  units  pyramidal  isolated  pyr_isolated  spikes_end_s  pos_end_s  lfp_end_s  pos_lost_pct  track_perimeter_cm  direction_flipped  theta_channel  pyr_layer_channels
242        64            13 32552.083     81         49        66            43       17696.3    17696.3    17696.3           0.9                 656               True             16                   8
261        64             8 32552.083     46         32        36            25       19964.3    19964.4    19964.4           0.4                 668               True             40                   7
272        64            12 32552.083    178        110       119            83       18246.7    18246.7    18246.7           0.6                 675               True              8                  12
292       128            16 20000.000    115         85        47            31       22827.0    22827.0    22827.0          40.6                 706              False             56                   8
314       128            10 20000.000    265        212       131           103       23442.1    23442.1    23442.1          22.8                 688              False            104                  10

Epochs (consolidated as GetEventsManip1.m does), minutes:
rat    P1    A   P2   SB   S1   SA   S2  n_PF_blocks  n_PAF_blocks  n_sleep_blocks
242 11.71 5.84 8.40 80.1 65.0 60.6 63.0            2             1               4
261  9.99 6.16 9.06 84.2 97.0 61.8 64.5            2             1               4
272  8.87 6.26 6.57 67.7 63.8 61.2 77.4            2             1               4
292  6.11 6.70 6.04 84.5 87.6 83.9 88.0            2             1               4
314  9.39 7.12 8.10 88.3 90.0 86.9 87.1            2             1               4

Event names per rat:
242 ['PassiveForward', 'PseudoActiveForward', 'SleepBaseline', 'SleepPassiveForward', 'SleepPseudoActiveForward']
261 ['PassiveForward', 'PseudoActiveForward', 'SleepBaseline', 'SleepPassiveForward', 'SleepPseudoActiveForward']
272 ['PassiveForward', 'PostPassiveForward', 'PostPseudoActiveForward', 'PseudoActiveForward', 'SleepBaseline', 'SleepPassiveForward', 'SleepPseudoActiveForward']
292 ['PassiveForward', 'PostPassiveForward', 'PostPseudoActiveForward', 'PseudoActiveForward', 'SleepBaseline', 'SleepPassiveForward', 'SleepPseudoActiveForward']
314 ['PassiveForward', 'PostPassiveForward', 'PostPseudoActiveForward', 'PseudoActiveForward', 'SleepBaseline', 'SleepPassiveForward', 'SleepPseudoActiveForward']

Position ranges (cm) and velocity during travel:
242 x [  4. 230.] y [  5. 186.] velocity median/95th pct (cm/s) [40.6 50. ] moving periods 12
261 x [  1. 230.] y [  2. 186.] velocity median/95th pct (cm/s) [48.4 59. ] moving periods 20
272 x [  0. 236.] y [  7. 186.] velocity median/95th pct (cm/s) [50.  61.3] moving periods 34
292 x [  1. 247.] y [  2. 185.] velocity median/95th pct (cm/s) [48.3 56.6] moving periods 6
314 x [  1. 246.] y [  0. 182.] velocity median/95th pct (cm/s) [51.5 59.1] moving periods 17

Theta phase (deg, Hilbert phase of the 6-10 Hz LFP, 0 at peaks) of the pyramidal cells' spikes on each
pyramidal-layer channel, Active travel, moving periods; channels more than 90 deg from the mean of the
others have reversed theta and are left out of the theta readings (helper, reduce_lfp):
242: theta channel 16; reversed []; spike phase by channel {4: -116, 16: -91, 32: -124, 36: -98, 40: -97, 44: -146, 52: -135, 60: -154}
261: theta channel 40; reversed []; spike phase by channel {32: -174, 36: 168, 40: -168, 44: -175, 48: -170, 52: -173, 60: 149}
272: theta channel 8; reversed [24, 28, 32, 36]; spike phase by channel {1: -106, 8: -67, 24: 113, 28: 111, 32: 150, 36: 127, 40: -124, 44: -104, 48: -107, 52: -89, 56: -100, 60: -110}
292: theta channel 56; reversed []; spike phase by channel {0: -51, 24: -28, 33: -34, 40: -30, 48: -13, 56: -16, 72: -22, 96: -51}
314: theta channel 104; reversed []; spike phase by channel {8: -24, 16: -11, 24: -36, 48: -9, 56: -5, 80: -14, 88: -22, 96: -30, 104: -39, 120: -37}
In [5]:
print("Head-position samples lost (LED not tracked), % of samples in travel, sleep and elsewhere; and share of")
print("sleep LFP samples at the 16-bit limit (|x| = 32767), on the theta channel and on any pyramidal-layer channel:")
rows = []
for name in D.RATS:
    P = PREP[name]
    lost = np.isnan(P["xy"][:, 0])
    trv = D.in_intervals(P["t"], np.array([P["ep"]["travel"][c] for c in D.CONDS]))
    slp = D.in_intervals(P["t"], np.array([P["ep"]["sleep"][s] for s in D.SLEEPS]))
    rows.append(dict(rat=name[6:9], lost_pct_all=round(100 * lost.mean(), 1), lost_pct_travel=round(100 * lost[trv].mean(), 2),
                     lost_pct_sleep=round(100 * lost[slp].mean(), 1), lost_pct_other=round(100 * lost[~trv & ~slp].mean(), 1),
                     share_of_lost_in_sleep_pct=round(100 * (lost & slp).sum() / max(lost.sum(), 1), 1),
                     lfp_sat_sleep_theta_pct=round(100 * RAT[name]["lfp_sat"]["theta"], 3),
                     lfp_sat_sleep_any_pyr_pct=round(100 * RAT[name]["lfp_sat"]["any_pyr"], 3)))
print(pd.DataFrame(rows).to_string(index=False))
Head-position samples lost (LED not tracked), % of samples in travel, sleep and elsewhere; and share of
sleep LFP samples at the 16-bit limit (|x| = 32767), on the theta channel and on any pyramidal-layer channel:
rat  lost_pct_all  lost_pct_travel  lost_pct_sleep  lost_pct_other  share_of_lost_in_sleep_pct  lfp_sat_sleep_theta_pct  lfp_sat_sleep_any_pyr_pct
242           0.9             5.64             0.4           100.0                        36.3                    0.042                      0.168
261           0.4             4.55             0.1             NaN                        21.6                    2.385                      2.563
272           0.6             3.99             0.3             1.6                        42.8                    0.393                      0.802
292          40.6             0.65            44.3            11.1                        98.7                    0.000                      0.000
314          22.8             0.55            25.2             0.9                        99.7                    0.000                      0.000
/tmp/ipykernel_2529/1257455360.py:10: RuntimeWarning: Mean of empty slice
  lost_pct_sleep=round(100 * lost[slp].mean(), 1), lost_pct_other=round(100 * lost[~trv & ~slp].mean(), 1),
/home/runner/work/encore/encore/executed/drieu-2018/.venv/lib/python3.13/site-packages/numpy/_core/_methods.py:142: RuntimeWarning: invalid value encountered in scalar divide
  ret = ret.dtype.type(ret / rcount)

Clock checks. The spikes, positions and LFP of each rat end within a second of each other (table above). Below, place-field sharpness (spatial information) with spike times shifted against positions, and ripple rates in sleep and in SWS. The shift test turns out unable to detect an offset: the train moves at a near-constant speed around a closed track, so a time shift only rotates the fields, and the information barely changes (for example 0.245 bits at 0 s and 0.244 at -10 s in rat 242). That spikes, positions and LFP share a clock is therefore consistent with the data, not shown here. The decoding notebook gives further support: theta sequences there sweep ahead of the decoded current position, which needs spikes, LFP phase and positions aligned within a theta cycle.

In [6]:
def spatial_info(P, c, shift):
    cd = P["cond"][c]
    ok = np.isfinite(P["lin_unw"])
    tt, lu = P["t"][ok], P["lin_unw"][ok]
    occ = np.bincount(np.minimum((cd["occ_lin"] * D.NBINS).astype(int), D.NBINS - 1), minlength=D.NBINS) / D.POS_FS
    po = occ / occ.sum()
    out = []
    for i in D.place_cells(P, c):
        st = PREP_UNITS[P["name"]][i]
        a, b = cd["interval"]
        st = st[(st >= a) & (st <= b)] + shift
        k = np.clip(np.round(st * D.POS_FS).astype(int), 0, len(P["t"]) - 1)
        st = st[P["mv"][k]]
        sl = np.mod(np.interp(st, tt, lu), 1)
        rate, _ = D.firing_curve(sl, cd["occ_lin"], 4.5 / (P["L"] / D.NBINS))
        lam = np.sum(po * rate)
        with np.errstate(divide="ignore", invalid="ignore"):
            out.append(np.nansum(po * rate / lam * np.log2(np.where(rate > 0, rate / lam, 1))))
    return np.mean(out)

PREP_UNITS = {name: [u["times"] for u in RAT[name]["units"]] for name in D.RATS}
shifts = [-10, -2, -0.5, 0, 0.5, 2, 10]
rows = []
for name in D.RATS:
    P = PREP[name]
    rows.append([name[6:9]] + [round(spatial_info(P, "A", s), 3) for s in shifts])
print("Spatial information (bits/spike), Active place cells, spike times shifted by (s):")
print(pd.DataFrame(rows, columns=["rat"] + [str(s) for s in shifts]).to_string(index=False))
rows = []
for name in D.RATS:
    P, LF = PREP[name], LFPS[name]
    rip_sleep = np.mean([len(LF["sleep"][s]["ripples"]) / np.diff(LF["sleep"][s]["interval"])[0] for s in D.SLEEPS])
    rip_sws = []
    for s in D.SLEEPS:
        rp, sw = LF["sleep"][s]["ripples"], LF["sleep"][s]["sws"]
        dur = np.sum(np.diff(sw, axis=1)) if len(sw) else np.nan
        rip_sws.append(np.sum(D.in_intervals(rp[:, 1], sw)) / dur if len(sw) else np.nan)
    rows.append(dict(rat=name[6:9], ripples_per_s_sleep=round(rip_sleep, 3), ripples_per_s_in_SWS=round(np.nanmean(rip_sws), 3)))
print(pd.DataFrame(rows).to_string(index=False))
Spatial information (bits/spike), Active place cells, spike times shifted by (s):
rat   -10    -2  -0.5     0   0.5     2    10
242 0.244 0.240 0.246 0.245 0.249 0.250 0.219
261 0.718 0.727 0.735 0.731 0.724 0.701 0.687
272 0.325 0.325 0.322 0.325 0.321 0.323 0.317
292 0.260 0.269 0.276 0.274 0.273 0.272 0.259
314 0.444 0.445 0.443 0.444 0.441 0.436 0.437
rat  ripples_per_s_sleep  ripples_per_s_in_SWS
242                0.628                 0.885
261                0.710                 0.914
272                0.668                 0.907
292                0.623                 0.857
314                0.734                 1.004

Units and place cells¶

Putative pyramidal cells: k-means on waveform width, trough-to-peak duration and firing rate (Methods, Data acquisition; claims file, Common methods). DiscriminateUnits.m clusters on the two durations only, and its rate exclusion of pyramidal cells above 5 Hz never applies: it tests strcmp(rate,'on') on the numeric array rate instead of ratelim, which is always false. The two classifications are compared below. Well-isolated: L-ratio < 0.05. Place cells per condition: well-isolated pyramidal cells with at least one field (Methods, Firing fields), under the field readings of the claims file: (a) no minimum field size, (b) 10 bins; and, as a variant, the settings of BatchPlaceFields.m (kernel 5 bins = 12 cm, minimum 10 bins, fields over 3/4 of the track dropped, at least 50 spikes in Active and 30 in Passive).

In [7]:
rows = []
for name in D.RATS:
    r, P = RAT[name], PREP[name]
    pyr_code, _ = D.classify_units(r["units"], P["ep"]["travel"]["A"], reading="code")
    d = dict(rat=name[6:9], units=len(r["units"]), pyr_methods=int(P["pyr"].sum()), pyr_code=int(pyr_code.sum()),
             agree=int((P["pyr"] == pyr_code).sum()), pyr_iso=int((P["pyr"] & P["iso"]).sum()),
             median_waves_per_unit=int(np.median([u["n_wave"] for u in r["units"]])))
    for rd in ["a", "b", "c", "code"]:
        for c in D.CONDS:
            d[f"{c}_{rd}"] = len(D.place_cells(P, c, rd))
    rows.append(d)
pc = pd.DataFrame(rows)
print(pc.to_string(index=False))
tot = pc.sum(numeric_only=True)
print()
for rd in ["a", "b", "c", "code"]:
    print(f"reading {rd}: totals P1 {tot[f'P1_{rd}']}, A {tot[f'A_{rd}']}, P2 {tot[f'P2_{rd}']}  (paper 94, 150, 135; tolerance 10%)")
    long = pd.DataFrame([(r_, c, pc.loc[i, f"{c}_{rd}"]) for i, r_ in enumerate(pc.rat) for c in D.CONDS], columns=["rat", "cond", "n"])
    res = AnovaRM(long, "n", "rat", within=["cond"]).fit()
    print(res.anova_table.round(4).to_string())
    within = [abs(tot[f'{c}_{rd}'] - e) <= 0.1 * e for c, e in zip(D.CONDS, [94, 150, 135])]
    print("   within tolerance:", dict(zip(D.CONDS, within)), " P1 lowest:", tot[f'P1_{rd}'] < min(tot[f'A_{rd}'], tot[f'P2_{rd}']))
rat  units  pyr_methods  pyr_code  agree  pyr_iso  median_waves_per_unit  P1_a  A_a  P2_a  P1_b  A_b  P2_b  P1_c  A_c  P2_c  P1_code  A_code  P2_code
242     81           49        49     81       43                    800    31   31    32    30   29    31    19   22    26        9      16        9
261     46           32        32     46       25                    800    14   13    14    13   13    11    10   11     9        8      10        8
272    178          110       112    176       83                    800    67   63    71    57   60    63    39   46    47       15      31       23
292    115           85        19     49       31                    800    25   24    28    22   24    26    20   21    23        9      11       15
314    265          212       201    252      103                    800    70   72    83    61   69    76    50   58    66       20      36       45

reading a: totals P1 207, A 203, P2 228  (paper 94, 150, 135; tolerance 10%)
      F Value  Num DF  Den DF  Pr > F
cond   4.2515     2.0     8.0  0.0552
   within tolerance: {'P1': np.False_, 'A': np.False_, 'P2': np.False_}  P1 lowest: False
reading b: totals P1 183, A 195, P2 207  (paper 94, 150, 135; tolerance 10%)
      F Value  Num DF  Den DF  Pr > F
cond   2.6874     2.0     8.0   0.128
   within tolerance: {'P1': np.False_, 'A': np.False_, 'P2': np.False_}  P1 lowest: True
reading c: totals P1 138, A 158, P2 171  (paper 94, 150, 135; tolerance 10%)
      F Value  Num DF  Den DF  Pr > F
cond   5.0937     2.0     8.0  0.0374
   within tolerance: {'P1': np.False_, 'A': np.True_, 'P2': np.False_}  P1 lowest: True
reading code: totals P1 61, A 104, P2 100  (paper 94, 150, 135; tolerance 10%)
      F Value  Num DF  Den DF  Pr > F
cond   3.2605     2.0     8.0  0.0921
   within tolerance: {'P1': np.False_, 'A': np.False_, 'P2': np.False_}  P1 lowest: True

Result: partially reproduced, resting on an assumption. Under the claims file's readings the totals are 207, 203 and 228 (a) and 183, 195 and 207 (b) place cells against 94, 150 and 135, none within tolerance, and the ANOVA gives P = 0.055 and 0.128. With the Methods' 4.5 cm kernel and the size and spike limits of BatchPlaceFields.m (reading c, adopted) the totals are 138, 158 and 171: Active is within tolerance, Passive 1 is lowest and the ANOVA gives P = 0.037, so the order and the test hold but two totals do not. The code's own settings give 61, 104 and 100 (P = 0.092).

figs1-travel-similar¶

Train velocity, number of laps and travel duration did not differ between Passive 1, Active and Passive 2 (repeated-measures ANOVA, P > 0.05 for each, 5 rats).

Velocity from tracked head position (LinearVelocity, s.d. 30 samples, as the scripts); readings (a) all position samples of the travel, (b) samples above 5 cm/s. Laps: completed turns of the unwrapped linear position. Duration: the travel session's interval (the events file), and, as a variant, the time spent moving.

In [8]:
rows = []
for name in D.RATS:
    P = PREP[name]
    for c in D.CONDS:
        a, b = P["ep"]["travel"][c]
        s = (P["t"] >= a) & (P["t"] <= b)
        v = P["v"][s]
        lu = P["lin_unw"][s]
        lu = lu[np.isfinite(lu)]
        rows.append(dict(rat=name[6:9], cond=c, vel_a=np.nanmean(v), vel_b=np.nanmean(v[v > D.MINV]),
                         laps=np.floor(abs(lu[-1] - lu[0])), dur_min=(b - a) / 60,
                         moving_min=np.sum(D.in_intervals(P["t"][s], P["mov"])) / D.POS_FS / 60))
tv = pd.DataFrame(rows)
print(tv.round(2).to_string(index=False))
expected = {"vel": [46.80, 47.87, 46.73], "laps": [38.2, 30.8, 32.2], "dur_min": [8.24, 6.50, 7.20]}
tol = {"vel": [2.04, 1.83, 1.85], "laps": [2.8, 2.24, 1.77], "dur_min": [0.69, 0.33, 0.51]}
print()
for meas, col in [("vel", "vel_a"), ("vel", "vel_b"), ("laps", "laps"), ("dur_min", "dur_min"), ("dur_min", "moving_min")]:
    mean = tv.groupby("cond")[col].mean().reindex(D.CONDS)
    sem = tv.groupby("cond")[col].sem().reindex(D.CONDS)
    p = AnovaRM(tv, col, "rat", within=["cond"]).fit().anova_table["Pr > F"].iloc[0]
    f = AnovaRM(tv, col, "rat", within=["cond"]).fit().anova_table["F Value"].iloc[0]
    ok = [abs(m - e) <= t for m, e, t in zip(mean, expected[meas], tol[meas])]
    print(f"{col:11s} means {np.round(mean.values, 2)} (s.e.m. {np.round(sem.values, 2)}) expected {expected[meas]}; within tolerance {ok}; RM-ANOVA F = {f:.2f}, P = {p:.3f}")
rat cond  vel_a  vel_b  laps  dur_min  moving_min
242   P1  33.04  37.31  38.0    11.71        9.76
242    A  40.64  40.69  23.0     5.84        5.84
242   P2  37.79  38.89  30.0     8.40        8.18
261   P1  45.34  47.92  45.0     9.99        9.44
261    A  48.47  48.49  29.0     6.16        6.16
261   P2  35.98  41.33  30.0     9.06        7.42
272   P1  44.22  48.96  39.0     8.87        7.86
272    A  49.99  49.99  31.0     6.26        6.26
272   P2  44.86  47.03  29.0     6.57        6.18
292   P1  48.43  48.75  28.0     6.11        6.07
292    A  46.31  46.41  29.0     6.70        6.70
292   P2  49.17  49.55  28.0     6.04        5.96
314   P1  40.14  45.04  37.0     9.39        8.16
314    A  51.06  51.12  35.0     7.12        7.11
314   P2  49.35  50.23  39.0     8.10        7.96

vel_a       means [42.23 47.29 43.43] (s.e.m. [2.65 1.84 2.8 ]) expected [46.8, 47.87, 46.73]; within tolerance [False, True, False]; RM-ANOVA F = 2.04, P = 0.193
vel_b       means [45.6  47.34 45.41] (s.e.m. [2.19 1.84 2.26]) expected [46.8, 47.87, 46.73]; within tolerance [True, True, True]; RM-ANOVA F = 0.79, P = 0.487
laps        means [37.4 29.4 31.2] (s.e.m. [2.73 1.94 1.98]) expected [38.2, 30.8, 32.2]; within tolerance [True, True, True]; RM-ANOVA F = 4.35, P = 0.053
dur_min     means [9.21 6.42 7.63] (s.e.m. [0.91 0.22 0.57]) expected [8.24, 6.5, 7.2]; within tolerance [False, True, True]; RM-ANOVA F = 6.28, P = 0.023
moving_min  means [8.26 6.41 7.14] (s.e.m. [0.66 0.22 0.45]) expected [8.24, 6.5, 7.2]; within tolerance [True, True, True]; RM-ANOVA F = 4.68, P = 0.045

Result: not reproduced. Velocity above 5 cm/s (45.6, 47.3 and 45.4 cm/s, P = 0.487) and laps (37.4, 29.4 and 31.2, P = 0.053) are alike and within tolerance, but travel duration from the events file differs (9.21, 6.42 and 7.63 min, P = 0.023, Passive 1 outside tolerance), and so does the time moving (P = 0.045).

Firing fields: size, peak rate, coverage¶

fig1c-field-size-similar: Place field size was the same in the three travel conditions (Kruskal-Wallis, P > 0.05).

fig1c-peak-rate-lower-passive1: Place-cell peak firing rates were lower in Passive 1 than in Active.

figs2c-track-coverage: In every travel condition the place fields together covered the whole track.

In [9]:
def field_table(rd):
    rows = []
    for name in D.RATS:
        P = PREP[name]
        bin_cm = 600 / D.NBINS
        for c in D.CONDS:
            for i in D.place_cells(P, c, rd):
                f = P["cond"][c]["cells"][i]["readings"][rd]
                rate = f["rate"]
                for k, m in enumerate(f["fields"]):
                    rows.append(dict(rat=name[6:9], cond=c, cell=i, field=k, size_cm=m.sum() * bin_cm, peak=rate.max()))
    return pd.DataFrame(rows)

FT = {rd: field_table(rd) for rd in ["a", "b", "c", "code"]}
for rd in ["a", "b", "c", "code"]:
    ft = FT[rd]
    for sub, lab in [(ft[ft.field == 0], "peak field only"), (ft, "every field")]:
        g = [sub[sub.cond == c].size_cm.values for c in D.CONDS]
        h, p = stats.kruskal(*g)
        print(f"reading {rd:4s} {lab:15s}: median size (cm) {[round(np.median(x), 1) for x in g]}, n {[len(x) for x in g]}; KW H = {h:.2f}, P = {p:.4f}")
print("Field size per rat, median cm, reading a, peak field:")
print(FT["a"][FT["a"].field == 0].groupby(["rat", "cond"]).size_cm.median().unstack().reindex(columns=D.CONDS).round(1).to_string())
# distribution of field sizes, fields per place cell and spatial information per place cell
edges_cm = [0, 25, 50, 100, 200, 300, 450, 600.1]
def si_bits(rate, occ):
    po = occ / occ.sum()
    lam = np.sum(po * rate)
    with np.errstate(divide="ignore", invalid="ignore"):
        return np.nansum(po * rate / lam * np.log2(np.where(rate > 0, rate / lam, 1)))
for rd in ["a", "c"]:
    ft = FT[rd]
    print(f"reading {rd}: peak-field size histogram (cm bins {edges_cm[:-1]} to 600):")
    for c in D.CONDS:
        print(f"   {c}: {np.histogram(ft[(ft.cond == c) & (ft.field == 0)].size_cm, edges_cm)[0].tolist()}; "
              f"fields per place cell, median {ft[ft.cond == c].groupby(['rat', 'cell']).size().median():.0f}, "
              f"distribution {ft[ft.cond == c].groupby(['rat', 'cell']).size().value_counts().sort_index().to_dict()}")
    rows = []
    for name in D.RATS:
        P = PREP[name]
        for c in D.CONDS:
            cd = P["cond"][c]
            occ = np.bincount(np.minimum((cd["occ_lin"] * D.NBINS).astype(int), D.NBINS - 1), minlength=D.NBINS) / D.POS_FS
            for i in D.place_cells(P, c, rd):
                rows.append(dict(rat=name[6:9], cond=c, si=si_bits(cd["cells"][i]["readings"][rd]["rate"], occ)))
    si = pd.DataFrame(rows)
    print(f"   spatial information (bits/spike) per place cell, quartiles: " +
          "; ".join(f"{c} {np.round(np.percentile(si[si.cond == c].si, [25, 50, 75]), 2).tolist()}" for c in D.CONDS))
reading a    peak field only: median size (cm) [np.float64(120.0), np.float64(163.2), np.float64(108.0)], n [207, 203, 228]; KW H = 10.08, P = 0.0065
reading a    every field    : median size (cm) [np.float64(31.2), np.float64(28.8), np.float64(21.6)], n [1072, 819, 1357]; KW H = 34.81, P = 0.0000
reading b    peak field only: median size (cm) [np.float64(139.2), np.float64(170.4), np.float64(134.4)], n [183, 195, 207]; KW H = 5.31, P = 0.0703
reading b    every field    : median size (cm) [np.float64(57.6), np.float64(69.6), np.float64(55.2)], n [597, 455, 630]; KW H = 12.76, P = 0.0017
reading c    peak field only: median size (cm) [np.float64(100.8), np.float64(142.8), np.float64(98.4)], n [138, 158, 171]; KW H = 15.61, P = 0.0004
reading c    every field    : median size (cm) [np.float64(52.8), np.float64(64.8), np.float64(52.8)], n [546, 409, 592]; KW H = 14.07, P = 0.0009
reading code peak field only: median size (cm) [np.float64(199.2), np.float64(222.0), np.float64(235.2)], n [61, 104, 100]; KW H = 1.27, P = 0.5291
reading code every field    : median size (cm) [np.float64(136.8), np.float64(184.8), np.float64(127.2)], n [125, 145, 193]; KW H = 6.82, P = 0.0330
Field size per rat, median cm, reading a, peak field:
cond     P1      A     P2
rat                      
242   139.2  136.8  200.4
261   128.4  132.0   97.2
272   117.6  192.0  136.8
292   110.4  190.8   92.4
314   123.6  132.0   93.6
reading a: peak-field size histogram (cm bins [0, 25, 50, 100, 200, 300, 450] to 600):
   P1: [29, 25, 39, 45, 11, 13, 45]; fields per place cell, median 5, distribution {1: 54, 2: 17, 3: 9, 4: 22, 5: 18, 6: 14, 7: 11, 8: 20, 9: 15, 10: 6, 11: 7, 12: 4, 13: 4, 14: 4, 15: 2}
   A: [11, 14, 30, 70, 28, 15, 35]; fields per place cell, median 3, distribution {1: 53, 2: 26, 3: 25, 4: 24, 5: 20, 6: 12, 7: 10, 8: 12, 9: 12, 10: 4, 11: 3, 12: 2}
   P2: [24, 40, 45, 43, 20, 20, 36]; fields per place cell, median 5, distribution {1: 46, 2: 17, 3: 19, 4: 14, 5: 21, 6: 18, 7: 15, 8: 11, 9: 16, 10: 13, 11: 9, 12: 11, 13: 9, 14: 4, 15: 2, 16: 2, 18: 1}
   spatial information (bits/spike) per place cell, quartiles: P1 [0.06, 0.14, 0.27]; A [0.09, 0.22, 0.5]; P2 [0.07, 0.18, 0.34]
reading c: peak-field size histogram (cm bins [0, 25, 50, 100, 200, 300, 450] to 600):
   P1: [5, 25, 39, 45, 11, 13, 0]; fields per place cell, median 4, distribution {1: 18, 2: 19, 3: 25, 4: 24, 5: 20, 6: 11, 7: 15, 8: 6}
   A: [3, 12, 30, 70, 28, 15, 0]; fields per place cell, median 2, distribution {1: 50, 2: 39, 3: 32, 4: 17, 5: 11, 6: 2, 7: 6, 8: 1}
   P2: [3, 40, 45, 43, 20, 20, 0]; fields per place cell, median 3, distribution {1: 29, 2: 32, 3: 35, 4: 29, 5: 19, 6: 12, 7: 10, 8: 4, 9: 1}
   spatial information (bits/spike) per place cell, quartiles: P1 [0.09, 0.15, 0.26]; A [0.15, 0.27, 0.55]; P2 [0.11, 0.2, 0.34]

Result: not reproduced, resting on an assumption. Under the adopted field reading (c) field size differs between conditions: Kruskal-Wallis P = 0.0004 for the peak field (medians 100.8, 142.8 and 98.4 cm) and P = 0.0009 for every field. It also differs under readings (a) (P = 0.0065 and < 0.0001) and (b) with every field (P = 0.0017). Only the peak field under reading (b) (P = 0.070) and the code's settings for the peak field (P = 0.53) find no difference. Peak fields are large: under reading (a) 45 of 207 Passive 1 place cells have a peak field over 450 cm, place cells have a median of 3 to 5 fields, and the median spatial information is 0.14 to 0.22 bits per spike.

In [10]:
for rd in ["a", "b", "c", "code"]:
    ft = FT[rd][FT[rd].field == 0]
    g = {c: ft[ft.cond == c].peak.values for c in D.CONDS}
    h, p = stats.kruskal(*g.values())
    u, p_pa = stats.mannwhitneyu(g["P1"], g["A"], alternative="two-sided")
    u2, p_ap2 = stats.mannwhitneyu(g["A"], g["P2"], alternative="two-sided")
    print(f"reading {rd:4s}: median peak rate (Hz) P1 {np.median(g['P1']):.2f}, A {np.median(g['A']):.2f}, P2 {np.median(g['P2']):.2f}; "
          f"KW P = {p:.2e}; rank-sum P1 vs A P = {p_pa:.2e} (Bonferroni x3: {min(1, 3 * p_pa):.2e}); A vs P2 P = {p_ap2:.2e}")
print("Per rat, median peak rate, reading a:")
print(FT["a"][FT["a"].field == 0].groupby(["rat", "cond"]).peak.median().unstack().reindex(columns=D.CONDS).round(2).to_string())
reading a   : median peak rate (Hz) P1 2.51, A 3.82, P2 2.78; KW P = 2.59e-06; rank-sum P1 vs A P = 5.79e-07 (Bonferroni x3: 1.74e-06); A vs P2 P = 6.63e-04
reading b   : median peak rate (Hz) P1 2.81, A 3.95, P2 3.00; KW P = 1.52e-04; rank-sum P1 vs A P = 4.44e-05 (Bonferroni x3: 1.33e-04); A vs P2 P = 3.88e-03
reading c   : median peak rate (Hz) P1 2.32, A 3.15, P2 2.65; KW P = 1.23e-06; rank-sum P1 vs A P = 2.60e-07 (Bonferroni x3: 7.80e-07); A vs P2 P = 9.83e-04
reading code: median peak rate (Hz) P1 1.59, A 3.25, P2 1.76; KW P = 3.62e-06; rank-sum P1 vs A P = 7.08e-06 (Bonferroni x3: 2.12e-05); A vs P2 P = 8.67e-05
Per rat, median peak rate, reading a:
cond    P1     A    P2
rat                   
242   2.37  3.08  2.40
261   2.73  6.88  2.78
272   2.74  4.05  3.15
292   3.65  3.98  2.70
314   2.21  3.13  2.66

Result: reproduced. Under reading (c) the median peak rates are 2.32, 3.15 and 2.65 Hz; the rank-sum test of Passive 1 against Active gives P = 7.8 x 10^-7 after Bonferroni, below 0.001/3, and the Kruskal-Wallis P = 1.2 x 10^-6. Every other reading gives the same (Bonferroni P = 1.7 x 10^-6 to 1.3 x 10^-4).

In [11]:
for rd in ["a", "b", "c", "code"]:
    rows = []
    for c in D.CONDS:
        pooled = np.zeros(D.NBINS, bool)
        per = []
        for name in D.RATS:
            P = PREP[name]
            cov = np.zeros(D.NBINS, bool)
            for i in D.place_cells(P, c, rd):
                for m in P["cond"][c]["cells"][i]["readings"][rd]["fields"]:
                    cov |= m
            per.append(100 * cov.mean())
            pooled |= cov
        rows.append(dict(cond=c, pooled_pct=round(100 * pooled.mean(), 1), **{f"rat_{n[6:9]}": round(x, 1) for n, x in zip(D.RATS, per)}))
    print(f"reading {rd}:")
    print(pd.DataFrame(rows).to_string(index=False))
reading a:
cond  pooled_pct  rat_242  rat_261  rat_272  rat_292  rat_314
  P1       100.0    100.0    100.0    100.0    100.0    100.0
   A       100.0    100.0    100.0    100.0    100.0    100.0
  P2       100.0    100.0    100.0    100.0    100.0    100.0
reading b:
cond  pooled_pct  rat_242  rat_261  rat_272  rat_292  rat_314
  P1       100.0    100.0    100.0    100.0    100.0    100.0
   A       100.0    100.0    100.0    100.0    100.0    100.0
  P2       100.0    100.0    100.0    100.0    100.0    100.0
reading c:
cond  pooled_pct  rat_242  rat_261  rat_272  rat_292  rat_314
  P1       100.0    100.0    100.0    100.0    100.0    100.0
   A       100.0    100.0    100.0    100.0    100.0    100.0
  P2       100.0    100.0    100.0    100.0    100.0    100.0
reading code:
cond  pooled_pct  rat_242  rat_261  rat_272  rat_292  rat_314
  P1       100.0     99.6    100.0    100.0    100.0    100.0
   A       100.0    100.0    100.0    100.0    100.0    100.0
  P2       100.0     96.8    100.0    100.0    100.0    100.0

Result: reproduced. Fields cover 100% of the track in every condition, pooled and in each rat, under readings (a), (b) and (c); with the code's settings rat 242 reaches 99.6% and 96.8% in the passive conditions. With fields this large, coverage is expected.

Remapping¶

fig1d-no-remapping-p1-active: Place fields did not remap between Passive 1 and Active; the mean unsigned proportional field shift was smaller than under random remapping (P < 0.01, 2000 bootstraps), and peak-location shifts were non-uniform and centred on zero (Rayleigh P < 0.001, V-test P < 10^-4).

fig1e-no-remapping-active-p2: Place fields did not remap between Active and Passive 2 (bootstrap P ~ 0; Rayleigh P < 10^-9; V-test P < 10^-10).

figs2d-stability-p1-p2: Place fields were also stable between Passive 1 and Passive 2 (bootstrap P < 0.02; V-test P < 0.05), though the angular shifts did not depart from uniformity by the Rayleigh test (P > 0.05).

Following the criterion: shift = lag of the peak of the cross-correlogram of the two firing curves over the mean field size; the mean unsigned shift against 2000 shuffles of cell identity in the test condition. Cells pooled over rats. Readings: cells with a field in both conditions or in either; circular or linear correlogram. Field readings a and b.

In [12]:
def remap(c1, c2, rd, cellset, circular, rng):
    curves1, curves2, s1, s2, ang = [], [], [], [], []
    for name in D.RATS:
        P = PREP[name]
        pcs1, pcs2 = set(D.place_cells(P, c1, rd)), set(D.place_cells(P, c2, rd))
        cells = (pcs1 & pcs2) if cellset == "both" else (pcs1 | pcs2)
        for i in sorted(cells):
            f1 = P["cond"][c1]["cells"][i]["readings"][rd]
            f2 = P["cond"][c2]["cells"][i]["readings"][rd]
            a1 = f1["fields"][0].sum() if f1["fields"] else 0
            a2 = f2["fields"][0].sum() if f2["fields"] else 0
            if a1 == 0:
                a1 = a2
            if a2 == 0:
                a2 = a1
            curves1.append(f1["rate"]); curves2.append(f2["rate"]); s1.append(a1); s2.append(a2)
            d = (np.argmax(f2["rate"]) - np.argmax(f1["rate"])) / D.NBINS * 2 * np.pi
            ang.append(np.angle(np.exp(1j * d)))
    k = len(curves1)
    C1 = np.array(curves1); C2 = np.array(curves2)
    # lag matrix for every pair (i, j): curve1 of cell i against curve2 of cell j
    n = D.NBINS
    A = C1 - C1.mean(1, keepdims=True); B = C2 - C2.mean(1, keepdims=True)
    lag = np.zeros((k, k))
    if circular:
        FA, FB = np.conj(np.fft.fft(A, axis=1)), np.fft.fft(B, axis=1)
        lags = np.r_[np.arange(0, n // 2 + 1), np.arange(-(n - n // 2 - 1), 0)]
        for i in range(k):
            cc = np.real(np.fft.ifft(FA[i][None, :] * FB, axis=1))
            lag[i] = lags[np.argmax(cc, 1)]
    else:
        lags = np.arange(-(n - 1), n)
        for i in range(k):
            for j in range(k):
                lag[i, j] = lags[np.argmax(np.correlate(B[j], A[i], mode="full"))]
    s1, s2 = np.array(s1, float), np.array(s2, float)
    msize = (s1[:, None] + s2[None, :]) / 2
    prop = np.abs(lag) / msize
    obs = np.mean(np.diag(prop))
    null = np.array([np.mean(prop[np.arange(k), rng.permutation(k)]) for _ in range(2000)])
    p = np.mean(null <= obs)
    ang = np.array(ang)
    R, pr = D.rayleigh(ang)
    u, pv = D.vtest(ang)
    return dict(n=k, obs=obs, null_mean=null.mean(), null_min=null.min(), p_boot=p, rayleigh_R=R, rayleigh_p=pr, v_u=u, v_p=pv,
                mean_angle_deg=np.degrees(np.angle(np.mean(np.exp(1j * ang)))))

REMAP = {}
for pair, seed in [(("P1", "A"), 11), (("A", "P2"), 12), (("P1", "P2"), 13)]:
    rows = []
    for rd in ["a", "b", "c"]:
        for cellset in ["both", "either"]:
            for circ in [True, False]:
                rng = np.random.default_rng(seed)
                res = remap(pair[0], pair[1], rd, cellset, circ, rng)
                rows.append(dict(fields=rd, cells=cellset, correlogram="circular" if circ else "linear", **res))
    REMAP[pair] = pd.DataFrame(rows)

def show_remap(pair):
    df = REMAP[pair].copy()
    for col in ["rayleigh_p", "v_p"]:
        df[col] = df[col].map(lambda x: f"{x:.1e}")
    print(f"control {pair[0]}, test {pair[1]}")
    print(df.round(3).to_string(index=False))
In [13]:
show_remap(("P1", "A"))
control P1, test A
fields  cells correlogram   n   obs  null_mean  null_min  p_boot  rayleigh_R rayleigh_p   v_u     v_p  mean_angle_deg
     a   both    circular 179 0.991      0.994     0.795   0.501       0.215    2.4e-04 4.061 4.9e-05           3.330
     a   both      linear 179 1.006      1.078     0.838   0.208       0.215    2.4e-04 4.061 4.9e-05           3.330
     a either    circular 231 1.647      1.364     1.101   0.996       0.179    5.7e-04 3.798 1.5e-04          -9.576
     a either      linear 231 1.912      1.571     1.188   0.992       0.179    5.7e-04 3.798 1.5e-04          -9.576
     b   both    circular 162 0.780      0.856     0.676   0.088       0.235    1.2e-04 4.235 2.3e-05           0.936
     b   both      linear 162 0.770      0.923     0.718   0.014       0.235    1.2e-04 4.235 2.3e-05           0.936
     b either    circular 216 1.123      1.091     0.903   0.689       0.184    6.6e-04 3.768 1.6e-04          -9.058
     b either      linear 216 1.165      1.215     0.945   0.278       0.184    6.6e-04 3.768 1.6e-04          -9.058
     c   both    circular 111 0.959      1.256     0.940   0.000       0.265    3.7e-04 3.947 7.9e-05           2.300
     c   both      linear 111 0.994      1.373     0.958   0.000       0.265    3.7e-04 3.947 7.9e-05           2.300
     c either    circular 185 1.264      1.367     1.121   0.088       0.186    1.6e-03 3.507 4.5e-04         -11.228
     c either      linear 185 1.328      1.529     1.124   0.020       0.186    1.6e-03 3.507 4.5e-04         -11.228

Result: reproduced, resting on an assumption. Under the adopted field reading (c), with cells that have a field in both conditions (111 cells), one shuffled mean of 2000 is below the observed one under either correlogram (bootstrap P = 0.0005), the Rayleigh test gives P = 3.7 x 10^-4 and the two-tailed V-test P = 7.9 x 10^-5 (mean angle 2.3 deg): all three reach the legend's 0.01, 0.001 and 10^-4. The outcome rests on field reading (c), which the claims file does not list, and on cells with a field in both conditions; with cells in either condition under (c) the Rayleigh test gives P = 1.6 x 10^-3. Under the claims file's eight readings the bootstrap does not reach 0.01 (P = 0.014 with fields of 10 bins or more, cells in both conditions and the linear correlogram; 0.088 to 0.996 under the other seven), while the Rayleigh and V-tests are significant under all eight. Changed from partially reproduced after round 3 of verification.

In [14]:
show_remap(("A", "P2"))
control A, test P2
fields  cells correlogram   n   obs  null_mean  null_min  p_boot  rayleigh_R rayleigh_p   v_u     v_p  mean_angle_deg
     a   both    circular 196 0.946      1.051     0.856   0.054       0.270    4.7e-07 5.353 8.6e-08           0.994
     a   both      linear 196 0.989      1.173     0.877   0.011       0.270    4.7e-07 5.353 8.6e-08           0.994
     a either    circular 235 1.542      1.385     1.106   0.956       0.246    5.3e-07 5.302 1.1e-07          -6.800
     a either      linear 235 1.691      1.539     1.194   0.907       0.246    5.3e-07 5.302 1.1e-07          -6.800
     b   both    circular 181 0.766      0.921     0.729   0.001       0.269    1.6e-06 5.126 3.0e-07          -0.906
     b   both      linear 181 0.754      1.030     0.794   0.000       0.269    1.6e-06 5.126 3.0e-07          -0.906
     b either    circular 221 1.091      1.151     0.942   0.171       0.256    4.0e-07 5.366 8.1e-08          -5.341
     b either      linear 221 1.129      1.278     0.924   0.033       0.256    4.0e-07 5.366 8.1e-08          -5.341
     c   both    circular 136 0.955      1.278     1.040   0.000       0.308    1.8e-06 5.081 3.8e-07          -2.769
     c   both      linear 136 0.946      1.446     1.141   0.000       0.308    1.8e-06 5.081 3.8e-07          -2.769
     c either    circular 193 1.189      1.375     1.161   0.003       0.277    2.8e-07 5.397 6.8e-08          -7.926
     c either      linear 193 1.245      1.532     1.286   0.000       0.277    2.8e-07 5.397 6.8e-08          -7.926

Result: partially reproduced, resting on an assumption. With fields of 10 bins or more, cells in both conditions and the linear correlogram, no shuffled mean of 2000 is at or below the observed one (P < 0.0005), Rayleigh P = 1.6 x 10^-6 and two-tailed V-test P = 3.0 x 10^-7: all below 0.001 but not below the legend's 10^-9 and 10^-10. The other readings give bootstrap P = 0.001 to 0.96. Under field reading (c), cells in both conditions: bootstrap P < 0.0005, Rayleigh P = 1.8 x 10^-6 and V-test P = 3.8 x 10^-7, also partial.

In [15]:
show_remap(("P1", "P2"))
control P1, test P2
fields  cells correlogram   n   obs  null_mean  null_min  p_boot  rayleigh_R rayleigh_p   v_u     v_p  mean_angle_deg
     a   both    circular 196 1.531      1.359     1.024   0.952       0.168    3.9e-03 3.311 9.3e-04          -5.141
     a   both      linear 196 1.485      1.421     1.062   0.696       0.168    3.9e-03 3.311 9.3e-04          -5.141
     a either    circular 239 1.871      1.565     1.229   0.998       0.143    7.4e-03 3.026 2.5e-03         -14.573
     a either      linear 239 2.123      1.729     1.339   0.996       0.143    7.4e-03 3.026 2.5e-03         -14.573
     b   both    circular 166 1.116      1.004     0.805   0.935       0.171    7.4e-03 2.947 3.2e-03         -19.368
     b   both      linear 166 0.849      1.026     0.775   0.016       0.171    7.4e-03 2.947 3.2e-03         -19.368
     b either    circular 224 1.473      1.265     0.991   0.996       0.141    1.1e-02 2.948 3.2e-03          -9.035
     b either      linear 224 1.463      1.361     1.073   0.847       0.141    1.1e-02 2.948 3.2e-03          -9.035
     c   both    circular 114 1.502      1.556     1.235   0.314       0.204    8.5e-03 3.064 2.2e-03          -5.741
     c   both      linear 114 1.122      1.604     1.209   0.000       0.204    8.5e-03 3.064 2.2e-03          -5.741
     c either    circular 195 1.733      1.617     1.336   0.910       0.168    3.9e-03 3.310 9.3e-04          -5.039
     c either      linear 195 1.736      1.745     1.362   0.472       0.168    3.9e-03 3.310 9.3e-04          -5.039

Result: partially reproduced, resting on an assumption. With fields of 10 bins or more, cells in both conditions and the linear correlogram, the bootstrap (P = 0.016) and the two-tailed V-test (P = 0.0032) are significant, but the Rayleigh test, the paper's test of absence, finds non-uniformity under every reading (P = 0.0039 to 0.011), and under field reading (c) too (P = 0.0085, with bootstrap P < 0.0005 and V-test P = 0.0022 for cells in both conditions and the linear correlogram).

Theta frequency, power and asymmetry¶

fig2b-theta-frequency-unchanged: Theta frequency did not differ between travel conditions (repeated-measures ANOVA, P > 0.90).

fig2b-theta-power-reduced: Theta power was lower during passive travel than active travel (repeated-measures ANOVA, P < 10^-6), with power reduced at both the fundamental and the first harmonic.

fig2b-theta-asymmetry-reduced: The shape of theta cycles changed during passive travel, with decreased cycle asymmetry (Kruskal-Wallis, P < 10^-84).

Multitaper spectra of the detrended LFP in 2-s windows (Methods, Theta power, frequency and cycles). LFP readings: (a) the pyramidal-layer channel with the largest theta power, (b) the mean of the pyramidal-layer channels. Samples: (all) the whole travel session, (mov) moving periods only.

In [16]:
SPEC = {}
for name in D.RATS:
    P, LF = PREP[name], LFPS[name]
    for c in D.CONDS:
        tr = LF["travel"][c]
        n = len(tr["a"])
        tt = tr["t0"] + np.arange(n) / D.LFP_FS
        mvm = D.in_intervals(tt, P["mov"])
        for ch in ["a", "b"]:
            x = tr[ch]
            for samp in ["all", "mov"]:
                if samp == "all":
                    segs = [x]
                else:
                    i0, i1 = D.runs(mvm)
                    segs = [x[i:j] for i, j in zip(i0, i1) if j - i > 2 * D.LFP_FS]
                f, S, Sw = D.mt_psd(segs)
                SPEC[(name, c, ch, samp)] = (f, S, Sw)
# 8-s windows (0.125 Hz resolution) for the frequency, moving samples only (added after round 1)
SPEC8 = {}
for name in D.RATS:
    P, LF = PREP[name], LFPS[name]
    for c in D.CONDS:
        tr = LF["travel"][c]
        tt = tr["t0"] + np.arange(len(tr["a"])) / D.LFP_FS
        i0, i1 = D.runs(D.in_intervals(tt, P["mov"]))
        for ch in ["a", "b"]:
            f8, S8, _ = D.mt_psd([tr[ch][i:j] for i, j in zip(i0, i1) if j - i > 8 * D.LFP_FS], win=8.0)
            SPEC8[(name, c, ch)] = (f8, S8)
f = SPEC[(D.RATS[0], "P1", "a", "all")][0]
th_band = (f >= 6) & (f <= 10)
harm = (f >= 12) & (f <= 20)

def theta_table(ch, samp):
    rows = []
    for name in D.RATS:
        S = np.array([SPEC[(name, c, ch, samp)][1] for c in D.CONDS])
        mu, sd = S.mean(0), S.std(0, ddof=1)
        Sn = (S - mu) / sd
        for k, c in enumerate(D.CONDS):
            rows.append(dict(rat=name[6:9], cond=c, freq=f[th_band][np.argmax(S[k, th_band])],
                             power=Sn[k, th_band].max(), harmonic=Sn[k, harm].max(), raw_power=S[k, th_band].max()))
    return pd.DataFrame(rows)
In [17]:
for ch in ["a", "b"]:
    for samp in ["all", "mov"]:
        tt_ = theta_table(ch, samp)
        res = AnovaRM(tt_, "freq", "rat", within=["cond"]).fit().anova_table
        print(f"LFP {ch}, samples {samp}: theta frequency (Hz) by condition {tt_.groupby('cond').freq.mean().reindex(D.CONDS).round(2).to_dict()}; "
              f"RM-ANOVA F = {res['F Value'].iloc[0]:.2f}, P = {res['Pr > F'].iloc[0]:.3f}")
print(theta_table("a", "mov").pivot(index="rat", columns="cond", values="freq").reindex(columns=D.CONDS).to_string())
print("Frequency resolution of the 2-s spectra:", f[1] - f[0], "Hz")
for ch in ["a", "b"]:
    rows = []
    for name in D.RATS:
        for c in D.CONDS:
            f8, S8 = SPEC8[(name, c, ch)]
            band = (f8 >= 6) & (f8 <= 10)
            rows.append(dict(rat=name[6:9], cond=c, freq=f8[band][np.argmax(S8[band])]))
    t8 = pd.DataFrame(rows)
    res = AnovaRM(t8, "freq", "rat", within=["cond"]).fit().anova_table
    print(f"8-s windows ({f8[1] - f8[0]} Hz resolution), LFP {ch}, moving samples: frequency by condition {t8.groupby('cond').freq.mean().reindex(D.CONDS).round(3).to_dict()}; "
          f"RM-ANOVA F = {res['F Value'].iloc[0]:.2f}, P = {res['Pr > F'].iloc[0]:.3f}")
    print(t8.pivot(index="rat", columns="cond", values="freq").reindex(columns=D.CONDS).to_string())
LFP a, samples all: theta frequency (Hz) by condition {'P1': 6.9, 'A': 7.1, 'P2': 6.9}; RM-ANOVA F = 2.67, P = 0.130
LFP a, samples mov: theta frequency (Hz) by condition {'P1': 6.9, 'A': 7.1, 'P2': 6.9}; RM-ANOVA F = 2.67, P = 0.130
LFP b, samples all: theta frequency (Hz) by condition {'P1': 6.9, 'A': 7.1, 'P2': 7.0}; RM-ANOVA F = 1.00, P = 0.410
LFP b, samples mov: theta frequency (Hz) by condition {'P1': 6.9, 'A': 7.1, 'P2': 7.0}; RM-ANOVA F = 1.00, P = 0.410
cond   P1    A   P2
rat                
242   7.0  7.0  7.0
261   7.0  7.0  7.0
272   7.0  7.0  7.0
292   7.0  7.5  7.0
314   6.5  7.0  6.5
Frequency resolution of the 2-s spectra: 0.5 Hz
8-s windows (0.125 Hz resolution), LFP a, moving samples: frequency by condition {'P1': 6.975, 'A': 6.975, 'P2': 6.9}; RM-ANOVA F = 0.23, P = 0.799
cond     P1      A    P2
rat                     
242   7.375  7.000  7.25
261   6.875  7.000  7.00
272   7.250  6.875  6.75
292   6.875  7.125  7.00
314   6.500  6.875  6.50
8-s windows (0.125 Hz resolution), LFP b, moving samples: frequency by condition {'P1': 7.0, 'A': 6.975, 'P2': 6.95}; RM-ANOVA F = 0.08, P = 0.922
cond     P1      A    P2
rat                     
242   7.375  7.000  7.25
261   7.000  7.000  7.00
272   7.250  6.875  6.75
292   6.875  7.125  7.00
314   6.500  6.875  6.75

Result: reproduced. Theta frequency does not differ between conditions: with 2-s spectra the RM-ANOVA gives P = 0.13 to 0.41, and with 8-s spectra (0.125 Hz resolution) P = 0.80 (LFP a) and 0.92 (LFP b), means 6.9 to 7.0 Hz.

In [18]:
def posthoc_paired(df, col):
    out = {}
    w = df.pivot(index="rat", columns="cond", values=col)
    for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
        t, p = stats.ttest_rel(w[a], w[b])
        out[f"{a}-{b}"] = (round(t, 2), min(1, 3 * p))
    return out

for ch in ["a", "b"]:
    for samp in ["all", "mov"]:
        tt_ = theta_table(ch, samp)
        for col in ["power", "harmonic"]:
            res = AnovaRM(tt_, col, "rat", within=["cond"]).fit().anova_table
            print(f"LFP {ch}, {samp}, {col:8s}: means {tt_.groupby('cond')[col].mean().reindex(D.CONDS).round(2).to_dict()}; "
                  f"RM-ANOVA P = {res['Pr > F'].iloc[0]:.2e}; post hoc paired t (t, Bonferroni P) {posthoc_paired(tt_, col)}")
# reading (b) of the unit: one value per 2-s window, normalized with the rat's condition mean and s.d.
for ch in ["a"]:
    for samp in ["mov"]:
        rows = []
        for name in D.RATS:
            S = np.array([SPEC[(name, c, ch, samp)][1] for c in D.CONDS])
            mu, sd = S.mean(0), S.std(0, ddof=1)
            for c in D.CONDS:
                Sw = SPEC[(name, c, ch, samp)][2]
                Wn = (Sw - mu) / sd
                for v in Wn[:, th_band].max(1):
                    rows.append(dict(rat=name[6:9], cond=c, power=v))
        wdf = pd.DataFrame(rows)
        fit = smf.ols("power ~ C(cond) + C(rat)", data=wdf).fit()
        at = sm.stats.anova_lm(fit, typ=2)
        print(f"per-window reading, LFP {ch}, {samp}: n windows {wdf.groupby('cond').size().reindex(D.CONDS).to_dict()}; "
              f"medians {wdf.groupby('cond').power.median().reindex(D.CONDS).round(2).to_dict()}; two-way ANOVA (condition + rat) condition P = {at.loc['C(cond)', 'PR(>F)']:.2e}")
        for a, b in [("P1", "A"), ("A", "P2")]:
            print(f"   rank-sum {a} vs {b}: P = {stats.mannwhitneyu(wdf[wdf.cond == a].power, wdf[wdf.cond == b].power).pvalue:.2e}")
print(theta_table("a", "mov").pivot(index="rat", columns="cond", values="raw_power").reindex(columns=D.CONDS).round(0).to_string())
LFP a, all, power   : means {'P1': 0.66, 'A': 1.15, 'P2': 0.28}; RM-ANOVA P = 1.69e-01; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(-1.82), np.float64(0.4287540038526191)), 'A-P2': (np.float64(2.43), np.float64(0.21640202241547346)), 'P1-P2': (np.float64(0.69), 1)}
LFP a, all, harmonic: means {'P1': 0.71, 'A': 0.33, 'P2': 0.46}; RM-ANOVA P = 7.67e-01; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(0.86), 1), 'A-P2': (np.float64(-0.22), 1), 'P1-P2': (np.float64(0.52), 1)}
LFP a, mov, power   : means {'P1': 0.72, 'A': 1.15, 'P2': 0.21}; RM-ANOVA P = 1.35e-01; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(-1.64), np.float64(0.5266353724177104)), 'A-P2': (np.float64(2.69), np.float64(0.16331930099063444)), 'P1-P2': (np.float64(0.9), 1)}
LFP a, mov, harmonic: means {'P1': 0.81, 'A': 0.31, 'P2': 0.41}; RM-ANOVA P = 5.78e-01; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(1.32), np.float64(0.7710813574291656)), 'A-P2': (np.float64(-0.17), 1), 'P1-P2': (np.float64(0.82), 1)}
LFP b, all, power   : means {'P1': 0.16, 'A': 1.15, 'P2': 0.12}; RM-ANOVA P = 4.41e-02; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(-3.52), np.float64(0.07311150412136547)), 'A-P2': (np.float64(2.6), np.float64(0.18039859281284926)), 'P1-P2': (np.float64(0.1), 1)}
LFP b, all, harmonic: means {'P1': 0.32, 'A': 0.79, 'P2': 0.67}; RM-ANOVA P = 6.04e-01; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(-0.91), 1), 'A-P2': (np.float64(0.25), 1), 'P1-P2': (np.float64(-0.85), 1)}
LFP b, mov, power   : means {'P1': 0.19, 'A': 1.15, 'P2': 0.11}; RM-ANOVA P = 4.64e-02; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(-3.53), np.float64(0.07293074053572277)), 'A-P2': (np.float64(2.65), np.float64(0.1717591101700885)), 'P1-P2': (np.float64(0.17), 1)}
LFP b, mov, harmonic: means {'P1': 0.44, 'A': 0.78, 'P2': 0.56}; RM-ANOVA P = 7.67e-01; post hoc paired t (t, Bonferroni P) {'P1-A': (np.float64(-0.68), 1), 'A-P2': (np.float64(0.44), 1), 'P1-P2': (np.float64(-0.32), 1)}
per-window reading, LFP a, mov: n windows {'P1': 1219, 'A': 960, 'P2': 1060}; medians {'P1': 2.4, 'A': 3.51, 'P2': 1.71}; two-way ANOVA (condition + rat) condition P = 2.14e-04
   rank-sum P1 vs A: P = 2.24e-10
   rank-sum A vs P2: P = 3.87e-19
cond            P1             A            P2
rat                                           
242   2.336648e+09  3.079920e+09  1.767306e+09
261   1.760904e+09  2.694829e+09  1.449256e+09
272   2.276037e+09  3.654485e+09  2.659609e+09
292   2.419912e+07  4.078514e+07  2.758626e+07
314   2.879125e+07  4.894001e+07  2.502205e+07

Result: reproduced, resting on an assumption. With one value per 2-s window paired by rat (the claims file's reading b of the unit), the two-way ANOVA gives condition P = 2.1 x 10^-4, and Active is above Passive 1 (rank-sum P = 2.2 x 10^-10) and Passive 2 (P = 3.9 x 10^-19); medians 2.40, 3.51 and 1.71. With one value per rat Active is highest under every LFP reading, but the ANOVA gives P = 0.135 to 0.169 for the largest-theta channel and 0.044 to 0.046 for the channel mean, and no paired post hoc test reaches 0.05/3. The per-window test treats windows as independent. Power in 12-20 Hz does not differ (P = 0.58 to 0.77).

In [19]:
ASYM = {}
for ch in ["a", "b"]:
    rows = []
    for name in D.RATS:
        P, LF = PREP[name], LFPS[name]
        for c in D.CONDS:
            tr = LF["travel"][c]
            x = tr[ch]
            st, en, th = D.theta_cycles(x)
            tt = tr["t0"] + st / D.LFP_FS
            keep = D.in_intervals(tt, P["mov"])
            y, pk, trg = D.extrema_1_40(x)
            asy = D.asymmetry(st[keep], en[keep], y, pk, trg)
            for v in asy[np.isfinite(asy)]:
                rows.append((name[6:9], c, v))
    ASYM[ch] = pd.DataFrame(rows, columns=["rat", "cond", "asym"])
for ch in ["a", "b"]:
    df = ASYM[ch]
    g = {c: df[df.cond == c].asym.values for c in D.CONDS}
    h, p = stats.kruskal(*g.values())
    print(f"LFP {ch}: cycles {[len(v) for v in g.values()]}; median asymmetry {[round(np.median(v), 3) for v in g.values()]}; KW H = {h:.1f}, P = {p:.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(ASYM["a"].groupby(["rat", "cond"]).asym.median().unstack().reindex(columns=D.CONDS).round(3).to_string())
LFP a: cycles [12097, 9801, 9896]; median asymmetry [np.float64(-0.065), np.float64(-0.15), np.float64(-0.06)]; KW H = 92.0, P = 1.1e-20
   rank-sum P1 vs A: P (Bonferroni x3) = 7.0e-17
   rank-sum A vs P2: P (Bonferroni x3) = 3.7e-16
   rank-sum P1 vs P2: P (Bonferroni x3) = 1.0e+00
LFP b: cycles [10582, 8879, 8790]; median asymmetry [np.float64(-0.114), np.float64(-0.298), np.float64(-0.128)]; KW H = 408.5, P = 2.0e-89
   rank-sum P1 vs A: P (Bonferroni x3) = 2.1e-78
   rank-sum A vs P2: P (Bonferroni x3) = 2.2e-58
   rank-sum P1 vs P2: P (Bonferroni x3) = 5.3e-01
cond     P1      A     P2
rat                      
242  -0.162 -0.310 -0.132
261  -0.073 -0.251 -0.116
272   0.093  0.151  0.104
292  -0.112 -0.202 -0.113
314  -0.098 -0.153 -0.033

Result: reproduced. Median asymmetry is -0.065, -0.150 and -0.060, closer to zero in both passive conditions; Kruskal-Wallis P = 1.1 x 10^-20; Active differs from Passive 1 and Passive 2 at Bonferroni P = 7.0 x 10^-17 and 3.7 x 10^-16. LFP reading (b) gives P = 2.0 x 10^-89. In rat 272, whose theta channel changed, asymmetry is positive in all conditions (0.093, 0.151, 0.104), the reverse sign of the other rats.

Theta bursts and phase precession¶

fig2cd-spike-bursts-slower: Place cells oscillated faster than theta during active travel, while during passive travel their spike bursts recurred at lower frequencies, closer to theta frequency.

figs4b-proportions-oscillating-precessing: Fewer place cells oscillated faster than theta in passive travel (36/94 Passive 1, 90/150 Active, 63/135 Passive 2), and fewer were significantly phase precessing (14/94, 53/150, 21/135).

fig2f-phase-precession-degraded: The distribution of phase precession slopes over all place cells differed between passive and active travel, indicating an overall degradation of phase precession in passive travel.

figs4de-precession-range-similar: Among significantly phase-precessing cells, phase precession range and slopes did not differ between passive and active travel (Kruskal-Wallis and KS tests, P > 0.05).

Per place cell (field reading a) and condition, spikes during moving periods; theta phase from the theta channel (LFP reading a) under the two phase readings of the claims file. Burst frequency: spectrum of the spike train in units of theta cycles. Precession: in-field spikes, position normalized to the field (0 at entry, 1 at exit in the running direction), linear-circular regression with slopes searched within +/-2 pi rad per field (a standard range: one full cycle of precession over a field and more); at least 10 in-field spikes (a standard minimum).

In [20]:
PH = []
for name in D.RATS:
    P, LF = PREP[name], LFPS[name]
    for c in D.CONDS:
        tr = LF["travel"][c]
        x = tr["a"]
        tt = tr["t0"] + np.arange(len(x)) / D.LFP_FS
        uph = {rd: D.unwrapped_phase(x, rd) for rd in ["a", "b"]}
        for i in D.place_cells(P, c, "a"):
            cell = P["cond"][c]["cells"][i]
            inr = (cell["spk_t"] >= tt[0]) & (cell["spk_t"] <= tt[-1])
            st = cell["spk_t"][inr]
            fld = cell["readings"]["a"]["fields"][0]
            # field entry in the running direction: the first bin of the circular run of
            # field bins (a bin in the field whose predecessor is not); corrected after
            # round 1 of verification, which found the entry set to bin 0
            if fld.all():
                start, size = 0, D.NBINS
            else:
                start, size = int(np.flatnonzero(fld & ~np.roll(fld, 1))[0]), int(fld.sum())
            b = np.minimum(cell["spk_lin"][inr] * D.NBINS, D.NBINS - 1e-9)
            rel = np.mod(b - start, D.NBINS) / size
            inf = rel < 1
            assert np.all(fld[b[inf].astype(int)]), "in-field spikes outside the field"
            d = dict(rat=name[6:9], cond=c, cell=i, n_spikes=len(st), n_infield=int(inf.sum()), frac_infield=inf.mean() if len(st) else np.nan)
            for rd in ["a", "b"]:
                u = np.interp(st, tt, uph[rd]) / (2 * np.pi)
                d[f"burst_{rd}"] = D.spike_train_spectrum_peak(u)
                for w in [16, 32]:
                    d[f"sg{w}_{rd}"] = D.spike_train_spectrogram_peak(u, w)
                    d[f"sg{w}in_{rd}"] = D.spike_train_spectrogram_peak(u[inf], w) if inf.sum() >= 20 else np.nan
                if inf.sum() >= 10:
                    a_, phi0, rho, p = D.circ_lin_regression(rel[inf], np.mod(2 * np.pi * u[inf], 2 * np.pi))
                    d[f"slope_{rd}"], d[f"rho_{rd}"], d[f"p_{rd}"] = a_, rho, p
                else:
                    d[f"slope_{rd}"] = d[f"rho_{rd}"] = d[f"p_{rd}"] = np.nan
            PH.append(d)
PH = pd.DataFrame(PH)
print("place cells per condition:", PH.groupby("cond").size().reindex(D.CONDS).to_dict(),
      "; with >= 10 in-field spikes:", PH[PH.n_infield >= 10].groupby("cond").size().reindex(D.CONDS).to_dict())
print("fraction of a cell's spikes inside its peak field, quartiles:",
      {c: np.round(np.nanpercentile(PH[PH.cond == c].frac_infield, [25, 50, 75]), 3).tolist() for c in D.CONDS})
place cells per condition: {'P1': 207, 'A': 203, 'P2': 228} ; with >= 10 in-field spikes: {'P1': 195, 'A': 198, 'P2': 218}
fraction of a cell's spikes inside its peak field, quartiles: {'P1': [0.151, 0.288, 0.634], 'A': [0.338, 0.529, 0.727], 'P2': [0.167, 0.342, 0.621]}
In [21]:
for rd in ["a", "b"]:
    col = f"burst_{rd}"
    g = {c: PH[(PH.cond == c)][col].dropna().values for c in D.CONDS}
    h, p = stats.kruskal(*g.values())
    print(f"phase reading {rd}: cells with a mode in 0.75-1.25 {[len(v) for v in g.values()]} of {PH.groupby('cond').size().reindex(D.CONDS).tolist()}; "
          f"median mode (cycle^-1) {[round(np.median(v), 4) for v in g.values()]}; KW 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 = {pp:.1e} (Bonferroni x3 {min(1, 3 * pp):.1e})")
print(PH.groupby(["rat", "cond"]).burst_a.median().unstack().reindex(columns=D.CONDS).round(4).to_string())
# the Methods' spectrograms (added after round 1; the claims file says a spectrum): windows of 16 and 32 cycles,
# all spikes of the travel or in-field spikes only
for rd in ["a", "b"]:
    for col in [f"sg16_{rd}", f"sg32_{rd}", f"sg16in_{rd}", f"sg32in_{rd}"]:
        g = {c: PH[(PH.cond == c)][col].dropna().values for c in D.CONDS}
        h, p = stats.kruskal(*g.values())
        ph = {f"{a}-{b}": f"{min(1, 3 * stats.mannwhitneyu(g[a], g[b]).pvalue):.1e}" for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]}
        print(f"spectrogram {col}: n {[len(v) for v in g.values()]}; median mode {[round(np.median(v), 3) for v in g.values()]}; "
              f"KW P = {p:.1e}; rank-sum Bonferroni {ph}; fraction > 1: {[round(np.mean(v > 1), 3) for v in g.values()]}")
phase reading a: cells with a mode in 0.75-1.25 [207, 201, 226] of [207, 203, 228]; median mode (cycle^-1) [np.float64(0.9998), np.float64(1.0003), np.float64(0.9999)]; KW P = 8.2e-02
   rank-sum P1 vs A: P = 3.2e-02 (Bonferroni x3 9.5e-02)
   rank-sum A vs P2: P = 1.0e-01 (Bonferroni x3 3.1e-01)
   rank-sum P1 vs P2: P = 5.5e-01 (Bonferroni x3 1.0e+00)
phase reading b: cells with a mode in 0.75-1.25 [206, 202, 227] of [207, 203, 228]; median mode (cycle^-1) [np.float64(1.0), np.float64(1.0006), np.float64(1.0)]; KW P = 4.5e-02
   rank-sum P1 vs A: P = 3.4e-02 (Bonferroni x3 1.0e-01)
   rank-sum A vs P2: P = 2.7e-02 (Bonferroni x3 8.0e-02)
   rank-sum P1 vs P2: P = 8.9e-01 (Bonferroni x3 1.0e+00)
cond      P1       A      P2
rat                         
242   0.9998  0.9892  1.0000
261   0.9998  1.0091  1.0000
272   0.9998  1.0003  1.0000
292   0.9998  1.0020  1.0001
314   1.0000  1.0046  0.9997
spectrogram sg16_a: n [114, 151, 144]; median mode [np.float64(0.91), np.float64(0.925), np.float64(0.888)]; KW P = 5.3e-01; rank-sum Bonferroni {'P1-A': '1.0e+00', 'A-P2': '1.0e+00', 'P1-P2': '1.0e+00'}; fraction > 1: [np.float64(0.36), np.float64(0.344), np.float64(0.333)]
spectrogram sg32_a: n [160, 191, 185]; median mode [np.float64(0.965), np.float64(0.98), np.float64(0.95)]; KW P = 4.8e-01; rank-sum Bonferroni {'P1-A': '1.0e+00', 'A-P2': '7.7e-01', 'P1-P2': '1.0e+00'}; fraction > 1: [np.float64(0.394), np.float64(0.455), np.float64(0.395)]
spectrogram sg16in_a: n [110, 142, 122]; median mode [np.float64(0.918), np.float64(0.925), np.float64(0.908)]; KW P = 5.8e-01; rank-sum Bonferroni {'P1-A': '1.0e+00', 'A-P2': '9.6e-01', 'P1-P2': '1.0e+00'}; fraction > 1: [np.float64(0.318), np.float64(0.366), np.float64(0.377)]
spectrogram sg32in_a: n [125, 172, 160]; median mode [np.float64(0.97), np.float64(0.978), np.float64(0.943)]; KW P = 6.4e-01; rank-sum Bonferroni {'P1-A': '1.0e+00', 'A-P2': '1.0e+00', 'P1-P2': '1.0e+00'}; fraction > 1: [np.float64(0.408), np.float64(0.459), np.float64(0.412)]
spectrogram sg16_b: n [181, 199, 205]; median mode [np.float64(0.95), np.float64(1.02), np.float64(0.95)]; KW P = 2.2e-06; rank-sum Bonferroni {'P1-A': '8.7e-06', 'A-P2': '1.4e-04', 'P1-P2': '1.0e+00'}; fraction > 1: [np.float64(0.326), np.float64(0.563), np.float64(0.38)]
spectrogram sg32_b: n [196, 199, 211]; median mode [np.float64(1.005), np.float64(1.01), np.float64(0.99)]; KW P = 3.7e-02; rank-sum Bonferroni {'P1-A': '5.1e-01', 'A-P2': '2.5e-02', 'P1-P2': '9.6e-01'}; fraction > 1: [np.float64(0.551), np.float64(0.608), np.float64(0.464)]
spectrogram sg16in_b: n [136, 180, 160]; median mode [np.float64(0.943), np.float64(1.015), np.float64(0.97)]; KW P = 1.7e-05; rank-sum Bonferroni {'P1-A': '1.6e-05', 'A-P2': '5.3e-03', 'P1-P2': '5.2e-01'}; fraction > 1: [np.float64(0.353), np.float64(0.6), np.float64(0.412)]
spectrogram sg32in_b: n [146, 181, 173]; median mode [np.float64(1.0), np.float64(1.02), np.float64(0.995)]; KW P = 1.1e-01; rank-sum Bonferroni {'P1-A': '1.7e-01', 'A-P2': '2.7e-01', 'P1-P2': '1.0e+00'}; fraction > 1: [np.float64(0.534), np.float64(0.608), np.float64(0.486)]

Result: not reproduced. With the claims file's spectrum over the whole travel, the modes sit at 1.000 cycle^-1 (medians 0.9998, 1.0003 and 0.9999 under phase reading a, Kruskal-Wallis P = 0.082; reading b P = 0.045 with no post hoc test below 0.05 after Bonferroni). With the Methods' spectrograms (a variant; the reading is asked as a question), phase reading (b) and 16-cycle windows give medians 0.95, 1.02 and 0.95, Kruskal-Wallis P = 2.2 x 10^-6, Active above Passive 1 (Bonferroni P = 8.7 x 10^-6) and Passive 2 (P = 1.4 x 10^-4); phase reading (a) finds no difference with any window (P = 0.48 to 0.64).

In [22]:
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))

for rd in ["a", "b", "sg16_a", "sg32_a", "sg16in_a", "sg32in_a"]:
    n = PH.groupby("cond").size().reindex(D.CONDS)
    if rd.startswith("sg"):   # spectrogram readings of the oscillation (phase reading a)
        osc = PH.assign(o=PH[rd] > 1).groupby("cond").o.sum().reindex(D.CONDS)
        print(f"spectrogram {rd}: oscillating faster than theta:", {c: f"{osc[c]}/{n[c]} = {osc[c] / n[c]:.3f}" for c in D.CONDS})
        for a in ["P1", "P2"]:
            z, p = prop_test(osc["A"], n["A"], osc[a], n[a])
            print(f"   binomial proportion test osc, A vs {a}: z = {z:.2f}, P = {p:.2e}")
        continue
    osc = PH.assign(o=PH[f"burst_{rd}"] > 1).groupby("cond").o.sum().reindex(D.CONDS)
    prec = PH.assign(o=(PH[f"p_{rd}"] < 0.05) & (PH[f"slope_{rd}"] < 0)).groupby("cond").o.sum().reindex(D.CONDS)
    prec_any = PH.assign(o=(PH[f"p_{rd}"] < 0.05)).groupby("cond").o.sum().reindex(D.CONDS)
    print(f"phase reading {rd}:")
    print("  oscillating faster than theta:", {c: f"{osc[c]}/{n[c]} = {osc[c] / n[c]:.3f}" for c in D.CONDS}, " expected 0.383, 0.600, 0.467")
    print("  significant negative precession:", {c: f"{prec[c]}/{n[c]} = {prec[c] / n[c]:.3f}" for c in D.CONDS}, " expected 0.149, 0.353, 0.156")
    print("  significant regression, either sign:", {c: f"{prec_any[c]}/{n[c]} = {prec_any[c] / n[c]:.3f}" for c in D.CONDS})
    for lab, k in [("osc", osc), ("prec", prec)]:
        for a in ["P1", "P2"]:
            z, p = prop_test(k["A"], n["A"], k[a], n[a])
            print(f"   binomial proportion test {lab}, A vs {a}: z = {z:.2f}, P = {p:.2e}")
phase reading a:
  oscillating faster than theta: {'P1': '91/207 = 0.440', 'A': '121/203 = 0.596', 'P2': '110/228 = 0.482'}  expected 0.383, 0.600, 0.467
  significant negative precession: {'P1': '12/207 = 0.058', 'A': '50/203 = 0.246', 'P2': '20/228 = 0.088'}  expected 0.149, 0.353, 0.156
  significant regression, either sign: {'P1': '18/207 = 0.087', 'A': '67/203 = 0.330', 'P2': '31/228 = 0.136'}
   binomial proportion test osc, A vs P1: z = 3.17, P = 1.53e-03
   binomial proportion test osc, A vs P2: z = 2.36, P = 1.82e-02
   binomial proportion test prec, A vs P1: z = 5.32, P = 1.03e-07
   binomial proportion test prec, A vs P2: z = 4.46, P = 8.36e-06
phase reading b:
  oscillating faster than theta: {'P1': '106/207 = 0.512', 'A': '124/203 = 0.611', 'P2': '114/228 = 0.500'}  expected 0.383, 0.600, 0.467
  significant negative precession: {'P1': '13/207 = 0.063', 'A': '54/203 = 0.266', 'P2': '26/228 = 0.114'}  expected 0.149, 0.353, 0.156
  significant regression, either sign: {'P1': '34/207 = 0.164', 'A': '81/203 = 0.399', 'P2': '45/228 = 0.197'}
   binomial proportion test osc, A vs P1: z = 2.01, P = 4.39e-02
   binomial proportion test osc, A vs P2: z = 2.31, P = 2.09e-02
   binomial proportion test prec, A vs P1: z = 5.56, P = 2.64e-08
   binomial proportion test prec, A vs P2: z = 4.05, P = 5.11e-05
spectrogram sg16_a: oscillating faster than theta: {'P1': '41/207 = 0.198', 'A': '52/203 = 0.256', 'P2': '48/228 = 0.211'}
   binomial proportion test osc, A vs P1: z = 1.40, P = 1.60e-01
   binomial proportion test osc, A vs P2: z = 1.12, P = 2.63e-01
spectrogram sg32_a: oscillating faster than theta: {'P1': '63/207 = 0.304', 'A': '87/203 = 0.429', 'P2': '73/228 = 0.320'}
   binomial proportion test osc, A vs P1: z = 2.61, P = 9.03e-03
   binomial proportion test osc, A vs P2: z = 2.32, P = 2.01e-02
spectrogram sg16in_a: oscillating faster than theta: {'P1': '35/207 = 0.169', 'A': '52/203 = 0.256', 'P2': '46/228 = 0.202'}
   binomial proportion test osc, A vs P1: z = 2.16, P = 3.11e-02
   binomial proportion test osc, A vs P2: z = 1.35, P = 1.79e-01
spectrogram sg32in_a: oscillating faster than theta: {'P1': '51/207 = 0.246', 'A': '79/203 = 0.389', 'P2': '66/228 = 0.289'}
   binomial proportion test osc, A vs P1: z = 3.11, P = 1.89e-03
   binomial proportion test osc, A vs P2: z = 2.19, P = 2.88e-02
In [23]:
# Variant added after round 2 of verification: the same measures with the denominators restricted to the
# place cells of the adopted field reading (c) (figs2b-place-cell-count); in-field spikes are still those of
# the field holding the peak under reading (a).
full = {n[6:9]: n for n in D.RATS}
inc = pd.Series([i in set(D.place_cells(PREP[full[r]], c, "c")) for r, c, i in zip(PH.rat, PH.cond, PH.cell)], index=PH.index)
PHc = PH[inc]
n = PHc.groupby("cond").size().reindex(D.CONDS)
for rd in ["a", "b"]:
    osc = PHc.assign(o=PHc[f"burst_{rd}"] > 1).groupby("cond").o.sum().reindex(D.CONDS)
    prec = PHc.assign(o=(PHc[f"p_{rd}"] < 0.05) & (PHc[f"slope_{rd}"] < 0)).groupby("cond").o.sum().reindex(D.CONDS)
    print(f"field reading (c) place cells, phase reading {rd}:")
    print("  oscillating faster than theta:", {c: f"{osc[c]}/{n[c]} = {osc[c] / n[c]:.3f}" for c in D.CONDS}, " expected 0.383, 0.600, 0.467")
    print("  significant negative precession:", {c: f"{prec[c]}/{n[c]} = {prec[c] / n[c]:.3f}" for c in D.CONDS}, " expected 0.149, 0.353, 0.156")
    for lab, k in [("osc", osc), ("prec", prec)]:
        for a in ["P1", "P2"]:
            z, p = prop_test(k["A"], n["A"], k[a], n[a])
            print(f"   binomial proportion test {lab}, A vs {a}: z = {z:.2f}, P = {p:.2e}")
field reading (c) place cells, phase reading a:
  oscillating faster than theta: {'P1': '56/138 = 0.406', 'A': '95/158 = 0.601', 'P2': '74/171 = 0.433'}  expected 0.383, 0.600, 0.467
  significant negative precession: {'P1': '10/138 = 0.072', 'A': '48/158 = 0.304', 'P2': '18/171 = 0.105'}  expected 0.149, 0.353, 0.156
   binomial proportion test osc, A vs P1: z = 3.36, P = 7.91e-04
   binomial proportion test osc, A vs P2: z = 3.06, P = 2.25e-03
   binomial proportion test prec, A vs P1: z = 5.00, P = 5.67e-07
   binomial proportion test prec, A vs P2: z = 4.49, P = 7.03e-06
field reading (c) place cells, phase reading b:
  oscillating faster than theta: {'P1': '69/138 = 0.500', 'A': '103/158 = 0.652', 'P2': '87/171 = 0.509'}  expected 0.383, 0.600, 0.467
  significant negative precession: {'P1': '9/138 = 0.065', 'A': '49/158 = 0.310', 'P2': '23/171 = 0.135'}  expected 0.149, 0.353, 0.156
   binomial proportion test osc, A vs P1: z = 2.64, P = 8.23e-03
   binomial proportion test osc, A vs P2: z = 2.63, P = 8.64e-03
   binomial proportion test prec, A vs P1: z = 5.30, P = 1.19e-07
   binomial proportion test prec, A vs P2: z = 3.85, P = 1.18e-04

Result: partially reproduced. Under phase reading (a), 91/207 = 0.440, 121/203 = 0.596 and 110/228 = 0.482 of place cells oscillate faster than theta (Passive 1 outside tolerance), with Active above Passive 1 (P = 0.0015) and Passive 2 (P = 0.018); 12/207 = 0.058, 50/203 = 0.246 and 20/228 = 0.088 precess significantly (all outside tolerance), Active above both (P = 1.0 x 10^-7 and 8.4 x 10^-6). Reading (b) gives the same pattern (oscillation P = 0.044 and 0.021; precession P = 2.6 x 10^-8 and 5.1 x 10^-5). The tests hold under both readings; four of the six proportions are outside tolerance under each. With spectrogram windows of 32 cycles the oscillation tests also hold (P = 0.009 and 0.020); with 16 cycles they do not. With the place cells of field reading (c) as denominators (138, 158 and 171), the oscillating proportions are 0.406, 0.601 and 0.433, all within tolerance, the precessing ones 0.072, 0.304 and 0.105, all outside, and Active exceeds both passive conditions in both measures (P = 5.7 x 10^-7 to 0.0023): also partial.

In [24]:
for rd in ["a", "b"]:
    col = f"slope_{rd}"
    g = {c: PH[PH.cond == c][col].dropna().values for c in D.CONDS}
    print(f"phase reading {rd}: n {[len(v) for v in g.values()]}; median slope (rad per field) {[round(np.median(v), 3) for v in g.values()]}")
    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:.2e}")
phase reading a: n [195, 198, 218]; median slope (rad per field) [np.float64(-0.145), np.float64(-0.983), np.float64(-0.053)]
   KS P1 vs A: D = 0.136, P = 4.62e-02
   KS A vs P2: D = 0.142, P = 2.72e-02
   KS P1 vs P2: D = 0.093, P = 3.09e-01
phase reading b: n [195, 198, 218]; median slope (rad per field) [np.float64(0.157), np.float64(-0.434), np.float64(-0.44)]
   KS P1 vs A: D = 0.214, P = 1.90e-04
   KS A vs P2: D = 0.103, P = 2.05e-01
   KS P1 vs P2: D = 0.170, P = 4.28e-03

Result: partially reproduced. Phase reading (a): median slopes -0.145, -0.983 and -0.053 rad per field, Active most negative; KS Active against Passive 1 P = 0.046 and against Passive 2 P = 0.027, both below 0.05; the second is below 0.04 and the first is not, and neither is below 0.008. Reading (b): medians 0.157, -0.434 and -0.440 (Passive 2 slightly more negative than Active); KS Active against Passive 1 P = 1.9 x 10^-4, against Passive 2 P = 0.21. One or both comparisons are significant at 0.05 under each reading, so the claim holds in part under both.

In [25]:
for rd in ["a", "b"]:
    sig = PH[(PH[f"p_{rd}"] < 0.05) & (PH[f"slope_{rd}"] < 0)]
    g = {c: sig[sig.cond == c][f"slope_{rd}"].values for c in D.CONDS}
    rng_ = {c: np.degrees(np.abs(v)) for c, v in g.items()}
    print(f"phase reading {rd}: significant cells {[len(v) for v in g.values()]}")
    if min(len(v) for v in g.values()) >= 3:
        print(f"   range (deg per field) medians {[round(np.median(v), 1) for v in rng_.values()]}; KW P = {stats.kruskal(*rng_.values()).pvalue:.3f}")
        print(f"   slopes medians {[round(np.median(v), 3) for v in g.values()]}; KW P = {stats.kruskal(*g.values()).pvalue:.3f}")
        for a, b in [("P1", "A"), ("A", "P2"), ("P1", "P2")]:
            ks = stats.ks_2samp(g[a], g[b])
            print(f"   KS slopes {a} vs {b}: D = {ks.statistic:.3f}, P = {ks.pvalue:.3f}")
phase reading a: significant cells [12, 50, 20]
   range (deg per field) medians [np.float64(172.8), np.float64(202.9), np.float64(181.1)]; KW P = 0.975
   slopes medians [np.float64(-3.016), np.float64(-3.541), np.float64(-3.16)]; KW P = 0.975
   KS slopes P1 vs A: D = 0.213, P = 0.695
   KS slopes A vs P2: D = 0.190, P = 0.629
   KS slopes P1 vs P2: D = 0.250, P = 0.668
phase reading b: significant cells [13, 54, 26]
   range (deg per field) medians [np.float64(148.3), np.float64(187.7), np.float64(142.0)]; KW P = 0.529
   slopes medians [np.float64(-2.589), np.float64(-3.277), np.float64(-2.479)]; KW P = 0.529
   KS slopes P1 vs A: D = 0.269, P = 0.365
   KS slopes A vs P2: D = 0.272, P = 0.120
   KS slopes P1 vs P2: D = 0.154, P = 0.985

Result: reproduced. Among significantly precessing cells (12, 50 and 20 under phase reading a; 13, 54 and 26 under b), no test finds a difference: range and slope Kruskal-Wallis P = 0.975 (a) and 0.529 (b); KS of slopes P = 0.63 to 0.70 (a) and 0.12 to 0.99 (b). Median ranges are 173, 203 and 181 deg per field (a). With 12 and 20 cells in the passive conditions the tests have little power.

figs11-sleep-sessions-similar¶

SWS duration, number and rate of candidate events and ripple rate did not differ between sleep sessions (repeated-measures ANOVA, P > 0.05), and candidate events coincided with ripples alike in all sessions (KS, P > 0.05).

SWS from the theta channel; ripples from the pyramidal-layer channels; candidate events from the place cells (field reading a) of the travel session that precedes each post-travel sleep. Readings of the event threshold: mean and s.d. over (sws) SWS bins, as BatchCandidateEvents.m does, or (all) the whole sleep session. Ripple threshold 3 s.d. for every rat (Methods); BatchFindRipples.m uses 4 for rat 272.

In [26]:
SLEEP_OF = {"S1": "P1", "SA": "A", "S2": "P2"}
EVENTS = {}
rows = []
for name in D.RATS:
    P, LF = PREP[name], LFPS[name]
    for s in D.SLEEPS:
        sl = LF["sleep"][s]
        sws_min = np.sum(np.diff(sl["sws"], axis=1)) / 60 if len(sl["sws"]) else 0.0
        d = dict(rat=name[6:9], sleep=s, sws_min=sws_min, session_min=np.diff(sl["interval"])[0] / 60)
        rip = sl["ripples"]
        rip_sws = rip[D.in_intervals(rip[:, 1], sl["sws"])] if len(sl["sws"]) else rip[:0]
        d["ripples_per_min_sws"] = len(rip_sws) / sws_min if sws_min > 0 else np.nan
        if s in SLEEP_OF:
            c = SLEEP_OF[s]
            spk = np.sort(np.concatenate([PREP_UNITS[name][i] for i in D.place_cells(P, c, "a")]))
            for norm in ["sws", "all"]:
                ev = D.candidate_events(spk, sl["interval"], sl["sws"], norm=norm)
                EVENTS[(name, s, norm)] = ev
                d[f"events_{norm}"] = len(ev)
                d[f"events_per_min_{norm}"] = len(ev) / sws_min if sws_min > 0 else np.nan
                if len(ev) and len(rip_sws):
                    j = np.searchsorted(rip_sws[:, 1], ev[:, 1])
                    lo = rip_sws[np.clip(j - 1, 0, len(rip_sws) - 1), 1]
                    hi = rip_sws[np.clip(j, 0, len(rip_sws) - 1), 1]
                    dt = np.where(np.abs(ev[:, 1] - lo) < np.abs(ev[:, 1] - hi), ev[:, 1] - lo, ev[:, 1] - hi)
                    EVENTS[(name, s, norm, "dt")] = dt
                    d[f"frac_within_0.1s_{norm}"] = np.mean(np.abs(dt) < 0.1)
        rows.append(d)
SL = pd.DataFrame(rows)
print(SL.round(3).to_string(index=False))
print()
res = AnovaRM(SL, "sws_min", "rat", within=["sleep"]).fit().anova_table
print(f"SWS duration, 4 sessions: means {SL.groupby('sleep').sws_min.mean().reindex(D.SLEEPS).round(1).to_dict()}; RM-ANOVA P = {res['Pr > F'].iloc[0]:.3f}")
post = SL[SL.sleep != "SB"]
for col in ["events_sws", "events_per_min_sws", "events_all", "events_per_min_all", "ripples_per_min_sws"]:
    if post[col].isna().any():
        print(f"{col}: undefined for some rat (no SWS)"); continue
    res = AnovaRM(post, col, "rat", within=["sleep"]).fit().anova_table
    print(f"{col:22s}: means {post.groupby('sleep')[col].mean().reindex(['S1', 'SA', 'S2']).round(2).to_dict()}; RM-ANOVA P = {res['Pr > F'].iloc[0]:.3f}")
for norm in ["sws", "all"]:
    dts = {s: np.concatenate([EVENTS.get((n, s, norm, "dt"), np.zeros(0)) for n in D.RATS]) for s in SLEEP_OF}
    w = {s: v[np.abs(v) <= 0.5] for s, v in dts.items()}
    print(f"event peak minus nearest ripple peak (within +/-0.5 s), threshold over {norm}: n {[len(v) for v in w.values()]}, median (ms) {[round(1000 * np.median(v), 1) for v in w.values()]}")
    for a, b in [("S1", "SA"), ("SA", "S2"), ("S1", "S2")]:
        ks = stats.ks_2samp(w[a], w[b])
        print(f"   KS {a} vs {b}: D = {ks.statistic:.3f}, P = {ks.pvalue:.3f}")
rat sleep  sws_min  session_min  ripples_per_min_sws  events_sws  events_per_min_sws  frac_within_0.1s_sws  events_all  events_per_min_all  frac_within_0.1s_all
242    SB   48.833       80.134               45.215         NaN                 NaN                   NaN         NaN                 NaN                   NaN
242    S1   43.667       65.004               55.901      1938.0              44.382                 0.473      1959.0              44.863                 0.473
242    SA   44.750       60.618               55.464      1911.0              42.704                 0.491      1996.0              44.603                 0.489
242    S2   13.000       63.040               55.846       539.0              41.462                 0.417       427.0              32.846                 0.429
261    SB   34.083       84.189               60.851         NaN                 NaN                   NaN         NaN                 NaN                   NaN
261    S1   50.833       96.995               43.987      3690.0              72.590                 0.386      2590.0              50.951                 0.451
261    SA   38.333       61.811               56.243      2521.0              65.765                 0.460      2903.0              75.730                 0.431
261    S2   35.917       64.539               58.385      2176.0              60.585                 0.476      2184.0              60.807                 0.475
272    SB   13.417       67.708               69.168         NaN                 NaN                   NaN         NaN                 NaN                   NaN
272    S1   32.917       63.785               51.099      1259.0              38.248                 0.462      1249.0              37.944                 0.464
272    SA   17.667       61.230               45.396       740.0              41.887                 0.415       700.0              39.623                 0.426
272    S2   32.500       77.391               51.938      1362.0              41.908                 0.455      1470.0              45.231                 0.450
292    SB   53.333       84.507               46.762         NaN                 NaN                   NaN         NaN                 NaN                   NaN
292    S1   50.000       87.638               50.800      2944.0              58.880                 0.285      2266.0              45.320                 0.310
292    SA   32.500       83.867               56.246      1886.0              58.031                 0.294      1704.0              52.431                 0.300
292    S2   41.167       87.952               51.765      2395.0              58.178                 0.299      2472.0              60.049                 0.302
314    SB   33.583       88.285               57.588         NaN                 NaN                   NaN         NaN                 NaN                   NaN
314    S1   25.167       89.952               63.656       834.0              33.139                 0.270       875.0              34.768                 0.265
314    SA   58.583       86.922               61.041      2188.0              37.349                 0.302      2354.0              40.182                 0.305
314    S2   44.917       87.130               58.709      1550.0              34.508                 0.257      1941.0              43.213                 0.261

SWS duration, 4 sessions: means {'SB': 36.6, 'S1': 40.5, 'SA': 38.4, 'S2': 33.5}; RM-ANOVA P = 0.855
events_sws            : means {'S1': 2133.0, 'SA': 1849.2, 'S2': 1604.4}; RM-ANOVA P = 0.486
events_per_min_sws    : means {'S1': 49.45, 'SA': 49.15, 'S2': 47.33}; RM-ANOVA P = 0.552
events_all            : means {'S1': 1787.8, 'SA': 1931.4, 'S2': 1698.8}; RM-ANOVA P = 0.858
events_per_min_all    : means {'S1': 42.77, 'SA': 50.51, 'S2': 48.43}; RM-ANOVA P = 0.273
ripples_per_min_sws   : means {'S1': 53.09, 'SA': 54.88, 'S2': 55.33}; RM-ANOVA P = 0.716
event peak minus nearest ripple peak (within +/-0.5 s), threshold over sws: n [7229, 6330, 5461], median (ms) [np.float64(-9.2), np.float64(-9.8), np.float64(-8.1)]
   KS S1 vs SA: D = 0.027, P = 0.015
   KS SA vs S2: D = 0.024, P = 0.075
   KS S1 vs S2: D = 0.020, P = 0.180
event peak minus nearest ripple peak (within +/-0.5 s), threshold over all: n [6227, 6621, 5751], median (ms) [np.float64(-9.1), np.float64(-9.5), np.float64(-8.1)]
   KS S1 vs SA: D = 0.027, P = 0.018
   KS SA vs S2: D = 0.020, P = 0.156
   KS S1 vs S2: D = 0.032, P = 0.004

Result: not reproduced. SWS duration (P = 0.86), candidate event counts (P = 0.49) and rates (P = 0.55), and ripple rates (P = 0.72) do not differ across sleep sessions, but the KS test of event peak minus nearest ripple peak does: after Passive 1 against after Active P = 0.015 (threshold over SWS), and after Passive 1 against after Passive 2 P = 0.004 (threshold over the whole session), with D = 0.027 and 0.032 on about 6000 events each.

Summary¶

claim outcome
figs1-travel-similar not reproduced (duration differs)
figs2b-place-cell-count partially reproduced (assumed field reading c)
fig1c-field-size-similar not reproduced (assumed field reading c; most readings differ)
fig1c-peak-rate-lower-passive1 reproduced
figs2c-track-coverage reproduced
fig1d-no-remapping-p1-active reproduced (assumed field reading c, cells in both conditions)
fig1e-no-remapping-active-p2 partially reproduced (assumed reading)
figs2d-stability-p1-p2 partially reproduced (assumed reading)
fig2b-theta-frequency-unchanged reproduced
fig2b-theta-power-reduced reproduced (assumed per-window reading)
fig2b-theta-asymmetry-reduced reproduced
fig2cd-spike-bursts-slower not reproduced
figs4b-proportions-oscillating-precessing partially reproduced
fig2f-phase-precession-degraded partially reproduced
figs4de-precession-range-similar reproduced
figs11-sleep-sessions-similar not reproduced (event-ripple timing differs)

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

Differences from the paper's method. The LFP channels, the linearization and the place-cell lists are not in the data set and were rebuilt (see the record). Under the Methods' field definition nearly every isolated pyramidal cell has a field, with large and multiple fields; the size and spike limits of the paper's BatchPlaceFields.m (reading c) reduce the counts to 138, 158 and 171, still above the paper's 94, 150 and 135. Several results depend on choices the Methods leave open and the code settles differently: the field kernel and size limits, and the unit classification. The theta channel leaves out channels whose theta is reversed relative to the pyramidal cells' spikes (four in rat 272).

About the dataset. Spikes, positions and LFP end within a second of each other in every rat. Positions are lost for 40.6% and 22.8% of samples in rats 292 and 314, 98.7% and 99.7% of them in sleep; under 1% in the other rats. The sleep LFP reaches the 16-bit limit in 2.4% of samples on rat 261's theta channel, 0.39% in rat 272 and at most 0.04% in the others. The traced track perimeter is 656 to 706 cm against the paper's 6 m. Rats 292 and 314 were recorded at 20 kHz, and in them pyramidal cells fire near the theta peak (-5 to -51 deg) on every channel, while in the other rats they fire 67 to 211 deg before the peak, nearer the trough. The scripts in code.zip load channel lists, theta cycles and place-cell lists that are not included.

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