Reproducing Yu et al. (2017) from CRCNS hc-13¶
Paper. Yu JY, Kay K, Liu DF, Grossrubatscher I, Loback A, Sosa M, Chung JE, Karlsson MP, Larkin MC, Frank LM (2017). Distinct hippocampal-cortical memory representations for experiences associated with movement versus immobility. eLife 6:e27621, doi:10.7554/eLife.27621. The claims file was written from the version of record (PMC5576488): main text, figure legends, the legends of all figure supplements, and the Materials and methods.
Data set. CRCNS hc-13, Yu, Liu, Grossrubatscher and Frank (2017), "Simultaneous extracellular
recordings from hippocampal area CA1 and dorsal medial prefrontal cortex from rats performing a
foraging task", doi:10.6080/K0H41PK8. Version: unversioned.
CRCNS data sets have no versions, and the paper cites the data set without one, so the version
used is the one published under hc-13/live/ in the public bucket crcnsarchive, the only copy of
the data (hc-13/orig/v0_7/ holds only the documentation of version 0.7 of the descriptor). The
data are one file, hc-13/live/data.tar.gz (8,719,155,400 bytes), whose MD5 in the data set's
checksums.md5 is f45a799b63c543d82d61933c0c87efbb; the notebook computes the MD5 of the bytes
it streams and prints whether they match, so a later change is detectable. The archive is a gzipped
tar, which can only be read from its start: it is streamed once, and each animal is reduced as its
files arrive (helper yu2017.py). Nothing is written to disk.
What the data set holds. The five foraging rats (T1, S2, Q1, R1, N2), task sessions only: CA1 and PFC spike times, LFP from one channel per tetrode, position, tetrode areas and an epoch type. It does not hold the six W-track rats the paper pools with them (from earlier papers and CRCNS hc-6), the rest sessions, or reward-well entry (beam-break) times.
How the claims are tested. Claims the claims file marks with_inputs pool the foraging and
W-track rats. The W-track data were not used here (hc-6 holds nine rats, and the paper does not say which rats and days were used, some of them coming from Kay et al. 2016);
each such claim is tested on the foraging rats, as the criteria allow ("the foraging task alone is
the test on the data set"), so its outcome is the outcome of that foraging-only test, and the pooled
count is blocked. The open details of the claims file (O1 to O7) are run under each reading the data
allow; O1 reading (a) needs beam-break times, which the data set lacks, so wells come from reading
(b) throughout. For the analyses around well entry and exit (Figure 2 and its supplements, Figure 4,
supplement 3), entries and exits are the starts and ends of every immobility period, O1 (b) as the
claims file writes it, and the outcomes rest on that. Well visits, immobility periods of at least
0.5 s within 15 cm of a well (visit_mask, not a reading in the claims file), are shown as a
variant; whether the claims file's O1 (b) misreads the paper's entries is asked in
questions/crcns-hc-13.yaml.
| Claim | Tested | Data |
|---|---|---|
| fig1-iap-map-counts | blocked (pooled counts need the W-track rats, not identifiable in a public archive) | with_inputs |
| fig1s4b-foraging-counts | tested | dataset |
| fig1d-well-specificity | tested, foraging rats | with_inputs |
| fig1e-iap-lower-speed | tested, foraging rats | with_inputs |
| fig1s4d-foraging-speed | tested | dataset |
| fig1f-iap-smaller-coverage | tested, foraging rats | with_inputs |
| fig1s1d-transition-interval | tested | dataset |
| fig2c-continuous-transition | tested, foraging rats | with_inputs |
| fig2s1cd-theta-autocorrelation | tested, foraging rats | with_inputs |
| fig2s1ij-theta-behavior-correlation | tested, foraging rats | with_inputs |
| fig2s2-fewer-coincident-spikes | tested, foraging rats | with_inputs |
| fig3c-iap-swr-activation | tested, foraging rats | with_inputs |
| fig3s3-iap-same-well-coactivity | blocked after selection (2 IAP pairs) | with_inputs |
| fig4a-swr-counts | tested, foraging rats | with_inputs |
| fig4b-coactivity | tested, foraging rats | with_inputs |
| fig4s1b-offset-matched-coactivity | tested, foraging rats | with_inputs |
| fig4s2c-spatial-proximity-control | tested, foraging rats | with_inputs |
| fig4s3-overlapping-pairs | tested, foraging rats | with_inputs |
| fig4c-iap-swr-shorter | tested, foraging rats | with_inputs |
| fig4d-iap-swr-lower-power | tested, foraging rats | with_inputs |
| fig4s5-cells-spikes-per-swr | tested, foraging rats | with_inputs |
| fig4s67-matched-subsamples | tested, foraging rats | with_inputs |
| fig4s8-interspersed | tested, foraging rats | with_inputs |
| fig4e-iap-spike-earlier | tested, foraging rats | with_inputs |
| pfc-unit-selection | tested | dataset |
| fig5-pfc-modulated-fraction | tested | dataset |
| fig5dg-pfc-groups | tested | dataset |
| fig5s1d-shuffle-control | tested | dataset |
| pfc-regression-joint-swr | tested | dataset |
| fig6c-similarity-index | blocked (no beam-break well entry times) | dataset |
| fig6e-coincidence-index | tested | dataset |
| fig6s2-no-proximity-difference | tested | dataset |
Two claims have no section of their own: fig1-iap-map-counts (the foraging part of its count is under fig1s4b-foraging-counts) and fig6c-similarity-index (the claims file fixes well entry as the infrared beam break, Methods, PFC and CA1 spiking activity, and the data set has no beam-break times).
import time
import resource
import warnings
import numpy as np
import pandas as pd
from scipy import stats
from scipy.ndimage import gaussian_filter1d as gaussian
import matplotlib.pyplot as plt
import yu2017 as Y
warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
started = time.time()
R, STREAM = Y.stream_dataset(Y.process_animal)
print(f"streamed {STREAM['bytes'] / 1e9:.2f} GB of {Y.DATASET} ({Y.VERSION}) in {time.time() - started:.0f} s; "
f"MD5 {STREAM['md5']} {'matches' if STREAM['md5'] == Y.MD5 else 'DIFFERS FROM'} checksums.md5")
print("peak memory", round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6, 1), "GB")
processing S2
processing T1
processing R1
processing Q1
processing N2
streamed 8.72 GB of hc-13 (unversioned) in 846 s; MD5 f45a799b63c543d82d61933c0c87efbb matches checksums.md5 peak memory 6.2 GB
ANIMALS = [a for a in ["T1", "S2", "Q1", "R1", "N2"] if a in R]
TB = {a: Y.day_tables(R[a]) for a in ANIMALS}
def ca1_cells(o2="a", reading="amplitude", speed_key="speed", width_max=None):
out = []
for a in ANIMALS:
tb = TB[a] if speed_key == "speed" else Y.day_tables(R[a], speed_key)
out += Y.classify_ca1(R[a], tb, swr_reading=reading, o2=o2, width_max=(width_max or {}).get(a, 0.4))
return out
CELLS = {o2: ca1_cells(o2) for o2 in "ab"}
VISIT_RADIUS, VISIT_MIN_S = 15.0, 0.5
def visit_mask(per):
"""Immobility periods taken as well visits, a variant of the entry and exit analyses (not a reading in the claims file).
O1 (b) of the claims file makes every immobility period an entry and exit. Many periods are brief
dips of speed below 4 cm/s away from the wells, and their +-1.5 s windows cover about half of task
time. The paper's entries are visits to a well ("Subjects are immobile during periods at the well",
Figure 1, supplement 1B), so a visit is taken as an immobility period whose mean position is within
15 cm of its well and which lasts at least 0.5 s. Radius and duration are choices; the paper gives
neither. All immobility periods, the claims file's reading as written, decide the outcomes; whether that
reading misreads the paper is asked in questions/crcns-hc-13.yaml.
"""
return (per["dist"] < VISIT_RADIUS) & ((per["end"] - per["start"]) >= VISIT_MIN_S)
C = CELLS["a"] # main reading of O2 (SWR time kept in the denominator); (b) shown where it differs
print("CA1 pyramidal cell-days:", len(C))
CA1 pyramidal cell-days: 194
Data check¶
print("Archive members (name, bytes):")
for name, size in STREAM["members"]:
print(f" {name:28s} {size:>12d}")
rows = []
for a in ANIMALS:
for day, dd in R[a]["days"].items():
for ep, p in dd["epochs"].items():
rows.append(dict(animal=a, day=day, epoch=ep, type=dd["tasktype"].get(ep), minutes=(p["t"][-1] - p["t"][0]) / 60,
frame_hz=p["fs"], tracked=p["tracked"].mean(), cm_per_pixel=p["cm_per_pixel"],
x_cm=f"{p['x'].min():.0f}-{p['x'].max():.0f}", y_cm=f"{p['y'].min():.0f}-{p['y'].max():.0f}",
speed_p99=np.percentile(p["speed"], 99), immobile=(p["speed"] < 4).mean()))
S = pd.DataFrame(rows)
print("\nDays and task sessions per animal (paper: 4, 9, 9, 11 and 12 days, 2 to 3 sessions of 15 to 45 min a day):")
print(S.groupby("animal").agg(days=("day", "nunique"), sessions=("epoch", "size"), min_minutes=("minutes", "min"),
max_minutes=("minutes", "max")).round(1).to_string())
print("\nEpoch types:", S.type.value_counts().to_dict(), "; epoch numbers:", sorted(S.epoch.unique()))
print("Frame rate (Hz):", S.frame_hz.min().round(2), "to", S.frame_hz.max().round(2),
"; tracked fraction:", S.tracked.min().round(3), "to", S.tracked.max().round(3),
"; cm per pixel:", sorted(S.cm_per_pixel.unique()))
print("Speed 99th percentile per session (cm/s):", S.speed_p99.min().round(1), "to", S.speed_p99.max().round(1),
"; fraction of time immobile (< 4 cm/s):", S.immobile.min().round(2), "to", S.immobile.max().round(2))
print("Position ranges (cm) per animal:")
print(S.groupby("animal").agg(x=("x_cm", lambda v: sorted(set(v))[:2]), y=("y_cm", lambda v: sorted(set(v))[:2])).to_string())
Archive members (name, bytes):
data/S2/S2eeg.mat 2240717536
data/S2/S2rawpos.mat 6108762
data/S2/S2cellinfo.mat 29174
data/S2/S2spikes.mat 44891440
data/S2/S2task.mat 274
data/S2/S2tetinfo.mat 3793
data/T1/T1task.mat 295
data/T1/T1rawpos.mat 7580050
data/T1/T1cellinfo.mat 35858
data/T1/T1eeg.mat 2845123499
data/T1/T1tetinfo.mat 4817
data/T1/T1spikes.mat 90588824
data/R1/R1task.mat 283
data/R1/R1spikes.mat 83292304
data/R1/R1cellinfo.mat 28332
data/R1/R1rawpos.mat 3609057
data/R1/R1eeg.mat 1272519942
data/R1/R1tetinfo.mat 3846
data/Q1/Q1rawpos.mat 3009969
data/Q1/Q1spikes.mat 25643126
data/Q1/Q1tetinfo.mat 1725
data/Q1/Q1task.mat 246
data/Q1/Q1cellinfo.mat 4067
data/Q1/Q1eeg.mat 1116738598
data/N2/N2cellinfo.mat 8978
data/N2/N2task.mat 272
data/N2/N2spikes.mat 14221716
data/N2/N2eeg.mat 1227647293
data/N2/N2rawpos.mat 3385576
data/N2/N2tetinfo.mat 3340
Days and task sessions per animal (paper: 4, 9, 9, 11 and 12 days, 2 to 3 sessions of 15 to 45 min a day):
days sessions min_minutes max_minutes
animal
N2 9 27 9.5 19.8
Q1 4 12 14.9 38.5
R1 11 33 7.8 15.7
S2 9 27 10.2 35.9
T1 12 35 6.3 52.9
Epoch types: {'Run': 134} ; epoch numbers: [np.int64(2), np.int64(4), np.int64(6)]
Frame rate (Hz): 29.94 to 30.03 ; tracked fraction: 0.993 to 1.0 ; cm per pixel: [np.float64(1.08)]
Speed 99th percentile per session (cm/s): 48.0 to 89.4 ; fraction of time immobile (< 4 cm/s): 0.02 to 0.27
Position ranges (cm) per animal:
x y
animal
N2 [100-294, 92-287] [14-220, 14-222]
Q1 [100-291, 92-288] [0-221, 0-224]
R1 [100-289, 91-292] [13-224, 13-227]
S2 [100-287, 100-292] [14-215, 15-221]
T1 [100-288, 100-289] [10-218, 12-195]
The archive holds 30 files, six per animal, as the data descriptor lists (eeg, rawpos, spikes, cellinfo, task, tetinfo); the descriptor's other files are all present. Days per animal (Q1 4, S2 9, N2 9, R1 11, T1 12) agree with the paper's 4, 9, 9, 11 and 12 days. Each day has three task sessions except one day of T1, which has two (35 sessions over its 12 days, as printed above); some are shorter than the paper's 15 to 45 min (6.3 to 52.9 min). Position is one point per frame at 30 Hz, nearly always tracked, at 1.08 cm per pixel, so the maze spans about 190 by 210 cm; the descriptor's "Nx3" rawpos is time, x and y, and the paper's two diodes are already combined.
urows = []
for a in ANIMALS:
for u in R[a]["units"]:
n = sum(len(v) for v in u["spikes"].values())
urows.append(dict(animal=a, day=u["day"], area=u["area"], width_ms=u["spikewidth_ms"], n=n))
U = pd.DataFrame(urows)
print("Unit-days whose area is empty in both cellinfo and tetinfo (left out of every analysis):", int((U.area == "").sum()),
U[U.area == ""].groupby("animal").size().to_dict(), "; with spikes:", int(((U.area == "") & (U.n > 0)).sum()))
print("Unit-days by animal and area (cellinfo area), with and without spikes:")
print(pd.crosstab(U.animal, [U.area, U.n > 0]).to_string())
print("Spike width (ms) by area and animal, 5th, 50th and 95th percentiles:")
print(U.groupby(["area", "animal"]).width_ms.quantile([0.05, 0.5, 0.95]).unstack().round(3).to_string())
tet = pd.DataFrame([dict(animal=a, day=d, tet=t, area=ar) for a in ANIMALS for d, v in R[a]["tet_area"].items() for t, ar in v.items()])
print("\nTetrode areas (tetinfo):", tet.area.value_counts().to_dict(), "; no corpus callosum or reference tetrode is listed.")
ee = []
for a in ANIMALS:
for d, inf in R[a]["eeg_info"].items():
for ep, e in inf.get("epochs", {}).items():
p = R[a]["days"][d]["epochs"][ep]
ee.append(dict(animal=a, day=d, epoch=ep, n_ca1=len(e["tetrodes"]), fs=e["samprate"],
start_spread_ms=1000 * (max(e["starttimes"]) - min(e["starttimes"])),
eeg_minus_pos_start_s=e["starttime"] - p["t"][0], minutes=e["n"] / e["samprate"] / 60))
E = pd.DataFrame(ee)
print("CA1 LFP: sampling rate", E.fs.min().round(3), "to", E.fs.max().round(3), "Hz; CA1 tetrodes per day",
E.n_ca1.min(), "to", E.n_ca1.max(), "; spread of start times across tetrodes (ms) up to", E.start_spread_ms.max().round(2))
print("LFP start minus position start (s):", E.eeg_minus_pos_start_s.min().round(3), "to", E.eeg_minus_pos_start_s.max().round(3))
nodays = [(a, d) for a in ANIMALS for d, inf in R[a]["eeg_info"].items() if len(inf["ca1_tetrodes"]) < 3]
print("Days with fewer than 3 CA1 tetrodes (no SWR detection):", nodays)
Unit-days whose area is empty in both cellinfo and tetinfo (left out of every analysis): 11 {'N2': 4, 'Q1': 1, 'R1': 2, 'S2': 3, 'T1': 1} ; with spikes: 11
Unit-days by animal and area (cellinfo area), with and without spikes:
area CA1 PFC
n True False True False True
animal
N2 4 0 59 1 35
Q1 1 0 18 0 24
R1 2 6 65 13 211
S2 3 0 135 10 165
T1 1 2 110 1 272
Spike width (ms) by area and animal, 5th, 50th and 95th percentiles:
0.05 0.50 0.95
area animal
N2 0.505 0.524 0.633
Q1 0.287 0.287 0.287
R1 0.457 0.489 0.520
S2 0.208 0.209 0.239
T1 0.375 0.375 0.375
CA1 N2 0.333 0.503 0.601
Q1 0.184 0.304 0.369
R1 0.267 0.505 0.586
S2 0.218 0.294 0.395
T1 0.205 0.247 0.322
PFC N2 0.493 0.566 0.660
Q1 0.238 0.343 0.464
R1 0.428 0.516 0.602
S2 0.184 0.336 0.419
T1 0.242 0.305 0.383
Tetrode areas (tetinfo): {'PFC': 680, 'CA1': 209} ; no corpus callosum or reference tetrode is listed.
CA1 LFP: sampling rate 1500.0 to 1500.0 Hz; CA1 tetrodes per day 3 to 6 ; spread of start times across tetrodes (ms) up to 45.3
LFP start minus position start (s): -48.762 to 4.965
Days with fewer than 3 CA1 tetrodes (no SWR detection): []
Units are counted per day (O4): the files number units within each day, and nothing links a unit
across days. The spike width in cellinfo equals the spikes struct's spikewidth divided by 30, as the
descriptor says. Its distribution differs by animal: in R1 and N2 the median is about 0.5 ms, for CA1
and PFC units alike, against 0.25 to 0.34 ms in the other three rats, so the paper's < 0.4 ms rule
removes almost every CA1 unit of R1 and N2 (the Methods name two spike filters, 600 to 6000 Hz or
300 to 6000 Hz, which may be why; the data do not say which animal used which, and the data set holds
no waveforms to check it). 11 unit-days, all with spikes, have no area in cellinfo or tetinfo and are
left out. The tetinfo areas are CA1 and PFC only: no corpus callosum or reference tetrode is listed,
and the descriptor does not say how the stored LFP is referenced. The paper's Methods (Recording) say
the CA1 LFP was recorded against a corpus callosum tetrode; the LFP is used as stored and cannot be
re-referenced to ground for the spectrograms. LFP is at 1500 Hz, as the paper says. In R1 and N2 the
tetrodes of one session start up to 45 ms apart; they are aligned to the latest start before the
consensus envelope is taken.
sw = []
for a in ANIMALS:
for d, dd in R[a]["days"].items():
for rd, v in dd["swr"].items():
dur = v["end"] - v["start"]
imm = sum(((p["speed"] < 4).sum() / p["fs"]) for p in dd["epochs"].values())
sw.append(dict(animal=a, day=d, reading=rd, threshold_z=v["thr"], mode_z=v["mode"], events_all=v["n_all"],
events_immobile=len(v["start"]), rate_hz=len(v["start"]) / imm, median_ms=1000 * np.median(dur),
frac_imm_in_events=v["frac_imm_in_events"], frac_imm_above_thr=v["frac_imm_above_thr"]))
SW = pd.DataFrame(sw)
print("SWR detection per day, readings O5 (a) amplitude and (b) squared envelope, and a fixed 3 SD threshold on the amplitude (sensitivity check):")
print(SW.groupby(["reading", "animal"]).agg(days=("day", "size"), thr_min=("threshold_z", "min"), thr_max=("threshold_z", "max"),
swrs=("events_immobile", "sum"), rate_hz=("rate_hz", "median"),
median_ms=("median_ms", "median"), imm_in_events=("frac_imm_in_events", "median"),
imm_above_thr=("frac_imm_above_thr", "median")).round(3).to_string())
print("(imm_in_events: median over days of the fraction of immobile time inside detected events; imm_above_thr: of immobile samples above the threshold)")
# Synthetic check of the threshold rule: the envelope of pure Gaussian noise (Rayleigh distributed), and pure Gaussian values
rng_n = np.random.default_rng(2)
for name, x in (("Rayleigh (envelope of Gaussian noise)", np.abs(rng_n.normal(size=10 ** 6) + 1j * rng_n.normal(size=10 ** 6))),
("Gaussian", rng_n.normal(size=10 ** 6))):
zn = (x - x.mean()) / x.std()
mode_n, thr_n = Y.noise_threshold(zn)
print(f"Synthetic {name}: mode {mode_n:.2f} z, threshold {thr_n:.2f} z, fraction of pure-noise samples above it {(zn > thr_n).mean():.4f}")
print("\nUnder reading (b) the threshold is below the envelope mean on",
int((SW[SW.reading == "squared"].threshold_z < 0).sum()), "of", int((SW.reading == "squared").sum()),
"days, so events, which end where the envelope returns to the mean, are not bounded; reading (a) is used below.")
SWR detection per day, readings O5 (a) amplitude and (b) squared envelope, and a fixed 3 SD threshold on the amplitude (sensitivity check):
days thr_min thr_max swrs rate_hz median_ms imm_in_events imm_above_thr
reading animal
amplitude N2 9 0.037 0.254 7884 2.211 47.333 0.129 0.171
Q1 4 0.582 0.841 8234 2.205 49.333 0.124 0.173
R1 11 0.068 0.809 4221 1.304 52.667 0.085 0.128
S2 9 0.215 0.632 16170 2.432 49.333 0.142 0.199
T1 12 0.351 0.639 12315 1.992 55.000 0.131 0.163
fixed3sd N2 9 3.000 3.000 797 0.243 127.667 0.033 0.015
Q1 4 3.000 3.000 604 0.177 78.833 0.015 0.015
R1 11 3.000 3.000 687 0.216 102.333 0.025 0.014
S2 9 3.000 3.000 1268 0.190 120.333 0.027 0.013
T1 12 3.000 3.000 2168 0.340 95.333 0.038 0.020
squared N2 9 -0.141 -0.095 20885 6.813 36.667 0.323 0.439
Q1 4 -0.347 -0.218 29931 8.589 35.333 0.389 0.517
R1 11 -0.208 -0.040 18931 6.032 30.667 0.230 0.388
S2 9 -0.117 -0.057 41472 5.629 34.000 0.254 0.374
T1 12 -0.213 -0.102 42606 6.272 34.000 0.286 0.410
(imm_in_events: median over days of the fraction of immobile time inside detected events; imm_above_thr: of immobile samples above the threshold)
Synthetic Rayleigh (envelope of Gaussian noise): mode -0.37 z, threshold 1.16 z, fraction of pure-noise samples above it 0.1311 Synthetic Gaussian: mode 0.03 z, threshold 3.75 z, fraction of pure-noise samples above it 0.0001 Under reading (b) the threshold is below the envelope mean on 45 of 45 days, so events, which end where the envelope returns to the mean, are not bounded; reading (a) is used below.
The paper's threshold (the 99.99th percentile of the mirrored noise distribution) lies at 0.04 to 0.84 z of the envelope amplitude: the part of the distribution below its mode is short, so its mirror image is narrow. The same rule applied to the envelope of pure Gaussian noise (Rayleigh distributed) puts the threshold at 1.16 z, and 13% of the pure-noise samples exceed it; on Gaussian values it gives 3.75 z, near the true 99.99th percentile (3.72). The rule is only exact for a symmetric noise distribution, and an envelope's is skewed to the right. In the data 13 to 20% of immobile samples lie above the threshold (median per animal), and 9 to 14% of immobile time lies inside events, at 1.3 to 2.4 events per second of immobility. These events therefore include many that a fixed threshold would call noise: a fixed 3 SD threshold, the standard method the Methods say they replaced, gives 0.18 to 0.34 events per second and 1.5 to 3.8% of immobile time inside events. That threshold is not the paper's method and decides no outcome; it is run as a sensitivity check for fig4a, fig3c, fig5 and fig5dg. With the squared envelope (O5 reading (b)) the threshold lies below the mean on every day, so every event would start and end where the envelope crosses the mean and the detection reduces to "above the mean for 20 ms"; that reading is shown in the table and not used further. The amplitude reading (a) is used, as the claims file reads the Methods, with median durations of 47 to 55 ms.
# Wells: four clusters of immobile positions per day (O1 (b))
wr = []
for a in ANIMALS:
for d, t in TB[a].items():
p = t["periods"]
dur = p["end"] - p["start"]
wr.append(dict(animal=a, day=d, wells=np.round(t["wells"]).astype(int).tolist(), periods=len(dur),
median_period_s=np.median(dur), median_dist_cm=np.median(p["dist"]),
frac_time_within_15cm=dur[p["dist"] < 15].sum() / dur.sum(), min_well_s=np.bincount(p["well"], dur, 4).min()))
WR = pd.DataFrame(wr)
print(WR.round(2).to_string(index=False))
def seg_dist(x, y, a, b):
ab = b - a
tt = np.clip(((x - a[0]) * ab[0] + (y - a[1]) * ab[1]) / (ab @ ab), 0, 1)
return np.hypot(x - (a[0] + tt * ab[0]), y - (a[1] + tt * ab[1]))
# Maze paths: positions during movement against the four perimeter segments and the two diagonals joining the wells
fig, ax = plt.subplots(2, len(ANIMALS), figsize=(3 * len(ANIMALS), 5.5))
seg_rows = []
for k, a in enumerate(ANIMALS):
W = TB[a][next(iter(TB[a]))]["wells"]
eps = [p for dd in R[a]["days"].values() for p in dd["epochs"].values()]
mx = np.concatenate([p["x"][p["speed"] > 4] for p in eps]); my = np.concatenate([p["y"][p["speed"] > 4] for p in eps])
ix = np.concatenate([p["x"][p["speed"] < 4] for p in eps]); iy = np.concatenate([p["y"][p["speed"] < 4] for p in eps])
dper = np.min([seg_dist(mx, my, W[i], W[(i + 1) % 4]) for i in range(4)], 0)
ddia = np.min([seg_dist(mx, my, W[0], W[2]), seg_dist(mx, my, W[1], W[3])], 0)
seg_rows.append(dict(animal=a, moving_within_15cm_of_perimeter=(dper < 15).mean(), moving_within_15cm_of_diagonal_only=((dper >= 15) & (ddia < 15)).mean(),
moving_far_from_both=((dper >= 15) & (ddia >= 15)).mean()))
for r_, (xx, yy, ttl) in enumerate(((mx, my, "moving > 4 cm/s"), (ix, iy, "immobile < 4 cm/s"))):
h, xe_, ye_ = np.histogram2d(xx, yy, [np.arange(60, 330, 4), np.arange(0, 250, 4)])
ax[r_, k].imshow(np.log10(h.T + 1), origin="lower", extent=(60, 330, 0, 250), cmap="Greys")
ax[r_, k].plot(*np.vstack([W, W[:1]]).T, c="tab:blue", lw=0.8)
ax[r_, k].scatter(W[:, 0], W[:, 1], c="r", s=12)
ax[r_, k].set_title(f"{a}, {ttl}", fontsize=8)
plt.tight_layout(); plt.show()
print("Fraction of moving frames by distance to the maze's perimeter segments and diagonals (wells joined):")
print(pd.DataFrame(seg_rows).round(3).to_string(index=False))
print("Images: log10 of frame counts in 4 cm bins, x 60 to 330 cm and y 0 to 250 cm, which hold every position (position ranges in the data check).")
animal day wells periods median_period_s median_dist_cm frac_time_within_15cm min_well_s
T1 14 [[110, 25], [274, 37], [282, 189], [110, 209]] 1951 0.23 99.63 0.33 72.93
T1 15 [[110, 25], [274, 37], [282, 189], [110, 209]] 1873 0.27 10.11 0.56 55.78
T1 16 [[110, 25], [274, 37], [282, 189], [110, 209]] 1200 0.27 2.92 0.96 109.77
T1 17 [[110, 25], [274, 37], [282, 189], [110, 209]] 1268 0.28 2.92 0.96 139.26
T1 18 [[110, 25], [274, 37], [282, 189], [110, 209]] 1568 0.30 2.92 0.89 131.66
T1 19 [[110, 25], [274, 37], [282, 189], [110, 209]] 1060 0.27 2.67 0.96 101.19
T1 20 [[110, 25], [274, 37], [282, 189], [110, 209]] 844 0.30 2.20 0.99 73.90
T1 21 [[110, 25], [274, 37], [282, 189], [110, 209]] 1220 0.30 2.20 0.98 96.39
T1 22 [[110, 25], [274, 37], [282, 189], [110, 209]] 759 0.30 3.03 0.97 6.81
T1 23 [[110, 25], [274, 37], [282, 189], [110, 209]] 715 0.27 3.01 0.97 3.37
T1 24 [[110, 25], [274, 37], [282, 189], [110, 209]] 444 0.30 2.58 0.99 0.00
T1 25 [[110, 25], [274, 37], [282, 189], [110, 209]] 476 0.27 1.98 1.00 0.17
S2 14 [[109, 26], [273, 34], [285, 190], [113, 210]] 1833 0.27 4.54 0.94 159.82
S2 15 [[109, 26], [273, 34], [285, 190], [113, 210]] 1977 0.30 5.94 0.95 96.89
S2 16 [[109, 26], [273, 34], [285, 190], [113, 210]] 1491 0.30 2.44 0.98 133.56
S2 17 [[109, 26], [273, 34], [285, 190], [113, 210]] 1550 0.27 1.99 0.98 152.08
S2 18 [[109, 26], [273, 34], [285, 190], [113, 210]] 1412 0.28 2.29 0.96 139.33
S2 19 [[109, 26], [273, 34], [285, 190], [113, 210]] 1310 0.30 1.84 0.99 183.00
S2 20 [[109, 26], [273, 34], [285, 190], [113, 210]] 1097 0.27 4.10 0.93 57.02
S2 21 [[109, 26], [273, 34], [285, 190], [113, 210]] 865 0.27 2.20 0.93 2.30
S2 23 [[109, 26], [273, 34], [285, 190], [113, 210]] 738 0.27 1.76 0.99 1.50
Q1 11 [[104, 26], [272, 30], [284, 190], [112, 214]] 1657 0.30 8.26 0.37 39.01
Q1 13 [[104, 26], [272, 30], [284, 190], [112, 214]] 1602 0.30 2.43 0.64 104.73
Q1 14 [[104, 26], [272, 30], [284, 190], [112, 214]] 1192 0.30 2.43 0.68 80.62
Q1 15 [[104, 26], [272, 30], [284, 190], [112, 214]] 1404 0.27 2.28 0.62 90.19
R1 1 [[102, 26], [274, 34], [282, 198], [110, 210]] 326 0.23 6.37 0.83 3.94
R1 2 [[102, 26], [274, 34], [282, 198], [110, 210]] 432 0.23 10.08 0.73 14.75
R1 3 [[102, 26], [274, 34], [282, 198], [110, 210]] 480 0.27 7.18 0.82 30.30
R1 4 [[102, 26], [274, 34], [282, 198], [110, 210]] 504 0.23 8.97 0.80 0.83
R1 5 [[102, 26], [274, 34], [282, 198], [110, 210]] 794 0.27 3.47 0.80 1.03
R1 6 [[102, 26], [274, 34], [282, 198], [110, 210]] 878 0.30 7.27 0.89 33.36
R1 9 [[102, 26], [274, 34], [282, 198], [110, 210]] 714 0.28 2.02 0.86 1.80
R1 10 [[102, 26], [274, 34], [282, 198], [110, 210]] 622 0.37 2.97 0.97 0.20
R1 12 [[102, 26], [274, 34], [282, 198], [110, 210]] 686 0.30 3.24 0.98 0.63
R1 13 [[102, 26], [274, 34], [282, 198], [110, 210]] 580 0.30 3.07 0.99 34.67
R1 14 [[102, 26], [274, 34], [282, 198], [110, 210]] 491 0.30 3.13 0.97 1.70
N2 1 [[106, 25], [266, 33], [282, 197], [106, 209]] 374 0.23 3.93 0.86 4.51
N2 2 [[106, 25], [266, 33], [282, 197], [106, 209]] 674 0.27 5.54 0.93 6.37
N2 3 [[106, 25], [266, 33], [282, 197], [106, 209]] 522 0.27 2.74 0.96 29.03
N2 4 [[106, 25], [266, 33], [282, 197], [106, 209]] 588 0.27 4.92 0.89 5.17
N2 5 [[106, 25], [266, 33], [282, 197], [106, 209]] 946 0.27 2.73 0.86 4.70
N2 6 [[106, 25], [266, 33], [282, 197], [106, 209]] 968 0.27 4.35 0.95 7.67
N2 8 [[106, 25], [266, 33], [282, 197], [106, 209]] 973 0.27 3.29 0.53 8.31
N2 9 [[106, 25], [266, 33], [282, 197], [106, 209]] 1046 0.27 21.87 0.42 10.11
N2 10 [[106, 25], [266, 33], [282, 197], [106, 209]] 1068 0.27 6.68 0.84 3.74
Fraction of moving frames by distance to the maze's perimeter segments and diagonals (wells joined):
animal moving_within_15cm_of_perimeter moving_within_15cm_of_diagonal_only moving_far_from_both
T1 0.626 0.249 0.125
S2 0.698 0.208 0.094
Q1 0.580 0.309 0.111
R1 0.635 0.253 0.112
N2 0.637 0.268 0.095
Images: log10 of frame counts in 4 cm bins, x 60 to 330 cm and y 0 to 250 cm, which hold every position (position ranges in the data check).
The data set holds only the task sessions (epochs 2, 4 and 6, type Run); the rest sessions the
paper describes are not in it. The task struct holds only the epoch type: there are no reward well
positions, no beam-break (well entry) times and no rewarded-well contingencies, so wells are found
from the immobile positions (O1 reading (b)), once per animal. In every animal the four wells sit at
the corners of the tracked area (images above). On most days more than 80% of immobile time is within
15 cm of a well; on some days of T1, Q1 and N2 it is under 60%, so the paper's "almost all immobility
periods occurred at reward well locations" holds only in part. Immobility periods are short (median
0.23 to 0.37 s) and many (326 to 1977 a day), so many "entries" and "exits" under O1 (b) as written are
brief pauses. Movement follows the four perimeter segments joining the wells in 58 to 70% of moving
frames, and lies within 15 cm of a diagonal only in 21 to 31%: the paths include the diagonals
(Figure 1, supplement 1A, "Paths connect all reward wells"), so the linearization of fig1f is also run
with them.
# Clocks. Spikes against position: IAP rate at its well with true spike times and with spikes shifted by 30 s
# (circularly within the day). LFP (SWR times) against spikes: CA1 pyramidal rate inside SWRs, true and shifted by 1 s.
rng = np.random.default_rng(0)
chk = []
for a in ANIMALS:
ca = [c for c in C if c["animal"] == a]
for shift in (0.0, 30.0):
r = []
for c in ca:
if c["label"] != "IAP":
continue
tb = TB[a][c["day"]]
per = tb["periods"]
m = per["well"] == c["best_well"]
sp = c["spikes"] + shift
r.append(Y.in_intervals(np.sort(sp), np.sort(per["start"][m]), np.sort(per["end"][m])).sum() / (per["end"][m] - per["start"][m]).sum())
chk.append(dict(animal=a, test="IAP rate at its well (Hz)", shift_s=shift, value=np.mean(r) if r else np.nan, n=len(r)))
for shift in (0.0, 1.0):
r = []
for c in ca:
v = R[a]["days"][c["day"]]["swr"].get("amplitude")
if v is None or not len(v["start"]):
continue
o = np.argsort(v["start"])
st, en = v["start"][o] + shift, v["end"][o] + shift
n = (np.searchsorted(c["spikes"], en) - np.searchsorted(c["spikes"], st)).sum()
r.append(n / (en - st).sum())
chk.append(dict(animal=a, test="CA1 pyramidal rate in SWRs (Hz)", shift_s=shift, value=np.mean(r) if r else np.nan, n=len(r)))
# All CA1 units with > 200 spikes and mean rate < 10 Hz, any spike width, so that R1, Q1 and N2 (no IAP, R1 no
# pyramidal cell) are covered: spatial information of the 4 cm occupancy map (bits per spike) with true spikes and
# with spikes shifted by 30 s, and rate inside SWRs (true and SWRs shifted by 1 s).
def spatial_info(eps, sp, shift):
xe_, ye_ = np.arange(0, 324, 4), np.arange(0, 264, 4)
occ = np.zeros((len(xe_) - 1, len(ye_) - 1)); cnt = np.zeros_like(occ)
for p in eps:
occ += np.histogram2d(p["x"], p["y"], [xe_, ye_], weights=np.gradient(p["t"]))[0]
s = sp + shift
s = s[(s >= p["t"][0]) & (s <= p["t"][-1])]
cnt += np.histogram2d(np.interp(s, p["t"], p["x"]), np.interp(s, p["t"], p["y"]), [xe_, ye_])[0]
v = occ > 0
po, r = occ[v] / occ[v].sum(), cnt[v] / occ[v]
rm = (po * r).sum()
return np.nansum(po * r / rm * np.log2(np.where(r > 0, r / rm, 1))) if rm > 0 else np.nan
for a in ANIMALS:
v_true, v_shift, s_true, s_shift = [], [], [], []
for u in R[a]["units"]:
if u["area"] != "CA1" or u["day"] not in TB[a]:
continue
dd = R[a]["days"][u["day"]]
sp = np.sort(np.concatenate([u["spikes"].get(ep, np.zeros(0)) for ep in dd["epochs"]]))
if len(sp) <= 200 or len(sp) / sum(TB[a][u["day"]]["session_s"].values()) >= 10:
continue
eps = list(dd["epochs"].values())
v_true.append(spatial_info(eps, sp, 0.0)); v_shift.append(spatial_info(eps, sp, 30.0))
sv = dd["swr"].get("amplitude")
if sv is not None and len(sv["start"]):
o = np.argsort(sv["start"])
for shift, acc in ((0.0, s_true), (1.0, s_shift)):
st, en = sv["start"][o] + shift, sv["end"][o] + shift
acc.append((np.searchsorted(sp, en) - np.searchsorted(sp, st)).sum() / (en - st).sum())
for test, vals in (("CA1 units < 10 Hz, any width: spatial information (bits/spike)", ((0.0, v_true), (30.0, v_shift))),
("CA1 units < 10 Hz, any width: rate in SWRs (Hz)", ((0.0, s_true), (1.0, s_shift)))):
for shift, v in vals:
chk.append(dict(animal=a, test=test, shift_s=shift, value=np.mean(v) if v else np.nan, n=len(v)))
print("Units per row:", pd.DataFrame(chk).groupby(["test", "animal"]).n.max().to_dict())
print(pd.DataFrame(chk).pivot_table(index=["test", "animal"], columns="shift_s", values="value").round(2).to_string())
Units per row: {('CA1 pyramidal rate in SWRs (Hz)', 'N2'): 7, ('CA1 pyramidal rate in SWRs (Hz)', 'Q1'): 12, ('CA1 pyramidal rate in SWRs (Hz)', 'R1'): 0, ('CA1 pyramidal rate in SWRs (Hz)', 'S2'): 106, ('CA1 pyramidal rate in SWRs (Hz)', 'T1'): 69, ('CA1 units < 10 Hz, any width: rate in SWRs (Hz)', 'N2'): 45, ('CA1 units < 10 Hz, any width: rate in SWRs (Hz)', 'Q1'): 12, ('CA1 units < 10 Hz, any width: rate in SWRs (Hz)', 'R1'): 34, ('CA1 units < 10 Hz, any width: rate in SWRs (Hz)', 'S2'): 113, ('CA1 units < 10 Hz, any width: rate in SWRs (Hz)', 'T1'): 70, ('CA1 units < 10 Hz, any width: spatial information (bits/spike)', 'N2'): 45, ('CA1 units < 10 Hz, any width: spatial information (bits/spike)', 'Q1'): 12, ('CA1 units < 10 Hz, any width: spatial information (bits/spike)', 'R1'): 34, ('CA1 units < 10 Hz, any width: spatial information (bits/spike)', 'S2'): 113, ('CA1 units < 10 Hz, any width: spatial information (bits/spike)', 'T1'): 70, ('IAP rate at its well (Hz)', 'N2'): 0, ('IAP rate at its well (Hz)', 'Q1'): 0, ('IAP rate at its well (Hz)', 'R1'): 0, ('IAP rate at its well (Hz)', 'S2'): 6, ('IAP rate at its well (Hz)', 'T1'): 8}
shift_s 0.0 1.0 30.0
test animal
CA1 pyramidal rate in SWRs (Hz) N2 1.78 0.47 NaN
Q1 1.57 0.69 NaN
S2 0.61 0.28 NaN
T1 1.14 0.49 NaN
CA1 units < 10 Hz, any width: rate in SWRs (Hz) N2 1.43 0.40 NaN
Q1 1.57 0.69 NaN
R1 1.89 0.60 NaN
S2 0.59 0.27 NaN
T1 1.14 0.50 NaN
CA1 units < 10 Hz, any width: spatial information (bits/spike) N2 3.51 NaN 1.69
Q1 2.40 NaN 1.03
R1 3.01 NaN 1.35
S2 3.66 NaN 1.38
T1 3.37 NaN 1.44
IAP rate at its well (Hz) S2 7.65 NaN 2.51
T1 6.87 NaN 3.62
The clocks agree: in every animal with IAPs, their rate at the well falls by about half or more when spikes are shifted by 30 s (by two thirds in S2, 7.65 to 2.51 Hz), and the CA1 pyramidal rate inside SWRs falls by more than half when the SWR times (from the LFP) are shifted by 1 s. Using all CA1 units below 10 Hz with more than 200 spikes, whatever their width, covers every animal: the rate inside SWRs falls from 0.59 to 1.89 Hz to 0.27 to 0.69 Hz when the SWRs are shifted by 1 s, and the spatial information of the rate map falls from 2.40 to 3.66 to 1.03 to 1.69 bits per spike when spikes are shifted by 30 s, in all five rats, R1 and Q1 included. These checks are consistent with a shared clock for spikes, LFP and position; they do not show it to the sample.
Cell selection¶
fig1s4b-foraging-counts¶
In the foraging task, 33 CA1 units are IAPs and 244 are MAPs.
(Figure 1, supplement 4B legend; data: dataset)
Cell selection as in the Methods (Cell selection) and the helper's docstring; IAP threshold 3 Hz at one or more wells during immobility, SWR spikes excluded, readings O2 (a) and (b). Variants: speed unsmoothed (O3), other IAP thresholds, and no spike-width rule in R1 and N2.
def counts(cells):
df = pd.DataFrame([dict(animal=c["animal"], day=c["day"], label=c["label"]) for c in cells])
return df
for o2 in "ab":
df = counts(CELLS[o2])
print(f"O2 reading ({o2}):", df.label.value_counts().to_dict())
print(pd.crosstab(df.animal, df.label).to_string())
nsp = ca1_cells("a", speed_key="speed_raw")
print("Unsmoothed speed (O3 variant):", pd.Series([c["label"] for c in nsp]).value_counts().to_dict())
for thr in (2.0, 2.5, 3.5, 4.0):
print(f"IAP rate threshold {thr} Hz (variant of the paper's 3 Hz):",
sum(c["well_rates"].max() >= thr for c in C), "IAPs")
wv = ca1_cells("a", width_max={"R1": np.inf, "N2": np.inf})
print("Variant, no spike-width rule in R1 and N2 (their stored widths run about 0.2 ms longer, see the data check):",
pd.Series([c["label"] for c in wv]).value_counts().to_dict(), pd.crosstab(pd.Series([c["animal"] for c in wv]), pd.Series([c["label"] for c in wv])).to_dict())
allca1 = sum(1 for a in ANIMALS for u in R[a]["units"] if u["area"] == "CA1")
print("CA1 unit-days in the data set:", allca1, "; pyramidal after width, rate and spike-count rules:", len(C))
print("Expected (Figure 1, supplement 4B): 33 IAPs (tolerance 3.3) and 244 MAPs (24.4).")
print("Unique units across days cannot be counted: the files carry no unit identifier across days (O4 variant not possible).")
O2 reading (a): {'MAP': 180, 'IAP': 14}
label IAP MAP
animal
N2 0 7
Q1 0 12
S2 6 100
T1 8 61
O2 reading (b): {'MAP': 177, 'IAP': 17}
label IAP MAP
animal
N2 0 7
Q1 1 11
S2 6 100
T1 10 59
Unsmoothed speed (O3 variant): {'MAP': 175, 'IAP': 19}
IAP rate threshold 2.0 Hz (variant of the paper's 3 Hz): 21 IAPs
IAP rate threshold 2.5 Hz (variant of the paper's 3 Hz): 17 IAPs
IAP rate threshold 3.5 Hz (variant of the paper's 3 Hz): 13 IAPs
IAP rate threshold 4.0 Hz (variant of the paper's 3 Hz): 10 IAPs
Variant, no spike-width rule in R1 and N2 (their stored widths run about 0.2 ms longer, see the data check): {'MAP': 250, 'IAP': 16} {'IAP': {'N2': 1, 'Q1': 0, 'R1': 1, 'S2': 6, 'T1': 8}, 'MAP': {'N2': 44, 'Q1': 12, 'R1': 33, 'S2': 100, 'T1': 61}}
CA1 unit-days in the data set: 395 ; pyramidal after width, rate and spike-count rules: 194
Expected (Figure 1, supplement 4B): 33 IAPs (tolerance 3.3) and 244 MAPs (24.4).
Unique units across days cannot be counted: the files carry no unit identifier across days (O4 variant not possible).
Result: not reproduced. Under O2 reading (a) there are 14 IAPs and 180 MAPs, under (b) 17 and 177, against 33 (tolerance 3.3) and 244 (24.4); neither count is within tolerance under either reading, and unsmoothed speed gives 19 and 175. Of 395 CA1 unit-days, 194 pass the width, rate and spike-count rules; R1 contributes none and N2 seven, because their stored spike widths run about 0.2 ms longer than the other rats'. Without the width rule in R1 and N2 there are 16 IAPs and 250 MAPs: the MAP count then falls within tolerance, the IAP count still does not. A threshold of 2 Hz in place of 3 Hz gives 21 IAPs.
fig1d-well-specificity¶
IAP firing is specific to a single reward well, with well specificity indices close to 1 in both tasks.
(Figure 1D; Figure 1, supplement 4F legend; data: with_inputs)
Index as in the Methods (Well specificity) with the wells in their order around the maze, 90 degrees apart.
def specificity(r):
if r.max() <= 0:
return np.nan
v = r / r.max()
ang = np.arange(4) * np.pi / 2 # wells in their order around the maze (corners), 90 degrees apart
return np.abs((v * np.exp(1j * ang)).sum())
def specificity_sum(r):
"""Variant: rates normalized to their sum (bounded by 1), not stated in the paper."""
if r.max() <= 0:
return np.nan
v = r / r.sum()
return np.abs((v * np.exp(1j * np.arange(4) * np.pi / 2)).sum())
for o2 in "ab":
spec = np.array([specificity(c["well_rates"]) for c in CELLS[o2] if c["label"] == "IAP"])
specm = np.array([specificity(c["well_rates"]) for c in CELLS[o2] if c["label"] == "MAP"])
print(f"O2 ({o2}): IAP well specificity median {np.nanmedian(spec):.3f} (IQR {np.nanpercentile(spec, 25):.3f}-"
f"{np.nanpercentile(spec, 75):.3f}, range {np.nanmin(spec):.2f}-{np.nanmax(spec):.2f}, n = {len(spec)}); "
f"MAPs median {np.nanmedian(specm):.3f} (n = {len(specm)})")
spec = np.array([specificity(c["well_rates"]) for c in C if c["label"] == "IAP"])
print("By animal (O2 a):", {a: round(float(np.nanmedian([specificity(c["well_rates"]) for c in C if c["label"] == "IAP" and c["animal"] == a])), 3)
for a in ANIMALS if any(c["label"] == "IAP" and c["animal"] == a for c in C)})
print("Criterion: median >= 0.8 (0.9 stricter):", np.nanmedian(spec) >= 0.8, np.nanmedian(spec) >= 0.9)
print("Index above 1 (possible with rates divided by the maximum, as the Methods and the criterion have it):", int((spec > 1.0001).sum()), "of", len(spec))
ss = np.array([specificity_sum(c["well_rates"]) for c in C if c["label"] == "IAP"])
print(f"Variant, rates divided by their sum: IAP median {np.nanmedian(ss):.3f}, range {np.nanmin(ss):.2f}-{np.nanmax(ss):.2f}")
O2 (a): IAP well specificity median 0.998 (IQR 0.995-1.000, range 0.39-1.08, n = 14); MAPs median 0.992 (n = 180)
O2 (b): IAP well specificity median 0.997 (IQR 0.995-1.000, range 0.40-1.08, n = 17); MAPs median 0.991 (n = 177)
By animal (O2 a): {'T1': 0.996, 'S2': 0.999}
Criterion: median >= 0.8 (0.9 stricter): True True
Index above 1 (possible with rates divided by the maximum, as the Methods and the criterion have it): 2 of 14
Variant, rates divided by their sum: IAP median 0.989, range 0.15-1.00
Result: reproduced on the foraging rats. The median well specificity of the 14 IAPs is 0.998 (O2 b: 0.997, 17 IAPs), above both 0.8 and the stricter 0.9. With rates divided by the maximum, as the Methods have it, the index can exceed 1 (2 of 14 IAPs); with rates divided by their sum the median is 0.989. The MAP median is also high (0.992), since most MAPs fire little at any well.
fig1s4d-foraging-speed¶
In the foraging task alone, IAP spikes occur at much lower speeds than MAP spikes.
(Figure 1, supplement 4D legend; data: dataset)
def spike_speed(c, key="speed"):
dd = R[c["animal"]]["days"][c["day"]]
v = []
for p in dd["epochs"].values():
s = c["spikes"][(c["spikes"] >= p["t"][0]) & (c["spikes"] <= p["t"][-1])]
v.append(np.interp(s, p["t"], p[key]))
return np.median(np.concatenate(v))
for key in ("speed", "speed_raw"):
for o2 in "ab":
ms = {lab: np.array([spike_speed(c, key) for c in CELLS[o2] if c["label"] == lab]) for lab in ("IAP", "MAP")}
t = stats.ranksums(ms["IAP"], ms["MAP"])
print(f"{key}, O2 ({o2}): median spike speed IAPs {np.median(ms['IAP']):.2f} cm/s (n = {len(ms['IAP'])}), "
f"MAPs {np.median(ms['MAP']):.2f} (n = {len(ms['MAP'])}); rank-sum z = {t.statistic:.2f}, p = {t.pvalue:.2g}")
MS = {lab: np.array([spike_speed(c) for c in C if c["label"] == lab]) for lab in ("IAP", "MAP")}
print("Per animal (smoothed, O2 a):")
for a in ANIMALS:
i = [spike_speed(c) for c in C if c["animal"] == a and c["label"] == "IAP"]
m = [spike_speed(c) for c in C if c["animal"] == a and c["label"] == "MAP"]
print(f" {a}: IAP {np.median(i) if i else np.nan:.2f} (n = {len(i)}), MAP {np.median(m) if m else np.nan:.2f} (n = {len(m)})")
speed, O2 (a): median spike speed IAPs 11.80 cm/s (n = 14), MAPs 27.79 (n = 180); rank-sum z = -4.26, p = 2e-05 speed, O2 (b): median spike speed IAPs 11.65 cm/s (n = 17), MAPs 28.20 (n = 177); rank-sum z = -4.88, p = 1.1e-06
speed_raw, O2 (a): median spike speed IAPs 14.47 cm/s (n = 14), MAPs 27.03 (n = 180); rank-sum z = -4.23, p = 2.3e-05 speed_raw, O2 (b): median spike speed IAPs 14.59 cm/s (n = 17), MAPs 27.47 (n = 177); rank-sum z = -4.83, p = 1.4e-06 Per animal (smoothed, O2 a): T1: IAP 11.02 (n = 8), MAP 32.27 (n = 61) S2: IAP 12.72 (n = 6), MAP 26.63 (n = 100) Q1: IAP nan (n = 0), MAP 20.40 (n = 12) R1: IAP nan (n = 0), MAP nan (n = 0) N2: IAP nan (n = 0), MAP 23.99 (n = 7)
Result: reproduced. The median speed at spike times is 11.80 cm/s for IAPs and 27.79 cm/s for MAPs (rank-sum p = 2e-05; O2 b p = 1.1e-06; unsmoothed speed p = 2.3e-05). In T1 and S2, the two rats with IAPs, the IAP median is lower (11.02 against 32.27, 12.72 against 26.63 cm/s).
fig1e-iap-lower-speed¶
IAPs spike at lower movement speeds than MAPs; the median speed at the times of spikes is lower for IAPs.
(Figure 1E; Results, Identification of CA1 place cells, paragraph 3; data: with_inputs)
t = stats.ranksums(MS["IAP"], MS["MAP"])
print(f"Foraging rats only (the W-track rats are not in hc-13): IAP median {np.median(MS['IAP']):.2f} cm/s, "
f"MAP median {np.median(MS['MAP']):.2f} cm/s, rank-sum p = {t.pvalue:.2g} (n = {len(MS['IAP'])} and {len(MS['MAP'])})")
Foraging rats only (the W-track rats are not in hc-13): IAP median 11.80 cm/s, MAP median 27.79 cm/s, rank-sum p = 2e-05 (n = 14 and 180)
Result: reproduced on the foraging rats. IAPs spike at lower speeds than MAPs (11.80 against 27.79 cm/s, rank-sum p = 2e-05, 14 and 180 cells). The W-track rats are not tested.
fig1f-iap-smaller-coverage¶
IAPs are active over smaller regions of the environment (smaller spatial coverage) than MAPs.
(Figure 1F; Figure 1, supplement 4E legend; data: with_inputs)
The legend of Figure 1, supplement 4E speaks of "place fields on path segments"; positions and spikes during movement (> 4 cm/s) are shown as a further variant of both readings.
def moving_only(dd, spikes):
"""Positions and spikes at speed > 4 cm/s (variant: 'place fields on path segments', Figure 1, supplement 4E)."""
eps, sp = [], []
for p in dd["epochs"].values():
m = p["speed"] > 4
eps.append(dict(t=p["t"][m], x=p["x"][m], y=p["y"][m], dt=np.gradient(p["t"])[m]))
s = spikes[(spikes >= p["t"][0]) & (spikes <= p["t"][-1])]
sp.append(s[np.interp(s, p["t"], p["speed"]) > 4])
return eps, np.concatenate(sp)
def coverage_square(c, moving=False, min_occ=0.0):
dd = R[c["animal"]]["days"][c["day"]]
if moving:
eps, sp = moving_only(dd, c["spikes"])
else:
eps, sp = [dict(p, dt=np.gradient(p["t"])) for p in dd["epochs"].values()], c["spikes"]
m, _, _ = Y.occupancy_map(eps, sp, min_occ=min_occ)
return np.nansum(m > 2.0)
def coverage_linear(c, moving=False, diagonals=False, min_occ=0.0):
"""Positions projected on the four maze segments joining neighbouring wells (and, as a variant, the two
diagonals), 2 cm bins along them; ``min_occ`` (s) leaves out bins visited for less (variant)."""
dd = R[c["animal"]]["days"][c["day"]]
W = TB[c["animal"]][c["day"]]["wells"]
segs = [(W[i], W[(i + 1) % 4]) for i in range(4)] + ([(W[0], W[2]), (W[1], W[3])] if diagonals else [])
lens = [np.hypot(*(b - a)) for a, b in segs]
offs = np.concatenate([[0], np.cumsum(lens)])
edges = np.arange(0, offs[-1] + 2, 2.0)
occ = np.zeros(len(edges) - 1)
cnt = np.zeros(len(edges) - 1)
def lin(x, y):
best_d = np.full(len(x), np.inf)
L = np.zeros(len(x))
for k, (a, b) in enumerate(segs):
ab = b - a
tt = np.clip(((x - a[0]) * ab[0] + (y - a[1]) * ab[1]) / (ab @ ab), 0, 1)
d = np.hypot(x - (a[0] + tt * ab[0]), y - (a[1] + tt * ab[1]))
m = d < best_d
best_d[m] = d[m]
L[m] = offs[k] + tt[m] * lens[k]
return L
eps, sp = moving_only(dd, c["spikes"]) if moving else ([dict(p, dt=np.gradient(p["t"])) for p in dd["epochs"].values()], c["spikes"])
for p in eps:
occ += np.histogram(lin(p["x"], p["y"]), edges, weights=p["dt"])[0]
s = sp[(sp >= p["t"][0]) & (sp <= p["t"][-1])] if len(p["t"]) else sp[:0]
if len(s):
cnt += np.histogram(lin(np.interp(s, p["t"], p["x"]), np.interp(s, p["t"], p["y"])), edges)[0]
rate = np.where(occ > min_occ, cnt / np.maximum(occ, 1e-9), np.nan)
return np.nansum(rate > 2.0)
from functools import partial
cov = {}
for name, fn, mv in (("(a) 2 cm square bins, all task time", coverage_square, False),
("(b) linearized on the segments, all task time", coverage_linear, False),
("(a) 2 cm square bins, movement > 4 cm/s", coverage_square, True),
("(b) linearized on the segments, movement > 4 cm/s", coverage_linear, True),
("variant (b) with the two diagonals, all task time", partial(coverage_linear, diagonals=True), False),
("variant (a), bins with >= 0.1 s occupancy", partial(coverage_square, min_occ=0.1), False),
("variant (b), bins with >= 0.1 s occupancy", partial(coverage_linear, min_occ=0.1), False)):
v = {lab: np.array([fn(c, mv) for c in C if c["label"] == lab]) for lab in ("IAP", "MAP")}
t = stats.ranksums(v["IAP"], v["MAP"])
cov[name] = v
print(f"{name}: bins > 2 Hz, IAP median {np.median(v['IAP']):.0f} (n = {len(v['IAP'])}), MAP median {np.median(v['MAP']):.0f} "
f"(n = {len(v['MAP'])}); rank-sum p = {t.pvalue:.2g}")
(a) 2 cm square bins, all task time: bins > 2 Hz, IAP median 208 (n = 14), MAP median 203 (n = 180); rank-sum p = 0.62
(b) linearized on the segments, all task time: bins > 2 Hz, IAP median 20 (n = 14), MAP median 23 (n = 180); rank-sum p = 0.67
(a) 2 cm square bins, movement > 4 cm/s: bins > 2 Hz, IAP median 207 (n = 14), MAP median 203 (n = 180); rank-sum p = 0.62
(b) linearized on the segments, movement > 4 cm/s: bins > 2 Hz, IAP median 20 (n = 14), MAP median 23 (n = 180); rank-sum p = 0.7
variant (b) with the two diagonals, all task time: bins > 2 Hz, IAP median 32 (n = 14), MAP median 31 (n = 180); rank-sum p = 0.47
variant (a), bins with >= 0.1 s occupancy: bins > 2 Hz, IAP median 166 (n = 14), MAP median 162 (n = 180); rank-sum p = 0.41
variant (b), bins with >= 0.1 s occupancy: bins > 2 Hz, IAP median 20 (n = 14), MAP median 23 (n = 180); rank-sum p = 0.67
Result: not reproduced. IAPs do not cover fewer bins than MAPs: with 2 cm square bins the medians are 208 and 203 bins (p = 0.62), linearized on the four perimeter segments 20 and 23 (p = 0.67), and with movement only 207 and 203 (p = 0.62) and 20 and 23 (p = 0.70). The variants do not change this: with the two diagonals added to the linearization 32 and 31 (p = 0.47), and with bins visited for at least 0.1 s 166 and 162 (p = 0.41, square bins) and 20 and 23 (p = 0.67, linearized).
fig1s1d-transition-interval¶
The animals switch between movement and immobility every 6 to 7 s; the autocorrelation of well entry and exit times peaks at 6.4 to 6.6 s in the foraging task.
(Figure 1, supplement 1D legend; Results, Identification of CA1 place cells, paragraph 1; data: dataset)
Entries and exits are the starts and ends of immobility periods (O1 (b)). The criterion's "peak
away from zero lag" is taken as the maximum after the first trough at positive lag. Variants: only
periods of at least 0.5 s or 1 s, the well visits used for Figure 2 (visit_mask), and visits
defined as runs of frames within 15 cm of a well.
def entry_exit_acg(min_dur=0.0, maxlag=20.0, binw=0.2, sigma=0.5, visits=False):
h = 0
edges = np.arange(-maxlag, maxlag + binw / 2, binw)
for a in ANIMALS:
for d, t in TB[a].items():
p = t["periods"]
keep = visit_mask(p) if visits else (p["end"] - p["start"]) >= min_dur
for ep in np.unique(p["epoch"]):
m = keep & (p["epoch"] == ep)
ts = np.sort(np.concatenate([p["start"][m], p["end"][m]]))
h = h + np.histogram(Y.lags(ts, ts, maxlag), edges)[0]
cen = 0.5 * (edges[1:] + edges[:-1])
hs = gaussian(h.astype(float), sigma / binw)
return cen, hs
def peak_after_trough(cen, hs):
"""The peak away from zero lag: the maximum at lags beyond the first local minimum at positive lag."""
i0 = np.flatnonzero(cen > 0)
x, y = cen[i0], hs[i0]
mins = [i for i in range(1, len(y) - 1) if y[i] < y[i - 1] and y[i] <= y[i + 1]]
if not mins:
return np.nan
j = mins[0]
return x[j + np.argmax(y[j:])]
fig, ax = plt.subplots(1, 3, figsize=(12, 3))
for k, md in enumerate((0.0, 0.5, 1.0)):
cen, hs = entry_exit_acg(md)
pk = peak_after_trough(cen, hs)
loc = [round(float(cen[i]), 1) for i in range(1, len(cen) - 1) if cen[i] > 0.5 and hs[i] > hs[i - 1] and hs[i] >= hs[i + 1]][:5]
print(f"immobility periods >= {md} s: peak after the first trough at {pk:.1f} s; first local maxima above 0.5 s: {loc}")
ax[k].plot(cen[cen > 0], hs[cen > 0]); ax[k].set_title(f"periods >= {md} s"); ax[k].set_xlabel("lag (s)")
plt.show()
cen, hs = entry_exit_acg(visits=True)
print(f"Well visits (immobility periods >= {VISIT_MIN_S} s within {VISIT_RADIUS:.0f} cm of a well, as for Figure 2 below): "
f"peak after the first trough at {peak_after_trough(cen, hs):.1f} s")
# Variant: well visits as runs of frames within 15 cm of a well centre (a radius the paper does not give)
h = 0
edges = np.arange(-20, 20.1, 0.2)
for a in ANIMALS:
for d, t in TB[a].items():
for ep, p in R[a]["days"][d]["epochs"].items():
dmin = np.min([np.hypot(p["x"] - w[0], p["y"] - w[1]) for w in t["wells"]], 0)
s0, e0 = Y.runs(dmin < 15)
ts = np.sort(np.concatenate([p["t"][s0], p["t"][np.minimum(e0, len(p["t"]) - 1)]]))
h = h + np.histogram(Y.lags(ts, ts, 20), edges)[0]
cen = 0.5 * (edges[1:] + edges[:-1])
hs = gaussian(h.astype(float), 0.5 / 0.2)
print(f"Variant, visits within 15 cm of a well: peak after the first trough at {peak_after_trough(cen, hs):.1f} s")
print("Expected 6.5 s, tolerance 5.76 to 7.26 s. Plotted: lags 0 to 20 s, all values shown.")
immobility periods >= 0.0 s: peak after the first trough at 14.3 s; first local maxima above 0.5 s: [14.3] immobility periods >= 0.5 s: peak after the first trough at 14.3 s; first local maxima above 0.5 s: [14.3, 16.3] immobility periods >= 1.0 s: peak after the first trough at 16.5 s; first local maxima above 0.5 s: [14.3, 16.5]
Well visits (immobility periods >= 0.5 s within 15 cm of a well, as for Figure 2 below): peak after the first trough at 14.1 s
Variant, visits within 15 cm of a well: peak after the first trough at 4.1 s Expected 6.5 s, tolerance 5.76 to 7.26 s. Plotted: lags 0 to 20 s, all values shown.
Result: not reproduced. The peak of the autocorrelation of entry and exit times after its first trough is at 14.3 s for all immobility periods, outside 5.76 to 7.26 s; with periods of at least 0.5 s it is at 14.3 s, of at least 1 s at 16.5 s, and for the well visits used below (periods of at least 0.5 s within 15 cm of a well) at 14.1 s. Runs of frames within 15 cm of a well give 4.1 s. No definition tried gives a peak in the paper's range.
SWR content¶
def swr_table(cells, reading="amplitude"):
"""One row per SWR of the days with SWR detection: type by MAP/IAP content, duration, power, well at its start."""
rows, parts = [], {}
for a in ANIMALS:
for d, dd in R[a]["days"].items():
v = dd["swr"].get(reading)
if v is None or not len(v["start"]):
continue
o = np.argsort(v["start"])
swr = {k: (np.asarray(v[k])[o] if np.ndim(v[k]) else v[k]) for k in v}
cs = [c for c in cells if c["animal"] == a and c["day"] == d]
M = Y.swr_participation(cs, swr) if cs else np.zeros((0, len(swr["start"])), int)
lab = np.array([c["label"] for c in cs])
nm = (M[lab == "MAP"] > 0).sum(0) if len(cs) else 0
ni = (M[lab == "IAP"] > 0).sum(0) if len(cs) else 0
sm = M[lab == "MAP"].sum(0) if len(cs) else 0
si = M[lab == "IAP"].sum(0) if len(cs) else 0
W = TB[a][d]["wells"]
well = np.full(len(swr["start"]), -1)
for ep, p in dd["epochs"].items():
m = swr["epoch"] == ep
x = np.interp(swr["start"][m], p["t"], p["x"])
y = np.interp(swr["start"][m], p["t"], p["y"])
well[m] = np.argmin([(x - w[0]) ** 2 + (y - w[1]) ** 2 for w in W], 0)
df = pd.DataFrame(dict(animal=a, day=d, epoch=swr["epoch"], start=swr["start"], end=swr["end"],
dur=swr["end"] - swr["start"], n_map=nm, n_iap=ni, s_map=sm, s_iap=si, well=well,
p_rip=swr.get("power_ripple", np.full(len(o), np.nan)),
p_gam=swr.get("power_gamma", np.full(len(o), np.nan))))
df["type"] = np.select([(df.n_map > 0) & (df.n_iap > 0), df.n_map > 0, df.n_iap > 0], ["MAP & IAP", "MAP", "IAP"], "none")
rows.append(df)
parts[(a, d)] = (cs, M, df.index.size)
return pd.concat(rows, ignore_index=True), parts
SWRT, PARTS = swr_table(C)
SWRT_B, _ = swr_table(CELLS["b"])
SWRT_3, _ = swr_table(C, "fixed3sd") # sensitivity check only: fixed 3 SD threshold, not the paper's method
DAYS_BOTH = {(a, d) for (a, d), (cs, M, n) in PARTS.items() if {"MAP", "IAP"} <= {c["label"] for c in cs}}
print("SWRs on days with SWR detection:", len(SWRT), "; by type:", SWRT.type.value_counts().to_dict())
print("Fixed 3 SD threshold (sensitivity check):", len(SWRT_3), "; by type:", SWRT_3.type.value_counts().to_dict())
print("Days with at least one IAP and one MAP:", sorted(DAYS_BOTH))
SWRs on days with SWR detection: 48824 ; by type: {'none': 41882, 'MAP': 4998, 'IAP': 1651, 'MAP & IAP': 293}
Fixed 3 SD threshold (sensitivity check): 5524 ; by type: {'none': 3625, 'MAP': 1636, 'IAP': 170, 'MAP & IAP': 93}
Days with at least one IAP and one MAP: [('S2', 14), ('S2', 15), ('S2', 16), ('S2', 17), ('S2', 19), ('S2', 21), ('T1', 16), ('T1', 18), ('T1', 19), ('T1', 20), ('T1', 22), ('T1', 24)]
fig4a-swr-counts¶
Most SWRs contain only MAPs (12881, 67%) or only IAPs (5009, 26%); only 1311 (7%) contain both, far fewer than the 4671 (24%) expected if MAPs and IAPs took part independently.
(Figure 4A; Results, Separate reactivation, paragraph 3; data: with_inputs)
Coactivity and SWR content use the amplitude reading of O5. The z-score of coactivity uses the exact mean and variance of the permutation distribution (hypergeometric), the limit of the paper's 5000 permutations.
def swr_counts(T, label=""):
t = T[T.type != "none"]
N = len(t)
if N == 0:
print(f"{label}: no SWRs with MAP or IAP spikes"); return np.nan, np.nan, np.nan
c = t.type.value_counts()
pm = (t.n_map > 0).mean()
pi = (t.n_iap > 0).mean()
exp_both = pm * pi * N
obs = c.get("MAP & IAP", 0)
chi = stats.chisquare([obs, N - obs], [exp_both, N - exp_both])
print(f"{label} N = {N}: MAP only {c.get('MAP', 0)} ({c.get('MAP', 0) / N:.3f}), IAP only {c.get('IAP', 0)} ({c.get('IAP', 0) / N:.3f}), "
f"both {obs} ({obs / N:.3f}); expected both {exp_both:.0f} ({exp_both / N:.3f}); chi2 = {chi.statistic:.1f}, p = {chi.pvalue:.2g}")
return c.get("MAP", 0) / N, c.get("IAP", 0) / N, obs / N
fr = swr_counts(SWRT, "O2 (a)")
swr_counts(SWRT_B, "O2 (b)")
for a in ANIMALS:
if ((SWRT.animal == a) & (SWRT.type != "none")).any():
swr_counts(SWRT[SWRT.animal == a], f" {a}")
in_both = lambda T: T[[(a, d) in DAYS_BOTH for a, d in zip(T.animal, T.day)]]
swr_counts(in_both(SWRT), "Variant, only days with at least one IAP and one MAP, O2 (a)")
for a in ANIMALS:
t_ = in_both(SWRT)
if ((t_.animal == a) & (t_.type != "none")).any():
swr_counts(t_[t_.animal == a], f" {a}")
fr3 = swr_counts(SWRT_3, "Sensitivity, fixed 3 SD threshold (not the paper's method), all days")
swr_counts(in_both(SWRT_3), "Sensitivity, fixed 3 SD threshold, days with at least one IAP and one MAP")
print("Expected fractions 0.67 +- 0.067, 0.26 +- 0.026, 0.07 +- 0.007; within tolerance:",
[abs(x - e) <= t for x, e, t in zip(fr, (0.67, 0.26, 0.07), (0.067, 0.026, 0.007))])
O2 (a) N = 6942: MAP only 4998 (0.720), IAP only 1651 (0.238), both 293 (0.042); expected both 1482 (0.213); chi2 = 1212.4, p = 1.3e-265 O2 (b) N = 6942: MAP only 4709 (0.678), IAP only 1926 (0.277), both 307 (0.044); expected both 1613 (0.232); chi2 = 1378.2, p = 1.1e-301 T1 N = 2411: MAP only 1435 (0.595), IAP only 919 (0.381), both 57 (0.024); expected both 604 (0.251); chi2 = 660.9, p = 9.4e-146 S2 N = 3260: MAP only 2292 (0.703), IAP only 732 (0.225), both 236 (0.072); expected both 751 (0.230); chi2 = 458.4, p = 1.1e-101 Q1 N = 880: MAP only 880 (1.000), IAP only 0 (0.000), both 0 (0.000); expected both 0 (0.000); chi2 = nan, p = nan N2 N = 391: MAP only 391 (1.000), IAP only 0 (0.000), both 0 (0.000); expected both 0 (0.000); chi2 = nan, p = nan Variant, only days with at least one IAP and one MAP, O2 (a) N = 4172: MAP only 2228 (0.534), IAP only 1651 (0.396), both 293 (0.070); expected both 1175 (0.282); chi2 = 921.1, p = 2.5e-202 T1 N = 1491: MAP only 515 (0.345), IAP only 919 (0.616), both 57 (0.038); expected both 374 (0.251); chi2 = 359.3, p = 3.9e-80 S2 N = 2681: MAP only 1713 (0.639), IAP only 732 (0.273), both 236 (0.088); expected both 704 (0.262); chi2 = 421.5, p = 1.2e-93 Sensitivity, fixed 3 SD threshold (not the paper's method), all days N = 1899: MAP only 1636 (0.862), IAP only 170 (0.090), both 93 (0.049); expected both 239 (0.126); chi2 = 102.5, p = 4.3e-24 Sensitivity, fixed 3 SD threshold, days with at least one IAP and one MAP N = 923: MAP only 660 (0.715), IAP only 170 (0.184), both 93 (0.101); expected both 215 (0.232); chi2 = 89.7, p = 2.7e-21 Expected fractions 0.67 +- 0.067, 0.26 +- 0.026, 0.07 +- 0.007; within tolerance: [np.True_, np.True_, np.False_]
Result: partially reproduced. Of 6942 SWRs with MAP or IAP spikes, 0.720 hold only MAPs, 0.238 only IAPs and 0.042 both; the first two are within tolerance, the third is below 0.063. The expected count of SWRs with both is 1482 (0.213), and the observed 293 is far below it (chi-square 1212, p = 1e-265). Under O2 (b) the fractions are 0.678, 0.277 and 0.044. Only T1 and S2 have IAPs: T1 gives 0.024 with both, S2 0.072. The expected count pools days without IAPs, which cannot give SWRs with both. On the 12 days with at least one IAP and one MAP the fractions are 0.534, 0.396 and 0.070 (observed 293 against 1175 expected, p = 2.5e-202): the test holds, the third fraction is then within tolerance and the first two are not, so the claim is partly reproduced on either set of days. With a fixed 3 SD threshold (sensitivity check, not the paper's method) the fractions are 0.862, 0.090 and 0.049 over all days and 0.715, 0.184 and 0.101 on the 12 days, and SWRs with both are again fewer than expected (p = 4e-24 and 3e-21).
fig4c-iap-swr-shorter¶
IAP-SWRs are shorter than MAP-SWRs, and MAP & IAP-SWRs are the longest; the duration distributions differ between all pairs of groups.
(Figure 4C; Results, Distinct properties for SWRs involving movement and immobility representations, paragraphs 1 and 2; data: with_inputs)
G = {t: SWRT[SWRT.type == t] for t in ("IAP", "MAP", "MAP & IAP")}
print("Median duration (ms):", {t: round(1000 * g.dur.median(), 1) for t, g in G.items()}, "; n:", {t: len(g) for t, g in G.items()})
for x, y in (("IAP", "MAP"), ("IAP", "MAP & IAP"), ("MAP", "MAP & IAP")):
k = stats.ks_2samp(G[x].dur, G[y].dur)
print(f" KS {x} vs {y}: D = {k.statistic:.3f}, p = {k.pvalue:.2g}")
print("Per animal median duration (ms):")
print(SWRT[SWRT.type != "none"].groupby(["animal", "type"]).dur.median().mul(1000).round(1).unstack().to_string())
Median duration (ms): {'IAP': np.float64(52.7), 'MAP': np.float64(74.0), 'MAP & IAP': np.float64(79.3)} ; n: {'IAP': 1651, 'MAP': 4998, 'MAP & IAP': 293}
KS IAP vs MAP: D = 0.298, p = 7.9e-98 KS IAP vs MAP & IAP: D = 0.363, p = 8.2e-30 KS MAP vs MAP & IAP: D = 0.091, p = 0.019 Per animal median duration (ms): type IAP MAP MAP & IAP animal N2 NaN 84.0 NaN Q1 NaN 63.3 NaN S2 50.0 75.3 76.7 T1 54.7 81.3 100.0
Result: reproduced on the foraging rats. Median durations are 52.7 ms for IAP-SWRs, 74.0 ms for MAP-SWRs and 79.3 ms for MAP & IAP-SWRs, and all three KS tests give p < 0.05 (7.9e-98, 8.2e-30 and 0.019). In T1 and S2 separately the order is the same (54.7, 81.3, 100.0 and 50.0, 75.3, 76.7 ms).
fig4d-iap-swr-lower-power¶
IAP-SWRs have lower 150 to 250 Hz power than MAP-SWRs, and MAP & IAP-SWRs the highest; IAP-SWRs show the increase in gamma (about 30 Hz) LFP power characteristic of SWRs.
(Figure 4D; Results, Distinct properties for SWRs, paragraphs 1 and 2; data: with_inputs)
Multitaper power (time-bandwidth 3, 5 tapers) of each CA1 tetrode's stored LFP (the Methods say the CA1 LFP was recorded against a corpus callosum tetrode; the data set does not say how the stored LFP is referenced and holds no ground-referenced LFP), z-scored per frequency over the session, in the window from SWR start to 100 ms after, averaged over the CA1 tetrodes.
print("Mean z-scored 150-250 Hz power in the 100 ms after SWR onset:", {t: round(g.p_rip.mean(), 3) for t, g in G.items()},
"; medians:", {t: round(g.p_rip.median(), 3) for t, g in G.items()}, "; missing (window past the session end):",
int(SWRT.p_rip.isna().sum()))
for x, y in (("IAP", "MAP"), ("IAP", "MAP & IAP"), ("MAP", "MAP & IAP")):
r = stats.ranksums(G[x].p_rip.dropna(), G[y].p_rip.dropna())
print(f" rank-sum {x} vs {y}: z = {r.statistic:.2f}, p = {r.pvalue:.2g}")
g = G["IAP"].p_gam.dropna()
print(f"IAP-SWR mean z power at 25-35 Hz: {g.mean():.3f} (SEM {g.sem():.3f}, n = {len(g)}); one-sample t against 0 p = {stats.ttest_1samp(g, 0).pvalue:.2g}")
print("All groups, 25-35 Hz:", {t: round(v.p_gam.mean(), 3) for t, v in G.items()})
print("Per animal, 150-250 Hz mean:")
print(SWRT[SWRT.type != "none"].groupby(["animal", "type"]).p_rip.mean().round(3).unstack().to_string())
Mean z-scored 150-250 Hz power in the 100 ms after SWR onset: {'IAP': np.float64(0.57), 'MAP': np.float64(1.938), 'MAP & IAP': np.float64(2.146)} ; medians: {'IAP': np.float64(0.174), 'MAP': np.float64(0.882), 'MAP & IAP': np.float64(0.794)} ; missing (window past the session end): 3
rank-sum IAP vs MAP: z = -26.38, p = 2.2e-153
rank-sum IAP vs MAP & IAP: z = -10.57, p = 4.2e-26
rank-sum MAP vs MAP & IAP: z = 0.95, p = 0.34
IAP-SWR mean z power at 25-35 Hz: 0.573 (SEM 0.036, n = 1651); one-sample t against 0 p = 3.8e-54
All groups, 25-35 Hz: {'IAP': np.float64(0.573), 'MAP': np.float64(1.287), 'MAP & IAP': np.float64(1.47)}
Per animal, 150-250 Hz mean:
type IAP MAP MAP & IAP
animal
N2 NaN 3.065 NaN
Q1 NaN 1.513 NaN
S2 0.362 1.894 2.041
T1 0.736 1.960 2.576
Result: partially reproduced. IAP-SWRs have lower 150 to 250 Hz power than MAP-SWRs (p = 2.2e-153) and than MAP & IAP-SWRs (p = 4.2e-26), and their 25 to 35 Hz power is raised (mean 0.573 z, p = 3.8e-54). MAP & IAP-SWRs are not higher than MAP-SWRs (medians 0.794 and 0.882, p = 0.34), so the full order IAP < MAP < MAP & IAP does not hold.
fig4s5-cells-spikes-per-swr¶
IAP-SWRs contain fewer active cells (mean 1.03 against 1.31) and fewer spikes (mean 2.04 against 2.49) than MAP-SWRs.
(Figure 4, supplement 5 legend; data: with_inputs)
cm, ci = G["MAP"].n_map, G["IAP"].n_iap
sm_, si_ = G["MAP"].s_map, G["IAP"].s_iap
print(f"Cells active per SWR: IAP-SWR mean {ci.mean():.2f}, MAP-SWR mean {cm.mean():.2f}; rank-sum p = {stats.ranksums(ci, cm).pvalue:.2g}")
print(f"Spikes per SWR: IAP-SWR mean {si_.mean():.2f}, MAP-SWR mean {sm_.mean():.2f}; rank-sum p = {stats.ranksums(si_, sm_).pvalue:.2g}")
print("Expected 1.03, 1.31, 2.04, 2.49 (10% tolerance); within:",
[abs(x - e) <= 0.1 * e for x, e in zip((ci.mean(), cm.mean(), si_.mean(), sm_.mean()), (1.03, 1.31, 2.04, 2.49))])
print("Per animal means (cells IAP, cells MAP, spikes IAP, spikes MAP):")
for a in ANIMALS:
gi, gm = G["IAP"][G["IAP"].animal == a], G["MAP"][G["MAP"].animal == a]
print(f" {a}: {gi.n_iap.mean():.2f} {gm.n_map.mean():.2f} {gi.s_iap.mean():.2f} {gm.s_map.mean():.2f} (n = {len(gi)}, {len(gm)})")
Cells active per SWR: IAP-SWR mean 1.03, MAP-SWR mean 1.20; rank-sum p = 1.6e-14 Spikes per SWR: IAP-SWR mean 2.12, MAP-SWR mean 2.16; rank-sum p = 0.059 Expected 1.03, 1.31, 2.04, 2.49 (10% tolerance); within: [np.True_, np.True_, np.True_, np.False_] Per animal means (cells IAP, cells MAP, spikes IAP, spikes MAP): T1: 1.05 1.10 2.14 1.90 (n = 919, 1435) S2: 1.00 1.32 2.10 2.28 (n = 732, 2292) Q1: nan 1.08 nan 2.27 (n = 0, 880) R1: nan nan nan nan (n = 0, 0) N2: nan 1.08 nan 2.13 (n = 0, 391)
Result: not reproduced. IAP-SWRs hold fewer active cells than MAP-SWRs (1.03 against 1.20, p = 1.6e-14), but not significantly fewer spikes (2.12 against 2.16, p = 0.059). Three of the four means are within tolerance; the MAP-SWR spike mean (2.16) is below 2.24. The criterion's partial outcome needs both tests to hold.
fig4s67-matched-subsamples¶
IAP-SWRs remain shorter and lower in power than MAP-SWRs after matching the distributions of active cells, or of spikes, per SWR.
(Figure 4, supplements 6 and 7; Results, Distinct properties for SWRs, paragraph 1; data: with_inputs)
rng = np.random.default_rng(67)
def matched_subsamples(var_i, var_m, reading, nsub=1000, ndraw=500):
"""Draws of 500 SWRs from each group so that the distribution of `var` matches; returns p-values and median differences."""
vals = np.union1d(var_i.unique(), var_m.unique())
pi = var_i.value_counts(normalize=True).reindex(vals, fill_value=0).values
pm = var_m.value_counts(normalize=True).reindex(vals, fill_value=0).values
target = pi if reading == "a" else np.minimum(pi, pm)
target = target / target.sum()
wi = (target / np.where(pi > 0, pi, np.inf))[np.searchsorted(vals, var_i.values)]
wm = (target / np.where(pm > 0, pm, np.inf))[np.searchsorted(vals, var_m.values)]
wi, wm = wi / wi.sum(), wm / wm.sum()
out = []
for _ in range(nsub):
ii = rng.choice(len(var_i), ndraw, p=wi)
mm = rng.choice(len(var_m), ndraw, p=wm)
row = {}
for meas in ("dur", "p_rip"):
x, y = G["IAP"][meas].values[ii], G["MAP"][meas].values[mm]
x, y = x[~np.isnan(x)], y[~np.isnan(y)]
row[meas + "_p"] = stats.ranksums(y, x).pvalue
row[meas + "_diff"] = np.median(y) - np.median(x)
out.append(row)
return pd.DataFrame(out)
res67 = []
for match, (vi, vm) in (("cells", (G["IAP"].n_iap, G["MAP"].n_map)), ("spikes", (G["IAP"].s_iap, G["MAP"].s_map))):
for reading in "ab":
d = matched_subsamples(vi.reset_index(drop=True), vm.reset_index(drop=True), reading)
for meas in ("dur", "p_rip"):
res67.append(dict(match=match, reading=reading, measure=meas, median_p=d[meas + "_p"].median(),
frac_p_below_05=(d[meas + "_p"] < 0.05).mean(), frac_map_higher=(d[meas + "_diff"] > 0).mean(),
median_diff=d[meas + "_diff"].median()))
print(pd.DataFrame(res67).round(4).to_string(index=False))
print("Criterion: for both matchings and both measures, median p < 0.05 and MAP-SWR median higher in >= 95% of subsamples, under one reading.")
match reading measure median_p frac_p_below_05 frac_map_higher median_diff cells a dur 0.0 1.0 1.0 0.0167 cells a p_rip 0.0 1.0 1.0 0.6084 cells b dur 0.0 1.0 1.0 0.0170 cells b p_rip 0.0 1.0 1.0 0.6047 spikes a dur 0.0 1.0 1.0 0.0210 spikes a p_rip 0.0 1.0 1.0 0.7025 spikes b dur 0.0 1.0 1.0 0.0207 spikes b p_rip 0.0 1.0 1.0 0.7037 Criterion: for both matchings and both measures, median p < 0.05 and MAP-SWR median higher in >= 95% of subsamples, under one reading.
Result: reproduced on the foraging rats. After matching the distribution of active cells or of spikes per SWR, under both weightings, the median p-value of every comparison of duration and power is below 0.0001, and the MAP-SWR median is higher in all 1000 subsamples.
fig4s8-interspersed¶
There is no strong relation in timing between IAP-SWRs and MAP-SWRs; they are temporally interspersed.
(Figure 4, supplement 8; Results, Distinct properties for SWRs, paragraph 2; data: with_inputs)
Cross-correlogram of IAP-SWR and MAP-SWR starts within each session, 10 ms bins over +-2 s, each bin z-scored against 1000 controls with each MAP-SWR jittered uniformly by up to 1 s either way.
rng = np.random.default_rng(8)
edges = np.arange(-2, 2.0001, 0.01)
cen = 0.5 * (edges[1:] + edges[:-1])
obs = np.zeros(len(cen))
ctrl = np.zeros((1000, len(cen)))
for (a, d, ep), g in SWRT.groupby(["animal", "day", "epoch"]):
ti = np.sort(g.start[g.type == "IAP"].values)
tm = np.sort(g.start[g.type == "MAP"].values)
if not len(ti) or not len(tm):
continue
obs += np.histogram(Y.lags(ti, tm, 2.0), edges)[0]
for k in range(1000):
tms = np.sort(tm + rng.uniform(-1, 1, len(tm)))
ctrl[k] += np.histogram(Y.lags(ti, tms, 2.0), edges)[0]
z = (obs - ctrl.mean(0)) / ctrl.std(0)
out = np.abs(cen) >= 0.2
print(f"Bins with |z| > 2 outside |lag| < 0.2 s: {(np.abs(z[out]) > 2).sum()} of {out.sum()} ({(np.abs(z[out]) > 2).mean():.3f}); "
f"z range {z[out].min():.2f} to {z[out].max():.2f}; inside |lag| < 0.2 s min z {z[~out].min():.2f}")
print("Bins with |z| > 2 within 0.2-1 s and 1-2 s:", int((np.abs(z[(np.abs(cen) >= 0.2) & (np.abs(cen) < 1)]) > 2).sum()),
int((np.abs(z[np.abs(cen) >= 1]) > 2).sum()))
fig, ax = plt.subplots(figsize=(6, 2.5)); ax.plot(cen, z); ax.axhline(2, c="r", ls="--"); ax.axhline(-2, c="r", ls="--")
ax.set_xlabel("MAP-SWR start relative to IAP-SWR start (s)"); ax.set_ylabel("z"); plt.show()
Bins with |z| > 2 outside |lag| < 0.2 s: 18 of 360 (0.050); z range -1.30 to 3.79; inside |lag| < 0.2 s min z -1.29 Bins with |z| > 2 within 0.2-1 s and 1-2 s: 10 8
Result: reproduced on the foraging rats. Outside |lag| < 0.2 s, 18 of 360 bins (0.050) exceed +-2 z, at the 5% bound; z ranges from -1.30 to 3.79. The excess bins are spread over 0.2 to 1 s (10) and 1 to 2 s (8). The claim holds only at the bound, so it rests on the criterion's 5%.
fig4e-iap-spike-earlier¶
In SWRs with both MAPs and IAPs, IAPs spike earlier than MAPs, also after matching the SWR durations from which their spikes come.
(Figure 4E; Figure 4, supplement 9; Results, Distinct properties for SWRs, paragraph 2; data: with_inputs)
rng = np.random.default_rng(4)
both = SWRT[SWRT.type == "MAP & IAP"]
rec = {"IAP": [], "MAP": []}
for (a, d), g in both.groupby(["animal", "day"]):
cs = [c for c in C if c["animal"] == a and c["day"] == d]
for c in cs:
sp = c["spikes"]
lo = np.searchsorted(sp, g.start.values)
hi = np.searchsorted(sp, g.end.values, side="right")
for k in np.flatnonzero(hi > lo):
rel = sp[lo[k]:hi[k]] - g.start.values[k]
for j, r in enumerate(rel):
rec[c["label"]].append((r, j == 0, g.dur.values[k]))
for reading, first in (("(a) all spikes", False), ("(b) first spike of each cell in each SWR", True)):
v = {l: np.array([x[0] for x in rec[l] if (x[1] or not first)]) for l in rec}
du = {l: np.array([x[2] for x in rec[l] if (x[1] or not first)]) for l in rec}
r = stats.ranksums(v["IAP"], v["MAP"])
# matched: resample spikes so that the durations of their SWRs follow the overlap of the two distributions
bins = np.arange(0, max(du["IAP"].max(), du["MAP"].max()) + 0.02, 0.02)
hi_, hm_ = np.histogram(du["IAP"], bins, density=True)[0], np.histogram(du["MAP"], bins, density=True)[0]
tgt = np.minimum(hi_, hm_)
ps = []
for _ in range(200):
sel = {}
for l, hh in (("IAP", hi_), ("MAP", hm_)):
b = np.clip(np.digitize(du[l], bins) - 1, 0, len(tgt) - 1)
w = tgt[b] / np.where(hh[b] > 0, hh[b], np.inf)
sel[l] = v[l][rng.choice(len(v[l]), len(v[l]), p=w / w.sum())]
ps.append((stats.ranksums(sel["IAP"], sel["MAP"]).pvalue, np.median(sel["IAP"]) - np.median(sel["MAP"])))
ps = np.array(ps)
print(f"{reading}: median time from SWR start IAP {1000 * np.median(v['IAP']):.1f} ms (n = {len(v['IAP'])}), MAP {1000 * np.median(v['MAP']):.1f} ms "
f"(n = {len(v['MAP'])}); rank-sum p = {r.pvalue:.2g}. Duration-matched (200 resamples): median p = {np.median(ps[:, 0]):.2g}, "
f"IAP earlier in {(ps[:, 1] < 0).mean():.2f} of resamples")
print("MAP & IAP-SWRs:", len(both))
(a) all spikes: median time from SWR start IAP 31.8 ms (n = 699), MAP 51.2 ms (n = 650); rank-sum p = 1e-15. Duration-matched (200 resamples): median p = 4e-07, IAP earlier in 1.00 of resamples (b) first spike of each cell in each SWR: median time from SWR start IAP 20.1 ms (n = 294), MAP 42.9 ms (n = 373); rank-sum p = 7e-14. Duration-matched (200 resamples): median p = 9.4e-09, IAP earlier in 1.00 of resamples MAP & IAP-SWRs: 293
Result: reproduced on the foraging rats. In 293 MAP & IAP-SWRs, IAP spikes come earlier than MAP spikes (medians 31.8 and 51.2 ms after SWR start, p = 1e-15; first spikes 20.1 and 42.9 ms, p = 7e-14), and after matching SWR durations (median p = 4e-07 and 9.4e-09, IAPs earlier in all 200 resamples).
Cell pairs: correlograms and SWR coactivity¶
def mask_spikes(sp, starts, ends):
o = np.argsort(starts)
return sp[Y.in_intervals(sp, np.asarray(starts)[o], np.asarray(ends)[o])]
def union(starts, ends):
o = np.argsort(starts)
s, e = np.asarray(starts)[o], np.asarray(ends)[o]
out = []
for a, b in zip(s, e):
if out and a <= out[-1][1]:
out[-1][1] = max(out[-1][1], b)
else:
out.append([a, b])
out = np.array(out).reshape(-1, 2)
return out[:, 0], out[:, 1]
PREP = {}
for c in C:
a, d = c["animal"], c["day"]
dd = R[a]["days"][d]
tb = TB[a][d]
v = SWRT[(SWRT.animal == a) & (SWRT.day == d)]
nos = c["spikes"][~Y.in_intervals(c["spikes"], v.start.values, v.end.values)] if len(v) else c["spikes"]
per = tb["periods"]
win = {}
vm = visit_mask(per)
for k, t0 in (("entry", per["start"]), ("exit", per["end"]), ("entry_v", per["start"][vm]), ("exit_v", per["end"][vm])):
s, e = union(t0 - 1.5, t0 + 1.5)
win[k] = (s, e)
m, xe, ye = Y.occupancy_map([dict(p) for p in dd["epochs"].values()], c["spikes"])
if np.all(np.isnan(m)):
pk = (np.nan, np.nan)
else:
i, j = np.unravel_index(np.nanargmax(m), m.shape)
pk = (xe[i] + 1, ye[j] + 1)
PREP[id(c)] = dict(nos=nos, win=win, map=m, xe=xe, ye=ye, peak=pk, **{k: mask_spikes(c["spikes"], *win[k]) for k in win})
print("cells prepared:", len(PREP))
# How much of task time the +-1.5 s entry and exit windows cover, per day, for all immobility periods (O1 (b) as
# written) and for well visits (visit_mask, the variant shown below)
cov_rows = []
for a in ANIMALS:
for d, t in TB[a].items():
per = t["periods"]
T_ = sum(t["session_s"].values())
for defn, m in (("all immobility periods", np.ones(len(per["start"]), bool)), ("well visits", visit_mask(per))):
row = dict(animal=a, day=d, definition=defn, n_periods=int(m.sum()))
for k, t0 in (("entry", per["start"][m]), ("exit", per["end"][m]), ("either", np.concatenate([per["start"][m], per["end"][m]]))):
s, e = union(t0 - 1.5, t0 + 1.5)
row[f"cover_{k}"] = (e - s).sum() / T_
cov_rows.append(row)
COV = pd.DataFrame(cov_rows)
print("Fraction of task time inside the +-1.5 s windows, per day (min, median, max):")
print(COV.groupby("definition").agg(periods_median=("n_periods", "median"), **{f"{k}_{f}": (f"cover_{k}", f) for k in ("entry", "exit", "either")
for f in ("min", "median", "max")}).round(3).T.to_string())
cells prepared: 194 Fraction of task time inside the +-1.5 s windows, per day (min, median, max): definition all immobility periods well visits periods_median 946.000 229.000 entry_min 0.300 0.070 entry_median 0.487 0.207 entry_max 0.595 0.305 exit_min 0.307 0.070 exit_median 0.493 0.207 exit_max 0.590 0.299 either_min 0.321 0.087 either_median 0.526 0.254 either_max 0.621 0.373
def pair_type(c1, c2):
return "-".join(sorted([c1["label"], c2["label"]], reverse=True)).replace("MAP-IAP", "MAP-IAP")
edges10 = np.arange(-10, 10.0001, 0.01)
cen10 = 0.5 * (edges10[1:] + edges10[:-1])
prs = []
for (a, d), (cs, M, n) in PARTS.items():
T = SWRT[(SWRT.animal == a) & (SWRT.day == d)]
ep = T.epoch.values
B = M > 0
for i in range(len(cs)):
for j in range(i + 1, len(cs)):
c1, c2 = cs[i], cs[j]
# orient MAP-IAP pairs as MAP relative to IAP (lag = MAP time - IAP time)
if c1["label"] == "MAP" and c2["label"] == "IAP":
c1, c2, bi, bj = c2, c1, B[j], B[i]
else:
bi, bj = B[i], B[j]
P1, P2 = PREP[id(c1)], PREP[id(c2)]
row = dict(animal=a, day=d, type={"IAP-IAP": "IAP-IAP", "MAP-MAP": "MAP-MAP"}.get(c1["label"] + "-" + c2["label"], "MAP-IAP"),
same_tet=c1["tet"] == c2["tet"], z_a=Y.coactivity_z(bi, bj))
zs = [Y.coactivity_z(bi[ep == e], bj[ep == e]) for e in np.unique(ep)]
row["z_b"] = np.nanmean(zs) if np.isfinite(zs).any() else np.nan
# behavioural-scale correlogram of spikes outside SWRs (O7) and the 6.6 s window
l = Y.lags(P1["nos"], P2["nos"], 10.0)
h = np.histogram(l, edges10)[0].astype(float)
hs = gaussian(h, 15)
for name, L in (("off5", 5.0), ("off10", 10.0), ("off33", 3.3)):
m = np.abs(cen10) <= L
row[name] = cen10[m][np.argmax(hs[m])] if h[m].sum() else np.nan
m33 = np.abs(l) <= 3.3
row["n33_nos"] = m33.sum()
row["prop50_nos"] = (np.abs(l) <= 0.05).sum() / max(m33.sum(), 1)
la = Y.lags(c1["spikes"], c2["spikes"], 3.3)
row["n33_all"] = len(la)
row["prop50_all"] = (np.abs(la) <= 0.05).sum() / max(len(la), 1)
for k in ("entry", "exit", "entry_v", "exit_v"):
lw = Y.lags(P1[k], P2[k], 1.5)
row[f"n_{k}"] = len(lw)
hw = np.histogram(lw, np.arange(-1.5, 1.5001, 0.01))[0]
row[f"ccg_{k}"] = hw
ht = np.histogram(lw, np.arange(-0.125, 0.12501, 0.01))[0]
row[f"theta_{k}"] = (np.arange(-0.12, 0.1201, 0.01)[np.argmax(ht)] if ht.sum() else np.nan)
row["dist"] = np.hypot(P1["peak"][0] - P2["peak"][0], P1["peak"][1] - P2["peak"][1]) / 100.0
prs.append(row)
PR = pd.DataFrame(prs)
print("Simultaneously recorded CA1 pyramidal pairs:", PR.type.value_counts().to_dict(), "; same tetrode:", int(PR.same_tet.sum()))
print("Pairs with undefined coactivity (a cell in no SWR, or in all):", int(PR.z_a.isna().sum()))
# O7: the peak offset is the argmax within a truncated window, so a correlogram still rising at the window's edge puts
# its peak there. Histogram of |offset| per window, and the pairs pinned within one smoothing sigma (0.15 s) of the edge.
for off, L in (("off5", 5.0), ("off10", 10.0), ("off33", 3.3)):
PR[f"edge_{off}"] = PR[off].abs() >= L - 0.15
hh = np.histogram(PR[off].abs().dropna(), np.arange(0, L + 0.5, 0.5))[0]
print(f"|{off}| in 0.5 s bins from 0 to {L} s:", hh.tolist(), f"; pinned within 0.15 s of the {L} s edge:",
PR.groupby("type")[f"edge_{off}"].sum().astype(int).to_dict())
Simultaneously recorded CA1 pyramidal pairs: {'MAP-MAP': 722, 'MAP-IAP': 113, 'IAP-IAP': 2} ; same tetrode: 315
Pairs with undefined coactivity (a cell in no SWR, or in all): 0
|off5| in 0.5 s bins from 0 to 5.0 s: [106, 97, 87, 68, 62, 68, 55, 53, 69, 162] ; pinned within 0.15 s of the 5.0 s edge: {'IAP-IAP': 1, 'MAP-IAP': 18, 'MAP-MAP': 78}
|off10| in 0.5 s bins from 0 to 10.0 s: [87, 83, 75, 50, 47, 45, 34, 26, 35, 29, 25, 18, 29, 21, 32, 29, 37, 24, 37, 68] ; pinned within 0.15 s of the 10.0 s edge: {'IAP-IAP': 1, 'MAP-IAP': 12, 'MAP-MAP': 32}
|off33| in 0.5 s bins from 0 to 3.3 s: [127, 121, 109, 82, 94, 118, 172] ; pinned within 0.15 s of the 3.3 s edge: {'IAP-IAP': 1, 'MAP-IAP': 29, 'MAP-MAP': 108}
fig2c-continuous-transition¶
MAP and IAP spiking overlap in time as the animal enters and leaves a reward well, so the MAP-relative-to-IAP cross-correlogram has a tail extending beyond 0 s lag, a smooth and not an abrupt transition.
(Figure 2C; Results, Smooth transition between CA1 movement and immobility spatial representations, paragraph 2; data: with_inputs)
Spikes within 1.5 s of any entry (or exit) form the trains; their cross-correlogram over +-1.5 s
lags, MAP time minus IAP time, 10 ms bins. Restricting spikes to the union of the windows, and not
pairing spikes window by window, is a standard choice. Entries and exits are the starts and ends of
every immobility period (O1 (b) as the claims file writes it); the outcome rests on these. Their
windows cover 32 to 62% of task time (median 53%). Well visits (visit_mask, immobility periods of at
least 0.5 s within 15 cm of a well, not a reading in the claims file), whose windows cover 9 to 37%
(median 25%), are a variant.
fig, ax = plt.subplots(2, 2, figsize=(10, 5.5))
lagc = np.arange(-1.495, 1.5, 0.01)
for r_, (defn, sfx) in enumerate((("all immobility periods (O1 b as written)", ""), ("well visits (variant)", "_v"))):
for k, (name, rng_) in enumerate((("entry", (0, 0.5)), ("exit", (-0.5, 0)))):
col = name + sfx
sel = PR[(PR.type == "MAP-IAP") & (PR[f"n_{col}"] > 100)]
H = np.array([h / h.sum() for h in sel[f"ccg_{col}"]])
if len(H) == 0:
print(defn, name, "no pairs"); continue
med = np.median(H, 0)
iqr = np.percentile(H, 75, 0) - np.percentile(H, 25, 0)
lo = med - 1.58 * iqr / np.sqrt(len(H))
m = (lagc >= rng_[0]) & (lagc <= rng_[1])
other = (lagc > 0) if name == "exit" else (lagc < 0)
print(f"{defn}, {name}: MAP-IAP pairs with > 100 coincident events: {len(H)} (paper, both tasks: {207 if name == 'entry' else 217}); "
f"bins in {rng_} s with lower notch > 0: {(lo[m] > 0).sum()} of {m.sum()} ({(lo[m] > 0).mean():.2f})")
print(f" lower notch > 0 in the bins from 0 to 0.5 s on the other side of zero lag: {(lo[other & (np.abs(lagc) <= 0.5)] > 0).mean():.2f}; "
f"median CCG range {med.min():.4f} to {med.max():.4f}; median CCG summed over 0 to 0.5 s on the criterion's side "
f"{med[m].sum():.3f}, on the other side {med[other & (np.abs(lagc) <= 0.5)].sum():.3f}")
ax[r_, k].plot(lagc, med, c="k"); ax[r_, k].fill_between(lagc, lo, med + 1.58 * iqr / np.sqrt(len(H)), alpha=0.3)
ax[r_, k].set_title(f"{name}, {defn}", fontsize=9); ax[r_, k].set_xlabel("MAP time - IAP time (s)")
plt.tight_layout(); plt.show()
all immobility periods (O1 b as written), entry: MAP-IAP pairs with > 100 coincident events: 94 (paper, both tasks: 207); bins in (0, 0.5) s with lower notch > 0: 50 of 50 (1.00) lower notch > 0 in the bins from 0 to 0.5 s on the other side of zero lag: 1.00; median CCG range 0.0010 to 0.0040; median CCG summed over 0 to 0.5 s on the criterion's side 0.132, on the other side 0.148 all immobility periods (O1 b as written), exit: MAP-IAP pairs with > 100 coincident events: 93 (paper, both tasks: 217); bins in (-0.5, 0) s with lower notch > 0: 50 of 50 (1.00) lower notch > 0 in the bins from 0 to 0.5 s on the other side of zero lag: 1.00; median CCG range 0.0011 to 0.0038; median CCG summed over 0 to 0.5 s on the criterion's side 0.146, on the other side 0.138 well visits (variant), entry: MAP-IAP pairs with > 100 coincident events: 81 (paper, both tasks: 207); bins in (0, 0.5) s with lower notch > 0: 46 of 50 (0.92) lower notch > 0 in the bins from 0 to 0.5 s on the other side of zero lag: 0.94; median CCG range 0.0000 to 0.0044; median CCG summed over 0 to 0.5 s on the criterion's side 0.107, on the other side 0.147 well visits (variant), exit: MAP-IAP pairs with > 100 coincident events: 81 (paper, both tasks: 217); bins in (-0.5, 0) s with lower notch > 0: 50 of 50 (1.00) lower notch > 0 in the bins from 0 to 0.5 s on the other side of zero lag: 0.96; median CCG range 0.0000 to 0.0036; median CCG summed over 0 to 0.5 s on the criterion's side 0.130, on the other side 0.119
Result: reproduced on the foraging rats. With every immobility period (O1 (b) as written), for 94 MAP-IAP pairs at entry and 93 at exit (paper, both tasks: 207 and 217), the lower notch of the median cross-correlogram is above zero in all 50 bins from 0 to 0.5 s at entry and in all 50 bins from -0.5 to 0 s at exit. With the well-visit variant (81 and 81 pairs) it is above zero in 46 of 50 bins at entry and all 50 at exit. The lower notch is also above zero in 0.94 to 1.00 of the bins on the other side of zero lag, and the median correlogram holds about as much mass there (0.148 against 0.132 on the criterion's side at entry, 0.138 against 0.146 at exit, with every immobility period; 0.147 against 0.107 and 0.119 against 0.130 with well visits), so the criterion, as written, does not separate the smooth and abrupt scenarios of Figure 2A-B sharply.
fig2s1cd-theta-autocorrelation¶
During movement (speed > 4 cm/s) around well entry and exit, both MAP and IAP spike autocorrelations show peaks at theta intervals (0.125 s), which are less prominent during immobility (speed < 1 cm/s).
(Figure 2, supplement 1C-D legend; Results, Smooth transition, paragraph 3; data: with_inputs)
edges_a = np.arange(-0.5, 0.5001, 0.01)
cen_a = 0.5 * (edges_a[1:] + edges_a[:-1])
acg = {}
for c in C:
a, d = c["animal"], c["day"]
for k in ("entry", "exit", "entry_v", "exit_v"):
sp = PREP[id(c)][k]
spd = np.zeros(len(sp))
for p in R[a]["days"][d]["epochs"].values():
m = (sp >= p["t"][0]) & (sp <= p["t"][-1])
spd[m] = np.interp(sp[m], p["t"], p["speed"])
for state, sm in (("move", spd > 4), ("still", spd < 1)):
s = sp[sm]
l = Y.lags(s, s, 0.5)
l = l[l != 0]
h = np.histogram(l, edges_a)[0]
if h.sum() > 100:
acg.setdefault((c["label"], k, state), []).append(h / h.sum())
def theta_depth(mean_acg):
pos = cen_a > 0
x, y = cen_a[pos], mean_acg[pos]
band = (x >= 0.1) & (x <= 0.16)
loc = [i for i in np.flatnonzero(band) if 0 < i < len(y) - 1 and y[i] >= y[i - 1] and y[i] >= y[i + 1]]
if not loc:
return np.nan, np.nan
i = max(loc, key=lambda i: y[i])
return x[i], y[i] - y[:i].min()
for lab in ("MAP", "IAP"):
for k in ("entry", "exit", "entry_v", "exit_v"):
out = []
for state in ("move", "still"):
A_ = acg.get((lab, k, state), [])
if A_:
lag, dep = theta_depth(np.mean(A_, 0))
out.append(f"{state}: n = {len(A_)}, theta peak at {lag:.3f} s, depth {dep:.5f}" if np.isfinite(dep) else f"{state}: n = {len(A_)}, no local maximum in 0.10-0.16 s")
else:
out.append(f"{state}: no cells with > 100 coincident events")
print(f"{lab} {k.replace('_v', ' (well visits, variant)') if k.endswith('_v') else k + ' (all immobility periods, O1 b as written)'}: " + "; ".join(out))
MAP entry (all immobility periods, O1 b as written): move: n = 150, theta peak at 0.115 s, depth 0.00653; still: n = 54, theta peak at 0.135 s, depth 0.00140 MAP exit (all immobility periods, O1 b as written): move: n = 151, theta peak at 0.115 s, depth 0.00636; still: n = 51, theta peak at 0.135 s, depth 0.00193 MAP entry (well visits, variant): move: n = 68, theta peak at 0.105 s, depth 0.00479; still: n = 39, theta peak at 0.135 s, depth 0.00244 MAP exit (well visits, variant): move: n = 73, theta peak at 0.105 s, depth 0.00526; still: n = 37, theta peak at 0.135 s, depth 0.00255 IAP entry (all immobility periods, O1 b as written): move: n = 14, theta peak at 0.115 s, depth 0.00104; still: n = 13, theta peak at 0.115 s, depth 0.00043 IAP exit (all immobility periods, O1 b as written): move: n = 14, theta peak at 0.125 s, depth 0.00135; still: n = 13, theta peak at 0.105 s, depth 0.00053 IAP entry (well visits, variant): move: n = 13, theta peak at 0.115 s, depth 0.00089; still: n = 13, theta peak at 0.145 s, depth 0.00093 IAP exit (well visits, variant): move: n = 13, theta peak at 0.125 s, depth 0.00147; still: n = 13, theta peak at 0.145 s, depth 0.00119
Result: reproduced on the foraging rats. With every immobility period (O1 (b) as the claims file writes it), the mean autocorrelation at speed
4 cm/s has a local maximum between 0.115 and 0.125 s for MAPs and IAPs at entry and exit, and its depth is larger than at speed < 1 cm/s in all four cases (MAP 0.00653 against 0.00140 at entry and 0.00636 against 0.00193 at exit; IAP 0.00104 against 0.00043 and 0.00135 against 0.00053), so the criterion holds under the claims file's reading. The IAP depths are small (14 IAPs, from T1 and S2). The entry and exit windows cover about half of task time, so the test only weakly isolates the periods around transitions. With the well-visit variant (68 and 73 MAPs, 13 IAPs), which is not a reading in the claims file, three of four hold: MAPs at entry (0.00479 against 0.00244) and exit (0.00526 against 0.00255) and IAPs at exit (0.00147 against 0.00119), not IAPs at entry (0.00089 against 0.00093), a near tie on small IAP depths. The outcome was partially reproduced after round 1, on the well visits; the third verification round agreed to take it from the claims file's reading. If the claims file's O1 (b) is revised to well visits (asked in
questions/crcns-hc-13.yaml), this outcome should be tested again.
fig2s1ij-theta-behavior-correlation¶
Cross-correlation peak offsets of cell pairs on the theta time scale are significantly correlated with their peak offsets on the behavioral time scale of seconds.
(Figure 2, supplement 1I-J legend; data: with_inputs)
Theta-scale peak: the largest bin of the +-125 ms correlogram (10 ms bins) of spikes within the entry (exit) windows. Behavioural peak: the peak of the +-3.3 s correlogram of spikes outside SWRs, smoothed with a Gaussian of sigma 150 ms (legend).
for defn, sfx in (("all immobility periods (O1 b as written)", ""), ("well visits (variant)", "_v")):
for edge in (False, True):
for k in ("entry", "exit"):
for t in ("MAP-IAP", "MAP-MAP"):
col = k + sfx
sel = PR[(PR.type == t) & (PR[f"n_{col}"] > 100)].dropna(subset=[f"theta_{col}", "off33"])
if edge:
sel = sel[~sel.edge_off33]
if len(sel) < 3:
print(defn, k, t, "pairs:", len(sel)); continue
pr = stats.pearsonr(sel[f"theta_{col}"], sel.off33)
sr = stats.spearmanr(sel[f"theta_{col}"], sel.off33)
print(f"{defn}{', pairs pinned at the 3.3 s edge left out' if edge else ''}, {k} {t}: n = {len(sel)}, "
f"Pearson r = {pr.statistic:.3f} (p = {pr.pvalue:.2g}), Spearman rho = {sr.statistic:.3f} (p = {sr.pvalue:.2g})")
all immobility periods (O1 b as written), entry MAP-IAP: n = 92, Pearson r = 0.030 (p = 0.78), Spearman rho = -0.014 (p = 0.9) all immobility periods (O1 b as written), entry MAP-MAP: n = 248, Pearson r = -0.052 (p = 0.41), Spearman rho = -0.034 (p = 0.59) all immobility periods (O1 b as written), exit MAP-IAP: n = 92, Pearson r = -0.027 (p = 0.8), Spearman rho = -0.068 (p = 0.52) all immobility periods (O1 b as written), exit MAP-MAP: n = 252, Pearson r = 0.001 (p = 0.99), Spearman rho = 0.012 (p = 0.85) all immobility periods (O1 b as written), pairs pinned at the 3.3 s edge left out, entry MAP-IAP: n = 72, Pearson r = -0.060 (p = 0.62), Spearman rho = -0.097 (p = 0.42) all immobility periods (O1 b as written), pairs pinned at the 3.3 s edge left out, entry MAP-MAP: n = 220, Pearson r = -0.061 (p = 0.37), Spearman rho = -0.046 (p = 0.5) all immobility periods (O1 b as written), pairs pinned at the 3.3 s edge left out, exit MAP-IAP: n = 72, Pearson r = -0.137 (p = 0.25), Spearman rho = -0.177 (p = 0.14) all immobility periods (O1 b as written), pairs pinned at the 3.3 s edge left out, exit MAP-MAP: n = 224, Pearson r = 0.020 (p = 0.77), Spearman rho = 0.027 (p = 0.69) well visits (variant), entry MAP-IAP: n = 79, Pearson r = 0.047 (p = 0.68), Spearman rho = -0.035 (p = 0.76) well visits (variant), entry MAP-MAP: n = 99, Pearson r = -0.025 (p = 0.81), Spearman rho = -0.003 (p = 0.98) well visits (variant), exit MAP-IAP: n = 78, Pearson r = 0.072 (p = 0.53), Spearman rho = 0.037 (p = 0.75) well visits (variant), exit MAP-MAP: n = 93, Pearson r = 0.076 (p = 0.47), Spearman rho = 0.093 (p = 0.38) well visits (variant), pairs pinned at the 3.3 s edge left out, entry MAP-IAP: n = 63, Pearson r = 0.043 (p = 0.74), Spearman rho = 0.006 (p = 0.96) well visits (variant), pairs pinned at the 3.3 s edge left out, entry MAP-MAP: n = 84, Pearson r = -0.063 (p = 0.57), Spearman rho = -0.038 (p = 0.73) well visits (variant), pairs pinned at the 3.3 s edge left out, exit MAP-IAP: n = 63, Pearson r = 0.005 (p = 0.97), Spearman rho = -0.007 (p = 0.95) well visits (variant), pairs pinned at the 3.3 s edge left out, exit MAP-MAP: n = 78, Pearson r = 0.008 (p = 0.95), Spearman rho = 0.018 (p = 0.88)
Result: not reproduced. The theta-scale and behavioural-scale peaks are not correlated. With every immobility period (O1 (b) as written), at entry r = 0.030 (p = 0.78) for 92 MAP-IAP pairs and -0.052 (p = 0.41) for 248 MAP-MAP pairs, at exit -0.027 (p = 0.80) and 0.001 (p = 0.99); with the well-visit variant r = 0.047 (p = 0.68, 79 pairs), -0.025 (p = 0.81, 99), 0.072 (p = 0.53) and 0.076 (p = 0.47). Spearman correlations are as small (p >= 0.38). Leaving out the pairs whose 3.3 s peak is pinned at the window's edge (29 MAP-IAP and 108 MAP-MAP pairs, see the O7 histogram) gives no significant correlation either (p >= 0.14).
fig2s2-fewer-coincident-spikes¶
MAP-IAP pairs have a lower proportion of coincident spikes (within +-50 ms, out of spikes within +-3.3 s) than MAP-MAP or IAP-IAP pairs.
(Figure 2, supplement 2; Results, Smooth transition, paragraph 5; data: with_inputs)
Pairs with more than 100 spike pairs within +-3.3 s (Methods, Cross-correlations).
for rd, col, ncol in (("all task spikes", "prop50_all", "n33_all"), ("spikes outside SWRs", "prop50_nos", "n33_nos")):
sel = PR[PR[ncol] > 100]
g = {t: sel[sel.type == t][col] for t in ("MAP-MAP", "IAP-IAP", "MAP-IAP")}
r1 = stats.ranksums(g["MAP-IAP"], g["MAP-MAP"])
r2 = stats.ranksums(g["MAP-IAP"], g["IAP-IAP"]) if len(g["IAP-IAP"]) else None
print(f"{rd}: medians {{{', '.join(f'{t}: {v.median():.4f} (n = {len(v)})' for t, v in g.items())}}}; "
f"MAP-IAP vs MAP-MAP p = {r1.pvalue:.2g}; vs IAP-IAP p = {r2.pvalue if r2 else np.nan:.2g}")
all task spikes: medians {MAP-MAP: 0.0076 (n = 630), IAP-IAP: 0.0157 (n = 2), MAP-IAP: 0.0075 (n = 112)}; MAP-IAP vs MAP-MAP p = 0.7; vs IAP-IAP p = 0.28
spikes outside SWRs: medians {MAP-MAP: 0.0060 (n = 608), IAP-IAP: 0.0162 (n = 2), MAP-IAP: 0.0077 (n = 111)}; MAP-IAP vs MAP-MAP p = 0.41; vs IAP-IAP p = 0.31
Result: not reproduced. The proportion of spike pairs within +-50 ms is not lower for MAP-IAP pairs: medians 0.0075 (112 pairs) against 0.0076 for MAP-MAP (630) with all task spikes (p = 0.70), and 0.0077 against 0.0060 outside SWRs (p = 0.41). Only 2 IAP-IAP pairs exist (medians about 0.016; p = 0.28 and 0.31).
fig3c-iap-swr-activation¶
IAPs, like MAPs, increase their firing at the start of awake SWRs, both for SWRs at the well where the IAP has its place field and for SWRs elsewhere.
(Figure 3B-C; Results, Separate reactivation of immobility-associated spatial representations, paragraph 1; data: with_inputs)
In-field SWRs of an IAP are those whose start falls nearest its best well; MAP in-field SWRs are those at a position whose occupancy-map rate exceeds 2 Hz (claims file).
def pre_post(c, T):
sp = c["spikes"]
st = T.start.values
pre = np.searchsorted(sp, st) - np.searchsorted(sp, st - 0.25)
post = np.searchsorted(sp, st + 0.25) - np.searchsorted(sp, st)
return pre, post
def map_in_field(c, T):
P = PREP[id(c)]
dd = R[c["animal"]]["days"][c["day"]]
x = np.zeros(len(T)); y = np.zeros(len(T))
for ep, p in dd["epochs"].items():
m = T.epoch.values == ep
x[m] = np.interp(T.start.values[m], p["t"], p["x"]); y[m] = np.interp(T.start.values[m], p["t"], p["y"])
i = np.clip(np.digitize(x, P["xe"]) - 1, 0, P["map"].shape[0] - 1)
j = np.clip(np.digitize(y, P["ye"]) - 1, 0, P["map"].shape[1] - 1)
r = P["map"][i, j]
return np.nan_to_num(r) > 2.0
def fig3c_test(TT, label):
groups = {"MAP not in field": [], "IAP in field": [], "IAP not in field": []}
for c in C:
T = TT[(TT.animal == c["animal"]) & (TT.day == c["day"])]
if not len(T):
continue
pre, post = pre_post(c, T)
if c["label"] == "MAP":
nf = ~map_in_field(c, T)
groups["MAP not in field"].append((pre[nf], post[nf]))
else:
inf = T.well.values == c["best_well"]
groups["IAP in field"].append((pre[inf], post[inf]))
groups["IAP not in field"].append((pre[~inf], post[~inf]))
print(label)
for g, v in groups.items():
v = [x for x in v if len(x[0])]
pm = np.array([x[0].mean() for x in v]) / 0.25
qm = np.array([x[1].mean() for x in v]) / 0.25
ra = stats.ranksums(qm, pm)
pp = np.concatenate([x[0] for x in v]); qq = np.concatenate([x[1] for x in v])
rb = stats.ranksums(qq, pp)
print(f" {g}: cells {len(v)}; mean rate 250 ms before {pm.mean():.2f} Hz, after {qm.mean():.2f} Hz; "
f"(a) rank-sum over cells p = {ra.pvalue:.2g}; (b) over SWRs (n = {len(pp)}) p = {rb.pvalue:.2g}; "
f"cells with post > pre {np.mean(qm > pm):.2f}")
fig3c_test(SWRT, "SWRs as the claims file reads the Methods (O5 a):")
fig3c_test(SWRT_3, "Sensitivity, fixed 3 SD threshold (not the paper's method):")
SWRs as the claims file reads the Methods (O5 a): MAP not in field: cells 180; mean rate 250 ms before 0.14 Hz, after 0.25 Hz; (a) rank-sum over cells p = 9e-11; (b) over SWRs (n = 277717) p = 1.7e-16; cells with post > pre 0.92 IAP in field: cells 14; mean rate 250 ms before 7.32 Hz, after 6.99 Hz; (a) rank-sum over cells p = 0.63; (b) over SWRs (n = 5151) p = 0.63; cells with post > pre 0.29 IAP not in field: cells 14; mean rate 250 ms before 0.51 Hz, after 0.84 Hz; (a) rank-sum over cells p = 0.089; (b) over SWRs (n = 14135) p = 0.0044; cells with post > pre 1.00 Sensitivity, fixed 3 SD threshold (not the paper's method): MAP not in field: cells 180; mean rate 250 ms before 0.22 Hz, after 0.79 Hz; (a) rank-sum over cells p = 2.8e-30; (b) over SWRs (n = 27383) p = 3.6e-42; cells with post > pre 0.93 IAP in field: cells 13; mean rate 250 ms before 4.22 Hz, after 4.00 Hz; (a) rank-sum over cells p = 1; (b) over SWRs (n = 605) p = 0.53; cells with post > pre 0.38 IAP not in field: cells 14; mean rate 250 ms before 0.56 Hz, after 1.25 Hz; (a) rank-sum over cells p = 0.38; (b) over SWRs (n = 1551) p = 0.1; cells with post > pre 0.79
Result: partially reproduced. MAPs increase their firing after SWR start for SWRs outside their field (0.14 to 0.25 Hz, 92% of 180 cells; p = 9e-11 over cells, 1.7e-16 over SWRs). IAPs increase for SWRs away from their well (0.51 to 0.84 Hz, all 14 cells; p = 0.089 over cells, 0.0044 over SWRs) but not for SWRs at their well (7.32 to 6.99 Hz, 29% of cells; p = 0.63 under both readings). The criterion needs all three under one reading; two hold under reading (b). With a fixed 3 SD threshold (sensitivity check, not the paper's method) the in-field IAP comparison fails too (4.22 to 4.00 Hz, p = 1 and 0.53), and the not-in-field IAP increase is no longer significant (p = 0.38 and 0.10); the MAP increase holds (p = 2.8e-30).
fig3s3-iap-same-well-coactivity¶
IAP pairs with place fields at the same well are strongly coactive during SWRs, also for SWRs away from their fields, while IAP pairs at different wells are no more coactive than chance.
(Figure 3, supplement 3; Results, Separate reactivation, paragraph 2; data: with_inputs)
iap = []
for (a, d), (cs, M, n) in PARTS.items():
T = SWRT[(SWRT.animal == a) & (SWRT.day == d)]
B = M > 0
for i in range(len(cs)):
for j in range(i + 1, len(cs)):
if cs[i]["label"] == cs[j]["label"] == "IAP":
same = cs[i]["best_well"] == cs[j]["best_well"]
nf = T.well.values != cs[i]["best_well"]
ep = T.epoch.values
zb = np.nanmean([Y.coactivity_z(B[i][ep == e], B[j][ep == e]) for e in np.unique(ep)])
zbn = np.nanmean([Y.coactivity_z(B[i][nf & (ep == e)], B[j][nf & (ep == e)]) for e in np.unique(ep)])
iap.append(dict(same=same, z_all_a=Y.coactivity_z(B[i], B[j]), z_nf_a=Y.coactivity_z(B[i][nf], B[j][nf]),
z_all_b=zb, z_nf_b=zbn))
IP = pd.DataFrame(iap, columns=["same", "z_all_a", "z_nf_a", "z_all_b", "z_nf_b"])
IP["same"] = IP.same.astype(bool)
print("IAP pairs recorded together:", len(IP), "; at the same well:", int(IP.same.sum()))
for rd in ("ab" if len(IP) else ""):
s_all = IP[IP.same][f"z_all_{rd}"].dropna(); s_nf = IP[IP.same][f"z_nf_{rd}"].dropna(); dif = IP[~IP.same][f"z_all_{rd}"].dropna()
if min(len(s_all), len(s_nf), len(dif)) == 0:
print(rd, "groups:", len(s_all), len(s_nf), len(dif)); continue
kw = stats.kruskal(s_all, s_nf, dif)
rs = stats.ranksums(s_all, dif)
sr = stats.wilcoxon(dif) if len(dif) > 1 else None
print(f"O6 ({rd}): same well all SWRs median {s_all.median():.2f} (n = {len(s_all)}), same well not in field {s_nf.median():.2f} (n = {len(s_nf)}), "
f"different wells {dif.median():.2f} (n = {len(dif)}); Kruskal-Wallis p = {kw.pvalue:.2g}; same vs different rank-sum p = {rs.pvalue:.2g}; "
f"different vs 0 signed-rank p = {sr.pvalue if sr else np.nan:.2g}")
print("Paper (both tasks): 12, 11 and 14 pairs.")
IAP pairs recorded together: 2 ; at the same well: 0 a groups: 0 0 2 b groups: 0 0 2 Paper (both tasks): 12, 11 and 14 pairs.
Result: blocked (too few pairs). Only 2 IAP pairs are recorded on the same day, both at different wells, against the paper's 12, 11 and 14 pairs over both tasks; no test can be run.
fig4b-coactivity¶
Among pairs coactive within 3.3 s during the task, MAP-IAP pairs have lower SWR coactivity than MAP-MAP or IAP-IAP pairs.
(Figure 4B; Results, Separate reactivation, paragraph 4; data: with_inputs)
O7: peak of the smoothed correlogram (10 ms bins, sigma 150 ms) of spikes outside SWRs within +-5 s (a) or +-10 s (b); pairs with |peak| < 3.3 s. O6: z over all SWRs of the day (a) or per session, averaged (b).
def three_way(df, zcol):
g = {t: df[df.type == t][zcol].dropna() for t in ("MAP-MAP", "IAP-IAP", "MAP-IAP")}
r1 = stats.ranksums(g["MAP-IAP"], g["MAP-MAP"])
r2 = stats.ranksums(g["MAP-IAP"], g["IAP-IAP"]) if len(g["IAP-IAP"]) else None
return g, r1, r2
for off in ("off5", "off10"):
for zc in ("z_a", "z_b"):
sel = PR[PR[off].abs() < 3.3]
g, r1, r2 = three_way(sel, zc)
print(f"O7 {off[3:]} s, O6 ({zc[-1]}): medians {{{', '.join(f'{t}: {v.median():.2f} (n = {len(v)})' for t, v in g.items())}}}; "
f"MAP-IAP vs MAP-MAP p = {r1.pvalue:.2g}, vs IAP-IAP p = {r2.pvalue if r2 else np.nan:.2g}")
print("Per animal (O7 5 s, O6 a), medians:")
print(PR[PR.off5.abs() < 3.3].groupby(["animal", "type"]).z_a.median().round(2).unstack().to_string())
O7 5 s, O6 (a): medians {MAP-MAP: 1.58 (n = 466), IAP-IAP: -0.48 (n = 1), MAP-IAP: -0.01 (n = 54)}; MAP-IAP vs MAP-MAP p = 2.3e-05, vs IAP-IAP p = 0.66
O7 5 s, O6 (b): medians {MAP-MAP: 0.83 (n = 465), IAP-IAP: -1.85 (n = 1), MAP-IAP: 0.08 (n = 54)}; MAP-IAP vs MAP-MAP p = 0.00015, vs IAP-IAP p = 0.12
O7 10 s, O6 (a): medians {MAP-MAP: 1.99 (n = 369), IAP-IAP: nan (n = 0), MAP-IAP: 0.49 (n = 35)}; MAP-IAP vs MAP-MAP p = 0.0037, vs IAP-IAP p = nan
O7 10 s, O6 (b): medians {MAP-MAP: 1.12 (n = 368), IAP-IAP: nan (n = 0), MAP-IAP: 0.53 (n = 35)}; MAP-IAP vs MAP-MAP p = 0.016, vs IAP-IAP p = nan
Per animal (O7 5 s, O6 a), medians:
type IAP-IAP MAP-IAP MAP-MAP
animal
N2 NaN NaN 3.84
Q1 NaN NaN -0.04
S2 NaN 0.58 1.74
T1 -0.48 -0.31 0.54
Result: partially reproduced. Among pairs with peak offsets within 3.3 s, MAP-IAP pairs have lower coactivity than MAP-MAP pairs under every reading (medians -0.01 against 1.58, p = 2.3e-05, O7 5 s and O6 a; p = 0.00015 to 0.016 under the others). The comparison with IAP-IAP pairs cannot be made: one IAP-IAP pair passes (z = -0.48; p = 0.66).
fig4s1b-offset-matched-coactivity¶
When matched for the offset of the cross-correlation peak, MAP-MAP pairs still have higher SWR coactivity than MAP-IAP pairs, significantly so in each 1 s bin from 1 to 5 s.
(Figure 4, supplement 1B legend; data: with_inputs)
for off, edge in (("off5", False), ("off5", True), ("off10", False)):
for zc in ("z_a", "z_b"):
out = []
base = PR[~PR[f"edge_{off}"]] if edge else PR
for lo in range(5):
sel = base[(base[off].abs() >= lo) & (base[off].abs() < lo + 1)]
mm, mi = sel[sel.type == "MAP-MAP"][zc].dropna(), sel[sel.type == "MAP-IAP"][zc].dropna()
p = stats.ranksums(mm, mi).pvalue if len(mm) and len(mi) else np.nan
out.append(f"{lo}-{lo + 1} s: MM {mm.mean():.2f} (n = {len(mm)}) MI {mi.mean():.2f} (n = {len(mi)}) p = {p:.2g}")
print(f"O7 {off[3:]} s{' with pairs pinned at the 5 s edge left out' if edge else ''}, O6 ({zc[-1]}): " + "; ".join(out))
O7 5 s, O6 (a): 0-1 s: MM 3.82 (n = 183) MI 1.79 (n = 20) p = 0.0055; 1-2 s: MM 2.39 (n = 138) MI 0.30 (n = 17) p = 0.02; 2-3 s: MM 1.47 (n = 117) MI 0.00 (n = 13) p = 0.037; 3-4 s: MM 1.15 (n = 86) MI 0.03 (n = 21) p = 0.0018; 4-5 s: MM 0.98 (n = 189) MI -0.42 (n = 41) p = 8.6e-06 O7 5 s, O6 (b): 0-1 s: MM 2.25 (n = 182) MI 0.96 (n = 20) p = 0.008; 1-2 s: MM 1.42 (n = 138) MI 0.22 (n = 17) p = 0.035; 2-3 s: MM 0.91 (n = 117) MI 0.13 (n = 13) p = 0.074; 3-4 s: MM 0.73 (n = 86) MI 0.26 (n = 21) p = 0.02; 4-5 s: MM 0.65 (n = 188) MI -0.29 (n = 41) p = 1.9e-05 O7 5 s with pairs pinned at the 5 s edge left out, O6 (a): 0-1 s: MM 3.82 (n = 183) MI 1.79 (n = 20) p = 0.0055; 1-2 s: MM 2.39 (n = 138) MI 0.30 (n = 17) p = 0.02; 2-3 s: MM 1.47 (n = 117) MI 0.00 (n = 13) p = 0.037; 3-4 s: MM 1.15 (n = 86) MI 0.03 (n = 21) p = 0.0018; 4-5 s: MM 1.08 (n = 111) MI -0.38 (n = 23) p = 0.0004 O7 5 s with pairs pinned at the 5 s edge left out, O6 (b): 0-1 s: MM 2.25 (n = 182) MI 0.96 (n = 20) p = 0.008; 1-2 s: MM 1.42 (n = 138) MI 0.22 (n = 17) p = 0.035; 2-3 s: MM 0.91 (n = 117) MI 0.13 (n = 13) p = 0.074; 3-4 s: MM 0.73 (n = 86) MI 0.26 (n = 21) p = 0.02; 4-5 s: MM 0.69 (n = 111) MI -0.24 (n = 23) p = 0.00047 O7 10 s, O6 (a): 0-1 s: MM 4.29 (n = 155) MI 2.55 (n = 15) p = 0.041; 1-2 s: MM 2.55 (n = 116) MI 0.77 (n = 9) p = 0.19; 2-3 s: MM 1.55 (n = 83) MI 0.32 (n = 9) p = 0.14; 3-4 s: MM 1.18 (n = 47) MI 0.20 (n = 13) p = 0.014; 4-5 s: MM 1.13 (n = 56) MI 0.16 (n = 8) p = 0.25 O7 10 s, O6 (b): 0-1 s: MM 2.52 (n = 154) MI 1.34 (n = 15) p = 0.041; 1-2 s: MM 1.53 (n = 116) MI 0.59 (n = 9) p = 0.38; 2-3 s: MM 0.96 (n = 83) MI 0.36 (n = 9) p = 0.27; 3-4 s: MM 0.75 (n = 47) MI 0.39 (n = 13) p = 0.066; 4-5 s: MM 0.82 (n = 56) MI 0.13 (n = 8) p = 0.2
Result: reproduced on the foraging rats, under O7 (a) and O6 (a). MAP-MAP pairs have higher mean coactivity than MAP-IAP pairs in every 1 s bin, with p = 0.02, 0.037, 0.0018 and 8.6e-06 in the bins from 1 to 5 s. The 4 to 5 s bin holds 189 MAP-MAP pairs against 86 in the 3 to 4 s bin, because pairs whose correlogram still rises at the 5 s edge are pinned there (162 pairs in the last 0.5 s bin, 97 within 0.15 s of the edge; O7 histogram above). Leaving out the pinned pairs leaves 111 MAP-MAP and 23 MAP-IAP pairs in that bin and it still passes (p = 0.0004), so the four bins hold without them. Under O6 (b) one bin misses (2 to 3 s, p = 0.074). With the +-10 s window (O7 b), 8 to 13 MAP-IAP pairs per bin, only the 3 to 4 s bin is significant under O6 (a) (p = 0.014), and no bin from 1 to 5 s is under O6 (b) (3 to 4 s, p = 0.066). The criterion asks for one reading, and O7 (a) with O6 (a) is the only one that passes.
fig4s2c-spatial-proximity-control¶
Among pairs with place field peaks less than 0.5 m apart, MAP-IAP pairs still have lower SWR coactivity than MAP-MAP and IAP-IAP pairs, and MAP-MAP pairs have higher coactivity than MAP-IAP pairs at every field distance up to 1 m.
(Figure 4, supplement 2B-C legend; data: with_inputs)
for zc in ("z_a", "z_b"):
out = []
for lo in (0, 0.25, 0.5, 0.75):
sel = PR[(PR.dist >= lo) & (PR.dist < lo + 0.25)]
mm, mi = sel[sel.type == "MAP-MAP"][zc].dropna(), sel[sel.type == "MAP-IAP"][zc].dropna()
p = stats.ranksums(mm, mi).pvalue if len(mm) and len(mi) else np.nan
out.append(f"{lo}-{lo + 0.25} m: MM {mm.mean():.2f} (n = {len(mm)}) MI {mi.mean():.2f} (n = {len(mi)}) p = {p:.2g}")
print(f"Panel B, O6 ({zc[-1]}): " + "; ".join(out))
sel = PR[PR.dist < 0.5]
g, r1, r2 = three_way(sel, zc)
kw = stats.kruskal(*[v for v in g.values() if len(v)])
print(f"Panel C, O6 ({zc[-1]}): medians {{{', '.join(f'{t}: {v.median():.2f} (n = {len(v)})' for t, v in g.items())}}}; KW p = {kw.pvalue:.2g}; "
f"MAP-IAP vs MAP-MAP p = {r1.pvalue:.2g}, vs IAP-IAP p = {r2.pvalue if r2 else np.nan:.2g}")
Panel B, O6 (a): 0-0.25 m: MM 3.09 (n = 48) MI 0.85 (n = 3) p = 0.38; 0.25-0.5 m: MM 2.63 (n = 93) MI 1.04 (n = 4) p = 0.54; 0.5-0.75 m: MM 2.56 (n = 130) MI -0.24 (n = 18) p = 0.0019; 0.75-1.0 m: MM 2.72 (n = 144) MI 0.64 (n = 15) p = 0.011
Panel C, O6 (a): medians {MAP-MAP: 1.60 (n = 141), IAP-IAP: nan (n = 0), MAP-IAP: 0.51 (n = 7)}; KW p = 0.28; MAP-IAP vs MAP-MAP p = 0.28, vs IAP-IAP p = nan
Panel B, O6 (b): 0-0.25 m: MM 1.73 (n = 46) MI 0.61 (n = 3) p = 0.34; 0.25-0.5 m: MM 1.64 (n = 93) MI 0.57 (n = 4) p = 0.5; 0.5-0.75 m: MM 1.59 (n = 126) MI -0.05 (n = 18) p = 0.0014; 0.75-1.0 m: MM 1.58 (n = 144) MI 0.43 (n = 15) p = 0.016
Panel C, O6 (b): medians {MAP-MAP: 0.93 (n = 139), IAP-IAP: nan (n = 0), MAP-IAP: 0.21 (n = 7)}; KW p = 0.22; MAP-IAP vs MAP-MAP p = 0.22, vs IAP-IAP p = nan
Result: not reproduced. MAP-MAP pairs have higher mean coactivity than MAP-IAP pairs in all four distance bins, but the difference is significant only from 0.5 to 1 m (p = 0.0019 and 0.011); below 0.5 m there are 3 and 4 MAP-IAP pairs (p = 0.38 and 0.54). Among pairs closer than 0.5 m (panel C), 7 MAP-IAP pairs do not differ from 141 MAP-MAP pairs (p = 0.28), and no IAP-IAP pair is that close.
fig4s3-overlapping-pairs¶
MAP-IAP pairs whose spikes overlap during the transition at well entry or exit still have lower SWR coactivity than MAP-MAP and IAP-IAP pairs.
(Figure 4, supplement 3; Results, Separate reactivation, paragraph 4; data: with_inputs)
for defn, sfx in (("all immobility periods (O1 b as written)", ""), ("well visits (variant)", "_v")):
for zc in ("z_a", "z_b"):
for k in ("entry", "exit"):
sel = PR[PR[f"n_{k}{sfx}"] > 100]
g, r1, r2 = three_way(sel, zc)
lower = lambda x, y: "lower" if g["MAP-IAP"].median() < g[y].median() else "not lower"
print(f"{defn}, O6 ({zc[-1]}) {k}: medians {{{', '.join(f'{t}: {v.median():.2f} (n = {len(v)})' for t, v in g.items())}}}; "
f"MAP-IAP vs MAP-MAP p = {r1.pvalue:.2g} (MAP-IAP {lower(0, 'MAP-MAP')}), "
f"vs IAP-IAP p = {r2.pvalue if r2 else np.nan:.2g} (MAP-IAP {lower(0, 'IAP-IAP') if r2 else 'n/a'})")
all immobility periods (O1 b as written), O6 (a) entry: medians {MAP-MAP: 1.47 (n = 249), IAP-IAP: -1.60 (n = 2), MAP-IAP: -0.31 (n = 94)}; MAP-IAP vs MAP-MAP p = 9.9e-09 (MAP-IAP lower), vs IAP-IAP p = 0.23 (MAP-IAP not lower)
all immobility periods (O1 b as written), O6 (a) exit: medians {MAP-MAP: 1.36 (n = 253), IAP-IAP: -1.60 (n = 2), MAP-IAP: -0.31 (n = 93)}; MAP-IAP vs MAP-MAP p = 3e-08 (MAP-IAP lower), vs IAP-IAP p = 0.22 (MAP-IAP not lower)
all immobility periods (O1 b as written), O6 (b) entry: medians {MAP-MAP: 0.82 (n = 248), IAP-IAP: -1.75 (n = 2), MAP-IAP: -0.14 (n = 94)}; MAP-IAP vs MAP-MAP p = 1.9e-07 (MAP-IAP lower), vs IAP-IAP p = 0.027 (MAP-IAP not lower)
all immobility periods (O1 b as written), O6 (b) exit: medians {MAP-MAP: 0.78 (n = 252), IAP-IAP: -1.75 (n = 2), MAP-IAP: -0.13 (n = 93)}; MAP-IAP vs MAP-MAP p = 5.3e-07 (MAP-IAP lower), vs IAP-IAP p = 0.028 (MAP-IAP not lower)
well visits (variant), O6 (a) entry: medians {MAP-MAP: 1.14 (n = 99), IAP-IAP: -1.60 (n = 2), MAP-IAP: -0.31 (n = 81)}; MAP-IAP vs MAP-MAP p = 2.6e-05 (MAP-IAP lower), vs IAP-IAP p = 0.23 (MAP-IAP not lower)
well visits (variant), O6 (a) exit: medians {MAP-MAP: 1.03 (n = 95), IAP-IAP: -1.60 (n = 2), MAP-IAP: -0.11 (n = 81)}; MAP-IAP vs MAP-MAP p = 0.00028 (MAP-IAP lower), vs IAP-IAP p = 0.21 (MAP-IAP not lower)
well visits (variant), O6 (b) entry: medians {MAP-MAP: 0.78 (n = 99), IAP-IAP: -1.75 (n = 2), MAP-IAP: -0.07 (n = 81)}; MAP-IAP vs MAP-MAP p = 0.00017 (MAP-IAP lower), vs IAP-IAP p = 0.03 (MAP-IAP not lower)
well visits (variant), O6 (b) exit: medians {MAP-MAP: 0.76 (n = 95), IAP-IAP: -1.75 (n = 2), MAP-IAP: -0.06 (n = 81)}; MAP-IAP vs MAP-MAP p = 0.001 (MAP-IAP lower), vs IAP-IAP p = 0.03 (MAP-IAP not lower)
Result: partially reproduced. Among pairs with overlapping spikes, MAP-IAP pairs have lower coactivity than MAP-MAP pairs at entry and at exit: with every immobility period (O1 (b) as written) p = 9.9e-09 and 3e-08 (O6 a), with the well-visit variant p = 2.6e-05 and 0.00028 (O6 a; 81 MAP-IAP against 99 and 95 MAP-MAP pairs). They are not lower than the 2 IAP-IAP pairs, whose medians are -1.60 (O6 a) and -1.75 (O6 b), against MAP-IAP medians of -0.31 to -0.06. Under O6 (b) the IAP-IAP comparison gives p = 0.027 and 0.028 (all periods) and 0.03 (well visits), but in the wrong direction: MAP-IAP pairs are higher. Two of the four comparisons hold, under each reading and each definition of entry.
PFC¶
def day_spikes(u, dd):
return np.sort(np.concatenate([u["spikes"].get(ep, np.zeros(0)) for ep in dd["epochs"]]))
PFC = []
for a in ANIMALS:
for u in R[a]["units"]:
if u["area"] != "PFC":
continue
dd = R[a]["days"][u["day"]]
sp = day_spikes(u, dd)
tm = ti = nm = ni = 0
for p in dd["epochs"].values():
s = sp[(sp >= p["t"][0]) & (sp <= p["t"][-1])]
spd = np.interp(s, p["t"], p["speed"])
dt = np.gradient(p["t"])
tm += dt[p["speed"] > 4].sum(); ti += dt[p["speed"] < 4].sum()
nm += (spd > 4).sum(); ni += (spd < 4).sum()
T = SWRT[(SWRT.animal == a) & (SWRT.day == u["day"])]
both_ep = any(((g.type == "MAP").any() and (g.type == "IAP").any()) for _, g in T.groupby("epoch"))
labs = {c["label"] for c in C if c["animal"] == a and c["day"] == u["day"]}
PFC.append(dict(animal=a, day=u["day"], tet=u["tet"], unit=u["unit"], spikes=sp, n=len(sp),
rate_move=nm / tm if tm else 0, rate_still=ni / ti if ti else 0,
sel_a=both_ep, sel_b={"MAP", "IAP"} <= labs))
PF = pd.DataFrame([{k: v for k, v in p.items() if k != "spikes"} for p in PFC])
PF["active"] = (PF.rate_move > 1) | (PF.rate_still > 1)
pfc-unit-selection¶
Of 712 PFC units, 112 were active in the task (mean rate > 1 Hz during movement or immobility) and recorded in sessions with both MAP- and IAP-SWRs.
(Results, Prefrontal cortical activity changes during SWRs, paragraph 2; Methods, Cell selection; data: dataset)
PFC units are cellinfo units with area PFC, counted per day. The variant uses the CA1 cells selected without the width rule in R1 and N2 to classify SWRs.
print("PFC unit-days in the data set:", len(PF), "; with at least one spike:", int((PF.n > 0).sum()))
print("Active (mean rate > 1 Hz during movement or immobility):", int(PF.active.sum()))
print("Selected, reading (a) a session with at least one MAP-SWR and one IAP-SWR:", int((PF.active & PF.sel_a).sum()))
print("Selected, reading (b) the day has at least one CA1 IAP and one MAP:", int((PF.active & PF.sel_b).sum()))
print("By animal:")
print(PF.assign(sel=PF.active & PF.sel_a).groupby("animal").agg(units=("n", "size"), active=("active", "sum"), selected_a=("sel", "sum")).to_string())
SW_V, _ = swr_table(wv)
nv = 0
for p, (_, r) in zip(PFC, PF.iterrows()):
T = SW_V[(SW_V.animal == p["animal"]) & (SW_V.day == p["day"])]
nv += bool(r.active and any(((g.type == "MAP").any() and (g.type == "IAP").any()) for _, g in T.groupby("epoch")))
print("Variant, CA1 cells without the spike-width rule in R1 and N2 (reading a):", nv)
print("Expected 712 (tolerance 71.2) and 112 (11.2).")
PFC unit-days in the data set: 732 ; with at least one spike: 707
Active (mean rate > 1 Hz during movement or immobility): 349
Selected, reading (a) a session with at least one MAP-SWR and one IAP-SWR: 94
Selected, reading (b) the day has at least one CA1 IAP and one MAP: 94
By animal:
units active selected_a
animal
N2 36 30 0
Q1 24 15 0
R1 224 136 0
S2 175 75 47
T1 273 93 47
Variant, CA1 cells without the spike-width rule in R1 and N2 (reading a): 113 Expected 712 (tolerance 71.2) and 112 (11.2).
Result: partially reproduced. The data set holds 732 PFC unit-days (707 with spikes), within tolerance of 712. Of 349 active units, 94 are selected under either reading, below 100.8: only S2 and T1, the rats with IAPs, contribute. With CA1 cells selected without the width rule in R1 and N2, 113 units are selected, within tolerance.
rng5 = np.random.default_rng(5)
EDGES_P = np.arange(-0.5, 0.5001, 0.01)
def modulation(sp, starts, durs, center="start", nshuf=1000, rng=rng5):
"""SWR modulation index and its significance (Methods, PFC SWR modulation index; Jadhav et al. 2016)."""
md = durs.mean()
if len(starts) == 0:
return np.nan, np.nan
ins = np.searchsorted(sp, starts + md) - np.searchsorted(sp, starts)
c0 = starts if center == "start" else starts + durs / 2
win = np.searchsorted(sp, c0 + 0.5) - np.searchsorted(sp, c0 - 0.5)
r_swr, r_1s = ins.sum() / (md * len(starts)), win.sum() / len(starts)
mi = (r_swr - r_1s) / r_1s if r_1s > 0 else np.nan
t, idx = Y.window_spikes(sp, starts, 0.5)
rel = t - starts[idx]
obs = np.histogram(rel, EDGES_P)[0]
sh = rng.uniform(0, 1, (nshuf, len(starts)))
rs = np.mod(rel[None, :] + 0.5 + sh[:, idx], 1.0) - 0.5
b = np.clip(((rs + 0.5) / 0.01).astype(int), 0, 99)
ctrl = np.zeros((nshuf, 100))
np.add.at(ctrl, (np.repeat(np.arange(nshuf), b.shape[1]), b.ravel()), 1)
mu = ctrl.mean(0)
m = (EDGES_P[:-1] >= 0) & (EDGES_P[:-1] < md)
dev_obs = ((obs[m] - mu[m]) ** 2).sum()
dev_c = ((ctrl[:, m] - mu[m]) ** 2).sum(1)
p = (dev_c > dev_obs).mean()
return mi, p
def mod_table(TT, rng=rng5):
MOD = []
for k, p in enumerate(PFC):
r = PF.iloc[k]
if not (r.active and (r.sel_a or r.sel_b)):
continue
T = TT[(TT.animal == p["animal"]) & (TT.day == p["day"])]
row = dict(k=k, animal=p["animal"], day=p["day"], sel_a=r.sel_a, sel_b=r.sel_b)
for typ, key in (("MAP", "map"), ("IAP", "iap"), ("MAP & IAP", "both")):
g = T[T.type == typ]
for center in ("start", "mid"):
mi, pv = modulation(p["spikes"], g.start.values, g.dur.values, center, rng=rng) if len(g) else (np.nan, np.nan)
row[f"mi_{key}_{center}"] = mi
if center == "start":
row[f"p_{key}"] = pv
row[f"n_{key}"] = len(g)
MOD.append(row)
return pd.DataFrame(MOD)
MD = mod_table(SWRT)
print("PFC units tested for modulation:", len(MD))
PFC units tested for modulation: 94
fig5-pfc-modulated-fraction¶
About 63% of the selected PFC units (70 of 112) are significantly modulated during one or both types of SWRs, almost twice the fraction found without separating SWR types.
(Results, Prefrontal cortical activity changes during SWRs, paragraph 3; data: dataset)
Significance as the Methods give it, with the claims file's choice of PETH window (+-0.5 s), bin (10 ms) and shift (uniform over the whole 1 s window); the modulation index uses the mean duration of the SWR type.
for rd in ("a", "b"):
m = MD[MD[f"sel_{rd}"]]
sig = (m.p_map < 0.05) | (m.p_iap < 0.05)
print(f"Selection ({rd}): {int(sig.sum())} of {len(m)} modulated during MAP- or IAP-SWRs ({sig.mean():.3f}); "
f"MAP-SWR {int((m.p_map < 0.05).sum())}, IAP-SWR {int((m.p_iap < 0.05).sum())}")
allswr = []
for _, r in m.iterrows():
p = PFC[int(r.k)]
T = SWRT[(SWRT.animal == p["animal"]) & (SWRT.day == p["day"])]
allswr.append(modulation(p["spikes"], T.start.values, T.dur.values)[1])
print(f" without separating SWR types (all detected SWRs): {(np.array(allswr) < 0.05).sum()} of {len(m)} ({(np.array(allswr) < 0.05).mean():.3f})")
print("Expected fraction 0.63 (tolerance 0.063) and 70 units (7).")
MD3 = mod_table(SWRT_3, rng=np.random.default_rng(53))
m3 = MD3[MD3.sel_a]
sig3 = (m3.p_map < 0.05) | (m3.p_iap < 0.05)
print(f"Sensitivity, fixed 3 SD threshold (not the paper's method), the same {len(m3)} units of selection (a): {int(sig3.sum())} modulated "
f"({sig3.mean():.3f}); MAP-SWR {int((m3.p_map < 0.05).sum())}, IAP-SWR {int((m3.p_iap < 0.05).sum())}; "
f"units with no IAP-SWR under this threshold: {int((m3.n_iap == 0).sum())}")
Selection (a): 31 of 94 modulated during MAP- or IAP-SWRs (0.330); MAP-SWR 18, IAP-SWR 14
without separating SWR types (all detected SWRs): 22 of 94 (0.234) Selection (b): 31 of 94 modulated during MAP- or IAP-SWRs (0.330); MAP-SWR 18, IAP-SWR 14
without separating SWR types (all detected SWRs): 22 of 94 (0.234) Expected fraction 0.63 (tolerance 0.063) and 70 units (7).
Sensitivity, fixed 3 SD threshold (not the paper's method), the same 94 units of selection (a): 28 modulated (0.298); MAP-SWR 17, IAP-SWR 19; units with no IAP-SWR under this threshold: 0
Result: not reproduced. 31 of 94 selected units (0.330) are modulated during MAP- or IAP-SWRs, against 0.63 (tolerance 0.063); 22 (0.234) are modulated when SWR types are not separated, so the fraction rises when types are separated, though not to twice. With a fixed 3 SD threshold (sensitivity check, not the paper's method) 28 of the same 94 units (0.298) are modulated, so the low fraction does not come from the low threshold.
fig5dg-pfc-groups¶
Significantly modulated PFC units fall into units excited only during IAP-SWRs (14), excited only during MAP-SWRs (20) and inhibited during either or both (33); only 3 are excited during both, fewer than the 9 expected by chance.
(Figure 5D-G; Results, Prefrontal cortical activity changes during SWRs, paragraph 3; data: dataset)
def groups_of(m, center="start"):
def state(p, mi):
return np.where(p < 0.05, np.where(mi > 0, "+", "-"), "ns")
sm, si = state(m.p_map, m[f"mi_map_{center}"]), state(m.p_iap, m[f"mi_iap_{center}"])
g = np.select([(si == "+") & (sm == "+"), (si == "+"), (sm == "+"), (si == "-") | (sm == "-")],
["IAP- and MAP-SWR+", "IAP-SWR+", "MAP-SWR+", "IAP/MAP-SWR-"], "none")
return pd.Series(g, index=m.index)
K = {"IAP-SWR+": 2, "MAP-SWR+": 2, "IAP/MAP-SWR-": 3, "IAP- and MAP-SWR+": 1}
for center in ("start", "mid"):
m = MD[MD.sel_a]
g = groups_of(m, center)
mod = g[g != "none"]
N = len(mod)
out = []
for grp, kk in K.items():
o = int((mod == grp).sum())
p2 = stats.binomtest(o, N, kk / 8).pvalue if N else np.nan
p1 = stats.binomtest(o, N, kk / 8, alternative="less" if o < N * kk / 8 else "greater").pvalue if N else np.nan
out.append(f"{grp}: {o} (expected {N * kk / 8:.1f}; binomial two-sided p = {p2:.2g}, one-sided p = {p1:.2g})")
print(f"1 s window centred on SWR {center} (selection a, {N} modulated):\n " + "\n ".join(out))
MD["group"] = groups_of(MD)
print("Expected counts 14, 20, 33, 3 (tolerance 1.4, 2, 3.3, 1).")
g3 = groups_of(m3)
mod3 = g3[g3 != "none"]
print(f"Sensitivity, fixed 3 SD threshold ({len(mod3)} modulated):", {grp: f"{int((mod3 == grp).sum())} (expected {len(mod3) * kk / 8:.1f}, "
f"two-sided p = {stats.binomtest(int((mod3 == grp).sum()), len(mod3), kk / 8).pvalue:.2g})" for grp, kk in K.items()} if len(mod3) else "none")
1 s window centred on SWR start (selection a, 31 modulated):
IAP-SWR+: 2 (expected 7.8; binomial two-sided p = 0.013, one-sided p = 0.0084)
MAP-SWR+: 12 (expected 7.8; binomial two-sided p = 0.095, one-sided p = 0.064)
IAP/MAP-SWR-: 17 (expected 11.6; binomial two-sided p = 0.062, one-sided p = 0.037)
IAP- and MAP-SWR+: 0 (expected 3.9; binomial two-sided p = 0.027, one-sided p = 0.016)
1 s window centred on SWR mid (selection a, 31 modulated):
IAP-SWR+: 2 (expected 7.8; binomial two-sided p = 0.013, one-sided p = 0.0084)
MAP-SWR+: 12 (expected 7.8; binomial two-sided p = 0.095, one-sided p = 0.064)
IAP/MAP-SWR-: 17 (expected 11.6; binomial two-sided p = 0.062, one-sided p = 0.037)
IAP- and MAP-SWR+: 0 (expected 3.9; binomial two-sided p = 0.027, one-sided p = 0.016)
Expected counts 14, 20, 33, 3 (tolerance 1.4, 2, 3.3, 1).
Sensitivity, fixed 3 SD threshold (28 modulated): {'IAP-SWR+': '2 (expected 7.0, two-sided p = 0.028)', 'MAP-SWR+': '8 (expected 7.0, two-sided p = 0.66)', 'IAP/MAP-SWR-': '17 (expected 10.5, two-sided p = 0.017)', 'IAP- and MAP-SWR+': '1 (expected 3.5, two-sided p = 0.25)'}
Result: not reproduced. The groups hold 2 (IAP-SWR+), 12 (MAP-SWR+), 17 (inhibited) and 0 (excited in both) units, against 14, 20, 33 and 3. The excited-in-both group is below its expected 3.9 (two-sided p = 0.027), but the IAP-SWR+ group is also below expectation (2 against 7.8, p = 0.013), where the paper finds no difference. Centring the 1 s window on the SWR midpoint gives the same groups. With a fixed 3 SD threshold (sensitivity check) the groups are 2, 8, 17 and 1 of 28, and IAP-SWR+ is again below expectation (p = 0.028). The binomial tests treat units as independent, as the paper's test does.
fig5s1d-shuffle-control¶
PFC modulation differs between MAP- and IAP-SWRs because of SWR identity and not SWR duration; the difference between a unit's two indices shrinks when SWR identities are shuffled but not when durations are matched.
(Figure 5, supplement 1D legend; Results, Prefrontal cortical activity changes during SWRs, paragraph 4; data: dataset)
For each unit, 100 permutations of SWR identity and 100 draws of 250 SWRs per type weighted to the overlap of the two duration distributions (seeded); the unit's shuffled and matched values are the means over its replicates. The paper does not say how many it used; one replicate per unit, and the spread of the test over single replicates, are shown.
rng51 = np.random.default_rng(51)
NREP = 100
rows, reps = [], []
for _, r in MD[MD.sel_a & (MD.group != "none")].iterrows():
p = PFC[int(r.k)]
T = SWRT[(SWRT.animal == p["animal"]) & (SWRT.day == p["day"]) & SWRT.type.isin(["MAP", "IAP"])]
typ = T.type.values
st, du = T.start.values, T.dur.values
d_data = abs(r.mi_map_start - r.mi_iap_start)
# duration matching: draws weighted to the overlap of the two duration distributions
bins = np.arange(0, du.max() + 0.02, 0.02)
hm = np.histogram(du[typ == "MAP"], bins, density=True)[0]
hi = np.histogram(du[typ == "IAP"], bins, density=True)[0]
tgt = np.minimum(hm, hi)
wsel = {}
for t_, hh in (("MAP", hm), ("IAP", hi)):
sel = np.flatnonzero(typ == t_)
b = np.clip(np.digitize(du[sel], bins) - 1, 0, len(tgt) - 1)
w = tgt[b] / np.where(hh[b] > 0, hh[b], np.inf)
wsel[t_] = (sel, w / w.sum())
sh_, ma_ = [], []
for rep_ in range(NREP):
perm = rng51.permutation(typ)
mi_m = modulation(p["spikes"], st[perm == "MAP"], du[perm == "MAP"], nshuf=1, rng=rng51)[0]
mi_i = modulation(p["spikes"], st[perm == "IAP"], du[perm == "IAP"], nshuf=1, rng=rng51)[0]
sh_.append(abs(mi_m - mi_i))
mm = []
for t_ in ("MAP", "IAP"):
sel, w = wsel[t_]
pick = np.sort(rng51.choice(sel, 250, p=w))
o = np.argsort(st[pick])
mm.append(modulation(p["spikes"], st[pick][o], du[pick][o], nshuf=1, rng=rng51)[0])
ma_.append(abs(mm[0] - mm[1]))
rows.append(dict(data=d_data, shuffle_first=sh_[0], matched_first=ma_[0], shuffle=np.nanmean(sh_), matched=np.nanmean(ma_)))
reps.append((sh_, ma_))
SH = pd.DataFrame(rows).replace([np.inf, -np.inf], np.nan)
print(f"Medians of |MAP-SWR index - IAP-SWR index| (n = {len(SH)} units; shuffle and matched are each unit's mean over {NREP} replicates):",
SH.median().round(3).to_dict())
print("data vs shuffle (mean of replicates) rank-sum p =", f"{stats.ranksums(SH.data.dropna(), SH.shuffle.dropna()).pvalue:.2g}",
"; data vs matched p =", f"{stats.ranksums(SH.data.dropna(), SH.matched.dropna()).pvalue:.2g}")
print("Single replicate per unit, as before (the first):", f"shuffle p = {stats.ranksums(SH.data.dropna(), SH.shuffle_first.dropna()).pvalue:.2g},",
f"matched p = {stats.ranksums(SH.data.dropna(), SH.matched_first.dropna()).pvalue:.2g}")
ps_sh = [stats.ranksums(SH.data.dropna(), pd.Series([x[0][j] for x in reps]).replace([np.inf, -np.inf], np.nan).dropna()).pvalue for j in range(NREP)]
ps_ma = [stats.ranksums(SH.data.dropna(), pd.Series([x[1][j] for x in reps]).replace([np.inf, -np.inf], np.nan).dropna()).pvalue for j in range(NREP)]
print(f"Over the {NREP} single-replicate tests: shuffle p median {np.median(ps_sh):.2g}, below 0.05 in {np.mean(np.array(ps_sh) < 0.05):.2f}; "
f"matched p median {np.median(ps_ma):.2g}, below 0.05 in {np.mean(np.array(ps_ma) < 0.05):.2f}")
Medians of |MAP-SWR index - IAP-SWR index| (n = 31 units; shuffle and matched are each unit's mean over 100 replicates): {'data': 0.394, 'shuffle_first': 0.194, 'matched_first': 0.373, 'shuffle': 0.328, 'matched': 0.495}
data vs shuffle (mean of replicates) rank-sum p = 0.36 ; data vs matched p = 0.73
Single replicate per unit, as before (the first): shuffle p = 0.043, matched p = 0.93
Over the 100 single-replicate tests: shuffle p median 0.11, below 0.05 in 0.23; matched p median 0.83, below 0.05 in 0.00
Result: not reproduced. For 31 modulated units the median |MAP-SWR index - IAP-SWR index| is 0.394; averaged over 100 identity shuffles per unit it is 0.328 (rank-sum p = 0.36), and averaged over 100 duration-matched draws 0.495 (p = 0.73). The matched set is like the data, but the shuffle does not lower the difference significantly. A single shuffle per unit gives p from below 0.05 (23 of 100 single-replicate tests, the first gives p = 0.043) to well above it (median p = 0.11), so the one-replicate result of the first round (p = 0.17) was within this spread.
pfc-regression-joint-swr¶
For 15 PFC units, the MAP-SWR and IAP-SWR modulation indices together explain 73% of the variance of the MAP & IAP-SWR modulation index.
(Results, Prefrontal cortical activity changes during SWRs, paragraph 5; Figure 5, supplement 2; data: dataset)
import statsmodels.api as sm
for rd, mask in (("(a) modulated by MAP- or IAP-SWRs, all three types recorded", MD.sel_a & (MD.group != "none") & (MD.n_both > 0)),
("(b) all selected units with all three types", MD.sel_a & (MD.n_both > 0))):
m = MD[mask].dropna(subset=["mi_map_start", "mi_iap_start", "mi_both_start"])
if len(m) < 4:
print(rd, "units:", len(m)); continue
fit = sm.OLS(m.mi_both_start, sm.add_constant(m[["mi_map_start", "mi_iap_start"]])).fit()
print(f"{rd}: n = {len(m)}, R2 = {fit.rsquared:.3f}, F-test p = {fit.f_pvalue:.2g}")
print("Expected R2 0.73 (tolerance 0.073), n = 15 in the paper.")
(a) modulated by MAP- or IAP-SWRs, all three types recorded: n = 20, R2 = 0.272, F-test p = 0.067 (b) all selected units with all three types: n = 82, R2 = 0.044, F-test p = 0.17 Expected R2 0.73 (tolerance 0.073), n = 15 in the paper.
Result: not reproduced. The MAP-SWR and IAP-SWR indices explain R2 = 0.272 of the MAP & IAP-SWR index for 20 modulated units with all three types (F-test p = 0.067), and 0.044 for all 82 selected units with all three (p = 0.17), against 0.73.
fig6e-coincidence-index¶
Outside SWRs, PFC IAP-SWR+ units are more coactive with CA1 IAPs than MAPs and PFC MAP-SWR+ units more coactive with CA1 MAPs than IAPs; inhibited units are the least coactive.
(Figure 6D-E; Results, PFC SWR modulation pattern correlates with task activity, paragraph 3; data: dataset)
Cross-correlograms of spikes outside SWRs, 100 ms bins over +-10 s, z-scored over the bins; the value in the bin centred on 0 lag.
edges_c = np.arange(-10.05, 10.0501, 0.1)
zero_bin = len(edges_c) // 2 - 1
cc = []
for _, r in MD[MD.sel_a & MD.group.isin(["IAP-SWR+", "MAP-SWR+", "IAP/MAP-SWR-"])].iterrows():
p = PFC[int(r.k)]
T = SWRT[(SWRT.animal == p["animal"]) & (SWRT.day == p["day"])]
o = np.argsort(T.start.values)
ps = p["spikes"][~Y.in_intervals(p["spikes"], T.start.values[o], T.end.values[o])]
for c in C:
if c["animal"] != p["animal"] or c["day"] != p["day"]:
continue
h = np.histogram(Y.lags(ps, PREP[id(c)]["nos"], 10.05), edges_c)[0].astype(float)
if h.std() == 0:
continue
zc = (h - h.mean()) / h.std()
cc.append(dict(k=int(r.k), group=r.group, label=c["label"], z0=zc[np.argmin(np.abs(0.5 * (edges_c[1:] + edges_c[:-1])))]))
CC = pd.DataFrame(cc)
res6 = {}
for grp in ("IAP-SWR+", "MAP-SWR+", "IAP/MAP-SWR-"):
g = CC[CC.group == grp]
within = [i - m_ for _, u in g.groupby("k") for i in u[u.label == "IAP"].z0 for m_ in u[u.label == "MAP"].z0]
allc = [i - m_ for i in g[g.label == "IAP"].z0 for m_ in g[g.label == "MAP"].z0]
res6[grp] = np.array(within)
print(f"{grp}: PFC units {g.k.nunique()}; within-unit index n = {len(within)}, median {np.median(within) if within else np.nan:.3f}; "
f"all combinations n = {len(allc)}, median {np.median(allc) if allc else np.nan:.3f}")
if len(res6["IAP-SWR+"]) and len(res6["MAP-SWR+"]):
print("IAP-SWR+ vs MAP-SWR+ rank-sum p =", f"{stats.ranksums(res6['IAP-SWR+'], res6['MAP-SWR+']).pvalue:.2g}")
IAP-SWR+: PFC units 2; within-unit index n = 22, median 0.156; all combinations n = 44, median 0.337 MAP-SWR+: PFC units 12; within-unit index n = 117, median -1.708; all combinations n = 1560, median -1.604 IAP/MAP-SWR-: PFC units 17; within-unit index n = 154, median -0.869; all combinations n = 2888, median -0.785 IAP-SWR+ vs MAP-SWR+ rank-sum p = 0.00058
Result: reproduced, with two IAP-SWR+ units. The coincidence index pairing CA1 cells within a PFC unit has median 0.156 for IAP-SWR+ units (22 values from 2 units) and -1.708 for MAP-SWR+ units (117 values from 12 units), rank-sum p = 0.00058; inhibited units have median -0.869. With all combinations the medians are 0.337 and -1.604. The rank-sum treats the 22 and 117 values as independent, as the paper's test does, though they come from 2 and 12 PFC units and share cells, so the p-value overstates the evidence; the IAP-SWR+ side rests on two units, from groups (fig5dg) that did not reproduce.
fig6s2-no-proximity-difference¶
PFC cell pairs within a modulation group do not differ from pairs across groups in spatial proximity (inter-spike distance) or temporal proximity (cross-correlation peak offset).
(Figure 6, supplement 2; Results, PFC SWR modulation pattern correlates with task activity, paragraph 3; data: dataset)
rng62 = np.random.default_rng(62)
pp = []
mods = MD[MD.sel_a & (MD.group != "none")]
for (a, d), g in mods.groupby(["animal", "day"]):
ks = list(g.k.astype(int)); grp = dict(zip(g.k.astype(int), g.group))
pos = {}
for k in ks:
sp = PFC[k]["spikes"]
xs, ys = [], []
for p in R[a]["days"][d]["epochs"].values():
s = sp[(sp >= p["t"][0]) & (sp <= p["t"][-1])]
xs.append(np.interp(s, p["t"], p["x"])); ys.append(np.interp(s, p["t"], p["y"]))
xy = np.column_stack([np.concatenate(xs), np.concatenate(ys)])
pos[k] = xy[rng62.choice(len(xy), min(2000, len(xy)), replace=False)]
for i in range(len(ks)):
for j in range(i + 1, len(ks)):
A_, B_ = pos[ks[i]], pos[ks[j]]
dist = np.sqrt(((A_[:, None, :] - B_[None, :, :]) ** 2).sum(-1)).mean()
h = np.histogram(Y.lags(PFC[ks[i]]["spikes"], PFC[ks[j]]["spikes"], 10.0), np.arange(-10, 10.0001, 0.1))[0]
off = abs(np.arange(-9.95, 10, 0.1)[np.argmax(h)]) if h.sum() else np.nan
pp.append(dict(within=grp[ks[i]] == grp[ks[j]], dist=dist, offset=off))
PP = pd.DataFrame(pp, columns=["within", "dist", "offset"])
for col in ("dist", "offset"):
w, x = PP[PP.within.astype(bool)][col].dropna(), PP[~PP.within.astype(bool)][col].dropna()
p = stats.ranksums(w, x).pvalue if len(w) and len(x) else np.nan
print(f"{col}: within-group median {w.median():.2f} (n = {len(w)}), across-group {x.median():.2f} (n = {len(x)}); rank-sum p = {p:.2g}")
print("Mean distance between spike positions is estimated from up to 2000 spikes per cell (seeded); paper: 39 within and 169 across.")
dist: within-group median 106.29 (n = 14), across-group 107.09 (n = 28); rank-sum p = 0.52 offset: within-group median 1.50 (n = 14), across-group 1.85 (n = 28); rank-sum p = 0.34 Mean distance between spike positions is estimated from up to 2000 spikes per cell (seeded); paper: 39 within and 169 across.
Result: reproduced. Among modulated PFC units, pairs within a group do not differ from pairs across groups in mean spike-position distance (medians 106.29 and 107.09 cm, p = 0.52) or in the offset of their cross-correlation peak (1.50 and 1.85 s, p = 0.34), with 14 and 28 pairs.
print(f"notebook run time {time.time() - started:.0f} s; peak memory "
f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
notebook run time 990 s; peak memory 6.2 GB
Summary¶
| Claim | Outcome |
|---|---|
| fig1-iap-map-counts | blocked (data_missing: the pooled count needs W-track rats the paper does not identify in a public archive) |
| fig1s4b-foraging-counts | not reproduced |
| fig1d-well-specificity | reproduced (foraging rats) |
| fig1e-iap-lower-speed | reproduced (foraging rats) |
| fig1s4d-foraging-speed | reproduced |
| fig1f-iap-smaller-coverage | not reproduced |
| fig1s1d-transition-interval | not reproduced |
| fig2c-continuous-transition | reproduced (foraging rats) |
| fig2s1cd-theta-autocorrelation | reproduced (foraging rats) |
| fig2s1ij-theta-behavior-correlation | not reproduced |
| fig2s2-fewer-coincident-spikes | not reproduced |
| fig3c-iap-swr-activation | partially reproduced |
| fig3s3-iap-same-well-coactivity | blocked (other: 2 IAP pairs) |
| fig4a-swr-counts | partially reproduced |
| fig4b-coactivity | partially reproduced |
| fig4s1b-offset-matched-coactivity | reproduced (foraging rats) |
| fig4s2c-spatial-proximity-control | not reproduced |
| fig4s3-overlapping-pairs | partially reproduced |
| fig4c-iap-swr-shorter | reproduced (foraging rats) |
| fig4d-iap-swr-lower-power | partially reproduced |
| fig4s5-cells-spikes-per-swr | not reproduced |
| fig4s67-matched-subsamples | reproduced (foraging rats) |
| fig4s8-interspersed | reproduced (foraging rats) |
| fig4e-iap-spike-earlier | reproduced (foraging rats) |
| pfc-unit-selection | partially reproduced |
| fig5-pfc-modulated-fraction | not reproduced |
| fig5dg-pfc-groups | not reproduced |
| fig5s1d-shuffle-control | not reproduced |
| pfc-regression-joint-swr | not reproduced |
| fig6c-similarity-index | blocked (data_missing: no beam-break times) |
| fig6e-coincidence-index | reproduced |
| fig6s2-no-proximity-difference | reproduced |
A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.
How the analysis differs from the paper's. Only the foraging rats are analysed; claims the paper tests on both tasks pooled are tested on them alone, and their outcomes are those of the foraging-only test. Reward wells come from the immobile positions (O1 reading (b)), as the data set has no beam-break times. For the analyses around entry and exit, entries and exits are the starts and ends of every immobility period, as O1 (b) is written; their windows cover about half of task time. Well visits (immobility periods of at least 0.5 s within 15 cm of a well) are shown as a variant, and whether O1 (b) misreads the paper's entries is asked of a reader. SWRs are detected on the stored LFP, whose reference the data set does not state; the paper records CA1 LFP against corpus callosum and computes spectrograms on ground-referenced LFP, which cannot be rebuilt. The noise-based threshold, as the Methods describe it, is low (about 0 to 0.8 z of the envelope amplitude): 13 to 20% of immobile samples exceed it, about what the same rule lets through on pure noise, and it gives about 2 SWRs per second of immobility; the squared-envelope reading is degenerate. A fixed 3 SD threshold, run as a sensitivity check only, gives about 0.2 SWRs per second and leaves the outcomes of fig4a, fig3c, fig5 and fig5dg as they are. Coactivity z-scores use the exact permutation mean and variance. The spike-width rule is applied to the stored widths, which removes nearly every CA1 cell of R1 and N2, so the IAP analyses rest on T1 and S2 (14 IAPs) and the PFC analyses on the PFC units recorded with them.
What was found about the data set. It holds the five foraging rats with the days the paper
analysed (4, 9, 9, 11 and 12), but only their task sessions, and no beam-break times, well
positions or reward contingencies. Stored spike widths in R1 and N2 are about 0.2 ms longer than in
the other rats, for CA1 and PFC alike. Tetrodes of one session start up to 45 ms apart in R1 and N2.
No corpus callosum reference channel is included, and the LFP's reference is not stated. 11 unit-days have no area. The descriptor's summary calls the data set
"hc-7". The archive's MD5 matches its checksums.md5.