Jadhav, Rothschild, Roumis & Frank (2016) on CRCNS hc-28ΒΆ

Paper: Jadhav SP, Rothschild G, Roumis DK, Frank LM (2016). Coordinated excitation and inhibition of prefrontal ensembles during awake hippocampal sharp-wave ripple events. Neuron 90:113-127, doi:10.1016/j.neuron.2016.02.010.

Data: CRCNS hc-28 (doi:10.6080/K02N50G9), Jadhav & Frank, the three W-track rats HPa, HPb and HPc, days 1 to 8. CRCNS data sets are not versioned, so the version is recorded as unversioned (docs/archives.md). The files read are the current hc-28/live/ files of the public bucket crcnsarchive, the only published copy; the folder hc-28/orig/v06/ holds only the three cellinfo files replaced in version 0.61 of the description (March 2020), so live is the copy that matches the description the claims file was checked against. MD5 sums from hc-28/live/checksums.md5:

File MD5
data/HPa_data.tar.gz ca6a313b9936db3aff62f60597da34a3
data/HPb_data.tar.gz 2126599d004cdaca2fa2426f364453e3
data/HPc_data.tar.gz f9bddd6fe2c5c9c9dd0e406df1cf7ede

Claims: claims/crcns-hc-28/10.1016-j.neuron.2016.02.010.yaml, written from the version of record with its Supplemental Information. The paper pools six rats on two tasks; the data set holds the three W-track rats, so claims that pool both tasks are judged on the W-track data by the rule of the claims file's opening comment (pooled-value rule).

Each archive is streamed once (two at a time) and reduced in memory by hc28.reduce_animal; nothing is written to disk. The whole notebook takes about 32 minutes, 10 of them streaming.

Claim Tested or blocked
wtrack-learning, tables1-cell-counts, swr-detection-stats, figs2-swr-at-reward-wells tested
fig3-pfc-swr-modulation-fractions, ca1-swr-modulated, fig3-transient-responses, fig3de-ca1-precedes-pfc-peak, fig3e-onset-later-in-pfc, fig3f-swr-cross-covariance-lag tested
fig4-theta-locked-fraction, fig4a-preferred-phases, fig4-swr-modulated-more-theta-locked, fig4b-kappa, fig4c-theta-locked-more-swr-modulated, fig4-preferred-phase-concentration, theta-lag-past tested
fig5b-mean-rates, fig5c-spatial-coverage, figs3-arm-and-direction-selectivity, fig5e-speed-correlation, fig5f-pre-swr-vs-movement, figs3e-reward-modulation, fig5g-ensemble-cofiring tested
fig6-swr-correlated-pairs, fig6ab-both-signs, fig6c-theta-predicts-swr-correlation, figs4b-ca1-leads-in-theta, fig6e-glm-swr-prediction, fig6e-theta-trained-glm, figs4c-pfc-predicts-ca1 tested
fig7c-spatial-correlation, figs5-matched-selectivity, figs6-replay-content, fig8a-no-prerest-swr-correlation-relation, fig8bc-no-prerest-theta-spatial-relation, fig8d-glm-epoch-specific tested
ytrack-learning, figs7-both-tracks blocked, data missing: the Y-track rats are not in hc-28

Main readings, used throughout unless a section shows others (each is an assumption where the paper is silent): SWRs detected on any one ripple tetrode (reading a of the claims file), onset at the time the ripple envelope last rose above its mean before crossing 3 SD; both W-track runs of each day, including the wtr2 runs of days 6 to 8 (a section near the end repeats the downstream tests under the mean-envelope reading and without the wtr2 runs); SWR-aligned rasters of -500 to +500 ms; cell-days as units.

InΒ [1]:
import zlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from concurrent.futures import ProcessPoolExecutor
import hc28

pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)


def rng_for(name):
    """Each claim's section has its own generator, seeded from its name."""
    return np.random.default_rng(zlib.crc32(name.encode()))


def ranksum(a, b):
    a, b = np.asarray(a, float), np.asarray(b, float)
    a, b = a[np.isfinite(a)], b[np.isfinite(b)]
    if len(a) == 0 or len(b) == 0:
        return np.nan
    return stats.ranksums(a, b).pvalue


def msem(x):
    x = np.asarray(x, float); x = x[np.isfinite(x)]
    return f"{x.mean():.3f} +- {x.std(ddof=1) / np.sqrt(len(x)):.3f} (n = {len(x)})" if len(x) > 1 else f"n = {len(x)}"
InΒ [2]:
with ProcessPoolExecutor(2) as ex:
    R = dict(zip(hc28.ANIMALS, ex.map(hc28.reduce_animal, hc28.ANIMALS)))

Data checkΒΆ

InΒ [3]:
rows = []
for a, r in R.items():
    for d, day in r["days"].items():
        for e, (ty, env) in day["task"].items():
            ep = day["epochs"].get(e)
            rows.append(dict(animal=a, day=d, epoch=e, type=ty, environment=env,
                             used="run" if e in day["runs"] else ("pre-rest" if e == day["pre"] else ""),
                             minutes=None if ep is None else round((ep["end"] - ep["start"]) / 60, 1)))
ep_df = pd.DataFrame(rows)
print("Epochs by animal, day and environment (used: the W-track runs and the pre-rest):")
print(ep_df.pivot_table(index=["animal", "day"], columns="epoch", values="environment", aggfunc="first").fillna(""))
print("\nUsed epochs:", ep_df[ep_df.used != ""].groupby(["animal", "used"]).size().to_dict())
print("Run minutes per day: min %.1f, median %.1f, max %.1f" % tuple(
    np.percentile(ep_df[ep_df.used == "run"].groupby(["animal", "day"]).minutes.sum(), [0, 50, 100])))

# tetrodes
for a, r in R.items():
    d1 = r["days"][1]
    print(f"{a}: ripple tetrodes {d1['riptets']}, CA1 reference {d1['reftet']}; same on all days:",
          all(r["days"][d]["riptets"] == d1["riptets"] and r["days"][d]["reftet"] == d1["reftet"] for d in r["days"]))

# position, speed, LFP
P = np.vstack([ep["pos"] for r in R.values() for day in r["days"].values() for e, ep in day["epochs"].items() if e in day["runs"]])
print("\nRun position x %.1f to %.1f cm, y %.1f to %.1f cm (track about 80 x 80 cm per the SEP); speed 1st-99th "
      "percentile %.2f to %.1f cm/s, max %.1f" % (np.nanmin(P[:, 1]), np.nanmax(P[:, 1]), np.nanmin(P[:, 2]),
                                                   np.nanmax(P[:, 2]), *np.nanpercentile(P[:, 3], [1, 99]), np.nanmax(P[:, 3])))
for env in ("wtr1", "wtr2"):
    Pe = np.vstack([ep["pos"] for r in R.values() for day in r["days"].values() for e, ep in day["epochs"].items()
                    if e in day["runs"] and day["task"][e][1] == env])
    print(f"  {env}: x {np.nanmin(Pe[:, 1]):.1f} to {np.nanmax(Pe[:, 1]):.1f} cm, y {np.nanmin(Pe[:, 2]):.1f} to {np.nanmax(Pe[:, 2]):.1f} cm")
# position scale: the files give 'cmperpixel' (the descriptor calls it 'cmperpix'); the track geometry from linearcoord
# (centre well, centre junction, side junction, side well) gives the arm lengths in the units of the position columns
geo = []
for a, r in R.items():
    for d, day in r["days"].items():
        for e in day["runs"]:
            ep = day["epochs"][e]; lc = ep["linearcoord"]
            geo.append(dict(animal=a, environment=day["task"][e][1], cmperpixel=ep["pos_meta"].get("cmperpixel", [np.nan])[0],
                            centre_arm=np.hypot(*(lc[0][1] - lc[0][0])), side_wells_apart=np.hypot(*(lc[0][3] - lc[1][3])),
                            centre_to_side_well=np.hypot(*(lc[0][3] - lc[0][0])), x_span=np.ptp(ep["pos"][:, 1]), y_span=np.ptp(ep["pos"][:, 2])))
geo = pd.DataFrame(geo)
print("\nTrack geometry per animal and environment (median over run epochs; lengths in the position units):")
print(geo.groupby(["animal", "environment"]).median().round(2))
g1 = geo[geo.environment == "wtr1"]
print("wtr1: centre arm %.0f to %.0f, side wells %.0f to %.0f apart, position span per epoch up to %.0f x %.0f. Read as cm this is the "
      "~80 x 80 cm W-track of the SEP; read as pixels times cmperpixel (%.2f to %.2f) the centre arm would be %.0f to %.0f cm, too short. "
      "The position columns are in cm." % (g1.centre_arm.min(), g1.centre_arm.max(), g1.side_wells_apart.min(), g1.side_wells_apart.max(),
                                          g1.x_span.max(), g1.y_span.max(), g1.cmperpixel.min(), g1.cmperpixel.max(),
                                          (g1.centre_arm * g1.cmperpixel).min(), (g1.centre_arm * g1.cmperpixel).max()))
print("The pooled x and y ranges above are wider than one track because each animal's track sits at a different place in the camera frame.")
dts = [np.median(np.diff(ep["pos"][:, 0])) for r in R.values() for day in r["days"].values() for ep in day["epochs"].values()]
print("Position sampling interval: %.4f to %.4f s (30 Hz camera per the paper)" % (min(dts), max(dts)))
fss = [ep["lfp_fs"] for r in R.values() for day in r["days"].values() for ep in day["epochs"].values()]
print("LFP sampling rate: %.3f to %.3f Hz (1500 Hz per the paper)" % (min(fss), max(fss)))
spread = [ep.get("lfp_start_spread", np.nan) for r in R.values() for day in r["days"].values() for ep in day["epochs"].values()]
print("Spread of LFP start times across ripple tetrodes within an epoch: max %.4f s (aligned on the latest start)" % np.nanmax(spread))

# units
cells = hc28.cell_table(R)
print("\nCell-days with spikes in the W-track runs, by animal and area:")
print(cells.groupby(["animal", "area"]).size().unstack(fill_value=0))
w_spk = np.concatenate([u["width"] for r in R.values() for day in r["days"].values() for u in day["units"].values()])
w_ci = np.concatenate([u["ci_width"] for r in R.values() for day in r["days"].values() for u in day["units"].values()])
print("\nspikes 'spikewidth' (descriptor: points at 30 kHz): median %.2f, range %.2f to %.2f" % (np.median(w_spk), w_spk.min(), w_spk.max()))
print("cellinfo 'spikewidth' (descriptor: 'peak to trough width in ms'): median %.2f, range %.2f to %.2f"
      % (np.nanmedian(w_ci), np.nanmin(w_ci), np.nanmax(w_ci)))
print("Read as ms, the cellinfo widths (%.1f to %.1f ms) are far longer than any spike; divided by 30 they are %.2f to %.2f ms. "
      "Both fields are 30 kHz samples." % (np.nanmin(w_ci), np.nanmax(w_ci), np.nanmin(w_ci) / 30, np.nanmax(w_ci) / 30))
print("Width (ms) of included cells: %.2f to %.2f; rate (Hz) %.2f to %.2f" % (cells.width_ms.min(), cells.width_ms.max(), cells.rate.min(), cells.rate.max()))

# clocks: spikes inside their epoch, LFP covering the epoch
bad = 0; tot = 0
for r in R.values():
    for day in r["days"].values():
        for e, ep in day["epochs"].items():
            for u in day["units"].values():
                st = u["times"].get(e, np.zeros(0))
                tot += len(st)
                bad += np.sum((st < ep["start"] - 1) | (st > ep["end"] + 1))
print(f"\nSpikes outside their epoch's position time range (+-1 s): {bad} of {tot}")
cov = [(ep["lfp_t0"] - ep["start"], ep["lfp_t0"] + ep["lfp_n"] / ep["lfp_fs"] - ep["end"]) for r in R.values() for day in r["days"].values() for ep in day["epochs"].values()]
cov = np.array(cov)
print("LFP start minus position start: %.1f to %.1f s; LFP end minus position end: %.1f to %.1f s" % (cov[:, 0].min(), cov[:, 0].max(), cov[:, 1].min(), cov[:, 1].max()))
Epochs by animal, day and environment (used: the W-track runs and the pre-rest):
epoch              1     2 3     4          5     6          7
animal day                                                    
HPa    1    presleep   lin    wtr1             wtr1  postsleep
       2    presleep  wtr1    wtr1  postsleep                 
       3    presleep  wtr1    wtr1  postsleep                 
       4    presleep  wtr1    wtr1  postsleep                 
       5    presleep  wtr1    wtr1  postsleep                 
       6    presleep  wtr1    wtr2  postsleep                 
       7    presleep  wtr1    wtr2  postsleep                 
       8    presleep  wtr1    wtr2  postsleep                 
HPb    1    presleep   lin    wtr1             wtr1  postsleep
       2    presleep  wtr1    wtr1  postsleep                 
       3    presleep  wtr1    wtr1  postsleep                 
       4    presleep  wtr1    wtr1  postsleep                 
       5    presleep  wtr1    wtr1  postsleep                 
       6    presleep  wtr1    wtr2  postsleep                 
       7    presleep  wtr1    wtr2  postsleep                 
       8    presleep  wtr1    wtr2  postsleep                 
HPc    1    presleep   lin    wtr1             wtr1  postsleep
       2    presleep  wtr1    wtr1  postsleep                 
       3    presleep  wtr1    wtr1  postsleep                 
       4    presleep  wtr1    wtr1  postsleep                 
       5    presleep  wtr1    wtr1  postsleep                 
       6    presleep  wtr1    wtr2  postsleep                 
       7    presleep  wtr1    wtr2  postsleep                 
       8    presleep  wtr1    wtr2  postsleep                 

Used epochs: {('HPa', 'pre-rest'): 8, ('HPa', 'run'): 16, ('HPb', 'pre-rest'): 8, ('HPb', 'run'): 16, ('HPc', 'pre-rest'): 8, ('HPc', 'run'): 16}
Run minutes per day: min 39.6, median 40.3, max 41.4
HPa: ripple tetrodes [1, 4, 5, 6, 7, 8, 9, 11, 12, 14], CA1 reference [3]; same on all days: True
HPb: ripple tetrodes [1, 3, 4, 5, 6, 16, 17, 18, 20], CA1 reference [7]; same on all days: True
HPc: ripple tetrodes [1, 2, 3, 4, 5, 6], CA1 reference [7]; same on all days: True

Run position x 35.7 to 218.4 cm, y 0.3 to 134.2 cm (track about 80 x 80 cm per the SEP); speed 1st-99th percentile 0.02 to 38.9 cm/s, max 51.4
  wtr1: x 39.6 to 169.5 cm, y 4.1 to 119.7 cm
  wtr2: x 35.7 to 218.4 cm, y 0.3 to 134.2 cm

Track geometry per animal and environment (median over run epochs; lengths in the position units):
                    cmperpixel  centre_arm  side_wells_apart  centre_to_side_well  x_span  y_span
animal environment                                                                               
HPa    wtr1               0.65       75.81             65.29                32.42   95.35   97.53
       wtr2               0.69       75.51             73.69                34.43   98.38  107.30
HPb    wtr1               0.56       77.43             77.56                39.65  103.71  108.11
       wtr2               0.70       76.53             71.67                36.85  104.57  103.98
HPc    wtr1               0.64       78.58             78.95                38.97  107.87  106.90
       wtr2               0.50       76.87             73.16                37.20  102.51  107.24
wtr1: centre arm 58 to 81, side wells 49 to 81 apart, position span per epoch up to 111 x 112. Read as cm this is the ~80 x 80 cm W-track of the SEP; read as pixels times cmperpixel (0.50 to 0.65) the centre arm would be 29 to 52 cm, too short. The position columns are in cm.
The pooled x and y ranges above are wider than one track because each animal's track sits at a different place in the camera frame.
Position sampling interval: 0.0333 to 0.0334 s (30 Hz camera per the paper)
LFP sampling rate: 1500.000 to 1500.000 Hz (1500 Hz per the paper)
Spread of LFP start times across ripple tetrodes within an epoch: max 0.0000 s (aligned on the latest start)
Cell-days with spikes in the W-track runs, by animal and area:
area    CA1  PFC  iCA1
animal                
HPa     154   47    62
HPb     183   95    20
HPc     104   57     0

spikes 'spikewidth' (descriptor: points at 30 kHz): median 9.89, range 0.98 to 23.12
cellinfo 'spikewidth' (descriptor: 'peak to trough width in ms'): median 9.89, range 0.98 to 23.12
Read as ms, the cellinfo widths (1.0 to 23.1 ms) are far longer than any spike; divided by 30 they are 0.03 to 0.77 ms. Both fields are 30 kHz samples.
Width (ms) of included cells: 0.03 to 0.77; rate (Hz) 0.00 to 54.64

Spikes outside their epoch's position time range (+-1 s): 0 of 5092545
LFP start minus position start: -27.3 to 0.0 s; LFP end minus position end: 0.0 to 1.0 s

ClocksΒΆ

Spikes, LFP and position must share one clock. Two contrasts: the CA1 population rate around SWR onsets detected on the LFP, against the same onsets shifted by 10 s; and the spatial information of CA1 rate maps from position, against spikes shifted by 30 s.

InΒ [4]:
rng = rng_for("clock")
print("CA1 population rate 0-200 ms after SWR onset, relative to the run mean, per animal-day:")
for reading in ("any", "mean", "dca1"):
    real, shifted, low = [], [], []
    for a, r in R.items():
        for d, day in r["days"].items():
            on = hc28.swr_onsets(day, day["runs"], reading)
            st = np.sort(np.concatenate([hc28.spikes_in(u, day["runs"]) for u in day["units"].values() if hc28.region(u["area"]) == "CA1"]))
            T = hc28.epoch_time(day, day["runs"])
            base = len(st) / T
            real.append((hc28.swr_counts(st, on).sum() / (0.2 * len(on))) / base)
            shifted.append((hc28.swr_counts(st, on + 10.0).sum() / (0.2 * len(on))) / base)
            # reference: the CA1 rate in random 200 ms windows at speed < 4 cm/s, where the SWRs are
            for e in day["runs"]:
                ep = day["epochs"][e]
                tl = ep["pos"][ep["pos"][:, 3] < hc28.SWR_MAX_SPEED, 0]
                tr = rng.choice(tl, 500) if len(tl) else np.zeros(0)
                st_e = np.sort(np.concatenate([u["times"].get(e, np.zeros(0)) for u in day["units"].values() if hc28.region(u["area"]) == "CA1"]))
                low.append((hc28.swr_counts(st_e, tr).sum() / (0.2 * max(len(tr), 1))) / base)
    print(f"  reading {reading}: true onsets median {np.median(real):.2f} (range {min(real):.2f} to {max(real):.2f}); onsets + 10 s median "
          f"{np.median(shifted):.2f} (range {min(shifted):.2f} to {max(shifted):.2f}); random times at speed < 4 cm/s median {np.median(low):.2f}")


def spatial_info(maps, occ_w=None):
    r = np.concatenate(maps); ok = np.isfinite(r); r = r[ok]
    lam = r.mean()
    if lam <= 0:
        return np.nan
    x = r / lam
    return np.mean(np.where(x > 0, x * np.log2(np.where(x > 0, x, 1)), 0))


si_true, si_shift = [], []
for a, r in R.items():
    for d in (2, 5, 8):
        day = r["days"][d]
        ca1 = {k: u for k, u in day["units"].items() if hc28.region(u["area"]) == "CA1" and len(hc28.spikes_in(u, day["runs"])) > 100}
        sh = {}
        for k, u in ca1.items():
            tt = {}
            for e in day["runs"]:
                ep = day["epochs"][e]; st = u["times"].get(e, np.zeros(0))
                L = ep["end"] - ep["start"]
                tt[e] = np.sort((st - ep["start"] + 30.0) % L + ep["start"])
            sh[k] = {"times": tt}
        m1 = hc28.rate_maps(day, ca1); m2 = hc28.rate_maps(day, sh)
        si_true += [spatial_info(m1[k]) for k in ca1]; si_shift += [spatial_info(m2[k]) for k in ca1]
print("CA1 spatial information (bits/spike, days 2, 5, 8): true %.2f, spikes shifted 30 s %.2f (n = %d cell-days)"
      % (np.nanmedian(si_true), np.nanmedian(si_shift), len(si_true)))
CA1 population rate 0-200 ms after SWR onset, relative to the run mean, per animal-day:
  reading any: true onsets median 1.36 (range 0.98 to 2.00); onsets + 10 s median 0.98 (range 0.87 to 1.09); random times at speed < 4 cm/s median 0.90
  reading mean: true onsets median 1.64 (range 0.89 to 2.44); onsets + 10 s median 0.97 (range 0.78 to 1.16); random times at speed < 4 cm/s median 0.90
  reading dca1: true onsets median 1.48 (range 0.98 to 2.00); onsets + 10 s median 0.97 (range 0.90 to 1.09); random times at speed < 4 cm/s median 0.89
CA1 spatial information (bits/spike, days 2, 5, 8): true 3.11, spikes shifted 30 s 1.91 (n = 160 cell-days)

Claim wtrack-learningΒΆ

On the W-track all animals performed above chance by the third day of training and above 80% correct by the eighth and final day.

Trials are well-to-well runs read from position (claims file). A well visit is an entry into a zone of 15 cm around a well (the radius is not given; 10 and 20 cm are shown). Wells are the end points of the task's linearcoord polylines. The first outbound run of an epoch has no previous side and is not scored. Both W-track runs of each day are pooled (SEP: "Data were pooled across all sessions within a day").

InΒ [5]:
rows = []
for rad in (10.0, 15.0, 20.0):
    for a, r in R.items():
        for d, day in r["days"].items():
            tr = []
            for e in day["runs"]:
                tr += hc28.score_trials(hc28.well_visits(day["epochs"][e], rad))
            sc = np.array([t[5] for t in tr if t[5] is not None], bool)
            rows.append(dict(radius=rad, animal=a, day=d, trials=len(sc), correct=sc.mean(),
                             p_binom=stats.binomtest(int(sc.sum()), len(sc), 0.5, alternative="greater").pvalue))
beh = pd.DataFrame(rows)
print(beh.pivot_table(index=["radius", "day"], columns="animal", values="correct").round(2))
print("\nTrials scored per day (15 cm):", beh[beh.radius == 15].pivot_table(index="day", columns="animal", values="trials").to_dict())
for rad in (10.0, 15.0, 20.0):
    b = beh[beh.radius == rad]
    d3 = b[b.day == 3]; d8 = b[b.day == 8]
    print(f"radius {rad:.0f} cm: day 3 correct {d3.correct.round(2).tolist()}, binomial p {d3.p_binom.round(4).tolist()}; "
          f"day 8 correct {d8.correct.round(2).tolist()}; all > 0.8 on day 8: {bool((d8.correct > 0.8).all())}; "
          f"all > 0.5 on day 3: {bool((d3.correct > 0.5).all())}; all p < 0.05 on day 3: {bool((d3.p_binom < 0.05).all())}")
first_above = beh[(beh.radius == 15) & (beh.p_binom < 0.05)].groupby("animal").day.min()
print("First day above chance by the binomial test (15 cm):", first_above.to_dict())
animal       HPa   HPb   HPc
radius day                  
10.0   1    0.69  0.64  0.62
       2    0.84  0.77  0.76
       3    0.85  0.80  0.75
       4    0.88  0.76  0.79
       5    0.90  0.86  0.82
       6    0.81  0.76  0.80
       7    0.86  0.82  0.80
       8    0.93  0.88  0.92
15.0   1    0.69  0.64  0.62
       2    0.81  0.77  0.76
       3    0.85  0.80  0.75
       4    0.88  0.76  0.79
       5    0.90  0.86  0.82
       6    0.81  0.76  0.80
       7    0.86  0.82  0.80
       8    0.93  0.88  0.92
20.0   1    0.69  0.64  0.64
       2    0.83  0.77  0.76
       3    0.87  0.80  0.78
       4    0.88  0.76  0.80
       5    0.89  0.86  0.81
       6    0.84  0.76  0.79
       7    0.86  0.82  0.80
       8    0.92  0.88  0.92

Trials scored per day (15 cm): {'HPa': {1: 32.0, 2: 63.0, 3: 59.0, 4: 93.0, 5: 71.0, 6: 59.0, 7: 87.0, 8: 96.0}, 'HPb': {1: 47.0, 2: 39.0, 3: 54.0, 4: 51.0, 5: 99.0, 6: 76.0, 7: 65.0, 8: 85.0}, 'HPc': {1: 26.0, 2: 25.0, 3: 44.0, 4: 71.0, 5: 60.0, 6: 95.0, 7: 75.0, 8: 145.0}}
radius 10 cm: day 3 correct [0.85, 0.8, 0.75], binomial p [0.0, 0.0, 0.0006]; day 8 correct [0.93, 0.88, 0.92]; all > 0.8 on day 8: True; all > 0.5 on day 3: True; all p < 0.05 on day 3: True
radius 15 cm: day 3 correct [0.85, 0.8, 0.75], binomial p [0.0, 0.0, 0.0006]; day 8 correct [0.93, 0.88, 0.92]; all > 0.8 on day 8: True; all > 0.5 on day 3: True; all p < 0.05 on day 3: True
radius 20 cm: day 3 correct [0.87, 0.8, 0.78], binomial p [0.0, 0.0, 0.0001]; day 8 correct [0.92, 0.88, 0.92]; all > 0.8 on day 8: True; all > 0.5 on day 3: True; all p < 0.05 on day 3: True
First day above chance by the binomial test (15 cm): {'HPa': 1, 'HPb': 1, 'HPc': 2}

Result: reproduced. On day 3 the three rats scored 0.85, 0.80 and 0.75 correct (binomial p <= 0.0006 against 0.5), and on day 8 0.93, 0.88 and 0.92, all above 0.8; the 10 and 20 cm well zones give the same conclusion.

Claim tables1-cell-countsΒΆ

Before the spike-count criterion, the W-track animals yielded 446 CA1 cells (69 in intermediate CA1) and 172 PFC excitatory cells; after exclusions 165 W-track PFC cells entered the SWR analysis.

Cell-days (reading a): units with spikes in the day's W-track runs; areas from cellinfo. The data set has no identifier that follows a unit across days, so reading (b), unique units, cannot be counted. The spike criterion counts spikes in SWR-aligned rasters of -500 to +500 ms (and -1 to +1 s).

InΒ [6]:
cells_1s = hc28.cell_table(R, raster_w=1.0)
cells["included_1s"] = cells_1s["included"].values
tab = cells.assign(ca1=cells.region == "CA1", ica1=cells.area == "iCA1", pfc=cells.region == "PFC")
summ = []
for a, g in list(tab.groupby("animal")) + [("all", tab)]:
    exc = g[~g.fs]
    summ.append(dict(animal=a, CA1_all=int(g.ca1.sum()), CA1_exc=int(exc.ca1.sum()), iCA1_exc=int(exc.ica1.sum()),
                     PFC_all=int(g.pfc.sum()), PFC_exc=int(exc.pfc.sum()),
                     CA1_after50=int((g.included & g.ca1).sum()), PFC_after50=int((g.included & g.pfc).sum()),
                     PFC_after50_1s=int((g.included_1s & g.pfc).sum()), FS_CA1=int((g.fs & g.ca1).sum()), FS_PFC=int((g.fs & g.pfc).sum())))
summ = pd.DataFrame(summ).set_index("animal")
print(summ)
print("\nTable S1 (W-track): HPa 195/54/40, HPb 165/15/80, HPc 86/0/51 (CA1 / iCA1 / PFC); totals 446 / 69 / 172.")
print("Table S2: 165 W-track PFC cells in the SWR analysis.")
tot = summ.loc["all"]
for name, val, exp in [("CA1 excitatory before spike criterion", tot.CA1_exc, 446), ("iCA1", tot.iCA1_exc, 69),
                       ("PFC excitatory before spike criterion", tot.PFC_exc, 172), ("PFC after exclusions", tot.PFC_after50, 165)]:
    print(f"  {name}: {val} against {exp} (within 10%: {abs(val - exp) <= 0.1 * exp})")
pre_only = sum(1 for r in R.values() for day in r["days"].values() for u in day["units"].values()
               if hc28.region(u["area"]) and len(hc28.spikes_in(u, day["runs"])) == 0)
print(f"Units with spikes only in the pre-rest (not counted): {pre_only}")
        CA1_all  CA1_exc  iCA1_exc  PFC_all  PFC_exc  CA1_after50  PFC_after50  PFC_after50_1s  FS_CA1  FS_PFC
animal                                                                                                        
HPa         216      213        61       47       45          157           38              40       3       2
HPb         203      203        20       95       94          160           78              81       0       1
HPc         104       93         0       57       54           75           51              52      11       3
all         523      509        81      199      193          392          167             173      14       6

Table S1 (W-track): HPa 195/54/40, HPb 165/15/80, HPc 86/0/51 (CA1 / iCA1 / PFC); totals 446 / 69 / 172.
Table S2: 165 W-track PFC cells in the SWR analysis.
  CA1 excitatory before spike criterion: 509 against 446 (within 10%: False)
  iCA1: 81 against 69 (within 10%: False)
  PFC excitatory before spike criterion: 193 against 172 (within 10%: False)
  PFC after exclusions: 167 against 165 (within 10%: True)
Units with spikes only in the pre-rest (not counted): 104

Result: partially reproduced. After both exclusions 167 PFC cell-days remain, against 165 (within 10%). Before the spike criterion the counts are higher than Table S1: 509 CA1 against 446, 81 iCA1 against 69 and 193 PFC against 172 (all outside 10%). Unique units cannot be counted: the files carry no identifier that follows a unit across days.

Claim swr-detection-statsΒΆ

Over 53 days 19,888 SWRs were detected (381 +- 18 per day), lasting 96.7 +- 1.2 ms on average, at a mean rate of 0.12 +- 0.01 Hz.

SWRs per the SEP (150-250 Hz, 3 SD, speed < 4 cm/s, 1 s rule). Readings of the claims file: (a) an event on any one ripple tetrode, (b) the mean of the tetrodes' z-scored envelopes; epochs: runs only, or runs and the day's rest epochs used here (the pre-rest); rate over all time or time at < 4 cm/s. Duration is from the threshold crossing, or from the earlier return to the mean (the onset is not defined in the paper), to the return to the mean.

InΒ [7]:
rows = []
for reading in ("any", "mean", "dca1"):
    for epochs_name in ("runs", "runs+pre-rest"):
        for a, r in R.items():
            for d, day in r["days"].items():
                eps = day["runs"] + ([day["pre"]] if epochs_name != "runs" else [])
                n = 0; T = 0; Tlow = 0; dur_thr = []; dur_ext = []
                for e in eps:
                    ep = day["epochs"][e]; s = ep["swr"]
                    ev = s[reading][s["kept_" + reading]]
                    n += len(ev); T += ep["end"] - ep["start"]
                    Tlow += np.sum(ep["pos"][:, 3] < hc28.SWR_MAX_SPEED) * np.median(np.diff(ep["pos"][:, 0]))
                    dur_thr += list(ev[:, 2] - ev[:, 1]); dur_ext += list(ev[:, 2] - ev[:, 0])
                rows.append(dict(reading=reading, epochs=epochs_name, animal=a, day=d, n=n, rate_all=n / T,
                                 rate_low=n / Tlow, dur_thr=np.mean(dur_thr) * 1000, dur_ext=np.mean(dur_ext) * 1000,
                                 dur_thr_all=dur_thr, dur_ext_all=dur_ext))
swr_stats = pd.DataFrame(rows)
out = []
for (reading, eps), g in swr_stats.groupby(["reading", "epochs"]):
    dthr = np.concatenate(g.dur_thr_all.values) * 1000; dext = np.concatenate(g.dur_ext_all.values) * 1000
    out.append(dict(reading=reading, epochs=eps, days=len(g), total=g.n.sum(), per_day=g.n.mean(), per_day_sem=g.n.std(ddof=1) / np.sqrt(len(g)),
                    dur_from_thr=dthr.mean(), dur_from_mean=dext.mean(), rate_all=g.rate_all.mean(), rate_low=g.rate_low.mean()))
out = pd.DataFrame(out)
print(out.round(3).to_string())
print("\nExpected: 381 +- 38.1 per day, 96.7 +- 9.67 ms, 0.12 +- 0.012 Hz")
for _, o in out.iterrows():
    print(f"  {o.reading:4s} {o.epochs:14s} per day within: {abs(o.per_day - 381) <= 38.1}; duration within (from threshold / from mean): "
          f"{abs(o.dur_from_thr - 96.7) <= 9.67} / {abs(o.dur_from_mean - 96.7) <= 9.67}; rate within (all / low speed): "
          f"{abs(o.rate_all - 0.12) <= 0.012} / {abs(o.rate_low - 0.12) <= 0.012}")
print("\nEvents per ripple tetrode and run epoch (single-tetrode detection before the union of reading a; all speeds / speed < 4 cm/s):")
for a, r in R.items():
    n_all = np.array([sum(day["epochs"][e]["swr"]["n_per_tet"][k] for d_, day in r["days"].items() for e in day["runs"]) for k in range(len(r["days"][1]["riptets"]))])
    n_low = np.array([sum(day["epochs"][e]["swr"]["n_low_per_tet"][k] for d_, day in r["days"].items() for e in day["runs"]) for k in range(len(r["days"][1]["riptets"]))])
    n_ep = sum(len(day["runs"]) for day in r["days"].values())
    print(f"  {a}: tetrodes {r['days'][1]['riptets']}: per epoch {np.round(n_all / n_ep).astype(int).tolist()} / {np.round(n_low / n_ep).astype(int).tolist()}; "
          f"union (reading a, all speeds) per epoch {np.mean([len(day['epochs'][e]['swr']['any']) for day in r['days'].values() for e in day['runs']]):.0f}")
print("\nPer animal, reading (a), runs:")
print(swr_stats[(swr_stats.reading == "any") & (swr_stats.epochs == "runs")].groupby("animal")[["n", "rate_all", "rate_low", "dur_ext"]].mean().round(3))
  reading         epochs  days  total   per_day  per_day_sem  dur_from_thr  dur_from_mean  rate_all  rate_low
0     any           runs    24   9951   414.625       20.315        54.361         79.249     0.171     0.335
1     any  runs+pre-rest    24  24069  1002.875       51.505        67.129         96.473     0.216     0.294
2    dca1           runs    24   8479   353.292       18.470        55.097         80.126     0.145     0.284
3    dca1  runs+pre-rest    24  22244   926.833       47.751        66.992         96.568     0.200     0.272
4    mean           runs    24   3347   139.458       10.039        61.692         94.445     0.057     0.113
5    mean  runs+pre-rest    24  11861   494.208       23.031        78.612        117.272     0.107     0.145

Expected: 381 +- 38.1 per day, 96.7 +- 9.67 ms, 0.12 +- 0.012 Hz
  any  runs           per day within: True; duration within (from threshold / from mean): False / False; rate within (all / low speed): False / False
  any  runs+pre-rest  per day within: False; duration within (from threshold / from mean): False / True; rate within (all / low speed): False / False
  dca1 runs           per day within: True; duration within (from threshold / from mean): False / False; rate within (all / low speed): False / False
  dca1 runs+pre-rest  per day within: False; duration within (from threshold / from mean): False / True; rate within (all / low speed): False / False
  mean runs           per day within: False; duration within (from threshold / from mean): False / True; rate within (all / low speed): False / True
  mean runs+pre-rest  per day within: False; duration within (from threshold / from mean): False / False; rate within (all / low speed): False / False

Events per ripple tetrode and run epoch (single-tetrode detection before the union of reading a; all speeds / speed < 4 cm/s):
  HPa: tetrodes [1, 4, 5, 6, 7, 8, 9, 11, 12, 14]: per epoch [234, 279, 189, 120, 184, 116, 116, 125, 157, 131] / [163, 178, 102, 66, 137, 45, 48, 52, 66, 51]; union (reading a, all speeds) per epoch 958
  HPb: tetrodes [1, 3, 4, 5, 6, 16, 17, 18, 20]: per epoch [281, 206, 232, 129, 184, 129, 63, 163, 198] / [170, 113, 137, 50, 109, 59, 21, 77, 78]; union (reading a, all speeds) per epoch 1156
  HPc: tetrodes [1, 2, 3, 4, 5, 6]: per epoch [179, 190, 111, 175, 167, 216] / [102, 112, 56, 92, 96, 99]; union (reading a, all speeds) per epoch 574

Per animal, reading (a), runs:
              n  rate_all  rate_low  dur_ext
animal                                      
HPa     403.250     0.166     0.338   80.981
HPb     517.750     0.212     0.406   77.228
HPc     322.875     0.134     0.260   78.826

Result: partially reproduced. No reading matches all three values. With any one ripple tetrode and run epochs, 414.6 SWRs per day falls within 381 +- 38.1, but the mean duration (79.2 ms from the mean crossing, 54.4 ms from the threshold crossing) and the rate (0.171 Hz over all run time, 0.335 Hz at low speed) are outside. The mean-envelope reading matches the duration (94.4 ms) and the low-speed rate (0.113 Hz) but gives 139.5 SWRs per day.

Claim figs2-swr-at-reward-wellsΒΆ

Most SWRs occurred at reward wells; on the W-track the fraction was 0.71 +- 0.03 of SWRs (n = 24 days).

Per day, the fraction of run SWRs (reading a) whose position at onset lies within 10, 15 or 20 cm of a well (the end points of the task's linear coordinates).

InΒ [8]:
rows = []
for a, r in R.items():
    for d, day in r["days"].items():
        for rad in (10.0, 15.0, 20.0):
            n = k = 0
            for e in day["runs"]:
                ep = day["epochs"][e]; on = hc28.swr_onsets(day, [e]); W = hc28.wells(ep)
                x = np.interp(on, ep["pos"][:, 0], ep["pos"][:, 1]); y = np.interp(on, ep["pos"][:, 0], ep["pos"][:, 2])
                dmin = np.min([np.hypot(x - w[0], y - w[1]) for w in W.values()], 0)
                n += len(on); k += int((dmin < rad).sum())
            rows.append(dict(animal=a, day=d, radius=rad, frac=k / n, n=n))
wells_df = pd.DataFrame(rows)
for rad, g in wells_df.groupby("radius"):
    print(f"radius {rad:.0f} cm: fraction at wells {msem(g.frac)}; per animal {g.groupby('animal').frac.mean().round(3).to_dict()}; "
          f"within 0.71 +- 0.03: {abs(g.frac.mean() - 0.71) <= 0.03}")
radius 10 cm: fraction at wells 0.588 +- 0.031 (n = 24); per animal {'HPa': 0.482, 'HPb': 0.702, 'HPc': 0.58}; within 0.71 +- 0.03: False
radius 15 cm: fraction at wells 0.680 +- 0.032 (n = 24); per animal {'HPa': 0.553, 'HPb': 0.8, 'HPc': 0.687}; within 0.71 +- 0.03: False
radius 20 cm: fraction at wells 0.703 +- 0.032 (n = 24); per animal {'HPa': 0.582, 'HPb': 0.827, 'HPc': 0.701}; within 0.71 +- 0.03: True

Result: reproduced. With a 20 cm zone the fraction of run SWRs at the wells is 0.703 +- 0.032 over 24 days (within 0.71 +- 0.03); with 15 cm it is 0.680 and with 10 cm 0.588. Per animal it ranges from 0.582 (HPa) to 0.827 (HPb) at 20 cm.

SWR modulation of every included cellΒΆ

The shuffle of the SEP (SWR Modulation) on the included cell-days (fast-spiking cells and cells with fewer than 50 spikes in the SWR-aligned rasters excluded), SWRs of the day's W-track runs (reading a, onset at the earlier return of the envelope to its mean, see the SWR claim). Raster -500 to +500 ms (the background window starts at -500 ms); the -1 to +1 s raster is run for PFC as the claims file's second reading. 5000 shuffles per cell.

InΒ [9]:
rng = rng_for("swr-modulation")


def modulation_table(cells, w, regions, reading="any", nshuf=5000, flag="included", onset="ext"):
    out = {}
    for i, c in cells[cells[flag] & cells.region.isin(regions)].iterrows():
        day = R[c.animal]["days"][c.day]
        on = hc28.swr_onsets(day, day["runs"], reading, onset)
        st = hc28.spikes_in(day["units"][(c.tet, c.unit)], day["runs"])
        out[i] = hc28.swr_modulation(st, on, rng, w=w, nshuf=nshuf)
    return out


mod = modulation_table(cells, 0.5, ["PFC", "CA1"])
mod_1s = modulation_table(cells, 1.0, ["PFC"], flag="included_1s")
mod_b = modulation_table(cells, 0.5, ["PFC"], reading="mean")
mod_thr = modulation_table(cells, 0.5, ["PFC", "CA1"], onset="thr")
mod_d = modulation_table(cells, 0.5, ["PFC", "CA1"], reading="dca1")
hc28.BIN = 0.05
mod_50 = modulation_table(cells, 0.5, ["PFC"])
hc28.BIN = 0.010


def category(m):
    return "unmodulated" if not m["modulated"] else ("excited" if m["excited"] else "inhibited")


cells["category"] = pd.Series({i: category(m) for i, m in mod.items()})
cells["mi_ratio"] = pd.Series({i: m["mi_ratio"] for i, m in mod.items()})
cells["mi_z"] = pd.Series({i: m["mi_z"] for i, m in mod.items()})
cells["mi_raw"] = pd.Series({i: m["measure"] for i, m in mod.items()})
print("Cells with a modulation result:", cells.category.notna().sum())
Cells with a modulation result: 559

Claim fig3-pfc-swr-modulation-fractionsΒΆ

About a third of PFC neurons were significantly SWR modulated, in roughly equal numbers excited and inhibited; on the W-track 30 of 165 were SWR-excited (18%) and 26 of 165 SWR-inhibited (16%).

"Similar" is the claims file's rule: excited and inhibited within 10 percentage points of each other as fractions of the modulated cells.

InΒ [10]:
def fractions(mods, label):
    cat = pd.Series({i: category(m) for i, m in mods.items()})
    n = len(cat); ne = (cat == "excited").sum(); ni = (cat == "inhibited").sum(); nu = (cat == "unmodulated").sum()
    nm = ne + ni
    sim = abs(ne - ni) / nm if nm else np.nan
    print(f"{label}: n = {n}; excited {ne} ({ne / n:.3f}), inhibited {ni} ({ni / n:.3f}), unmodulated {nu}; "
          f"modulated {nm / n:.3f}; |excited - inhibited| / modulated = {sim:.3f}")
    return dict(n=n, exc=ne, inh=ni, unm=nu, fe=ne / n, fi=ni / n, sim=sim)


f_main = fractions({i: m for i, m in mod.items() if cells.loc[i, "region"] == "PFC"}, "raster +-0.5 s, reading a (main)")
f_1s = fractions(mod_1s, "raster +-1 s, reading a")
f_b = fractions(mod_b, "raster +-0.5 s, reading b (mean envelope)")
f_thr = fractions({i: m for i, m in mod_thr.items() if cells.loc[i, "region"] == "PFC"}, "raster +-0.5 s, reading a, onset at threshold crossing")
f_d = fractions({i: m for i, m in mod_d.items() if cells.loc[i, "region"] == "PFC"}, "raster +-0.5 s, dorsal CA1 ripple tetrodes only")
f_50 = fractions(mod_50, "raster +-0.5 s, reading a, 50 ms PSTH bins")
exp = dict(exc=(30, 3), inh=(26, 2.6), unm=(109, 10.9), fe=(0.18, 0.018), fi=(0.16, 0.016))
for lab, f in [("main", f_main), ("+-1 s", f_1s), ("reading b", f_b), ("threshold onset", f_thr), ("dorsal only", f_d), ("50 ms bins", f_50)]:
    ok = {k: abs(f[k] - v) <= t for k, (v, t) in exp.items()}
    print(f"  {lab}: within tolerance {ok}; similar (<= 0.10): {f['sim'] <= 0.10}")
pfc = cells[cells.category.notna() & (cells.region == "PFC")]
print("\nPer animal (main):")
tab_s2 = pd.DataFrame({"excited": [12, 13, 5], "inhibited": [11, 9, 6], "unmodulated": [15, 54, 40]}, index=hc28.ANIMALS)
print(pfc.groupby(["animal", "category"]).size().unstack(fill_value=0).join(tab_s2.add_suffix(" (Table S2)")))
print("Table S2 W-track totals 30 / 26 / 109 (165 cells).")
# chance level: the same test on spikes shifted 10 s from the SWRs, where no modulation is expected
rng_null = rng_for("swr-modulation-null")
null_mod = {}
for i in pfc.index:
    c = cells.loc[i]; day = R[c.animal]["days"][c.day]
    on = hc28.swr_onsets(day, day["runs"]) + 10.0
    null_mod[i] = hc28.swr_modulation(hc28.spikes_in(day["units"][(c.tet, c.unit)], day["runs"]), on, rng_null, nshuf=1000)["modulated"]
print(f"False-positive rate of the test on the real PFC spikes with SWR onsets shifted by 10 s: {np.mean(list(null_mod.values())):.3f} "
      f"(n = {len(null_mod)}; nominal 0.05)")
raster +-0.5 s, reading a (main): n = 167; excited 12 (0.072), inhibited 7 (0.042), unmodulated 148; modulated 0.114; |excited - inhibited| / modulated = 0.263
raster +-1 s, reading a: n = 173; excited 12 (0.069), inhibited 5 (0.029), unmodulated 156; modulated 0.098; |excited - inhibited| / modulated = 0.412
raster +-0.5 s, reading b (mean envelope): n = 167; excited 22 (0.132), inhibited 2 (0.012), unmodulated 143; modulated 0.144; |excited - inhibited| / modulated = 0.833
raster +-0.5 s, reading a, onset at threshold crossing: n = 167; excited 17 (0.102), inhibited 4 (0.024), unmodulated 146; modulated 0.126; |excited - inhibited| / modulated = 0.619
raster +-0.5 s, dorsal CA1 ripple tetrodes only: n = 167; excited 14 (0.084), inhibited 9 (0.054), unmodulated 144; modulated 0.138; |excited - inhibited| / modulated = 0.217
raster +-0.5 s, reading a, 50 ms PSTH bins: n = 167; excited 19 (0.114), inhibited 8 (0.048), unmodulated 140; modulated 0.162; |excited - inhibited| / modulated = 0.407
  main: within tolerance {'exc': np.False_, 'inh': np.False_, 'unm': np.False_, 'fe': np.False_, 'fi': np.False_}; similar (<= 0.10): False
  +-1 s: within tolerance {'exc': np.False_, 'inh': np.False_, 'unm': np.False_, 'fe': np.False_, 'fi': np.False_}; similar (<= 0.10): False
  reading b: within tolerance {'exc': np.False_, 'inh': np.False_, 'unm': np.False_, 'fe': np.False_, 'fi': np.False_}; similar (<= 0.10): False
  threshold onset: within tolerance {'exc': np.False_, 'inh': np.False_, 'unm': np.False_, 'fe': np.False_, 'fi': np.False_}; similar (<= 0.10): False
  dorsal only: within tolerance {'exc': np.False_, 'inh': np.False_, 'unm': np.False_, 'fe': np.False_, 'fi': np.False_}; similar (<= 0.10): False
  50 ms bins: within tolerance {'exc': np.False_, 'inh': np.False_, 'unm': np.False_, 'fe': np.False_, 'fi': np.False_}; similar (<= 0.10): False

Per animal (main):
        excited  inhibited  unmodulated  excited (Table S2)  inhibited (Table S2)  unmodulated (Table S2)
animal                                                                                                   
HPa           4          2           32                  12                    11                      15
HPb           6          4           68                  13                     9                      54
HPc           2          1           48                   5                     6                      40
Table S2 W-track totals 30 / 26 / 109 (165 cells).
False-positive rate of the test on the real PFC spikes with SWR onsets shifted by 10 s: 0.066 (n = 167; nominal 0.05)

Result: not reproduced. Of 167 PFC cell-days, 12 are SWR-excited (0.072) and 7 SWR-inhibited (0.042), against 30 and 26 of 165; 148 are unmodulated against 109. Excited and inhibited differ by 0.263 of the modulated cells, beyond the 0.10 rule. No variant comes close: the -1 to +1 s raster, the mean-envelope SWRs, the threshold-crossing onset, dorsal-CA1 tetrodes only and 50 ms bins give 17 to 27 modulated cells, with 2 to 9 inhibited. Every animal has fewer modulated cells than in Table S2 (HPa 6 against 23, HPb 10 against 22, HPc 3 against 11). With the SWR onsets shifted by 10 s the test flags 0.066 of the cells, close to its nominal 0.05.

Claim ca1-swr-modulatedΒΆ

Most CA1 cells were SWR modulated (429 of 536).

InΒ [11]:
ca1 = cells[cells.category.notna() & (cells.region == "CA1")]
fr = (ca1.category != "unmodulated").mean()
print(f"CA1 cell-days: {len(ca1)}; modulated {(ca1.category != 'unmodulated').sum()} ({fr:.3f}); expected 0.80 +- 0.08: {abs(fr - 0.80) <= 0.08}")
print("Excited / inhibited among modulated CA1:", ca1[ca1.category != "unmodulated"].category.value_counts().to_dict())
print("Per animal:", ca1.groupby("animal").apply(lambda g: round((g.category != "unmodulated").mean(), 3), include_groups=False).to_dict())
for lab, mm in (("onset at threshold crossing", mod_thr), ("dorsal CA1 ripple tetrodes", mod_d)):
    v = [m["modulated"] for i, m in mm.items() if cells.loc[i, "region"] == "CA1"]
    print(f"Variant, {lab}: {np.sum(v)} of {len(v)} modulated ({np.mean(v):.3f})")
print("dorsal CA1 cells only:", round((ca1[ca1.area == "CA1"].category != "unmodulated").mean(), 3), "; iCA1 only:",
      round((ca1[ca1.area == "iCA1"].category != "unmodulated").mean(), 3))
CA1 cell-days: 392; modulated 255 (0.651); expected 0.80 +- 0.08: False
Excited / inhibited among modulated CA1: {'excited': 253, 'inhibited': 2}
Per animal: {'HPa': 0.694, 'HPb': 0.538, 'HPc': 0.8}
Variant, onset at threshold crossing: 235 of 392 modulated (0.599)
Variant, dorsal CA1 ripple tetrodes: 265 of 392 modulated (0.676)
dorsal CA1 cells only: 0.687 ; iCA1 only: 0.439

Result: partially reproduced. Most CA1 cell-days are SWR modulated, 255 of 392 (0.651), but below 0.80 +- 0.08; the variants give 0.599 and 0.676. Per animal the fraction is 0.694, 0.538 and 0.800, and 0.439 for iCA1 cells.

Claim fig3-transient-responsesΒΆ

Both SWR-excited and SWR-inhibited PFC populations respond transiently, their mean rates returning to baseline within about 300 ms of SWR onset.

Population mean of the per-cell z-scored SWR-PSTHs (z-scored over the whole -500 to +500 ms PSTH, a standard choice). Baseline -500 to -100 ms. Return: the first bin after the extremum from which the population mean stays within (a) the baseline mean +- 1 SD, (b) the 2.5-97.5 percentile range of the baseline bins, through +500 ms.

InΒ [12]:
centers = next(iter(mod.values()))["centers"]
base = (centers > hc28.BACKGROUND[0]) & (centers < hc28.BACKGROUND[1])


def zpsth(i):
    p = mod[i]["psth"]; s = p.std()
    return (p - p.mean()) / s if s > 0 else np.zeros_like(p)


def return_time(pop, sign, how):
    b = pop[base]
    lo, hi = (b.mean() - b.std(), b.mean() + b.std()) if how == "a" else tuple(np.percentile(b, [2.5, 97.5]))
    after = np.flatnonzero(centers > 0)
    ext = after[np.argmax(sign * pop[after])]
    inside = (pop >= lo) & (pop <= hi)
    for j in range(ext, len(pop)):
        if inside[j:].all():
            return centers[j] - hc28.BIN / 2
    return np.nan


pops = {}
fig, ax = plt.subplots(figsize=(6, 3))
for catg, sign in (("excited", 1), ("inhibited", -1)):
    idx = pfc.index[pfc.category == catg]
    pop = np.mean([zpsth(i) for i in idx], 0)
    pops[catg] = pop
    for how in ("a", "b"):
        print(f"{catg} (n = {len(idx)}): extremum at {centers[centers > 0][np.argmax(sign * pop[centers > 0])] * 1000:.0f} ms; "
              f"back at baseline from {return_time(pop, sign, how) * 1000:.0f} ms (reading {how})")
    ax.plot(centers * 1000, pop, label=catg)
ax.axvline(300, ls=":", c="k"); ax.set_xlabel("time from SWR onset (ms)"); ax.set_ylabel("mean z-scored rate"); ax.legend()
print("Plotted range: %.2f to %.2f (all points within the axes)" % (min(p.min() for p in pops.values()), max(p.max() for p in pops.values())))
plt.show()
for a in R:
    s = pfc[pfc.animal == a]
    for catg, sign in (("excited", 1), ("inhibited", -1)):
        idx = s.index[s.category == catg]
        if len(idx) > 2:
            pop = np.mean([zpsth(i) for i in idx], 0)
            print(f"  {a} {catg} (n = {len(idx)}): back at baseline from {return_time(pop, sign, 'a') * 1000:.0f} ms (a), {return_time(pop, sign, 'b') * 1000:.0f} ms (b)")
excited (n = 12): extremum at 55 ms; back at baseline from 480 ms (reading a)
excited (n = 12): extremum at 55 ms; back at baseline from 330 ms (reading b)
inhibited (n = 7): extremum at 95 ms; back at baseline from 480 ms (reading a)
inhibited (n = 7): extremum at 95 ms; back at baseline from 480 ms (reading b)
Plotted range: -1.39 to 1.96 (all points within the axes)
No description has been provided for this image
  HPa excited (n = 4): back at baseline from nan ms (a), 220 ms (b)
  HPb excited (n = 6): back at baseline from nan ms (a), 330 ms (b)
  HPb inhibited (n = 4): back at baseline from nan ms (a), 480 ms (b)

Result: not reproduced. The excited population peaks at 55 ms and the inhibited population is lowest at 95 ms, but under the 1 SD reading both are back within the baseline band only from 480 ms; under the percentile reading the excited population returns at 330 ms and the inhibited at 480 ms. With 12 excited and 7 inhibited cells, the population means are noisy.

Claim fig3de-ca1-precedes-pfc-peakΒΆ

The peak of CA1 population SWR activity precedes the peak of SWR-excited and the trough of SWR-inhibited PFC activity (54 +- 2, 100 +- 9 and 84 +- 10 ms), while excited and inhibited PFC timing do not differ.

Per cell, the time of the peak (CA1 SWR-modulated cells, PFC excited) or trough (PFC inhibited) of the SWR-PSTH (10 ms bins, bin centres), searched in (a) 0-200 ms, (b) 0-500 ms.

InΒ [13]:
ca1_mod = ca1.index[ca1.category != "unmodulated"]
exc = pfc.index[pfc.category == "excited"]; inh = pfc.index[pfc.category == "inhibited"]
timing = {}
for win, lab in (((0.0, 0.2), "a"), ((0.0, 0.5), "b")):
    for sd_ref in ("baseline", "whole"):
        t_ca1 = np.array([hc28.psth_timing(mod[i]["psth"], centers, 1, win, sd_ref) for i in ca1_mod]) * 1000
        t_exc = np.array([hc28.psth_timing(mod[i]["psth"], centers, 1, win, sd_ref) for i in exc]) * 1000
        t_inh = np.array([hc28.psth_timing(mod[i]["psth"], centers, -1, win, sd_ref) for i in inh]) * 1000
        timing[(lab, sd_ref)] = (t_ca1, t_exc, t_inh)
for lab in ("a", "b"):
    t_ca1, t_exc, t_inh = timing[(lab, "baseline")]
    print(f"Reading {lab}: peak CA1 {msem(t_ca1[:, 0])}, excited {msem(t_exc[:, 0])}, inhibited trough {msem(t_inh[:, 0])} ms")
    p1, p2, p3 = ranksum(t_ca1[:, 0], t_exc[:, 0]), ranksum(t_ca1[:, 0], t_inh[:, 0]), ranksum(t_exc[:, 0], t_inh[:, 0])
    print(f"   rank-sum CA1 vs excited p = {p1:.2g}, CA1 vs inhibited p = {p2:.2g}, excited vs inhibited p = {p3:.2g}")
    print(f"   CA1 earlier than both at p < 0.05: {np.nanmean(t_ca1[:, 0]) < min(np.nanmean(t_exc[:, 0]), np.nanmean(t_inh[:, 0])) and p1 < 0.05 and p2 < 0.05}; "
          f"excited vs inhibited not different at 0.01: {p3 >= 0.01}")
    print(f"   means within tolerance: CA1 54+-2 {abs(np.nanmean(t_ca1[:, 0]) - 54) <= 2}, excited 100+-9 {abs(np.nanmean(t_exc[:, 0]) - 100) <= 9}, "
          f"inhibited 84+-10 {abs(np.nanmean(t_inh[:, 0]) - 84) <= 10}")
pd_ca1 = np.array([zpsth(i) for i in ca1_mod]).mean(0)
print("Population CA1 peak at %.0f ms; excited PFC peak at %.0f ms; inhibited PFC trough at %.0f ms" % (
    centers[centers > 0][np.argmax(pd_ca1[centers > 0])] * 1000, centers[centers > 0][np.argmax(pops["excited"][centers > 0])] * 1000,
    centers[centers > 0][np.argmin(pops["inhibited"][centers > 0])] * 1000))
Reading a: peak CA1 46.176 +- 2.541 (n = 255), excited 59.167 +- 14.640 (n = 12), inhibited trough 86.429 +- 13.702 (n = 7) ms
   rank-sum CA1 vs excited p = 0.35, CA1 vs inhibited p = 0.0036, excited vs inhibited p = 0.12
   CA1 earlier than both at p < 0.05: False; excited vs inhibited not different at 0.01: True
   means within tolerance: CA1 54+-2 False, excited 100+-9 False, inhibited 84+-10 True
Reading b: peak CA1 53.745 +- 3.992 (n = 255), excited 74.167 +- 19.324 (n = 12), inhibited trough 135.000 +- 51.824 (n = 7) ms
   rank-sum CA1 vs excited p = 0.22, CA1 vs inhibited p = 0.0039, excited vs inhibited p = 0.19
   CA1 earlier than both at p < 0.05: False; excited vs inhibited not different at 0.01: True
   means within tolerance: CA1 54+-2 True, excited 100+-9 False, inhibited 84+-10 False
Population CA1 peak at 15 ms; excited PFC peak at 55 ms; inhibited PFC trough at 95 ms

Result: not reproduced. Peak times are CA1 46.2 +- 2.5 ms, excited PFC 59.2 +- 14.6 ms and inhibited PFC trough 86.4 +- 13.7 ms (0-200 ms search). CA1 is earlier than the inhibited trough (p = 0.0036) but not significantly earlier than the excited peak (p = 0.35); excited and inhibited do not differ (p = 0.12). The 0-500 ms search gives the same pattern (p = 0.22 for CA1 against excited). Only the inhibited trough (86.4 ms) is within its tolerance.

Claim fig3e-onset-later-in-pfcΒΆ

SWR modulation onset (the first rise or fall of 1 SD from the mean) is later for PFC than for CA1 cells, and does not differ between excited and inhibited PFC cells.

Onset: first bin after 0 at which the PSTH is 1 SD above (below) the mean, with the mean and SD of (a) the baseline -500 to -100 ms, (b) the whole PSTH.

InΒ [14]:
for sd_ref, lab in (("baseline", "a"), ("whole", "b")):
    t_ca1, t_exc, t_inh = timing[("a", sd_ref)]
    o1, o2, o3 = t_ca1[:, 1], t_exc[:, 1], t_inh[:, 1]
    p1, p2, p3 = ranksum(o1, o2), ranksum(o1, o3), ranksum(o2, o3)
    print(f"Reading {lab}: onset CA1 {msem(o1)}, excited {msem(o2)}, inhibited {msem(o3)} ms; "
          f"no onset found: {np.isnan(o1).sum()}, {np.isnan(o2).sum()}, {np.isnan(o3).sum()}")
    print(f"   rank-sum CA1 vs excited p = {p1:.2g}, CA1 vs inhibited p = {p2:.2g}, excited vs inhibited p = {p3:.2g}; "
          f"both later at 0.05: {np.nanmean(o2) > np.nanmean(o1) and np.nanmean(o3) > np.nanmean(o1) and p1 < 0.05 and p2 < 0.05}; "
          f"excited vs inhibited not different at 0.01: {p3 >= 0.01}")
Reading a: onset CA1 10.098 +- 1.036 (n = 255), excited 13.333 +- 4.410 (n = 12), inhibited 20.714 +- 7.190 (n = 7) ms; no onset found: 0, 0, 0
   rank-sum CA1 vs excited p = 0.58, CA1 vs inhibited p = 0.093, excited vs inhibited p = 0.35; both later at 0.05: False; excited vs inhibited not different at 0.01: True
Reading b: onset CA1 13.392 +- 1.020 (n = 255), excited 19.167 +- 5.430 (n = 12), inhibited 29.286 +- 8.959 (n = 7) ms; no onset found: 0, 0, 0
   rank-sum CA1 vs excited p = 0.4, CA1 vs inhibited p = 0.052, excited vs inhibited p = 0.31; both later at 0.05: False; excited vs inhibited not different at 0.01: True

Result: not reproduced. Onsets are CA1 10.1 ms, excited 13.3 ms and inhibited 20.7 ms with the baseline SD; neither PFC group is later than CA1 at p < 0.05 (p = 0.58 and 0.093). With the SD of the whole PSTH the inhibited group is later (p = 0.036) but the excited is not (p = 0.40). Excited and inhibited do not differ under either reading.

Theta phase locking of every included cellΒΆ

SEP, Theta Phase Locking: phases of the CA1 reference (corpus callosum) LFP at 150 Hz, 6-12 Hz; spikes in theta periods (speed > 5 cm/s, no SWR on any ripple tetrode); cells with at least 50 such spikes; Rayleigh test p < 0.05; kappa from a von Mises maximum-likelihood fit. Phase 0 deg is the theta peak and 180 deg the trough of the reference LFP. A spike's phase is interpolated between the 150 Hz samples (on the unwrapped phase).

InΒ [15]:
th_rows = {}
phases = {}
for i, c in cells[cells.category.notna()].iterrows():
    day = R[c.animal]["days"][c.day]
    ph = hc28.theta_spike_phases(day, day["units"][(c.tet, c.unit)])
    phases[i] = ph
    if len(ph) >= 50:
        p, Rb, mu = hc28.rayleigh(ph)
        th_rows[i] = dict(n_theta=len(ph), p_rayleigh=p, kappa=hc28.vm_kappa(ph), mean_phase=mu, peak_phase=hc28.hist_peak_phase(ph),
                          peak_phase45=hc28.hist_peak_phase(ph, 45))
    else:
        th_rows[i] = dict(n_theta=len(ph))
th = pd.DataFrame.from_dict(th_rows, orient="index")
for col in th:
    cells[col] = th[col]
cells["theta_locked"] = cells.p_rayleigh < 0.05
print("Cells with >= 50 theta spikes:", cells.groupby("region").apply(lambda g: int((g.n_theta >= 50).sum()), include_groups=False).to_dict(),
      "of", cells[cells.category.notna()].groupby("region").size().to_dict())
Cells with >= 50 theta spikes: {'CA1': 387, 'PFC': 163} of {'CA1': 392, 'PFC': 167}

Claim fig4-theta-locked-fractionΒΆ

60% of PFC neurons (189 of 312) were significantly phase locked to hippocampal theta.

Denominator: all PFC cells of the SWR analysis.

InΒ [16]:
pfc = cells[cells.category.notna() & (cells.region == "PFC")]
nl = int(pfc.theta_locked.sum())
print(f"PFC theta locked: {nl} of {len(pfc)} ({nl / len(pfc):.3f}); of cells with >= 50 theta spikes: {nl} of {(pfc.n_theta >= 50).sum()} "
      f"({nl / (pfc.n_theta >= 50).sum():.3f}); expected 0.60 +- 0.06")
print("Per animal:", pfc.groupby("animal").theta_locked.mean().round(3).to_dict())
for a_thr in (0.01, 0.05):
    print(f"  Rayleigh p < {a_thr}: {(pfc.p_rayleigh < a_thr).sum()} of {len(pfc)}")
print("CA1 theta locked:", int(cells[(cells.region == 'CA1') & cells.category.notna()].theta_locked.sum()), "of", int((cells.region == 'CA1').sum() and cells[(cells.region == 'CA1') & cells.category.notna()].shape[0]))
PFC theta locked: 91 of 167 (0.545); of cells with >= 50 theta spikes: 91 of 163 (0.558); expected 0.60 +- 0.06
Per animal: {'HPa': 0.763, 'HPb': 0.513, 'HPc': 0.431}
  Rayleigh p < 0.01: 70 of 167
  Rayleigh p < 0.05: 91 of 167
CA1 theta locked: 342 of 392

Result: reproduced. 91 of 167 PFC cell-days (0.545) are theta locked at Rayleigh p < 0.05, inside 0.60 +- 0.06 by 0.005, at the edge of the tolerance. Per animal the fraction is 0.763, 0.513 and 0.431.

Claim fig4a-preferred-phasesΒΆ

CA1 neurons prefer the falling phase of theta, while PFC neurons are most often locked to the theta trough.

Preferred phase: the peak of each locked cell's phase histogram, in 15 deg bins (a standard choice that divides the 45 deg group bins evenly) and in 45 deg bins; the circular mean of the spike phases as a variant; the inverted reference (phase + 180 deg) as the second polarity reading.

InΒ [17]:
def circmean(deg):
    a = np.radians(deg)
    return np.degrees(np.arctan2(np.sin(a).mean(), np.cos(a).mean())) % 360


ca1_l = cells[(cells.region == "CA1") & cells.theta_locked.fillna(False).astype(bool)]
pfc_l = pfc[pfc.theta_locked.fillna(False).astype(bool)]
for col in ("peak_phase", "peak_phase45", "mean_phase"):
    for flip in (0, 180):
        c_ph = (ca1_l[col] + flip) % 360; p_ph = (pfc_l[col] + flip) % 360
        cm = circmean(c_ph); pm = circmean(p_ph)
        h, e = np.histogram(p_ph, np.arange(0, 361, 45))
        modal = (e[np.argmax(h)], e[np.argmax(h)] + 45)
        falling = 0 < cm < 180
        trough = modal[0] <= 180 < modal[1] or modal[0] < 180 <= modal[1]
        h15 = np.histogram(p_ph, np.arange(0, 361, 15))[0] if col == "peak_phase" else None
        print(f"{col}, reference {'inverted' if flip else 'as recorded'}: CA1 circular mean {cm:.0f} deg (n = {len(c_ph)}), falling (0-180): {falling}; "
              f"PFC circular mean {pm:.0f} deg (n = {len(p_ph)}), modal 45-deg bin {modal}, contains 180: {trough}; "
              f"CA1 earlier than PFC: {((pm - cm) % 360) < 180}; PFC 45-deg histogram {h.tolist()}" +
              (f"; PFC 15-deg histogram {h15.tolist()}" if h15 is not None else ""))
print("Columns: peak_phase = peak of each cell's 15-degree spike-phase histogram (3 possible values per 45-degree bin); "
      "peak_phase45 = peak of a 45-degree histogram; mean_phase = circular mean of the spike phases.")
peak_phase, reference as recorded: CA1 circular mean 38 deg (n = 342), falling (0-180): True; PFC circular mean 131 deg (n = 91), modal 45-deg bin (np.int64(45), np.int64(90)), contains 180: False; CA1 earlier than PFC: True; PFC 45-deg histogram [10, 19, 12, 8, 15, 12, 10, 5]; PFC 15-deg histogram [4, 4, 2, 8, 6, 5, 4, 3, 5, 1, 4, 3, 5, 7, 3, 3, 2, 7, 6, 1, 3, 2, 2, 1]
peak_phase, reference inverted: CA1 circular mean 218 deg (n = 342), falling (0-180): False; PFC circular mean 311 deg (n = 91), modal 45-deg bin (np.int64(225), np.int64(270)), contains 180: False; CA1 earlier than PFC: True; PFC 45-deg histogram [15, 12, 10, 5, 10, 19, 12, 8]; PFC 15-deg histogram [5, 7, 3, 3, 2, 7, 6, 1, 3, 2, 2, 1, 4, 4, 2, 8, 6, 5, 4, 3, 5, 1, 4, 3]
peak_phase45, reference as recorded: CA1 circular mean 37 deg (n = 342), falling (0-180): True; PFC circular mean 135 deg (n = 91), modal 45-deg bin (np.int64(45), np.int64(90)), contains 180: False; CA1 earlier than PFC: True; PFC 45-deg histogram [11, 14, 14, 12, 11, 12, 12, 5]
peak_phase45, reference inverted: CA1 circular mean 217 deg (n = 342), falling (0-180): False; PFC circular mean 315 deg (n = 91), modal 45-deg bin (np.int64(225), np.int64(270)), contains 180: False; CA1 earlier than PFC: True; PFC 45-deg histogram [11, 12, 12, 5, 11, 14, 14, 12]
mean_phase, reference as recorded: CA1 circular mean 28 deg (n = 342), falling (0-180): True; PFC circular mean 148 deg (n = 91), modal 45-deg bin (np.int64(90), np.int64(135)), contains 180: False; CA1 earlier than PFC: True; PFC 45-deg histogram [12, 12, 14, 9, 13, 14, 7, 10]
mean_phase, reference inverted: CA1 circular mean 208 deg (n = 342), falling (0-180): False; PFC circular mean 328 deg (n = 91), modal 45-deg bin (np.int64(45), np.int64(90)), contains 180: False; CA1 earlier than PFC: True; PFC 45-deg histogram [13, 14, 7, 10, 12, 12, 14, 9]
Columns: peak_phase = peak of each cell's 15-degree spike-phase histogram (3 possible values per 45-degree bin); peak_phase45 = peak of a 45-degree histogram; mean_phase = circular mean of the spike phases.

Result: not reproduced. CA1 cells prefer the falling phase (circular mean 38 deg with the reference as recorded) and PFC preferred phases come later (circular mean 131 deg), but the modal 45-degree bin of PFC preferred phases is 45 to 90 deg (19 cells), which does not contain the trough; the 180 to 225 deg bin holds 15. Peaks taken from 45-degree histograms tie the 45 to 90 and 90 to 135 deg bins (14 cells each), and the circular mean phases tie the 90 to 135 and 225 to 270 deg bins (14 each); no tied bin contains 180 deg. With the reference inverted, CA1 is outside the falling phase (218 deg).

Claim fig4-swr-modulated-more-theta-lockedΒΆ

Most SWR-modulated PFC neurons were also theta locked (44 of 57 excited, 77%; 37 of 52 inhibited, 71%), more than unmodulated neurons (108 of 203, 53%), with no difference between excited and inhibited.

InΒ [18]:
from statsmodels.stats.proportion import proportions_ztest
g = pfc.groupby("category").theta_locked.agg(["sum", "size"])
g["frac"] = g["sum"] / g["size"]
print(g)


def zprop(a, b):
    if g.loc[a, "size"] == 0 or g.loc[b, "size"] == 0:
        return np.nan
    return proportions_ztest([g.loc[a, "sum"], g.loc[b, "sum"]], [g.loc[a, "size"], g.loc[b, "size"]])[1]


pe_u, pi_u, pe_i = zprop("excited", "unmodulated"), zprop("inhibited", "unmodulated"), zprop("excited", "inhibited")
print(f"z tests: excited vs unmodulated p = {pe_u:.3g}, inhibited vs unmodulated p = {pi_u:.3g}, excited vs inhibited p = {pe_i:.3g}")
print("Expected fractions 0.77 +- 0.077, 0.71 +- 0.071, 0.53 +- 0.053")
             sum  size      frac
category                        
excited       11    12  0.916667
inhibited      6     7  0.857143
unmodulated   74   148  0.500000
z tests: excited vs unmodulated p = 0.00541, inhibited vs unmodulated p = 0.0647, excited vs inhibited p = 0.683
Expected fractions 0.77 +- 0.077, 0.71 +- 0.071, 0.53 +- 0.053

Result: not reproduced. 11 of 12 excited (0.917), 6 of 7 inhibited (0.857) and 74 of 148 unmodulated (0.500) cells are theta locked. Excited exceed unmodulated (p = 0.0054), but inhibited do not reach p <= 0.01 (p = 0.065, 7 cells); excited and inhibited do not differ (p = 0.68). The unmodulated fraction is within its tolerance; the modulated fractions are above theirs.

Claim fig4b-kappaΒΆ

Theta-locked SWR-excited and SWR-inhibited PFC cells lock more strongly (kappa 0.2 +- 0.02 and 0.25 +- 0.04) than SWR-unmodulated cells (0.12 +- 0.01), with no difference between excited and inhibited.

Readings: (a) theta-locked cells only, (b) all cells with >= 50 theta spikes.

InΒ [19]:
for lab, s in (("a", pfc[pfc.theta_locked.fillna(False).astype(bool)]), ("b", pfc[pfc.n_theta >= 50])):
    k = {c: s[s.category == c].kappa for c in ("excited", "inhibited", "unmodulated")}
    print(f"Reading {lab}: " + "; ".join(f"{c} {msem(v)}" for c, v in k.items()))
    print(f"   rank-sum excited vs unmodulated p = {ranksum(k['excited'], k['unmodulated']):.3g}, inhibited vs unmodulated p = "
          f"{ranksum(k['inhibited'], k['unmodulated']):.3g}, excited vs inhibited p = {ranksum(k['excited'], k['inhibited']):.3g}")
Reading a: excited 0.272 +- 0.071 (n = 11); inhibited 0.101 +- 0.019 (n = 6); unmodulated 0.191 +- 0.026 (n = 74)
   rank-sum excited vs unmodulated p = 0.129, inhibited vs unmodulated p = 0.171, excited vs inhibited p = 0.0444
Reading b: excited 0.265 +- 0.065 (n = 12); inhibited 0.095 +- 0.017 (n = 7); unmodulated 0.135 +- 0.014 (n = 144)
   rank-sum excited vs unmodulated p = 0.00253, inhibited vs unmodulated p = 0.77, excited vs inhibited p = 0.018

Result: not reproduced. For theta-locked cells kappa is 0.272 (excited), 0.101 (inhibited) and 0.191 (unmodulated), with no difference at p < 0.01 (excited against unmodulated p = 0.13, inhibited against unmodulated p = 0.17, excited against inhibited p = 0.044). Over all cells with 50 theta spikes excited exceed unmodulated (p = 0.0025), but inhibited (0.095) do not (p = 0.77).

Claim fig4c-theta-locked-more-swr-modulatedΒΆ

Theta-modulated PFC neurons (n = 189) are more strongly SWR modulated than neurons that are not theta modulated (n = 123), SWR modulation index 5.2 +- 0.8 against 2.5 +- 0.4.

Index readings: (a) measure / mean shuffled measure, (b) z-score against the shuffled measures, (c) the raw measure (Hz^2).

InΒ [20]:
locked = pfc.theta_locked.fillna(False).astype(bool)
for lab, col in (("a", "mi_ratio"), ("b", "mi_z"), ("c", "mi_raw")):
    x, y = pfc.loc[locked, col], pfc.loc[~locked, col]
    print(f"Reading {lab}: theta modulated {msem(x)}, not theta modulated {msem(y)}; rank-sum p = {ranksum(x, y):.3g}; "
          f"medians {x.median():.3g} and {y.median():.3g}")
print("Expected 5.2 +- 0.8 and 2.5 +- 0.4")
Reading a: theta modulated 1.368 +- 0.123 (n = 91), not theta modulated 0.999 +- 0.038 (n = 76); rank-sum p = 0.0039; medians 1.07 and 0.943
Reading b: theta modulated 1.133 +- 0.380 (n = 91), not theta modulated 0.010 +- 0.109 (n = 76); rank-sum p = 0.00533; medians 0.212 and -0.172
Reading c: theta modulated 27.419 +- 6.265 (n = 91), not theta modulated 9.334 +- 1.387 (n = 76); rank-sum p = 2.06e-05; medians 8.75 and 3.57
Expected 5.2 +- 0.8 and 2.5 +- 0.4

Result: partially reproduced. Theta-modulated PFC cells (91) are more strongly SWR modulated than the others (76) under every reading of the index (rank-sum p = 0.0039, 0.0053 and 2.1e-05), but no reading gives values near 5.2 and 2.5 (ratio 1.37 and 1.00; z 1.13 and 0.01; raw 27.4 and 9.3).

Claim fig4-preferred-phase-concentrationΒΆ

Preferred theta phases of SWR-excited neurons are more concentrated than those of SWR-unmodulated neurons (p = 0.005), while SWR-inhibited and unmodulated neurons do not differ, nor do excited and inhibited (p > 0.1).

Two-sample Kuiper tests on the preferred phases (histogram peak) of all cells of each group with a preferred phase (>= 50 theta spikes; the paper's n are all cells of each group), and of locked cells only.

InΒ [21]:
from astropy.stats import kuiper_two
for lab, s, col in (("all cells with >= 50 theta spikes", pfc[pfc.n_theta >= 50], "peak_phase"), ("theta-locked only", pfc[locked], "peak_phase"),
                    ("all cells, circular mean phase (no ties)", pfc[pfc.n_theta >= 50], "mean_phase")):
    ph = {c: s[s.category == c][col].values for c in ("excited", "inhibited", "unmodulated")}
    out = []
    for a_, b_ in (("excited", "unmodulated"), ("excited", "inhibited"), ("inhibited", "unmodulated")):
        if len(ph[a_]) > 1 and len(ph[b_]) > 1:
            D, p = kuiper_two(ph[a_], ph[b_])
            out.append(f"{a_} vs {b_} p = {p:.3g} (n = {len(ph[a_])}, {len(ph[b_])})")
    rb = {c: hc28.rayleigh(v)[1] if len(v) else np.nan for c, v in ph.items()}
    print(f"{lab}: " + "; ".join(out))
    print("   resultant length of preferred phases:", {c: round(v, 3) for c, v in rb.items()})
all cells with >= 50 theta spikes: excited vs unmodulated p = 0.351 (n = 12, 144); excited vs inhibited p = 0.343 (n = 12, 7); inhibited vs unmodulated p = 0.808 (n = 7, 144)
   resultant length of preferred phases: {'excited': np.float64(0.41), 'inhibited': np.float64(0.371), 'unmodulated': np.float64(0.039)}
theta-locked only: excited vs unmodulated p = 0.427 (n = 11, 74); excited vs inhibited p = 0.422 (n = 11, 6); inhibited vs unmodulated p = 0.885 (n = 6, 74)
   resultant length of preferred phases: {'excited': np.float64(0.446), 'inhibited': np.float64(0.271), 'unmodulated': np.float64(0.061)}
all cells, circular mean phase (no ties): excited vs unmodulated p = 0.139 (n = 12, 144); excited vs inhibited p = 0.125 (n = 12, 7); inhibited vs unmodulated p = 0.232 (n = 7, 144)
   resultant length of preferred phases: {'excited': np.float64(0.517), 'inhibited': np.float64(0.354), 'unmodulated': np.float64(0.061)}

Result: not reproduced. The preferred phases of excited cells are not more concentrated than those of unmodulated cells by the Kuiper test (p = 0.35 over all cells with a preferred phase, 0.43 over locked cells, 0.14 with circular mean phases), although their resultant length is larger (0.41 against 0.039). The other two comparisons are not significant (p = 0.34 and 0.81).

Claim theta-lag-pastΒΆ

PFC cells phase lock best to hippocampal theta about 15 ms in the past.

Theta phase read at spike time + shift, shifts -100 to +100 ms in 5 ms steps; kappa per shift over the theta-locked PFC cells. A negative best shift means theta in the past. Readings: (a) the shift that maximizes mean kappa, (b) the median of each cell's best shift.

InΒ [22]:
shifts = np.arange(-0.100, 0.1001, 0.005)
K = []
for i in pfc.index[locked]:
    c = cells.loc[i]; day = R[c.animal]["days"][c.day]; u = day["units"][(c.tet, c.unit)]
    K.append([hc28.vm_kappa(hc28.theta_spike_phases(day, u, s)) for s in shifts])
K = np.array(K)
mk = K.mean(0)
best_a = shifts[np.argmax(mk)] * 1000
best_b = np.median(shifts[np.argmax(K, 1)]) * 1000
print(f"n = {len(K)} theta-locked PFC cells; mean kappa at 0 ms {mk[np.argmin(abs(shifts))]:.3f}, max {mk.max():.3f}")
print(f"Reading a: best shift {best_a:.0f} ms; reading b: median best shift {best_b:.0f} ms; expected -15 +- 10 ms")
print("Mean kappa by shift (ms: kappa):", {int(round(s * 1000)): round(v, 3) for s, v in zip(shifts[::4], mk[::4])})
n = 91 theta-locked PFC cells; mean kappa at 0 ms 0.195, max 0.195
Reading a: best shift 0 ms; reading b: median best shift -15 ms; expected -15 +- 10 ms
Mean kappa by shift (ms: kappa): {-100: np.float64(0.173), -80: np.float64(0.18), -60: np.float64(0.186), -40: np.float64(0.191), -20: np.float64(0.194), 0: np.float64(0.195), 20: np.float64(0.193), 40: np.float64(0.19), 60: np.float64(0.185), 80: np.float64(0.178), 100: np.float64(0.17)}

Result: reproduced. Under reading (b) the median of the cells' best shifts is -15 ms, theta in the past. Under reading (a) the mean kappa peaks at 0 ms. Mean kappa varies little across shifts (0.170 to 0.195 between -100 and +100 ms), so the outcome rests on reading (b).

Firing properties of the PFC groupsΒΆ

InΒ [23]:
def speed_at(day, e, t):
    ep = day["epochs"][e]
    return np.interp(t, ep["pos"][:, 0], ep["pos"][:, 3])


def time_where(day, e, cond):
    ep = day["epochs"][e]
    dt = np.median(np.diff(ep["pos"][:, 0]))
    return np.sum(cond(ep["pos"][:, 3])) * dt


prop = {}
maps_all = {}
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    day = R[a]["days"][d]
    units = {(r.tet, r.unit): day["units"][(r.tet, r.unit)] for r in g.itertuples()}
    maps = hc28.rate_maps(day, units)
    maps_ns = hc28.rate_maps(day, units, speed=0)
    T_theta = hc28.theta_time(day, 0.0)
    on = hc28.swr_onsets(day, day["runs"])
    for i, r in zip(g.index, g.itertuples()):
        u = units[(r.tet, r.unit)]
        maps_all[i] = maps[(r.tet, r.unit)]
        n_theta = 0; n4 = 0; T4 = 0; n10 = 0; T10 = 0
        for e in day["runs"]:
            st = u["times"].get(e, np.zeros(0))
            if len(st) == 0:
                T4 += time_where(day, e, lambda v: v > 4); T10 += time_where(day, e, lambda v: v > 10)
                continue
            m, _ = hc28.theta_mask_times(day, e, st)
            n_theta += m.sum()
            v = speed_at(day, e, st)
            n4 += np.sum(v > 4); T4 += time_where(day, e, lambda v: v > 4)
            n10 += np.sum(v > 10); T10 += time_where(day, e, lambda v: v > 10)
        st = hc28.spikes_in(u, day["runs"])
        pre = (np.searchsorted(st, on - 0.1) - np.searchsorted(st, on - 0.5)).sum() / (0.4 * len(on))
        ai_m, di_m = hc28.arm_direction_index(maps[(r.tet, r.unit)], "mean")
        ai_p, di_p = hc28.arm_direction_index(maps[(r.tet, r.unit)], "peak")
        prop[i] = dict(rate_theta=n_theta / T_theta, rate_v4=n4 / T4, rate_run=r.rate, coverage=hc28.coverage(maps[(r.tet, r.unit)]),
                       coverage_nospeed=hc28.coverage(maps_ns[(r.tet, r.unit)]), arm_mean=ai_m, dir_mean=di_m, arm_peak=ai_p, dir_peak=di_p,
                       pre_swr_rate=pre, highspeed_rate=n10 / T10)
prop = pd.DataFrame.from_dict(prop, orient="index")
for col in prop:
    cells[col] = prop[col]
pfc = cells[cells.category.notna() & (cells.region == "PFC")]
cats = ("excited", "inhibited", "unmodulated")

Claim fig5b-mean-ratesΒΆ

SWR-excited and SWR-inhibited PFC cells fire at higher mean rates during movement than SWR-unmodulated cells (4.2 +- 0.5, 3.2 +- 0.4 and 2.1 +- 0.2 Hz), and excited and inhibited do not differ.

Readings: (a) speed > 5 cm/s with no SWR (theta periods), (b) speed > 4 cm/s, (c) the whole run.

InΒ [24]:
for lab, col in (("a", "rate_theta"), ("b", "rate_v4"), ("c", "rate_run")):
    v = {c: pfc[pfc.category == c][col] for c in cats}
    print(f"Reading {lab}: " + "; ".join(f"{c} {msem(x)} Hz" for c, x in v.items()))
    print(f"   rank-sum excited vs unmodulated p = {ranksum(v['excited'], v['unmodulated']):.3g}, inhibited vs unmodulated p = "
          f"{ranksum(v['inhibited'], v['unmodulated']):.3g}, excited vs inhibited p = {ranksum(v['excited'], v['inhibited']):.3g}")
Reading a: excited 4.506 +- 0.998 (n = 12) Hz; inhibited 6.867 +- 1.268 (n = 7) Hz; unmodulated 2.769 +- 0.235 (n = 148) Hz
   rank-sum excited vs unmodulated p = 0.0482, inhibited vs unmodulated p = 0.00204, excited vs inhibited p = 0.151
Reading b: excited 4.558 +- 1.005 (n = 12) Hz; inhibited 6.762 +- 1.263 (n = 7) Hz; unmodulated 2.755 +- 0.234 (n = 148) Hz
   rank-sum excited vs unmodulated p = 0.0433, inhibited vs unmodulated p = 0.00198, excited vs inhibited p = 0.176
Reading c: excited 4.530 +- 1.089 (n = 12) Hz; inhibited 6.318 +- 1.478 (n = 7) Hz; unmodulated 2.554 +- 0.219 (n = 148) Hz
   rank-sum excited vs unmodulated p = 0.0512, inhibited vs unmodulated p = 0.00312, excited vs inhibited p = 0.237

Result: not reproduced. Inhibited cells fire faster than unmodulated cells during movement (6.87 against 2.77 Hz, p = 0.0020) but excited cells (4.51 Hz) do not reach p < 0.01 (p = 0.048); excited and inhibited do not differ (p = 0.15). Readings (b) and (c) give the same pattern.

Claim fig5c-spatial-coverageΒΆ

SWR-excited PFC neurons cover more of the environment (0.70 +- 0.05) than SWR-inhibited (0.54 +- 0.05) and SWR-unmodulated neurons (0.50 +- 0.02), which do not differ, and CA1 cells cover less than all PFC groups.

Linearized rate maps on the 4 trajectories (out-left, in-left, out-right, in-right), 2 cm bins, speed > 5 cm/s (no speed filter as a variant); coverage = fraction of bins above 25% of the peak, cells with peak > 3 Hz. The wtr1 and wtr2 runs of days 6 to 8 are on different tracks and get bins of their own; maps from the wtr1 runs alone are a variant.

InΒ [25]:
ca1c = cells[cells.category.notna() & (cells.region == "CA1")]
for col in ("coverage", "coverage_nospeed"):
    v = {c: pfc[pfc.category == c][col] for c in cats}
    v["CA1"] = ca1c[col]
    print(f"{col}: " + "; ".join(f"{c} {msem(x)}" for c, x in v.items()))
    print(f"   excited vs inhibited p = {ranksum(v['excited'], v['inhibited']):.3g}, excited vs unmodulated p = {ranksum(v['excited'], v['unmodulated']):.3g}, "
          f"inhibited vs unmodulated p = {ranksum(v['inhibited'], v['unmodulated']):.3g}; CA1 vs " +
          ", ".join(f"{c} p = {ranksum(v['CA1'], v[c]):.3g}" for c in cats))
print("Range of coverage: %.2f to %.2f" % (cells.coverage.min(), cells.coverage.max()))
# variant: rate maps from the wtr1 runs only (days 6 to 8 lose their wtr2 run)
cov_w1 = {}
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    day = R[a]["days"][d]
    units = {(r.tet, r.unit): day["units"][(r.tet, r.unit)] for r in g.itertuples()}
    m1 = hc28.rate_maps(day, units, epochs=[e for e in day["runs"] if day["task"][e][1] == "wtr1"])
    for i, r in zip(g.index, g.itertuples()):
        cov_w1[i] = hc28.coverage(m1[(r.tet, r.unit)])
cells["coverage_wtr1"] = pd.Series(cov_w1)
pfc = cells[cells.category.notna() & (cells.region == "PFC")]
v = {c: pfc[pfc.category == c].coverage_wtr1 for c in cats}
print("coverage, wtr1 runs only: " + "; ".join(f"{c} {msem(x)}" for c, x in v.items()) +
      f"; excited vs inhibited p = {ranksum(v['excited'], v['inhibited']):.3g}, excited vs unmodulated p = {ranksum(v['excited'], v['unmodulated']):.3g}")
coverage: excited 0.229 +- 0.072 (n = 11); inhibited 0.506 +- 0.106 (n = 7); unmodulated 0.229 +- 0.017 (n = 142); CA1 0.068 +- 0.003 (n = 367)
   excited vs inhibited p = 0.0416, excited vs unmodulated p = 0.651, inhibited vs unmodulated p = 0.012; CA1 vs excited p = 0.0569, inhibited p = 2.27e-05, unmodulated p = 1.44e-23
coverage_nospeed: excited 0.258 +- 0.076 (n = 11); inhibited 0.462 +- 0.098 (n = 7); unmodulated 0.231 +- 0.016 (n = 142); CA1 0.066 +- 0.003 (n = 367)
   excited vs inhibited p = 0.135, excited vs unmodulated p = 0.932, inhibited vs unmodulated p = 0.0179; CA1 vs excited p = 0.00721, inhibited p = 3.34e-05, unmodulated p = 1.55e-25
Range of coverage: 0.00 to 0.86
coverage, wtr1 runs only: excited 0.250 +- 0.073 (n = 11); inhibited 0.505 +- 0.107 (n = 7); unmodulated 0.260 +- 0.019 (n = 140); excited vs inhibited p = 0.0515, excited vs unmodulated p = 0.667

Result: not reproduced. Coverage of excited cells (0.229) is not higher than that of inhibited (0.506) or unmodulated cells (0.229); inhibited cells cover the most. CA1 cells cover less (0.068) than unmodulated and inhibited cells (p = 1.4e-23 and 2.3e-05) but not significantly less than excited cells (p = 0.057). Without the speed filter excited cells (0.258) cover slightly more than unmodulated cells (0.231, p = 0.93) and CA1 covers less than excited cells (p = 0.0072), but excited cells still cover less than inhibited cells (0.462). With maps from the wtr1 runs alone (excited 0.250, inhibited 0.505, unmodulated 0.260) the order is that of the main analysis. In no version do excited cells cover more than inhibited cells.

Claim figs3-arm-and-direction-selectivityΒΆ

CA1 cells are more selective than all PFC groups for arm and for inbound or outbound direction, and SWR-excited PFC cells are less direction selective than SWR-unmodulated cells.

Readings: the mean or the peak rate over each arm's (direction's) linearized bins.

InΒ [26]:
for how in ("mean", "peak"):
    for idx in ("arm", "dir"):
        col = f"{idx}_{how}"
        v = {c: pfc[pfc.category == c][col] for c in cats}
        v["CA1"] = ca1c[col]
        print(f"{col}: " + "; ".join(f"{c} {msem(x)}" for c, x in v.items()))
        print("   CA1 vs " + ", ".join(f"{c} p = {ranksum(v['CA1'], v[c]):.3g}" for c in cats) +
              f"; excited vs unmodulated p = {ranksum(v['excited'], v['unmodulated']):.3g}")
arm_mean: excited 0.090 +- 0.021 (n = 12); inhibited 0.110 +- 0.037 (n = 7); unmodulated 0.125 +- 0.011 (n = 146); CA1 0.361 +- 0.015 (n = 391)
   CA1 vs excited p = 0.000479, inhibited p = 0.0162, unmodulated p = 7.28e-20; excited vs unmodulated p = 0.555
dir_mean: excited 0.123 +- 0.033 (n = 12); inhibited 0.092 +- 0.039 (n = 7); unmodulated 0.120 +- 0.010 (n = 146); CA1 0.381 +- 0.013 (n = 391)
   CA1 vs excited p = 0.000297, inhibited p = 0.0013, unmodulated p = 3.32e-29; excited vs unmodulated p = 0.798
arm_peak: excited 0.289 +- 0.072 (n = 12); inhibited 0.086 +- 0.025 (n = 7); unmodulated 0.191 +- 0.014 (n = 146); CA1 0.315 +- 0.014 (n = 391)
   CA1 vs excited p = 0.814, inhibited p = 0.0137, unmodulated p = 4.79e-05; excited vs unmodulated p = 0.252
dir_peak: excited 0.303 +- 0.074 (n = 12); inhibited 0.112 +- 0.042 (n = 7); unmodulated 0.191 +- 0.013 (n = 146); CA1 0.338 +- 0.012 (n = 391)
   CA1 vs excited p = 0.632, inhibited p = 0.00653, unmodulated p = 6.23e-10; excited vs unmodulated p = 0.23

Result: not reproduced. With mean arm rates CA1 is more direction selective than every PFC group (p = 0.00030, 0.0013 and 3.3e-29) and more arm selective than excited and unmodulated cells (p = 0.00048 and 7.3e-20), but not than inhibited cells at p < 0.01 (p = 0.016). Excited cells are not less direction selective than unmodulated cells (0.123 against 0.120, p = 0.80). With peak rates CA1 does not exceed excited cells (p = 0.81 and 0.63).

Claim fig5e-speed-correlationΒΆ

SWR-excited cells have higher firing rate-speed correlations than SWR-inhibited cells, whose median correlation is below zero, while unmodulated cells do not differ from either.

Readings: (a) Pearson correlation of spike count and mean speed across 200 ms bins (and 1 s bins) of the runs; (b) correlation of rate in 2 cm/s speed bins (0-40 cm/s) with the bin centres. The median of the inhibited cells against zero: 1000 shuffles, circularly shifting each cell's spikes within each run epoch by a random amount (reading a), or permuting the time bins of speed (reading b).

InΒ [27]:
rng = rng_for("fig5e-speed-correlation")


def binned(day, u, binw):
    cs, vs = [], []
    for e in day["runs"]:
        ep = day["epochs"][e]
        edges = np.arange(ep["start"], ep["end"], binw)
        vs.append(np.histogram(ep["pos"][:, 0], edges, weights=ep["pos"][:, 3])[0] / np.maximum(np.histogram(ep["pos"][:, 0], edges)[0], 1))
        cs.append(np.histogram(u["times"].get(e, np.zeros(0)), edges)[0])
    return cs, vs


def speed_corr(cs, vs, how):
    c = np.concatenate(cs); v = np.concatenate(vs)
    if how == "time":
        return np.corrcoef(c, v)[0, 1] if c.std() > 0 else np.nan
    sb = np.arange(0, 42, 2)
    k = np.digitize(v, sb) - 1
    ok = (k >= 0) & (k < len(sb) - 1)
    occ = np.bincount(k[ok], minlength=len(sb) - 1); sp = np.bincount(k[ok], weights=c[ok], minlength=len(sb) - 1)
    good = occ >= 5
    rate = sp[good] / occ[good]
    return np.corrcoef(rate, (sb[:-1] + 1)[good])[0, 1] if rate.std() > 0 else np.nan


sc = {}
bins_cache = {}
for i, r in pfc.iterrows():
    day = R[r.animal]["days"][r.day]; u = day["units"][(r.tet, r.unit)]
    for binw in (0.2, 1.0):
        cs, vs = binned(day, u, binw)
        bins_cache[(i, binw)] = (cs, vs)
        sc[(i, binw, "time")] = speed_corr(cs, vs, "time")
        sc[(i, binw, "speedbin")] = speed_corr(cs, vs, "speedbin")
for binw in (0.2, 1.0):
    for how in ("time", "speedbin"):
        v = {c: np.array([sc[(i, binw, how)] for i in pfc.index[pfc.category == c]]) for c in cats}
        inh = pfc.index[pfc.category == "inhibited"]
        real_med = np.nanmedian(v["inhibited"])
        null = []
        for s in range(1000):
            vals = []
            for i in inh:
                cs, vs = bins_cache[(i, binw)]
                if how == "time":
                    cs2 = [np.roll(c, rng.integers(len(c))) for c in cs]; vs2 = vs
                else:
                    cs2 = cs; vs2 = [rng.permutation(x) for x in vs]
                vals.append(speed_corr(cs2, vs2, how))
            null.append(np.nanmedian(vals))
        p_med = np.mean(np.array(null) <= real_med)
        print(f"{binw * 1000:.0f} ms bins, {'time-bin' if how == 'time' else 'speed-bin'} correlation: " + "; ".join(f"{c} median {np.nanmedian(x):.3f}, mean {msem(x)}" for c, x in v.items()))
        print(f"   excited vs inhibited p = {ranksum(v['excited'], v['inhibited']):.3g}; inhibited median below shuffles p = {p_med:.3g} "
              f"({'circular shift' if how == 'time' else 'speed bins permuted'}); unmodulated vs excited p = {ranksum(v['unmodulated'], v['excited']):.3g}, "
              f"vs inhibited p = {ranksum(v['unmodulated'], v['inhibited']):.3g}")
200 ms bins, time-bin correlation: excited median -0.009, mean 0.008 +- 0.032 (n = 12); inhibited median 0.033, mean 0.070 +- 0.108 (n = 7); unmodulated median 0.012, mean 0.029 +- 0.010 (n = 148)
   excited vs inhibited p = 0.866; inhibited median below shuffles p = 0.965 (circular shift); unmodulated vs excited p = 0.712, vs inhibited p = 0.904
200 ms bins, speed-bin correlation: excited median -0.336, mean -0.241 +- 0.185 (n = 12); inhibited median -0.331, mean -0.028 +- 0.280 (n = 7); unmodulated median -0.224, mean -0.089 +- 0.050 (n = 148)
   excited vs inhibited p = 0.499; inhibited median below shuffles p = 0.012 (speed bins permuted); unmodulated vs excited p = 0.306, vs inhibited p = 0.698
1000 ms bins, time-bin correlation: excited median -0.010, mean 0.000 +- 0.054 (n = 12); inhibited median 0.041, mean 0.083 +- 0.138 (n = 7); unmodulated median 0.025, mean 0.043 +- 0.014 (n = 148)
   excited vs inhibited p = 0.612; inhibited median below shuffles p = 0.946 (circular shift); unmodulated vs excited p = 0.591, vs inhibited p = 0.973
1000 ms bins, speed-bin correlation: excited median -0.248, mean -0.240 +- 0.164 (n = 12); inhibited median -0.379, mean -0.020 +- 0.273 (n = 7); unmodulated median -0.153, mean -0.078 +- 0.047 (n = 148)
   excited vs inhibited p = 0.398; inhibited median below shuffles p = 0.002 (speed bins permuted); unmodulated vs excited p = 0.297, vs inhibited p = 0.829

Result: not reproduced. Excited and inhibited cells do not differ in their speed correlation under any reading (p = 0.40 to 0.87). The inhibited median is positive across time bins (0.033 at 200 ms) and negative across speed bins (-0.331), where the speed-bin shuffle puts it below chance (p = 0.012 and 0.002).

Claim fig5f-pre-swr-vs-movementΒΆ

SWR-inhibited cells fire more just before SWRs than during high-speed movement, while SWR-excited cells show the opposite preference.

Index (pre-SWR - high speed) / (pre-SWR + high speed); pre-SWR -500 to -100 ms before run SWR onsets, high speed > 10 cm/s (SEP).

InΒ [28]:
idx5f = (cells.pre_swr_rate - cells.highspeed_rate) / (cells.pre_swr_rate + cells.highspeed_rate)
cells["idx5f"] = idx5f
pfc = cells[cells.category.notna() & (cells.region == "PFC")]
v = {c: pfc[pfc.category == c].idx5f for c in cats}
print("; ".join(f"{c} {msem(x)}" for c, x in v.items()))
print(f"rank-sum inhibited vs excited p = {ranksum(v['inhibited'], v['excited']):.3g}; signs: excited mean {v['excited'].mean():.3f}, inhibited mean {v['inhibited'].mean():.3f}")
excited -0.086 +- 0.077 (n = 12); inhibited -0.125 +- 0.150 (n = 7); unmodulated -0.045 +- 0.025 (n = 148)
rank-sum inhibited vs excited p = 0.866; signs: excited mean -0.086, inhibited mean -0.125

Result: not reproduced. The index is negative in both groups (excited -0.086, inhibited -0.125) and does not differ (p = 0.87).

Claim figs3e-reward-modulationΒΆ

SWR-inhibited PFC cells increase their firing after reward more than SWR-excited cells.

Reward times: arrival in the 15 cm zone of the well at the end of a correct trial (reading a), or the first time speed drops below 4 cm/s in that visit (reading b). Index (post - pre) / (post + pre), post 0 to 2 s, pre -3 to -1 s (SEP).

InΒ [29]:
reward_times = {}
for a, r in R.items():
    for d, day in r["days"].items():
        ta, tb = [], []
        for e in day["runs"]:
            ep = day["epochs"][e]
            vis = hc28.well_visits(ep)
            tr = hc28.score_trials(vis)
            exits = {v[1]: v[2] for v in vis}
            for w0, w1, t0, t1, kind, ok in tr:
                if ok:
                    ta.append(t1)
                    sel = (ep["pos"][:, 0] >= t1) & (ep["pos"][:, 0] <= exits.get(t1, t1)) & (ep["pos"][:, 3] < 4)
                    tb.append(ep["pos"][sel, 0][0] if sel.any() else t1)
        reward_times[(a, d)] = (np.array(ta), np.array(tb))
rm = {}
for i, r in pfc.iterrows():
    day = R[r.animal]["days"][r.day]; st = hc28.spikes_in(day["units"][(r.tet, r.unit)], day["runs"])
    for k, rt in enumerate(reward_times[(r.animal, r.day)]):
        post = (np.searchsorted(st, rt + 2) - np.searchsorted(st, rt)).sum() / 2
        pre = (np.searchsorted(st, rt - 1) - np.searchsorted(st, rt - 3)).sum() / 2
        rm[(i, k)] = (post - pre) / (post + pre) if post + pre > 0 else np.nan
print("Rewarded trials per day: median", np.median([len(v[0]) for v in reward_times.values()]))
for k, lab in ((0, "a"), (1, "b")):
    v = {c: np.array([rm[(i, k)] for i in pfc.index[pfc.category == c]]) for c in cats}
    print(f"Reading {lab}: " + "; ".join(f"{c} {msem(x)}" for c, x in v.items()) +
          f"; inhibited vs excited p = {ranksum(v['inhibited'], v['excited']):.3g}")
Rewarded trials per day: median 52.0
Reading a: excited -0.147 +- 0.080 (n = 12); inhibited 0.103 +- 0.167 (n = 7); unmodulated -0.045 +- 0.037 (n = 147); inhibited vs excited p = 0.091
Reading b: excited -0.006 +- 0.133 (n = 12); inhibited -0.128 +- 0.152 (n = 7); unmodulated -0.030 +- 0.037 (n = 147); inhibited vs excited p = 0.8

Result: not reproduced. With arrival times the reward index of inhibited cells (0.103) is above that of excited cells (-0.147) but not significantly (p = 0.091, 7 and 12 cells); with the first slow sample the order reverses (p = 0.80).

Claim fig5g-ensemble-cofiringΒΆ

During movement, like-modulated PFC pairs fire together while excited-inhibited pairs do not; the theta cross-covariance peak of excited-inhibited pairs is lower than that of every other pair category.

Simultaneously recorded PFC pairs; standardized theta cross-covariance (theta periods >= 1 s, 10 ms bins, Poisson z normalization, Gaussian of 50 ms length and SD 16.7 ms); readings (a) the peak within -200 to +200 ms, (b) the value at zero lag; pairs on the same tetrode included and excluded.

InΒ [30]:
theta_spk = {}
theta_T = {}
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    day = R[a]["days"][d]
    theta_T[(a, d)] = hc28.theta_time(day, 1.0)
    for i, r in zip(g.index, g.itertuples()):
        theta_spk[i] = hc28.theta_period_spikes(day, day["units"][(r.tet, r.unit)])
pp = []
for (a, d), g in pfc.groupby(["animal", "day"]):
    idx = list(g.index)
    for x in range(len(idx)):
        for y in range(x + 1, len(idx)):
            i, j = idx[x], idx[y]
            if len(theta_spk[i]) == 0 or len(theta_spk[j]) == 0:
                continue
            lags, xc = hc28.std_xcov(theta_spk[i], theta_spk[j], theta_T[(a, d)])
            w = np.abs(lags) <= 0.2 + 1e-9
            pair = "-".join(sorted([cells.loc[i, "category"][:3], cells.loc[j, "category"][:3]]))
            pp.append(dict(animal=a, day=d, i=i, j=j, kind=pair, same_tet=cells.loc[i, "tet"] == cells.loc[j, "tet"],
                           peak=np.nanmax(xc[w]), zero=xc[np.argmin(np.abs(lags))]))
pp = pd.DataFrame(pp)
kinds = {"exc-exc": "excited-excited", "inh-inh": "inhibited-inhibited", "exc-inh": "excited-inhibited", "unm-unm": "unmodulated-unmodulated"}
for same in (True, False):
    s = pp if same else pp[~pp.same_tet]
    print(f"Pairs {'including' if same else 'excluding'} same-tetrode pairs: counts " + str({kinds.get(k, k): int((s.kind == k).sum()) for k in kinds}))
    for col in ("peak", "zero"):
        v = {k: s[s.kind == k][col] for k in ["exc-exc", "inh-inh", "exc-inh", "unm-unm", "exc-unm", "inh-unm"]}
        print(f"   {col}: " + "; ".join(f"{k} {msem(x)}" for k, x in v.items()))
        print("      excited-inhibited vs " + ", ".join(f"{k} p = {ranksum(v['exc-inh'], v[k]):.3g}" for k in v if k != "exc-inh"))
print("Expected pair counts 42 / 36 / 73 / 369 (excited-excited, inhibited-inhibited, excited-inhibited, unmodulated-unmodulated)")
Pairs including same-tetrode pairs: counts {'excited-excited': 2, 'inhibited-inhibited': 1, 'excited-inhibited': 3, 'unmodulated-unmodulated': 515}
   peak: exc-exc 7.612 +- 5.674 (n = 2); inh-inh n = 1; exc-inh -1.077 +- 1.675 (n = 3); unm-unm 1.048 +- 0.149 (n = 515); exc-unm 1.170 +- 0.316 (n = 77); inh-unm 1.049 +- 0.639 (n = 34)
      excited-inhibited vs exc-exc p = 0.0833, inh-inh p = 0.18, unm-unm p = 0.224, exc-unm p = 0.219, inh-unm p = 0.436
   zero: exc-exc 5.721 +- 7.164 (n = 2); inh-inh n = 1; exc-inh -2.648 +- 1.550 (n = 3); unm-unm 0.127 +- 0.149 (n = 515); exc-unm 0.167 +- 0.328 (n = 77); inh-unm 0.400 +- 0.673 (n = 34)
      excited-inhibited vs exc-exc p = 0.248, inh-inh p = 0.18, unm-unm p = 0.138, exc-unm p = 0.108, inh-unm p = 0.201
Pairs excluding same-tetrode pairs: counts {'excited-excited': 0, 'inhibited-inhibited': 1, 'excited-inhibited': 2, 'unmodulated-unmodulated': 312}
   peak: exc-exc n = 0; inh-inh n = 1; exc-inh 0.522 +- 0.863 (n = 2); unm-unm 0.777 +- 0.102 (n = 312); exc-unm 1.079 +- 0.358 (n = 61); inh-unm 0.723 +- 0.597 (n = 27)
      excited-inhibited vs exc-exc p = nan, inh-inh p = 0.221, unm-unm p = 0.845, exc-unm p = 0.845, inh-unm p = 0.863
   zero: exc-exc n = 0; inh-inh n = 1; exc-inh -1.595 +- 1.971 (n = 2); unm-unm 0.004 +- 0.090 (n = 312); exc-unm 0.141 +- 0.388 (n = 61); inh-unm 0.104 +- 0.629 (n = 27)
      excited-inhibited vs exc-exc p = nan, inh-inh p = 0.221, unm-unm p = 0.558, exc-unm p = 0.456, inh-unm p = 0.547
Expected pair counts 42 / 36 / 73 / 369 (excited-excited, inhibited-inhibited, excited-inhibited, unmodulated-unmodulated)

Result: not reproduced. With 12 excited and 7 inhibited cells only 2 excited-excited, 1 inhibited-inhibited and 3 excited-inhibited pairs exist (515 unmodulated-unmodulated), against 42, 36, 73 and 369. The 3 excited-inhibited pairs have a negative mean peak (-1.08) but differ from no category at p < 0.01 (smallest p = 0.083).

CA1-PFC pairsΒΆ

Pairs of simultaneously recorded CA1 cells and SWR-modulated PFC cells (same animal and day). SWR response: spike count 0-200 ms after each run SWR onset. Pairs need at least 5 SWRs in which both cells spike (SEP). CA1 cells: (a) SWR-modulated CA1 cells, (b) all included CA1 cells. SWR correlation: (a) Pearson over all SWRs of the day, (b) Pearson over the SWRs in which both spiked; Spearman over all SWRs as a variant. A pair is significant at p < 0.05.

InΒ [31]:
rng = rng_for("fig6-swr-correlated-pairs")
counts = {}
pre_counts = {}
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    day = R[a]["days"][d]
    on = hc28.swr_onsets(day, day["runs"])
    on_pre = hc28.swr_onsets(day, [day["pre"]])
    for i, r in zip(g.index, g.itertuples()):
        u = day["units"][(r.tet, r.unit)]
        counts[i] = hc28.swr_counts(hc28.spikes_in(u, day["runs"]), on)
        st_pre = u["times"].get(day["pre"], np.zeros(0))
        pre_counts[i] = hc28.swr_counts(np.sort(st_pre), on_pre) if len(st_pre) else None


def corr_p(x, y, kind="pearson"):
    if len(x) < 3 or np.std(x) == 0 or np.std(y) == 0:
        return np.nan, np.nan
    r = stats.pearsonr(x, y) if kind == "pearson" else stats.spearmanr(x, y)
    return float(r[0]), float(r[1])


rows = []
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    c_idx = g.index[g.region == "CA1"]; p_idx = g.index[(g.region == "PFC") & (g.category != "unmodulated")]
    for i in c_idx:
        for j in p_idx:
            x, y = counts[i], counts[j]
            both = (x > 0) & (y > 0)
            if both.sum() < 5:
                continue
            ra, pa = corr_p(x, y)
            rb, pb = corr_p(x[both], y[both])
            rs, ps = corr_p(x, y, "spearman")
            ysh = rng.permutation(y)
            rsh, psh = corr_p(x, ysh)
            rows.append(dict(animal=a, day=d, ca1=i, pfc=j, pfc_cat=cells.loc[j, "category"], ca1_mod=cells.loc[i, "category"] != "unmodulated",
                             n_joint=int(both.sum()), r=ra, p=pa, r_joint=rb, p_joint=pb, r_s=rs, p_s=ps, r_shuf=rsh, p_shuf=psh))
pairs = pd.DataFrame(rows)
print("CA1-PFC pairs with >= 5 joint SWRs:", len(pairs), "; with SWR-modulated CA1 cells:", int(pairs.ca1_mod.sum()))
CA1-PFC pairs with >= 5 joint SWRs: 286 ; with SWR-modulated CA1 cells: 198

Claim fig6-swr-correlated-pairsΒΆ

16% of CA1-PFC pairs (116 of 713) are significantly correlated across SWRs, more than the about 5% found after shuffling, with similar proportions for SWR-excited (72 of 393, 18%) and SWR-inhibited (44 of 320, 14%) PFC cells.

Shuffle: the PFC counts permuted across SWRs, once per pair; z test for two proportions.

InΒ [32]:
from statsmodels.stats.proportion import proportions_ztest
for ca1_lab, s0 in (("a, SWR-modulated CA1", pairs[pairs.ca1_mod]), ("b, all CA1", pairs)):
    for corr_lab, pcol in (("a, Pearson all SWRs", "p"), ("b, Pearson joint SWRs", "p_joint"), ("Spearman all SWRs (variant)", "p_s")):
        s = s0
        sig = s[pcol] < 0.05; shuf = s.p_shuf < 0.05
        z, pz = proportions_ztest([sig.sum(), shuf.sum()], [len(s), len(s)], alternative="larger")
        fe = sig[s.pfc_cat == "excited"].mean(); fi = sig[s.pfc_cat == "inhibited"].mean()
        print(f"CA1 {ca1_lab}; {corr_lab}: {sig.sum()} of {len(s)} significant ({sig.mean():.3f}); shuffled {shuf.mean():.3f}; z = {z:.2f}, p = {pz:.2g}; "
              f"excited PFC {sig[s.pfc_cat == 'excited'].sum()} of {(s.pfc_cat == 'excited').sum()} ({fe:.3f}), inhibited PFC "
              f"{sig[s.pfc_cat == 'inhibited'].sum()} of {(s.pfc_cat == 'inhibited').sum()} ({fi:.3f})")
print("Expected 0.16 +- 0.016, 0.18 +- 0.018, 0.14 +- 0.014; paper n = 713 (393 excited, 320 inhibited)")
print("Per animal (reading a, a):", pairs[pairs.ca1_mod].groupby("animal").apply(lambda g: f"{(g.p < 0.05).sum()}/{len(g)}", include_groups=False).to_dict())
main_pairs = pairs[pairs.ca1_mod].copy()
CA1 a, SWR-modulated CA1; a, Pearson all SWRs: 45 of 198 significant (0.227); shuffled 0.045; z = 5.27, p = 6.8e-08; excited PFC 28 of 127 (0.220), inhibited PFC 17 of 71 (0.239)
CA1 a, SWR-modulated CA1; b, Pearson joint SWRs: 8 of 198 significant (0.040); shuffled 0.045; z = -0.25, p = 0.6; excited PFC 5 of 127 (0.039), inhibited PFC 3 of 71 (0.042)
CA1 a, SWR-modulated CA1; Spearman all SWRs (variant): 45 of 198 significant (0.227); shuffled 0.045; z = 5.27, p = 6.8e-08; excited PFC 28 of 127 (0.220), inhibited PFC 17 of 71 (0.239)
CA1 b, all CA1; a, Pearson all SWRs: 63 of 286 significant (0.220); shuffled 0.049; z = 6.00, p = 9.7e-10; excited PFC 33 of 172 (0.192), inhibited PFC 30 of 114 (0.263)
CA1 b, all CA1; b, Pearson joint SWRs: 16 of 286 significant (0.056); shuffled 0.049; z = 0.38, p = 0.35; excited PFC 10 of 172 (0.058), inhibited PFC 6 of 114 (0.053)
CA1 b, all CA1; Spearman all SWRs (variant): 60 of 286 significant (0.210); shuffled 0.049; z = 5.73, p = 5e-09; excited PFC 33 of 172 (0.192), inhibited PFC 27 of 114 (0.237)
Expected 0.16 +- 0.016, 0.18 +- 0.018, 0.14 +- 0.014; paper n = 713 (393 excited, 320 inhibited)
Per animal (reading a, a): {'HPa': '12/83', 'HPb': '26/83', 'HPc': '7/32'}

Result: partially reproduced. 45 of 198 pairs of SWR-modulated CA1 and PFC cells (0.227) are significantly SWR correlated, against 0.045 after shuffling (z = 5.27, p = 6.8e-08), with similar fractions for excited (0.220) and inhibited (0.239) PFC cells. All three fractions are above their tolerances, and the pairs number 198 against 713. With all CA1 cells the fraction is 0.220 (p = 9.7e-10); with correlations over joint SWRs only, the fraction does not exceed the shuffle (0.040).

Claim fig6ab-both-signsΒΆ

Significant CA1-PFC SWR correlations include both positive and negative correlations, for both SWR-excited and SWR-inhibited PFC cells.

InΒ [33]:
sig = main_pairs[main_pairs.p < 0.05]
for c in ("excited", "inhibited"):
    s = sig[sig.pfc_cat == c]
    print(f"{c}: {int((s.r > 0).sum())} positive, {int((s.r < 0).sum())} negative significant pairs")
s = pairs[pairs.p < 0.05]
print("All CA1 cells (reading b):", {c: (int((s[s.pfc_cat == c].r > 0).sum()), int((s[s.pfc_cat == c].r < 0).sum())) for c in ("excited", "inhibited")})
excited: 21 positive, 7 negative significant pairs
inhibited: 7 positive, 10 negative significant pairs
All CA1 cells (reading b): {'excited': (22, 11), 'inhibited': (13, 17)}

Result: reproduced. Among significant pairs, excited PFC cells have 21 positive and 7 negative correlations and inhibited PFC cells 7 positive and 10 negative.

Claim fig3f-swr-cross-covariance-lagΒΆ

During SWRs the mean CA1-PFC cross-covariance peaks (excited pairs) or troughs (inhibited pairs) after zero lag, at 13 +- 7 and 20 +- 7 ms, so CA1 leads PFC.

Cross-covariance from the SWR-aligned rasters (-500 to +500 ms around each onset): CCG of PFC spikes relative to CA1 spikes in 10 ms bins, minus the coincidences expected from the mean rates in the rasters, Poisson z normalization, Gaussian of SD 16.7 ms; extremum within -200 to +200 ms. Readings: (a) the lag of the extremum of the mean over pairs, (b) the mean of the pairs' extremum lags. Pairs of fig6 (reading a: SWR-modulated CA1 cells).

InΒ [34]:
raster_spk = {}
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    day = R[a]["days"][d]; on = hc28.swr_onsets(day, day["runs"])
    for i, r in zip(g.index, g.itertuples()):
        st = hc28.spikes_in(day["units"][(r.tet, r.unit)], day["runs"])
        rel, idx = hc28.aligned(st, on, 0.5)
        raster_spk[i] = (np.sort(on[idx] + rel), len(on))
xcs = {"excited": [], "inhibited": []}
for r in main_pairs.itertuples():
    t1, n = raster_spk[r.ca1]; t2, _ = raster_spk[r.pfc]
    lags, xc = hc28.std_xcov(t1, t2, n * 1.0)
    xcs[r.pfc_cat].append(xc)
w = np.abs(lags) <= 0.2 + 1e-9
for c, sign in (("excited", 1), ("inhibited", -1)):
    X = np.array(xcs[c])
    if len(X) == 0:
        print(c, "no pairs"); continue
    mean = np.nanmean(X, 0)
    la = lags[w][np.argmax(sign * mean[w])] * 1000
    per = lags[w][np.argmax(sign * X[:, w], 1)] * 1000
    print(f"{c} PFC (n = {len(X)} pairs): reading a, extremum of the mean at {la:.0f} ms; reading b, mean of pair extrema {msem(per)} ms; "
          f"mean xcov at extremum {mean[w][np.argmax(sign * mean[w])]:.3f}")
print("Expected 13 +- 7 ms (excited, peak) and 20 +- 7 ms (inhibited, trough); positive lag = PFC after CA1")
excited PFC (n = 127 pairs): reading a, extremum of the mean at 20 ms; reading b, mean of pair extrema 1.260 +- 7.268 (n = 127) ms; mean xcov at extremum 0.730
inhibited PFC (n = 71 pairs): reading a, extremum of the mean at 200 ms; reading b, mean of pair extrema 35.915 +- 15.106 (n = 71) ms; mean xcov at extremum -0.725
Expected 13 +- 7 ms (excited, peak) and 20 +- 7 ms (inhibited, trough); positive lag = PFC after CA1

Result: not reproduced. The mean cross-covariance of 127 excited pairs peaks at 20 ms (within 13 +- 7), but that of 71 inhibited pairs is lowest at 200 ms, the edge of the window, so no trough is found inside it. The mean of per-pair extrema is 1.3 ms for excited and 35.9 ms for inhibited pairs, both outside the tolerances.

Claim fig6c-theta-predicts-swr-correlationΒΆ

Theta-period cross-covariance of CA1-PFC pairs predicts their SWR correlation (r = 0.39 for all 713 pairs, and 0.39 for each of the excited and inhibited groups), equally in the two groups.

Peak (within -200 to +200 ms) of the standardized theta cross-covariance (Poisson z, reading a; rate normalized, reading b) against the SWR correlation (reading a). Group difference: 1000 shuffles of pairs pooled and split at random into groups of the same sizes (SEP shuffle, assumed here).

InΒ [35]:
rng = rng_for("fig6c-theta-predicts-swr-correlation")
txc_peak, txc_peak_rel, txc_curve, txc_lagpeak = {}, {}, {}, {}
for r in main_pairs.itertuples():
    T = theta_T[(r.animal, r.day)]
    lags, xc = hc28.std_xcov(theta_spk[r.ca1], theta_spk[r.pfc], T)
    _, xr = hc28.std_xcov(theta_spk[r.ca1], theta_spk[r.pfc], T, norm="rel")
    w = np.abs(lags) <= 0.2 + 1e-9
    txc_peak[r.Index] = np.nanmax(xc[w]); txc_peak_rel[r.Index] = np.nanmax(xr[w]); txc_curve[r.Index] = xc
main_pairs["theta_peak"] = pd.Series(txc_peak); main_pairs["theta_peak_rel"] = pd.Series(txc_peak_rel)


def reg(x, y):
    ok = np.isfinite(x) & np.isfinite(y)
    res = stats.linregress(x[ok], y[ok])
    return res.rvalue, res.pvalue, int(ok.sum())


for col in ("theta_peak", "theta_peak_rel"):
    out = {}
    for c, s in (("all", main_pairs), ("excited", main_pairs[main_pairs.pfc_cat == "excited"]), ("inhibited", main_pairs[main_pairs.pfc_cat == "inhibited"])):
        out[c] = reg(s[col].values, s.r.values)
    se = main_pairs[main_pairs.pfc_cat == "excited"]; si = main_pairs[main_pairs.pfc_cat == "inhibited"]
    allp = main_pairs[[col, "r"]].dropna().values
    ne, ni = len(se[[col, "r"]].dropna()), len(si[[col, "r"]].dropna())
    diff = out["excited"][0] - out["inhibited"][0]
    null = []
    for _ in range(1000):
        perm = rng.permutation(len(allp))
        a_, b_ = allp[perm[:ne]], allp[perm[ne:ne + ni]]
        null.append(np.corrcoef(a_[:, 0], a_[:, 1])[0, 1] - np.corrcoef(b_[:, 0], b_[:, 1])[0, 1])
    p_diff = np.mean(np.abs(null) >= abs(diff))
    print(f"{col}: " + "; ".join(f"{c} r = {v[0]:.3f}, p = {v[1]:.2g}, n = {v[2]}" for c, v in out.items()) + f"; excited vs inhibited shuffle p = {p_diff:.3f}")
print("Expected r = 0.39 +- 0.039 in each")
theta_peak: all r = 0.479, p = 9.2e-13, n = 198; excited r = 0.460, p = 5.4e-08, n = 127; inhibited r = 0.580, p = 1.1e-07, n = 71; excited vs inhibited shuffle p = 0.259
theta_peak_rel: all r = 0.230, p = 0.0011, n = 198; excited r = 0.189, p = 0.033, n = 127; inhibited r = 0.383, p = 0.00097, n = 71; excited vs inhibited shuffle p = 0.395
Expected r = 0.39 +- 0.039 in each

Result: partially reproduced. The peak theta cross-covariance predicts the SWR correlation in all pairs (r = 0.479, p = 9.2e-13), in excited (r = 0.460) and in inhibited pairs (r = 0.580), with no group difference (shuffle p = 0.26), but all three r are above 0.39 +- 0.039. With rate normalization r is 0.230, 0.189 and 0.383 (group difference p = 0.40).

Claim figs4b-ca1-leads-in-thetaΒΆ

For CA1-PFC pairs with significant positive SWR correlations, the theta cross-covariance peaks after zero lag, so CA1 leads PFC during behavior as during SWRs.

InΒ [36]:
for c in ("excited", "inhibited"):
    s = main_pairs[(main_pairs.pfc_cat == c) & (main_pairs.p < 0.05) & (main_pairs.r > 0)]
    if len(s) == 0:
        print(c, "no positive significant pairs"); continue
    X = np.array([txc_curve[i] for i in s.index])
    mean = np.nanmean(X, 0)
    w = np.abs(lags) <= 0.2 + 1e-9
    print(f"{c}: {len(s)} positive significant pairs; mean theta cross-covariance peaks at {lags[w][np.argmax(mean[w])] * 1000:.0f} ms "
          f"(value {mean[w].max():.3f}); per-pair peak lags {msem(lags[w][np.argmax(X[:, w], 1)] * 1000)} ms")
print("Expected 46 +- 4.6 excited and 26 +- 2.6 inhibited positive significant pairs")
excited: 21 positive significant pairs; mean theta cross-covariance peaks at 20 ms (value 1.507); per-pair peak lags -2.381 +- 20.129 (n = 21) ms
inhibited: 7 positive significant pairs; mean theta cross-covariance peaks at 60 ms (value 4.386); per-pair peak lags 64.286 +- 21.697 (n = 7) ms
Expected 46 +- 4.6 excited and 26 +- 2.6 inhibited positive significant pairs

Result: partially reproduced. The mean theta cross-covariance of positive significant pairs peaks after 0 ms for excited (20 ms) and inhibited PFC cells (60 ms), so CA1 leads; the pairs number 21 and 7 against 46 and 26.

Claim fig7c-spatial-correlationΒΆ

The spatial correlation of CA1-PFC pairs is related to their SWR correlation (r = 0.2 for excited, 0.36 for inhibited PFC cells), more strongly for SWR-inhibited cells; SWR-correlated pairs have higher, and anticorrelated pairs lower and negative, spatial correlation than uncorrelated pairs.

Pearson correlation of the two cells' rate maps concatenated over the 4 trajectories (the mean of per-trajectory correlations as a variant).

InΒ [37]:
rng = rng_for("fig7c-spatial-correlation")


def sp_corr_mean(m1, m2):
    v = [hc28.spatial_corr([a], [b]) for a, b in zip(m1, m2)]
    return np.nanmean(v) if np.isfinite(v).any() else np.nan


main_pairs["spatial"] = [hc28.spatial_corr(maps_all[r.ca1], maps_all[r.pfc]) for r in main_pairs.itertuples()]
main_pairs["spatial_mean"] = [sp_corr_mean(maps_all[r.ca1], maps_all[r.pfc]) for r in main_pairs.itertuples()]
for col in ("spatial", "spatial_mean"):
    out = {c: reg(main_pairs[main_pairs.pfc_cat == c][col].values, main_pairs[main_pairs.pfc_cat == c].r.values) for c in ("excited", "inhibited")}
    allp = main_pairs[[col, "r"]].dropna().values
    ne, ni = out["excited"][2], out["inhibited"][2]
    diff = out["inhibited"][0] - out["excited"][0]
    null = []
    for _ in range(1000):
        perm = rng.permutation(len(allp))
        a_, b_ = allp[perm[:ni]], allp[perm[ni:ni + ne]]
        null.append(np.corrcoef(a_[:, 0], a_[:, 1])[0, 1] - np.corrcoef(b_[:, 0], b_[:, 1])[0, 1])
    p_diff = np.mean(np.array(null) >= diff)
    grp = np.where(main_pairs.p < 0.05, np.where(main_pairs.r > 0, "correlated", "anticorrelated"), "uncorrelated")
    v = {k: main_pairs[col][grp == k] for k in ("correlated", "anticorrelated", "uncorrelated")}
    print(f"{col}: " + "; ".join(f"{c} r = {x[0]:.3f}, p = {x[1]:.2g}, n = {x[2]}" for c, x in out.items()) +
          f"; inhibited stronger than excited, shuffle p = {p_diff:.3f}")
    print("   spatial correlation: " + "; ".join(f"{k} {msem(x)}" for k, x in v.items()) +
          f"; correlated vs uncorrelated p = {ranksum(v['correlated'], v['uncorrelated']):.3g}, anticorrelated vs uncorrelated p = "
          f"{ranksum(v['anticorrelated'], v['uncorrelated']):.3g}")
print("Expected r = 0.2 +- 0.02 (excited), 0.36 +- 0.036 (inhibited)")
spatial: excited r = 0.203, p = 0.022, n = 127; inhibited r = 0.404, p = 0.00047, n = 71; inhibited stronger than excited, shuffle p = 0.066
   spatial correlation: correlated 0.090 +- 0.025 (n = 28); anticorrelated -0.050 +- 0.015 (n = 17); uncorrelated 0.014 +- 0.012 (n = 153); correlated vs uncorrelated p = 0.00503, anticorrelated vs uncorrelated p = 0.0415
spatial_mean: excited r = 0.304, p = 0.0005, n = 127; inhibited r = 0.428, p = 0.0002, n = 71; inhibited stronger than excited, shuffle p = 0.142
   spatial correlation: correlated 0.094 +- 0.019 (n = 28); anticorrelated -0.044 +- 0.012 (n = 17); uncorrelated 0.010 +- 0.009 (n = 153); correlated vs uncorrelated p = 0.000598, anticorrelated vs uncorrelated p = 0.0221
Expected r = 0.2 +- 0.02 (excited), 0.36 +- 0.036 (inhibited)

Result: not reproduced. Spatial correlation is related to SWR correlation for excited pairs (r = 0.203, p = 0.022) and inhibited pairs (r = 0.404, p = 0.00047), but the inhibited relation is not significantly stronger (shuffle p = 0.066). SWR-correlated pairs have higher (0.090) and anticorrelated pairs lower and negative (-0.050) spatial correlation than uncorrelated pairs (p = 0.0050 and 0.042). With per-trajectory correlations r is 0.304 and 0.428 and the difference is not significant (p = 0.14).

Claim figs5-matched-selectivityΒΆ

With PFC cells matched for spatial coverage, excited and inhibited groups show similar spatial-SWR correlation relations (r = 0.32 and 0.39, not different).

PFC cells whose coverage lies within the interquartile range of SWR-inhibited coverage (Figure S5 legend). Readings: (a) all pairs within the range, (b) 100 random subsamples of the larger group to the size of the smaller (median r shown).

InΒ [38]:
rng = rng_for("figs5-matched-selectivity")
inh_cov = pfc[pfc.category == "inhibited"].coverage.dropna()
q1, q3 = np.percentile(inh_cov, [25, 75]) if len(inh_cov) else (np.nan, np.nan)
mp = main_pairs.copy(); mp["pfc_cov"] = cells.loc[mp.pfc, "coverage"].values
m = mp[(mp.pfc_cov >= q1) & (mp.pfc_cov <= q3)]
print(f"Inhibited coverage IQR {q1:.3f} to {q3:.3f} (n = {len(inh_cov)} cells); matched pairs: excited {(m.pfc_cat == 'excited').sum()}, inhibited {(m.pfc_cat == 'inhibited').sum()}")
out = {c: reg(m[m.pfc_cat == c].spatial.values, m[m.pfc_cat == c].r.values) for c in ("excited", "inhibited")}
allp = m[["spatial", "r"]].dropna().values
ne, ni = out["excited"][2], out["inhibited"][2]
diff = out["inhibited"][0] - out["excited"][0]
null = []
for _ in range(1000):
    perm = rng.permutation(len(allp))
    a_, b_ = allp[perm[:ni]], allp[perm[ni:ni + ne]]
    null.append(np.corrcoef(a_[:, 0], a_[:, 1])[0, 1] - np.corrcoef(b_[:, 0], b_[:, 1])[0, 1])
print("Reading a: " + "; ".join(f"{c} r = {x[0]:.3f}, p = {x[1]:.2g}, n = {x[2]}" for c, x in out.items()) +
      f"; difference shuffle p (two-sided) = {np.mean(np.abs(null) >= abs(diff)):.3f}")
se = m[m.pfc_cat == "excited"][["spatial", "r"]].dropna().values; si = m[m.pfc_cat == "inhibited"][["spatial", "r"]].dropna().values
k = min(len(se), len(si))
if k > 2:
    rs = [np.corrcoef(*(se if len(se) == k else se[rng.choice(len(se), k, replace=False)]).T)[0, 1] for _ in range(100)]
    ri = [np.corrcoef(*(si if len(si) == k else si[rng.choice(len(si), k, replace=False)]).T)[0, 1] for _ in range(100)]
    print(f"Reading b (subsamples of {k} pairs): excited median r = {np.median(rs):.3f}, inhibited median r = {np.median(ri):.3f}")
Inhibited coverage IQR 0.341 to 0.678 (n = 7 cells); matched pairs: excited 28, inhibited 27
Reading a: excited r = 0.379, p = 0.047, n = 28; inhibited r = 0.586, p = 0.0013, n = 27; difference shuffle p (two-sided) = 0.368
Reading b (subsamples of 27 pairs): excited median r = 0.379, inhibited median r = 0.586

Result: reproduced. Within the inhibited coverage range (0.341 to 0.678, from 7 cells), the 28 excited pairs (r = 0.379, p = 0.047) and the 27 inhibited pairs (r = 0.586, p = 0.0013) both show a positive relation, and the shuffle finds no difference (p = 0.368). The excited relation is only just significant, and the range comes from 7 inhibited cells.

GLM predictionsΒΆ

SEP, GLM: for each PFC cell, a Poisson GLM (log link) of its 0-200 ms SWR spike count on the counts of the simultaneously recorded CA1 cells (all included CA1 cells of the day); 90/10 splits; error = mean absolute difference; shuffled error from predictions shuffled across SWRs; performance = fractional improvement over the shuffled error; 5000 splits. Cells whose GLM does not converge are dropped. The movement-trained model uses 200 ms bins at speed > 5 cm/s outside SWRs (theta periods).

InΒ [39]:
rng = rng_for("fig6e-glm-swr-prediction")


def behavior_bins(day, idx):
    """200 ms bins of the run epochs fully inside theta periods (speed > 5 cm/s, no SWR)."""
    out = []
    for e in day["runs"]:
        ep = day["epochs"][e]
        if "theta_t" not in ep:
            continue
        edges = np.arange(ep["start"], ep["end"] - 0.2, 0.2)
        m, _ = hc28.theta_mask_times(day, e, ep["theta_t"])
        tt = ep["theta_t"]
        frac = np.histogram(tt, np.r_[edges, edges[-1] + 0.2], weights=m.astype(float))[0] / np.maximum(np.histogram(tt, np.r_[edges, edges[-1] + 0.2])[0], 1)
        good = frac == 1.0
        cols = [np.histogram(day["units"][(cells.loc[i, "tet"], cells.loc[i, "unit"])]["times"].get(e, np.zeros(0)), np.r_[edges, edges[-1] + 0.2])[0] for i in idx]
        out.append(np.array(cols).T[good])
    return np.vstack(out)


glm_rows = []
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    day = R[a]["days"][d]
    c_idx = list(g.index[g.region == "CA1"]); p_idx = list(g.index[g.region == "PFC"])
    if len(c_idx) == 0 or len(p_idx) == 0:
        continue
    Xs = np.array([counts[i] for i in c_idx]).T.astype(float)
    B = behavior_bins(day, c_idx + p_idx).astype(float)
    Xb, Yb = B[:, :len(c_idx)], B[:, len(c_idx):]
    for k, j in enumerate(p_idx):
        y = counts[j].astype(float)
        cv = hc28.glm_cv(Xs, y, rng)
        th2swr = hc28.glm_cross(Xb, Yb[:, k], Xs, y, rng)
        swr2th = hc28.glm_cross(Xs, y, Xb, Yb[:, k], rng)
        glm_rows.append(dict(animal=a, day=d, pfc=j, category=cells.loc[j, "category"], n_ca1=len(c_idx), n_swr=len(y), n_bins=len(Yb),
                             perf=cv["perf"], frac_better=cv["frac_better"], conv=cv["converged"],
                             perf_th2swr=th2swr["perf"], p_th2swr=th2swr["p"], perf_swr2th=swr2th["perf"], p_swr2th=swr2th["p"]))
glm = pd.DataFrame(glm_rows)
glm["modulated"] = glm.category != "unmodulated"
print(f"PFC cells: {len(glm)}; SWR GLM converged: {int(glm.conv.sum())}; dropped: {int((~glm.conv).sum())}")
print("CA1 ensemble sizes: %d to %d" % (glm.n_ca1.min(), glm.n_ca1.max()))
PFC cells: 167; SWR GLM converged: 105; dropped: 62
CA1 ensemble sizes: 3 to 32

Claim fig6e-glm-swr-predictionΒΆ

A GLM of CA1 ensemble SWR spiking predicts SWR spiking of SWR-modulated PFC cells above chance, better with larger CA1 ensembles and better than for unmodulated cells, with no difference between excited and inhibited cells.

Chance: (a) signed-rank test of performance against 0, (b) per cell, real error below the shuffled error in more than 95% of splits. Ensemble-size groups: (a) tertiles, (b) three equal-width groups, (c) 1, 2-3 and more than 3 cells.

InΒ [40]:
import statsmodels.formula.api as smf
from statsmodels.stats.anova import anova_lm


def anova_p(formula, data, term, typ=2):
    """p-value of a term in an OLS ANOVA; nan when a factor has a single level in the data."""
    try:
        t = anova_lm(smf.ols(formula, data=data).fit(), typ=typ)
        return t.loc[term, "PR(>F)"]
    except (ValueError, KeyError, np.linalg.LinAlgError):
        return np.nan


def size_groups(n, how):
    if how == "a":
        q = np.percentile(n, [100 / 3, 200 / 3]); return np.digitize(n, q, right=True)
    if how == "b":
        e = np.linspace(n.min(), n.max(), 4); return np.clip(np.digitize(n, e[1:-1], right=True), 0, 2)
    return np.where(n <= 1, 0, np.where(n <= 3, 1, 2))


gc = glm[glm.conv].copy()
mods = gc[gc.modulated]
print(f"Modulated cells: n = {len(mods)}; performance {msem(mods.perf)}; signed-rank vs 0 p = {stats.wilcoxon(mods.perf).pvalue:.3g}; "
      f"cells better than shuffle in > 95% of splits: {(mods.frac_better > 0.95).sum()} of {len(mods)}")
print(f"Unmodulated cells: n = {(~gc.modulated).sum()}; performance {msem(gc[~gc.modulated].perf)}")
for how in ("a", "b", "c"):
    gc["grp"] = size_groups(gc.n_ca1.values, how)
    m_ = gc[gc.modulated]
    if gc.grp.nunique() < 2:
        print(f"Groups ({how}): all ensembles fall in one group (sizes {gc.n_ca1.min()} to {gc.n_ca1.max()}); not testable")
        continue
    p1 = anova_p("perf ~ C(grp)", m_, "C(grp)", typ=1)
    pm = anova_p("perf ~ C(modulated) + C(grp)", gc, "C(modulated)"); pg = anova_p("perf ~ C(modulated) + C(grp)", gc, "C(grp)")
    pe = anova_p("perf ~ C(category) + C(grp)", m_, "C(category)")
    means = m_.groupby("grp").perf.mean().round(3).to_dict()
    print(f"Groups ({how}): sizes {gc.groupby('grp').n_ca1.agg(['min', 'max']).values.tolist()}; modulated perf by group {means}; "
          f"one-way ANOVA p = {p1:.3g}; two-way modulated p = {pm:.3g}, group p = {pg:.3g}; "
          f"excited vs inhibited p = {pe:.3g}; "
          f"modulated mean {gc[gc.modulated].perf.mean():.3f} vs unmodulated {gc[~gc.modulated].perf.mean():.3f}")
print("Excited / inhibited performance:", gc[gc.modulated].groupby("category").perf.agg(["mean", "size"]).round(3).to_dict())
Modulated cells: n = 16; performance 0.055 +- 0.011 (n = 16); signed-rank vs 0 p = 6.1e-05; cells better than shuffle in > 95% of splits: 0 of 16
Unmodulated cells: n = 89; performance 0.026 +- 0.004 (n = 89)
Groups (a): sizes [[3, 12], [14, 21], [22, 32]]; modulated perf by group {0: 0.052, 1: 0.038, 2: 0.064}; one-way ANOVA p = 0.624; two-way modulated p = 0.00685, group p = 0.014; excited vs inhibited p = 0.624; modulated mean 0.055 vs unmodulated 0.026
Groups (b): sizes [[3, 12], [14, 22], [23, 32]]; modulated perf by group {0: 0.052, 1: 0.033, 2: 0.101}; one-way ANOVA p = 0.0187; two-way modulated p = 0.00516, group p = 0.0186; excited vs inhibited p = 0.578; modulated mean 0.055 vs unmodulated 0.026
Groups (c): sizes [[3, 3], [4, 32]]; modulated perf by group {2: 0.055}; one-way ANOVA p = nan; two-way modulated p = 0.0049, group p = 0.0627; excited vs inhibited p = nan; modulated mean 0.055 vs unmodulated 0.026
Excited / inhibited performance: {'mean': {'excited': 0.049, 'inhibited': 0.065}, 'size': {'excited': 10, 'inhibited': 6}}

Result: reproduced. For 16 converged SWR-modulated PFC cells performance is 0.055 +- 0.011, above chance by the signed-rank test (p = 6.1e-05), though no single cell beats its shuffles in 95% of splits. With equal-width ensemble-size groups performance differs by group (one-way p = 0.019; means 0.052, 0.033 and 0.101), modulated exceed unmodulated cells (0.055 against 0.026, two-way p = 0.0051) and excited and inhibited do not differ (p = 0.58). With tertile groups the size effect among modulated cells is not significant (p = 0.62), and the 1, 2-3, > 3 grouping cannot be formed (ensembles have 3 to 32 CA1 cells). 62 of 167 cells were dropped for non-convergence. Under the mean-envelope reading (section on the other readings) modulated cells are not above chance (0.025, p = 0.077), so the outcome rests on reading (a).

Claim fig6e-theta-trained-glmΒΆ

GLMs trained on movement activity also predict PFC SWR spiking, better for modulated than unmodulated cells and better with larger ensembles, and predict SWRs better than SWR-trained models predict movement activity.

InΒ [41]:
gt = glm[np.isfinite(glm.perf_th2swr)].copy()
m_ = gt[gt.modulated]
print(f"Movement-trained, modulated cells n = {len(m_)}: performance {msem(m_.perf_th2swr)}; signed-rank vs 0 p = {stats.wilcoxon(m_.perf_th2swr).pvalue:.3g}; "
      f"cells above shuffle at p < 0.05: {(m_.p_th2swr < 0.05).sum()}")
print(f"Unmodulated: {msem(gt[~gt.modulated].perf_th2swr)}; SWR-trained to movement, modulated: {msem(m_.perf_swr2th)}")
for how in ("a", "b", "c"):
    gt["grp"] = size_groups(gt.n_ca1.values, how)
    if gt.grp.nunique() < 2:
        print(f"Groups ({how}): all ensembles fall in one group; not testable")
        continue
    pm = anova_p("perf_th2swr ~ C(modulated) + C(grp)", gt, "C(modulated)"); pg = anova_p("perf_th2swr ~ C(modulated) + C(grp)", gt, "C(grp)")
    long = pd.concat([gt.assign(perf2=gt.perf_th2swr, mtype="theta_to_swr"), gt.assign(perf2=gt.perf_swr2th, mtype="swr_to_theta")])
    long = long[np.isfinite(long.perf2)]
    pt = anova_p("perf2 ~ C(mtype) * C(grp)", long, "C(mtype)"); pi = anova_p("perf2 ~ C(mtype) * C(grp)", long, "C(mtype):C(grp)")
    print(f"Groups ({how}): sizes {gt.groupby('grp').n_ca1.agg(['min', 'max']).values.tolist()}, cells per group {gt.grp.value_counts().sort_index().tolist()}; modulated p = {pm:.3g}, group p = {pg:.3g}; "
          f"model type p = {pt:.3g}, model type x group p = {pi:.3g}; "
          f"perf by group (theta to SWR): {gt.groupby('grp').perf_th2swr.mean().round(3).to_dict()}")
print(f"theta-to-SWR mean {gt.perf_th2swr.mean():.3f} vs SWR-to-theta mean {gt.perf_swr2th.mean():.3f}")
Movement-trained, modulated cells n = 19: performance 0.038 +- 0.008 (n = 19); signed-rank vs 0 p = 1.91e-05; cells above shuffle at p < 0.05: 12
Unmodulated: 0.021 +- 0.003 (n = 130); SWR-trained to movement, modulated: 0.024 +- 0.007 (n = 16)
Groups (a): sizes [[3, 12], [14, 22], [23, 32]], cells per group [54, 60, 35]; modulated p = 0.034, group p = 0.00082; model type p = 0.0227, model type x group p = 0.492; perf by group (theta to SWR): {0: 0.012, 1: 0.028, 2: 0.035}
Groups (b): sizes [[3, 12], [14, 22], [23, 32]], cells per group [54, 60, 35]; modulated p = 0.034, group p = 0.00082; model type p = 0.0227, model type x group p = 0.492; perf by group (theta to SWR): {0: 0.012, 1: 0.028, 2: 0.035}
Groups (c): sizes [[3, 3], [4, 32]], cells per group [7, 142]; modulated p = 0.0305, group p = 0.0784; model type p = 0.0296, model type x group p = 0.278; perf by group (theta to SWR): {1: 0.002, 2: 0.025}
theta-to-SWR mean 0.024 vs SWR-to-theta mean 0.016

Result: not reproduced. Movement-trained models predict SWR spiking of modulated cells above chance (0.038, signed-rank p = 1.9e-05), better than for unmodulated cells (two-way p = 0.034) and better with larger ensembles (p = 0.00082, tertiles). The model type by size-group interaction, the criterion's test of theta-to-SWR against SWR-to-theta prediction, is not significant (p = 0.49), although theta-to-SWR performance (0.024) exceeds SWR-to-theta (0.016; model type p = 0.023). Groups (a) and (b) print the same results because they split these cells the same way (sizes above).

Claim figs4c-pfc-predicts-ca1ΒΆ

Reversing the model, SWR-modulated PFC ensembles predict CA1 SWR spiking, better than unmodulated PFC ensembles and better with larger ensembles, with excited and inhibited PFC cells predicting similarly.

Each included CA1 cell's SWR count predicted from the day's PFC cells of each category (modulated, excited, inhibited, unmodulated). Ensemble-size groups 1, 2-3 and more than 3 PFC cells (Figure S4C axis). 500 splits per model here, where the SEP uses 5000, to keep the notebook within its time; each performance is a mean over splits, so this sets its precision only.

InΒ [42]:
rng = rng_for("figs4c-pfc-predicts-ca1")
rev = []
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    c_idx = list(g.index[g.region == "CA1"])
    groups = {"modulated": list(g.index[(g.region == "PFC") & (g.category != "unmodulated")]),
              "excited": list(g.index[(g.region == "PFC") & (g.category == "excited")]),
              "inhibited": list(g.index[(g.region == "PFC") & (g.category == "inhibited")]),
              "unmodulated": list(g.index[(g.region == "PFC") & (g.category == "unmodulated")])}
    for kind, p_idx in groups.items():
        if len(p_idx) == 0:
            continue
        X = np.array([counts[j] for j in p_idx]).T.astype(float)
        if X.sum() == 0:
            continue
        for i in c_idx:
            cv = hc28.glm_cv(X, counts[i].astype(float), rng, splits=500)
            rev.append(dict(animal=a, day=d, ca1=i, kind=kind, n_pfc=len(p_idx), perf=cv["perf"], conv=cv["converged"]))
rev = pd.DataFrame(rev)
print("Models:", rev.groupby("kind").size().to_dict(), "; converged:", rev[rev.conv].groupby("kind").size().to_dict())
rc = rev[rev.conv].copy()
rc["grp"] = size_groups(rc.n_pfc.values, "c")
print("Performance by kind:", {k: msem(v.perf) for k, v in rc.groupby("kind")})
mu = rc[rc.kind.isin(["modulated", "unmodulated"])]
print(f"Two-way ANOVA modulated vs unmodulated: kind p = {anova_p('perf ~ C(kind) + C(grp)', mu, 'C(kind)'):.3g}, "
      f"size group p = {anova_p('perf ~ C(kind) + C(grp)', mu, 'C(grp)'):.3g}; one-way by kind p = {anova_p('perf ~ C(kind)', mu, 'C(kind)'):.3g}")
for k in ("modulated", "unmodulated"):
    s = rc[rc.kind == k]
    if s.grp.nunique() > 1:
        p1 = anova_p("perf ~ C(grp)", s, "C(grp)", typ=1)
        print(f"One-way ANOVA by size group, {k}: p = {p1:.3g}; means {s.groupby('grp').perf.mean().round(3).to_dict()} (groups 0: 1 cell, 1: 2-3, 2: > 3)")
    else:
        print(f"{k}: one size group only ({s.n_pfc.min()} to {s.n_pfc.max()} cells)")
ei = rc[rc.kind.isin(["excited", "inhibited"])]
if len(ei) and ei.kind.nunique() > 1:
    form = "perf ~ C(kind) + C(grp)" if ei.grp.nunique() > 1 else "perf ~ C(kind)"
    print(f"Excited vs inhibited: p = {anova_p(form, ei, 'C(kind)'):.3g}")
Models: {'excited': 184, 'inhibited': 108, 'modulated': 236, 'unmodulated': 392} ; converged: {'excited': 175, 'inhibited': 107, 'modulated': 226, 'unmodulated': 289}
Performance by kind: {'excited': '0.004 +- 0.001 (n = 175)', 'inhibited': '0.005 +- 0.001 (n = 107)', 'modulated': '0.005 +- 0.001 (n = 226)', 'unmodulated': '0.011 +- 0.001 (n = 289)'}
Two-way ANOVA modulated vs unmodulated: kind p = 0.901, size group p = 7.93e-05; one-way by kind p = 0.000558
One-way ANOVA by size group, modulated: p = 6.74e-05; means {0: 0.002, 1: 0.009} (groups 0: 1 cell, 1: 2-3, 2: > 3)
One-way ANOVA by size group, unmodulated: p = 0.0189; means {0: 0.004, 1: 0.006, 2: 0.013} (groups 0: 1 cell, 1: 2-3, 2: > 3)
Excited vs inhibited: p = 0.344

Result: not reproduced. Modulated PFC ensembles do not predict CA1 SWR spiking better than unmodulated ensembles (0.005 against 0.011; two-way p = 0.90, and unmodulated ensembles are higher by one-way ANOVA, p = 0.00056). Performance rises with ensemble size (p = 6.7e-05 for modulated ensembles) and excited and inhibited ensembles do not differ (p = 0.34).

Pre-task restΒΆ

SEP, Task and rest period comparisons: cells recorded in both the pre-rest and the run epochs of a day; PFC categories from behavior; SWRs of the pre-rest detected as in behavior (speed < 4 cm/s, 1 s rule).

InΒ [43]:
pre_rows = []
for r in main_pairs.itertuples():
    x, y = pre_counts.get(r.ca1), pre_counts.get(r.pfc)
    if x is None or y is None:
        continue
    rp, pp_ = corr_p(x, y)
    pre_rows.append(dict(idx=r.Index, r_pre=rp, p_pre=pp_, n_pre_swr=len(x)))
pre_df = pd.DataFrame(pre_rows).set_index("idx")
fp = main_pairs.join(pre_df, how="inner")
fp = fp[np.isfinite(fp.r_pre)]
print("Pre-rest SWRs per day:", {f"{a}{d}": len(hc28.swr_onsets(R[a]["days"][d], [R[a]["days"][d]["pre"]])) for a in R for d in R[a]["days"]})
print("Pairs with both cells in the pre-rest and a defined pre-rest correlation:", fp.groupby("pfc_cat").size().to_dict())
Pre-rest SWRs per day: {'HPa1': 611, 'HPa2': 633, 'HPa3': 664, 'HPa4': 631, 'HPa5': 610, 'HPa6': 629, 'HPa7': 609, 'HPa8': 582, 'HPb1': 560, 'HPb2': 662, 'HPb3': 591, 'HPb4': 591, 'HPb5': 591, 'HPb6': 1297, 'HPb7': 774, 'HPb8': 623, 'HPc1': 557, 'HPc2': 398, 'HPc3': 494, 'HPc4': 412, 'HPc5': 421, 'HPc6': 375, 'HPc7': 392, 'HPc8': 411}
Pairs with both cells in the pre-rest and a defined pre-rest correlation: {'excited': 120, 'inhibited': 71}

Claim fig8a-no-prerest-swr-correlation-relationΒΆ

On the W-track, SWR correlations of CA1-PFC pairs in the pre-task rest show no relation to their SWR correlations during the task (excited pairs r = 0.08, p = 0.2; inhibited r = 0.1, p > 0.1).

The paper's test: regression (Pearson r) at p < 0.05.

InΒ [44]:
for c in ("excited", "inhibited"):
    s = fp[fp.pfc_cat == c]
    rr, p_, n_ = reg(s.r.values, s.r_pre.values)
    print(f"{c}: r = {rr:.3f}, p = {p_:.3g}, n = {n_} pairs (expected 219 excited, 196 inhibited pairs)")
rr, p_, n_ = reg(fp.r.values, fp.r_pre.values)
print(f"all: r = {rr:.3f}, p = {p_:.3g}, n = {n_}")
excited: r = 0.065, p = 0.478, n = 120 pairs (expected 219 excited, 196 inhibited pairs)
inhibited: r = 0.127, p = 0.293, n = 71 pairs (expected 219 excited, 196 inhibited pairs)
all: r = 0.110, p = 0.128, n = 191

Result: reproduced. Pre-rest and task SWR correlations are unrelated in excited pairs (r = 0.065, p = 0.48, 120 pairs) and inhibited pairs (r = 0.127, p = 0.29, 71 pairs); the pairs are fewer than the paper's 219 and 196.

Claim fig8bc-no-prerest-theta-spatial-relationΒΆ

Pre-rest SWR correlations bear no relation to task theta cross-covariance (r = 0.02 and 0.12) or to task spatial correlation (r = -0.02 and 0.05) for excited and inhibited pairs.

InΒ [45]:
nsig = 0
for col in ("theta_peak", "spatial"):
    for c in ("excited", "inhibited"):
        s = fp[fp.pfc_cat == c]
        rr, p_, n_ = reg(s[col].values, s.r_pre.values)
        nsig += p_ < 0.05
        print(f"{col}, {c}: r = {rr:.3f}, p = {p_:.3g}, n = {n_}")
print(f"Significant at p < 0.05: {nsig} of 4")
theta_peak, excited: r = -0.025, p = 0.786, n = 120
theta_peak, inhibited: r = 0.146, p = 0.224, n = 71
spatial, excited: r = -0.111, p = 0.226, n = 120
spatial, inhibited: r = 0.177, p = 0.14, n = 71
Significant at p < 0.05: 0 of 4

Result: reproduced. None of the four relations is significant: theta cross-covariance r = -0.025 and 0.146, spatial correlation r = -0.111 and 0.177 (p = 0.14 to 0.79).

Claim fig8d-glm-epoch-specificΒΆ

GLMs trained on task SWRs fail to predict PFC spiking in pre-rest SWRs, and cross-epoch predictions are worse than within-task and within-pre-rest predictions.

SWR-modulated PFC cells (the population of Figure 6E) recorded in both epochs; CA1 ensemble: the day's included CA1 cells with spikes in both epochs (Figure S7D legend). Within-epoch: cross-validated as above (5000 splits); cross-epoch: trained on all SWRs of one epoch, applied to the other; chance by 1000 shuffles of the predictions across SWRs.

InΒ [46]:
rng = rng_for("fig8d-glm-epoch-specific")
g8 = []
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    c_idx = [i for i in g.index[g.region == "CA1"] if pre_counts.get(i) is not None]
    p_idx = [j for j in g.index[(g.region == "PFC") & (g.category != "unmodulated")] if pre_counts.get(j) is not None]
    if not c_idx or not p_idx:
        continue
    Xt = np.array([counts[i] for i in c_idx]).T.astype(float); Xp = np.array([pre_counts[i] for i in c_idx]).T.astype(float)
    for j in p_idx:
        yt, yp = counts[j].astype(float), pre_counts[j].astype(float)
        tt = hc28.glm_cv(Xt, yt, rng); ppp = hc28.glm_cv(Xp, yp, rng) if yp.sum() > 0 else dict(perf=np.nan, converged=False)
        both = (Xt.sum(0) > 0) & (Xp.sum(0) > 0)
        tp = hc28.glm_cross(Xt[:, both], yt, Xp[:, both], yp, rng) if yp.sum() > 0 else dict(perf=np.nan, p=np.nan, converged=False)
        pt = hc28.glm_cross(Xp[:, both], yp, Xt[:, both], yt, rng) if yp.sum() > 0 else dict(perf=np.nan, p=np.nan, converged=False)
        g8.append(dict(animal=a, day=d, pfc=j, task_task=tt["perf"], pre_pre=ppp["perf"], task_pre=tp["perf"], p_task_pre=tp["p"], pre_task=pt["perf"], p_pre_task=pt["p"]))
g8 = pd.DataFrame(g8)
for col in ("task_task", "task_pre", "pre_task", "pre_pre"):
    print(f"{col}: {msem(g8[col])}")
print(f"Task to pre-rest above chance: cells with shuffle p < 0.05: {(g8.p_task_pre < 0.05).sum()} of {g8.p_task_pre.notna().sum()}; "
      f"signed-rank of performance vs 0 p = {stats.wilcoxon(g8.task_pre.dropna()).pvalue if g8.task_pre.notna().sum() > 1 else np.nan:.3g}")
print(f"task_pre vs task_task p = {ranksum(g8.task_pre, g8.task_task):.3g}; pre_task vs task_task p = {ranksum(g8.pre_task, g8.task_task):.3g}; "
      f"pre_pre vs task_pre p = {ranksum(g8.pre_pre, g8.task_pre):.3g}; pre_pre vs pre_task p = {ranksum(g8.pre_pre, g8.pre_task):.3g}")
print("Cell counts (expected 38, 24, 22, 39):", {c: int(g8[c].notna().sum()) for c in ("task_task", "task_pre", "pre_task", "pre_pre")})
task_task: 0.056 +- 0.011 (n = 16)
task_pre: 0.003 +- 0.004 (n = 16)
pre_task: 0.009 +- 0.005 (n = 11)
pre_pre: 0.022 +- 0.010 (n = 11)
Task to pre-rest above chance: cells with shuffle p < 0.05: 3 of 16; signed-rank of performance vs 0 p = 0.597
task_pre vs task_task p = 0.000297; pre_task vs task_task p = 0.00188; pre_pre vs task_pre p = 0.0484; pre_pre vs pre_task p = 0.491
Cell counts (expected 38, 24, 22, 39): {'task_task': 16, 'task_pre': 16, 'pre_task': 11, 'pre_pre': 11}

Result: not reproduced. Task-trained models do not predict pre-rest SWR spiking above chance over cells (0.003, signed-rank p = 0.60; 3 of 16 cells pass their own shuffle), and both cross-epoch predictions are worse than task-to-task (p = 0.00030 and 0.0019). Pre-rest-to-pre-rest prediction (0.022) exceeds task-to-pre-rest (p = 0.048) but not pre-rest-to-task (p = 0.49), which the criterion requires. Cell counts are 16, 16, 11 and 11 against 38, 24, 22 and 39.

Claim figs6-replay-contentΒΆ

The SWR spiking of SWR-modulated PFC neurons is more related to the spatial content of CA1 replay than that of unmodulated neurons.

SEP, Replay analysis: candidate events are SWRs with at least 4 CA1 cells spiking; CA1 spikes are decoded in 15 ms bins with a Poisson model; an event is significant at p < 0.05 against 500 shuffles of its time bins; PFC cells with at least 10 significant events enter. Following the claims file, R is the correlation, per event, of the decoded probability summed across the SWR with the PFC cell's rate profile on the replayed trajectory, and each cell's value is the correlation across its significant events of R with its spike count 0-200 ms after onset, (a) Pearson, (b) Spearman. The replay score is the line fit of the cited Karlsson & Frank (2009).

Choices the paper does not state (standard choices): an event spans the SWR from its onset to its end; the CA1 cells are the day's included CA1 cell-days; the decoded track is the two sides of the W-track (centre well to left well, centre well to right well), each with the mean of its outbound and inbound rate maps in 4 cm bins, smoothed with a Gaussian of SD 4 cm, plus 0.1 Hz; the replayed side is the one with the larger summed probability; the line fit takes the largest mean probability within +-12 cm of a line of constant speed; events shorter than 3 bins are left out. Only the wtr1 runs are decoded, since the wtr2 track (days 6 to 8) has a geometry of its own.

InΒ [47]:
import time
rng = rng_for("figs6-replay-content")
# Replay is decoded within the wtr1 runs, with place fields from those runs: the wtr2 track of days 6 to 8 has a
# geometry of its own, so its fields cannot be laid on the same linear axis.
ev_rows, cell_rows = [], []
t0 = time.time()
for (a, d), g in cells[cells.category.notna()].groupby(["animal", "day"]):
    day = R[a]["days"][d]; runs = [e for e in day["runs"] if day["task"][e][1] == "wtr1"]
    c_idx = list(g.index[g.region == "CA1"]); p_idx = list(g.index[g.region == "PFC"])
    units = {i: day["units"][(cells.loc[i, "tet"], cells.loc[i, "unit"])] for i in c_idx + p_idx}
    mp = hc28.rate_maps(day, {i: u for i, u in units.items()}, epochs=runs)
    prof = {i: hc28.side_profiles(mp[i]) for i in c_idx + p_idx}
    fields = [np.array([prof[i][s] for i in c_idx]) for s in (0, 1)]
    ns = [f.shape[1] for f in fields]
    st_c = [hc28.spikes_in(units[i], runs) for i in c_idx]
    st_p = {j: hc28.spikes_in(units[j], runs) for j in p_idx}
    for e in runs:
        s = day["epochs"][e]["swr"]
        for on, end in s["any"][s["kept_any"]][:, [0, 2]]:
            nb = int(np.ceil((end - on) / hc28.REPLAY_BIN))
            edges = on + np.arange(nb + 1) * hc28.REPLAY_BIN
            cnt = np.array([np.histogram(x[(x >= on) & (x < edges[-1])], edges)[0] for x in st_c])
            if (cnt.sum(1) > 0).sum() < hc28.REPLAY_MIN_CELLS or nb < 3:
                continue
            post = hc28.decode(cnt, np.hstack(fields))
            side = int(post[:, ns[0]:].sum() > post[:, :ns[0]].sum())
            ps = post[:, :ns[0]] if side == 0 else post[:, ns[0]:]
            score, p = hc28.line_fit_p(ps, rng)
            row = dict(animal=a, day=d, onset=on, n_bins=nb, n_active=int((cnt.sum(1) > 0).sum()), side=side, score=score, p=p)
            summed = ps.sum(0)
            for j in p_idx:
                pr = prof[j][side]
                row[f"R_{j}"] = np.corrcoef(summed, pr)[0, 1] if np.std(pr) > 0 else np.nan
                row[f"n_{j}"] = int(np.searchsorted(st_p[j], on + 0.2) - np.searchsorted(st_p[j], on))
            ev_rows.append(row)
print(f"Candidate events (wtr1 runs, >= {hc28.REPLAY_MIN_CELLS} active CA1 cells, >= 3 bins of 15 ms): {len(ev_rows)}; {time.time() - t0:.0f} s")
ev = pd.DataFrame(ev_rows)
ev["significant"] = ev.p < 0.05
print(f"Significant replay events (p < 0.05 against {hc28.REPLAY_SHUFFLES} time-bin shuffles): {int(ev.significant.sum())} of {len(ev)} "
      f"({ev.significant.mean():.3f}; chance 0.05)")
print("Per animal:", ev.groupby("animal").significant.agg(["sum", "size"]).to_dict("index"))
print("Events: bins %d to %d (median %d), active CA1 cells %d to %d" % (ev.n_bins.min(), ev.n_bins.max(), ev.n_bins.median(), ev.n_active.min(), ev.n_active.max()))
sig_ev = ev[ev.significant]
for (a, d), g in cells[cells.category.notna() & (cells.region == "PFC")].groupby(["animal", "day"]):
    s = sig_ev[(sig_ev.animal == a) & (sig_ev.day == d)]
    for j in g.index:
        if f"R_{j}" not in s:   # no candidate event on this day
            cell_rows.append(dict(pfc=j, category=cells.loc[j, "category"], n_events=0))
            continue
        x, y = s[f"R_{j}"].values, s[f"n_{j}"].values
        ok = np.isfinite(x)
        row = dict(pfc=j, category=cells.loc[j, "category"], n_events=int(ok.sum()))
        if ok.sum() >= 10 and np.std(y[ok]) > 0:
            row["r_pearson"] = stats.pearsonr(x[ok], y[ok])[0]; row["r_spearman"] = stats.spearmanr(x[ok], y[ok])[0]
        cell_rows.append(row)
rc6 = pd.DataFrame(cell_rows)
rc6["modulated"] = rc6.category != "unmodulated"
q = rc6[rc6.r_pearson.notna()] if "r_pearson" in rc6 else rc6.iloc[:0]
print(f"PFC cell-days with >= 10 significant events: {int((rc6.n_events >= 10).sum())}; with a defined correlation (some SWR spikes): {len(q)} "
      f"({int(q.modulated.sum())} modulated, {int((~q.modulated).sum())} unmodulated; paper 17 and 21)")
for col, lab in (("r_pearson", "a, Pearson"), ("r_spearman", "b, Spearman")):
    if len(q) == 0:
        break
    x, y = q[q.modulated][col], q[~q.modulated][col]
    p1 = stats.ranksums(x, y, alternative="greater").pvalue if len(x) and len(y) else np.nan
    print(f"Reading {lab}: modulated {msem(x)}, unmodulated {msem(y)}; rank-sum p = {ranksum(x, y):.3g} (two-sided), {p1:.3g} (modulated greater)")
Candidate events (wtr1 runs, >= 4 active CA1 cells, >= 3 bins of 15 ms): 685; 176 s
Significant replay events (p < 0.05 against 500 time-bin shuffles): 206 of 685 (0.301; chance 0.05)
Per animal: {'HPa': {'sum': 119, 'size': 336}, 'HPb': {'sum': 50, 'size': 209}, 'HPc': {'sum': 37, 'size': 140}}
Events: bins 3 to 25 (median 9), active CA1 cells 4 to 13
PFC cell-days with >= 10 significant events: 45; with a defined correlation (some SWR spikes): 41 (8 modulated, 33 unmodulated; paper 17 and 21)
Reading a, Pearson: modulated -0.048 +- 0.081 (n = 8), unmodulated 0.038 +- 0.040 (n = 33); rank-sum p = 0.449 (two-sided), 0.775 (modulated greater)
Reading b, Spearman: modulated -0.042 +- 0.058 (n = 8), unmodulated 0.038 +- 0.041 (n = 33); rank-sum p = 0.357 (two-sided), 0.822 (modulated greater)

Result: not reproduced. Of 685 candidate events in the wtr1 runs, 206 (0.301) are significant replay events, against 0.05 expected by chance. 41 PFC cell-days have at least 10 significant events and some SWR spikes, 8 modulated and 33 unmodulated (paper 17 and 21). The correlation of R with the PFC SWR response is not higher for modulated cells: -0.048 against 0.038 (Pearson, rank-sum p = 0.45) and -0.042 against 0.038 (Spearman, p = 0.36).

Claims downstream of the classification, under the other readingsΒΆ

The claims from Figure 3 onwards rest on the SWR classification of the PFC cells, made above with reading (a) of SWR detection (an SWR on any one ripple tetrode) and both W-track runs of each day. Two choices the paper leaves open could change it:

  • Reading (b): SWRs from the mean of the tetrodes' z-scored envelopes. Its duration and low-speed rate match the paper's values, and it raises CA1 firing more than reading (a) does (data check above), but it finds about a third as many SWRs (claim swr-detection-stats).
  • The wtr2 runs. On days 6 to 8 the second run is on a second W-track, wtr2, with a geometry of its own (data check). The SEP says the animals "performed 2 sessions on the W-track every day for a total of 8 days" (Behavioral Tasks), which includes wtr2. The data set also serves Tang et al. (2017), whose novel environment these runs may be, so the variant leaves them out.

Each variant classifies the cells again, applies the 50-spike criterion again, and repeats the main test of each downstream claim's criterion. Under the wtr2 variant, the SWR-based quantities use the wtr1 runs only, while the theta, rate and rate-map measures stay pooled over both runs (coverage from the wtr1 runs alone is in the fig5c section). A second battery repeats the remaining downstream claims: fig3-transient-responses, the inhibited-stronger test of fig7c, figs5, fig8bc, the movement-trained GLM (fig6e-theta-trained-glm), figs4c and fig8d, and figs6. For figs6 the replay events and the per-cell correlations of the main analysis (reading a, wtr1 runs) are kept and only the cells' classification changes. The GLM of the first battery uses 500 splits per cell, and those of the second 200 (the main analysis uses 5000 for fig6e and fig8d, 500 for figs4c); each performance is a mean over splits, so this sets its precision only. The main reading is run through both batteries as a check against the claim sections above.

InΒ [48]:
rng = rng_for("other-readings")


def wtr1_runs(day):
    return [e for e in day["runs"] if day["task"][e][1] == "wtr1"]


variants = {"main (a, both runs)": None, "b, mean envelope": ("mean", lambda day: day["runs"]), "a, without wtr2": ("any", wtr1_runs)}
inc = cells[cells.category.notna()]
alt = {}
for vname, v in variants.items():
    if v is None:
        alt[vname] = dict(cat=inc.category, mi=inc.mi_ratio, psth={i: mod[i]["psth"] for i in inc.index}, counts=counts,
                          pre_counts=pre_counts, raster=raster_spk, pre_rate=inc.pre_swr_rate, dropped=0)
        continue
    reading, runs_of = v
    cat, mi, psth, cnt, pcnt, rast, prer = {}, {}, {}, {}, {}, {}, {}
    for (a, d), g in inc.groupby(["animal", "day"]):
        day = R[a]["days"][d]; runs = runs_of(day)
        on = hc28.swr_onsets(day, runs, reading); on_pre = hc28.swr_onsets(day, [day["pre"]], reading)
        for i, r in zip(g.index, g.itertuples()):
            u = day["units"][(r.tet, r.unit)]
            st = hc28.spikes_in(u, runs)
            cnt[i] = hc28.swr_counts(st, on)
            st_pre = u["times"].get(day["pre"], np.zeros(0))
            pcnt[i] = hc28.swr_counts(np.sort(st_pre), on_pre) if len(st_pre) else None
            rel, idx = hc28.aligned(st, on, 0.5)
            rast[i] = (np.sort(on[idx] + rel), len(on))
            prer[i] = (np.searchsorted(st, on - 0.1) - np.searchsorted(st, on - 0.5)).sum() / (0.4 * len(on))
            if len(rel) < hc28.MIN_RASTER_SPIKES:   # the spike criterion, applied again under this variant
                continue
            m = hc28.swr_modulation(st, on, rng)
            cat[i] = category(m); mi[i] = m["mi_ratio"]; psth[i] = m["psth"]
    alt[vname] = dict(cat=pd.Series(cat), mi=pd.Series(mi), psth=psth, counts=cnt, pre_counts=pcnt, raster=rast,
                      pre_rate=pd.Series(prer), dropped=len(inc) - len(cat))
print("Cells dropped by the spike criterion under each variant:", {k: v["dropped"] for k, v in alt.items()})
Cells dropped by the spike criterion under each variant: {'main (a, both runs)': 0, 'b, mean envelope': 147, 'a, without wtr2': 41}
InΒ [49]:
def battery(A):
    """The criterion's main tests of the claims downstream of the SWR classification, under one variant."""
    out = {}
    c = cells.loc[A["cat"].index].copy()
    c["category"] = A["cat"]; c["mi_ratio"] = A["mi"]; c["pre_swr_rate"] = A["pre_rate"].reindex(c.index)
    P = c[c.region == "PFC"]; C1 = c[c.region == "CA1"]
    grp = {k: P[P.category == k] for k in cats}
    n = {k: len(v) for k, v in grp.items()}
    out["fig3-pfc-swr-modulation-fractions"] = (f"{n['excited']} / {n['inhibited']} / {n['unmodulated']} of {len(P)} "
                                                f"(expected 30 / 26 / 109)")
    out["ca1-swr-modulated"] = f"{(C1.category != 'unmodulated').mean():.3f} of {len(C1)} (expected 0.80 +- 0.08)"
    # timing
    ca1m = C1.index[C1.category != "unmodulated"]
    tm = {k: np.array([hc28.psth_timing(A["psth"][i], centers, s) for i in idx]) * 1000
          for k, idx, s in (("CA1", ca1m, 1), ("excited", grp["excited"].index, 1), ("inhibited", grp["inhibited"].index, -1))}
    pk = {k: v[:, 0] if len(v) else np.zeros(0) for k, v in tm.items()}
    on_ = {k: v[:, 1] if len(v) else np.zeros(0) for k, v in tm.items()}
    out["fig3de-ca1-precedes-pfc-peak"] = (f"peak CA1 {np.nanmean(pk['CA1']):.0f}, excited {np.nanmean(pk['excited']):.0f}, inhibited "
                                           f"{np.nanmean(pk['inhibited']):.0f} ms; CA1 vs excited p = {ranksum(pk['CA1'], pk['excited']):.2g}, "
                                           f"vs inhibited p = {ranksum(pk['CA1'], pk['inhibited']):.2g}")
    out["fig3e-onset-later-in-pfc"] = (f"onset CA1 {np.nanmean(on_['CA1']):.0f}, excited {np.nanmean(on_['excited']):.0f}, inhibited "
                                       f"{np.nanmean(on_['inhibited']):.0f} ms; CA1 vs excited p = {ranksum(on_['CA1'], on_['excited']):.2g}, "
                                       f"vs inhibited p = {ranksum(on_['CA1'], on_['inhibited']):.2g}")
    # theta
    tl = P.groupby("category").theta_locked.agg(["sum", "size"]).reindex(list(cats)).fillna(0)
    zp = lambda a_, b_: proportions_ztest([tl.loc[a_, "sum"], tl.loc[b_, "sum"]], [tl.loc[a_, "size"], tl.loc[b_, "size"]])[1] if min(tl.loc[a_, "size"], tl.loc[b_, "size"]) > 0 else np.nan
    out["fig4-swr-modulated-more-theta-locked"] = ("locked " + ", ".join(f"{k} {tl.loc[k, 'sum'] / max(tl.loc[k, 'size'], 1):.2f}" for k in cats) +
                                                  f"; excited vs unmodulated p = {zp('excited', 'unmodulated'):.2g}, inhibited vs unmodulated p = {zp('inhibited', 'unmodulated'):.2g}")
    L = P[P.theta_locked.fillna(False).astype(bool)]
    k_ = {k: L[L.category == k].kappa for k in cats}
    out["fig4b-kappa"] = (f"kappa (locked cells) excited {k_['excited'].mean():.3f}, inhibited {k_['inhibited'].mean():.3f}, unmodulated "
                          f"{k_['unmodulated'].mean():.3f}; excited vs unmodulated p = {ranksum(k_['excited'], k_['unmodulated']):.2g}, "
                          f"inhibited vs unmodulated p = {ranksum(k_['inhibited'], k_['unmodulated']):.2g}")
    lk = P.theta_locked.fillna(False).astype(bool)
    out["fig4c-theta-locked-more-swr-modulated"] = (f"modulation index locked {P[lk].mi_ratio.mean():.2f}, not locked {P[~lk].mi_ratio.mean():.2f}; "
                                                    f"p = {ranksum(P[lk].mi_ratio, P[~lk].mi_ratio):.2g}")
    ph = {k: P[(P.category == k) & (P.n_theta >= 50)].peak_phase.values for k in cats}
    kp = lambda a_, b_: kuiper_two(ph[a_], ph[b_])[1] if min(len(ph[a_]), len(ph[b_])) > 1 else np.nan
    out["fig4-preferred-phase-concentration"] = (f"Kuiper excited vs unmodulated p = {kp('excited', 'unmodulated'):.2g}, excited vs inhibited "
                                                 f"p = {kp('excited', 'inhibited'):.2g}, inhibited vs unmodulated p = {kp('inhibited', 'unmodulated'):.2g}")
    # firing properties
    rr = {k: grp[k].rate_theta for k in cats}
    out["fig5b-mean-rates"] = (f"theta rate excited {rr['excited'].mean():.2f}, inhibited {rr['inhibited'].mean():.2f}, unmodulated "
                               f"{rr['unmodulated'].mean():.2f} Hz; excited vs unmodulated p = {ranksum(rr['excited'], rr['unmodulated']):.2g}, "
                               f"inhibited vs unmodulated p = {ranksum(rr['inhibited'], rr['unmodulated']):.2g}")
    cv_ = {k: grp[k].coverage for k in cats}
    out["fig5c-spatial-coverage"] = (f"coverage excited {cv_['excited'].mean():.3f}, inhibited {cv_['inhibited'].mean():.3f}, unmodulated "
                                     f"{cv_['unmodulated'].mean():.3f}; excited vs inhibited p = {ranksum(cv_['excited'], cv_['inhibited']):.2g}, "
                                     f"excited vs unmodulated p = {ranksum(cv_['excited'], cv_['unmodulated']):.2g}")
    dm = {k: grp[k].dir_mean for k in cats}
    out["figs3-arm-and-direction-selectivity"] = ("direction index (mean) CA1 vs " + ", ".join(f"{k} p = {ranksum(C1.dir_mean, dm[k]):.2g}" for k in cats) +
                                                  f"; excited vs unmodulated p = {ranksum(dm['excited'], dm['unmodulated']):.2g}")
    s5 = {k: np.array([sc.get((i, 0.2, "time"), np.nan) for i in grp[k].index]) for k in cats}
    out["fig5e-speed-correlation"] = (f"speed correlation (200 ms) excited {np.nanmedian(s5['excited']):.3f}, inhibited {np.nanmedian(s5['inhibited']):.3f}; "
                                      f"p = {ranksum(s5['excited'], s5['inhibited']):.2g}")
    i5 = (P.pre_swr_rate - P.highspeed_rate) / (P.pre_swr_rate + P.highspeed_rate)
    out["fig5f-pre-swr-vs-movement"] = (f"index excited {i5[P.category == 'excited'].mean():.3f}, inhibited {i5[P.category == 'inhibited'].mean():.3f}; "
                                        f"p = {ranksum(i5[P.category == 'excited'], i5[P.category == 'inhibited']):.2g}")
    r3 = {k: np.array([rm.get((i, 0), np.nan) for i in grp[k].index]) for k in cats}
    out["figs3e-reward-modulation"] = (f"reward index excited {np.nanmean(r3['excited']):.3f}, inhibited {np.nanmean(r3['inhibited']):.3f}; "
                                       f"p = {ranksum(r3['inhibited'], r3['excited']):.2g}")
    kind = pp.apply(lambda r: "-".join(sorted([str(A["cat"].get(r.i, "x"))[:3], str(A["cat"].get(r.j, "x"))[:3]])), axis=1)
    q = {k: pp.peak[kind == k] for k in ("exc-exc", "inh-inh", "exc-inh")}
    out["fig5g-ensemble-cofiring"] = (f"pairs {len(q['exc-exc'])} / {len(q['inh-inh'])} / {len(q['exc-inh'])} (exc-exc / inh-inh / exc-inh); "
                                      f"exc-inh vs exc-exc p = {ranksum(q['exc-inh'], q['exc-exc']):.2g}, vs inh-inh p = {ranksum(q['exc-inh'], q['inh-inh']):.2g}")
    # pairs
    rows_ = []
    rng_p = rng_for("other-readings-pairs")
    for (a, d), g in c.groupby(["animal", "day"]):
        for i in g.index[(g.region == "CA1") & (g.category != "unmodulated")]:
            for j in g.index[(g.region == "PFC") & (g.category != "unmodulated")]:
                x, y = A["counts"][i], A["counts"][j]
                if ((x > 0) & (y > 0)).sum() < 5:
                    continue
                r_, p_ = corr_p(x, y); _, psh = corr_p(x, rng_p.permutation(y))
                rows_.append(dict(animal=a, day=d, ca1=i, pfc=j, pfc_cat=c.loc[j, "category"], r=r_, p=p_, p_shuf=psh))
    pr = pd.DataFrame(rows_)
    if len(pr) == 0:
        return out
    sig = pr.p < 0.05
    out["fig6-swr-correlated-pairs"] = (f"{sig.sum()} of {len(pr)} pairs significant ({sig.mean():.3f}), shuffled {(pr.p_shuf < 0.05).mean():.3f}; "
                                        f"excited {sig[pr.pfc_cat == 'excited'].mean():.3f}, inhibited {sig[pr.pfc_cat == 'inhibited'].mean():.3f}")
    sg = pr[sig]
    out["fig6ab-both-signs"] = ", ".join(f"{k} {int((sg[sg.pfc_cat == k].r > 0).sum())} positive / {int((sg[sg.pfc_cat == k].r < 0).sum())} negative"
                                         for k in ("excited", "inhibited"))
    tp, xc_c, sp_ = [], {}, []
    for r in pr.itertuples():
        lags_, xc = hc28.std_xcov(theta_spk[r.ca1], theta_spk[r.pfc], theta_T[(r.animal, r.day)])
        w = np.abs(lags_) <= 0.2 + 1e-9
        tp.append(np.nanmax(xc[w])); xc_c[r.Index] = xc
        sp_.append(hc28.spatial_corr(maps_all[r.ca1], maps_all[r.pfc]))
    pr["theta_peak"] = tp; pr["spatial"] = sp_
    out["fig6c-theta-predicts-swr-correlation"] = ", ".join(f"{k} r = {reg(s.theta_peak.values, s.r.values)[0]:.2f} (p = {reg(s.theta_peak.values, s.r.values)[1]:.2g})"
                                                            for k, s in (("excited", pr[pr.pfc_cat == "excited"]), ("inhibited", pr[pr.pfc_cat == "inhibited"])))
    fb = []
    for k in ("excited", "inhibited"):
        s = pr[(pr.pfc_cat == k) & sig & (pr.r > 0)]
        if len(s):
            mxc = np.nanmean([xc_c[i] for i in s.index], 0); w = np.abs(lags_) <= 0.2 + 1e-9
            fb.append(f"{k} {len(s)} pairs, mean peak at {lags_[w][np.argmax(mxc[w])] * 1000:.0f} ms")
        else:
            fb.append(f"{k} no pairs")
    out["figs4b-ca1-leads-in-theta"] = "; ".join(fb)
    ff = []
    for k, sign in (("excited", 1), ("inhibited", -1)):
        X = []
        for r in pr[pr.pfc_cat == k].itertuples():
            t1, n_ = A["raster"][r.ca1]; t2, _ = A["raster"][r.pfc]
            lags_r, xc = hc28.std_xcov(t1, t2, n_ * 1.0); X.append(xc)
        if X:
            mean = np.nanmean(X, 0); w = np.abs(lags_r) <= 0.2 + 1e-9
            ff.append(f"{k} extremum of the mean at {lags_r[w][np.argmax(sign * mean[w])] * 1000:.0f} ms")
    out["fig3f-swr-cross-covariance-lag"] = "; ".join(ff)
    out["fig7c-spatial-correlation"] = ", ".join(f"{k} r = {reg(s.spatial.values, s.r.values)[0]:.2f} (p = {reg(s.spatial.values, s.r.values)[1]:.2g})"
                                                 for k, s in (("excited", pr[pr.pfc_cat == "excited"]), ("inhibited", pr[pr.pfc_cat == "inhibited"])))
    f8 = []
    for k in ("excited", "inhibited"):
        xs, ys = [], []
        for r in pr[pr.pfc_cat == k].itertuples():
            x, y = A["pre_counts"].get(r.ca1), A["pre_counts"].get(r.pfc)
            if x is None or y is None:
                continue
            rp, _ = corr_p(x, y)
            if np.isfinite(rp):
                xs.append(r.r); ys.append(rp)
        rr_, p_, n_ = reg(np.array(xs), np.array(ys)) if len(xs) > 2 else (np.nan, np.nan, len(xs))
        f8.append(f"{k} r = {rr_:.2f} (p = {p_:.2g}, n = {n_})")
    out["fig8a-no-prerest-swr-correlation-relation"] = ", ".join(f8)
    # GLM: SWR spiking of PFC cells from CA1 ensembles, 500 splits
    rng_g = rng_for("other-readings-glm")
    perf = []
    for (a, d), g in c.groupby(["animal", "day"]):
        c_idx = list(g.index[g.region == "CA1"])
        if not c_idx:
            continue
        Xs = np.array([A["counts"][i] for i in c_idx]).T.astype(float)
        for j in g.index[g.region == "PFC"]:
            cvr = hc28.glm_cv(Xs, A["counts"][j].astype(float), rng_g, splits=500)
            if cvr["converged"]:
                perf.append((c.loc[j, "category"] != "unmodulated", cvr["perf"]))
    pf = pd.DataFrame(perf, columns=["modulated", "perf"])
    mp_ = pf[pf.modulated].perf
    out["fig6e-glm-swr-prediction"] = (f"modulated {mp_.mean():.3f} (n = {len(mp_)}, signed-rank vs 0 p = {stats.wilcoxon(mp_).pvalue if len(mp_) > 1 else np.nan:.2g}), "
                                       f"unmodulated {pf[~pf.modulated].perf.mean():.3f}; p = {ranksum(mp_, pf[~pf.modulated].perf):.2g}")
    return out


res = {k: battery(A) for k, A in alt.items()}
tab = pd.DataFrame(res)
for claim, row in tab.iterrows():
    print(f"{claim}:")
    for k, v in row.items():
        print(f"   {k}: {v}")
fig3-pfc-swr-modulation-fractions:
   main (a, both runs): 12 / 7 / 148 of 167 (expected 30 / 26 / 109)
   b, mean envelope: 17 / 3 / 116 of 136 (expected 30 / 26 / 109)
   a, without wtr2: 11 / 6 / 144 of 161 (expected 30 / 26 / 109)
ca1-swr-modulated:
   main (a, both runs): 0.651 of 392 (expected 0.80 +- 0.08)
   b, mean envelope: 0.627 of 276 (expected 0.80 +- 0.08)
   a, without wtr2: 0.569 of 357 (expected 0.80 +- 0.08)
fig3de-ca1-precedes-pfc-peak:
   main (a, both runs): peak CA1 46, excited 59, inhibited 86 ms; CA1 vs excited p = 0.35, vs inhibited p = 0.0036
   b, mean envelope: peak CA1 48, excited 100, inhibited 28 ms; CA1 vs excited p = 0.00085, vs inhibited p = 0.33
   a, without wtr2: peak CA1 45, excited 61, inhibited 80 ms; CA1 vs excited p = 0.26, vs inhibited p = 0.027
fig3e-onset-later-in-pfc:
   main (a, both runs): onset CA1 10, excited 13, inhibited 21 ms; CA1 vs excited p = 0.58, vs inhibited p = 0.093
   b, mean envelope: onset CA1 10, excited 36, inhibited 10 ms; CA1 vs excited p = 0.00039, vs inhibited p = 0.82
   a, without wtr2: onset CA1 10, excited 17, inhibited 10 ms; CA1 vs excited p = 0.21, vs inhibited p = 0.76
fig4-swr-modulated-more-theta-locked:
   main (a, both runs): locked excited 0.92, inhibited 0.86, unmodulated 0.50; excited vs unmodulated p = 0.0054, inhibited vs unmodulated p = 0.065
   b, mean envelope: locked excited 0.59, inhibited 0.33, unmodulated 0.61; excited vs unmodulated p = 0.85, inhibited vs unmodulated p = 0.33
   a, without wtr2: locked excited 0.91, inhibited 1.00, unmodulated 0.52; excited vs unmodulated p = 0.013, inhibited vs unmodulated p = 0.021
fig4b-kappa:
   main (a, both runs): kappa (locked cells) excited 0.272, inhibited 0.101, unmodulated 0.191; excited vs unmodulated p = 0.13, inhibited vs unmodulated p = 0.17
   b, mean envelope: kappa (locked cells) excited 0.293, inhibited 1.065, unmodulated 0.146; excited vs unmodulated p = 0.017, inhibited vs unmodulated p = 0.088
   a, without wtr2: kappa (locked cells) excited 0.269, inhibited 0.090, unmodulated 0.193; excited vs unmodulated p = 0.25, inhibited vs unmodulated p = 0.066
fig4c-theta-locked-more-swr-modulated:
   main (a, both runs): modulation index locked 1.37, not locked 1.00; p = 0.0039
   b, mean envelope: modulation index locked 1.35, not locked 1.16; p = 0.9
   a, without wtr2: modulation index locked 1.32, not locked 0.96; p = 0.0022
fig4-preferred-phase-concentration:
   main (a, both runs): Kuiper excited vs unmodulated p = 0.35, excited vs inhibited p = 0.34, inhibited vs unmodulated p = 0.81
   b, mean envelope: Kuiper excited vs unmodulated p = 0.77, excited vs inhibited p = 0.72, inhibited vs unmodulated p = 0.77
   a, without wtr2: Kuiper excited vs unmodulated p = 0.38, excited vs inhibited p = 0.23, inhibited vs unmodulated p = 0.62
fig5b-mean-rates:
   main (a, both runs): theta rate excited 4.51, inhibited 6.87, unmodulated 2.77 Hz; excited vs unmodulated p = 0.048, inhibited vs unmodulated p = 0.002
   b, mean envelope: theta rate excited 3.76, inhibited 4.98, unmodulated 3.58 Hz; excited vs unmodulated p = 0.74, inhibited vs unmodulated p = 0.65
   a, without wtr2: theta rate excited 4.42, inhibited 8.52, unmodulated 2.83 Hz; excited vs unmodulated p = 0.06, inhibited vs unmodulated p = 0.00054
fig5c-spatial-coverage:
   main (a, both runs): coverage excited 0.229, inhibited 0.506, unmodulated 0.229; excited vs inhibited p = 0.042, excited vs unmodulated p = 0.65
   b, mean envelope: coverage excited 0.220, inhibited 0.358, unmodulated 0.269; excited vs inhibited p = 0.31, excited vs unmodulated p = 0.5
   a, without wtr2: coverage excited 0.238, inhibited 0.658, unmodulated 0.228; excited vs inhibited p = 0.0067, excited vs unmodulated p = 0.67
figs3-arm-and-direction-selectivity:
   main (a, both runs): direction index (mean) CA1 vs excited p = 0.0003, inhibited p = 0.0013, unmodulated p = 3.3e-29; excited vs unmodulated p = 0.8
   b, mean envelope: direction index (mean) CA1 vs excited p = 0.00013, inhibited p = 0.029, unmodulated p = 6.3e-23; excited vs unmodulated p = 0.26
   a, without wtr2: direction index (mean) CA1 vs excited p = 0.00078, inhibited p = 0.00075, unmodulated p = 3.6e-28; excited vs unmodulated p = 0.71
fig5e-speed-correlation:
   main (a, both runs): speed correlation (200 ms) excited -0.009, inhibited 0.033; p = 0.87
   b, mean envelope: speed correlation (200 ms) excited -0.037, inhibited -0.006; p = 0.27
   a, without wtr2: speed correlation (200 ms) excited -0.037, inhibited 0.061; p = 1
fig5f-pre-swr-vs-movement:
   main (a, both runs): index excited -0.086, inhibited -0.125; p = 0.87
   b, mean envelope: index excited -0.032, inhibited 0.054; p = 0.56
   a, without wtr2: index excited -0.066, inhibited -0.117; p = 0.76
figs3e-reward-modulation:
   main (a, both runs): reward index excited -0.147, inhibited 0.103; p = 0.091
   b, mean envelope: reward index excited -0.048, inhibited -0.346; p = 0.22
   a, without wtr2: reward index excited -0.049, inhibited 0.018; p = 0.42
fig5g-ensemble-cofiring:
   main (a, both runs): pairs 2 / 1 / 3 (exc-exc / inh-inh / exc-inh); exc-inh vs exc-exc p = 0.083, vs inh-inh p = 0.18
   b, mean envelope: pairs 6 / 0 / 4 (exc-exc / inh-inh / exc-inh); exc-inh vs exc-exc p = 0.83, vs inh-inh p = nan
   a, without wtr2: pairs 1 / 1 / 2 (exc-exc / inh-inh / exc-inh); exc-inh vs exc-exc p = 0.22, vs inh-inh p = 0.22
fig6-swr-correlated-pairs:
   main (a, both runs): 45 of 198 pairs significant (0.227), shuffled 0.066; excited 0.220, inhibited 0.239
   b, mean envelope: 17 of 137 pairs significant (0.124), shuffled 0.066; excited 0.131, inhibited 0.067
   a, without wtr2: 35 of 171 pairs significant (0.205), shuffled 0.053; excited 0.189, inhibited 0.233
fig6ab-both-signs:
   main (a, both runs): excited 21 positive / 7 negative, inhibited 7 positive / 10 negative
   b, mean envelope: excited 15 positive / 1 negative, inhibited 0 positive / 1 negative
   a, without wtr2: excited 17 positive / 4 negative, inhibited 4 positive / 10 negative
fig6c-theta-predicts-swr-correlation:
   main (a, both runs): excited r = 0.46 (p = 5.4e-08), inhibited r = 0.58 (p = 1.1e-07)
   b, mean envelope: excited r = 0.39 (p = 1e-05), inhibited r = 0.05 (p = 0.85)
   a, without wtr2: excited r = 0.47 (p = 1.5e-07), inhibited r = 0.61 (p = 1.9e-07)
figs4b-ca1-leads-in-theta:
   main (a, both runs): excited 21 pairs, mean peak at 20 ms; inhibited 7 pairs, mean peak at 60 ms
   b, mean envelope: excited 15 pairs, mean peak at 30 ms; inhibited no pairs
   a, without wtr2: excited 17 pairs, mean peak at 30 ms; inhibited 4 pairs, mean peak at 60 ms
fig3f-swr-cross-covariance-lag:
   main (a, both runs): excited extremum of the mean at 20 ms; inhibited extremum of the mean at 200 ms
   b, mean envelope: excited extremum of the mean at 10 ms; inhibited extremum of the mean at 80 ms
   a, without wtr2: excited extremum of the mean at 20 ms; inhibited extremum of the mean at 200 ms
fig7c-spatial-correlation:
   main (a, both runs): excited r = 0.20 (p = 0.022), inhibited r = 0.40 (p = 0.00047)
   b, mean envelope: excited r = 0.17 (p = 0.059), inhibited r = 0.13 (p = 0.66)
   a, without wtr2: excited r = 0.21 (p = 0.026), inhibited r = 0.41 (p = 0.0011)
fig8a-no-prerest-swr-correlation-relation:
   main (a, both runs): excited r = 0.07 (p = 0.48, n = 120), inhibited r = 0.13 (p = 0.29, n = 71)
   b, mean envelope: excited r = 0.10 (p = 0.35, n = 92), inhibited r = -0.07 (p = 0.82, n = 15)
   a, without wtr2: excited r = 0.01 (p = 0.92, n = 104), inhibited r = 0.17 (p = 0.2, n = 60)
fig6e-glm-swr-prediction:
   main (a, both runs): modulated 0.057 (n = 16, signed-rank vs 0 p = 6.1e-05), unmodulated 0.025; p = 0.0026
   b, mean envelope: modulated 0.025 (n = 12, signed-rank vs 0 p = 0.077), unmodulated 0.017; p = 0.3
   a, without wtr2: modulated 0.054 (n = 15, signed-rank vs 0 p = 6.1e-05), unmodulated 0.025; p = 0.0082
InΒ [50]:
def battery_more(A, glm_splits=200):
    """The criterion's main tests of the downstream claims the first battery leaves out, under one variant."""
    out = {}
    c = cells.loc[A["cat"].index].copy()
    c["category"] = A["cat"]
    P = c[c.region == "PFC"]
    # transient responses: population mean of z-scored PSTHs, return to the baseline band (readings a and b)
    tr = []
    for k, sign in (("excited", 1), ("inhibited", -1)):
        idx = P.index[P.category == k]
        if len(idx) == 0:
            tr.append(f"{k} no cells"); continue
        pop = np.mean([(A["psth"][i] - A["psth"][i].mean()) / A["psth"][i].std() if A["psth"][i].std() > 0 else np.zeros_like(A["psth"][i])
                       for i in idx], 0)
        tr.append(f"{k} (n = {len(idx)}) back at baseline from {return_time(pop, sign, 'a') * 1000:.0f} ms (a), {return_time(pop, sign, 'b') * 1000:.0f} ms (b)")
    out["fig3-transient-responses"] = "; ".join(tr) + " (expected within about 300 ms)"
    # SWR-correlation pairs, as in the first battery, with spatial correlation
    rng_p = rng_for("other-readings-pairs")
    rows_ = []
    for (a, d), g in c.groupby(["animal", "day"]):
        for i in g.index[(g.region == "CA1") & (g.category != "unmodulated")]:
            for j in g.index[(g.region == "PFC") & (g.category != "unmodulated")]:
                x, y = A["counts"][i], A["counts"][j]
                if ((x > 0) & (y > 0)).sum() < 5:
                    continue
                r_, p_ = corr_p(x, y); _, psh = corr_p(x, rng_p.permutation(y))
                lags_, xc = hc28.std_xcov(theta_spk[i], theta_spk[j], theta_T[(a, d)])
                xp, yp = A["pre_counts"].get(i), A["pre_counts"].get(j)
                rows_.append(dict(animal=a, day=d, ca1=i, pfc=j, pfc_cat=c.loc[j, "category"], r=r_, p=p_,
                                  spatial=hc28.spatial_corr(maps_all[i], maps_all[j]),
                                  theta_peak=np.nanmax(xc[np.abs(lags_) <= 0.2 + 1e-9]),
                                  r_pre=corr_p(xp, yp)[0] if xp is not None and yp is not None else np.nan))
    pr = pd.DataFrame(rows_)
    f8 = []
    for col in ("theta_peak", "spatial"):
        for k in ("excited", "inhibited"):
            s = pr[(pr.pfc_cat == k) & np.isfinite(pr.r_pre)]
            rr_, p_, n_ = reg(s[col].values, s.r_pre.values)
            f8.append(f"{col} {k} r = {rr_:.2f} (p = {p_:.2g}, n = {n_})")
    out["fig8bc-no-prerest-theta-spatial-relation"] = "; ".join(f8)
    rng_s = rng_for("other-readings-spatial")

    def diff_test(d_, two_sided):
        o = {k: reg(d_[d_.pfc_cat == k].spatial.values, d_[d_.pfc_cat == k].r.values) for k in ("excited", "inhibited")}
        allp = d_[["spatial", "r"]].dropna().values
        ne, ni = o["excited"][2], o["inhibited"][2]
        diff = o["inhibited"][0] - o["excited"][0]
        null = []
        for _ in range(1000):
            perm = rng_s.permutation(len(allp))
            a_, b_ = allp[perm[:ni]], allp[perm[ni:ni + ne]]
            null.append(np.corrcoef(a_[:, 0], a_[:, 1])[0, 1] - np.corrcoef(b_[:, 0], b_[:, 1])[0, 1])
        null = np.array(null)
        p = np.mean(np.abs(null) >= abs(diff)) if two_sided else np.mean(null >= diff)
        return "; ".join(f"{k} r = {x[0]:.2f} (p = {x[1]:.2g}, n = {x[2]})" for k, x in o.items()), p

    s7, p7 = diff_test(pr, False)
    out["fig7c-spatial-correlation"] = f"{s7}; inhibited stronger than excited, shuffle p = {p7:.3f}"
    inh_cov = P[P.category == "inhibited"].coverage.dropna()
    q1, q3 = np.percentile(inh_cov, [25, 75])
    pr["pfc_cov"] = cells.loc[pr.pfc, "coverage"].values
    m5 = pr[(pr.pfc_cov >= q1) & (pr.pfc_cov <= q3)]
    s5, p5 = diff_test(m5, True)
    out["figs5-matched-selectivity"] = f"inhibited coverage IQR {q1:.3f} to {q3:.3f} ({len(inh_cov)} cells); {s5}; difference shuffle p (two-sided) = {p5:.3f}"
    # replay content: the reading (a) wtr1 events and per-cell correlations, grouped by this variant's classification
    q6 = rc6[rc6.r_pearson.notna() & rc6.pfc.isin(A["cat"].index)].copy()
    q6["modulated"] = A["cat"].reindex(q6.pfc).values != "unmodulated"
    x6, y6 = q6[q6.modulated].r_pearson, q6[~q6.modulated].r_pearson
    out["figs6-replay-content"] = (f"modulated {x6.mean():.3f} (n = {len(x6)}), unmodulated {y6.mean():.3f} (n = {len(y6)}); "
                                   f"rank-sum p = {ranksum(x6, y6):.2g} (two-sided), "
                                   f"{stats.ranksums(x6, y6, alternative='greater').pvalue if len(x6) and len(y6) else np.nan:.2g} (modulated greater)")
    # GLMs
    rng_g = rng_for("other-readings-glm-more")
    th, rev_, g8_ = [], [], []
    for (a, d), g in c.groupby(["animal", "day"]):
        day = R[a]["days"][d]
        c_idx = list(g.index[g.region == "CA1"]); p_idx = list(g.index[g.region == "PFC"])
        if not c_idx or not p_idx:
            continue
        Xs = np.array([A["counts"][i] for i in c_idx]).T.astype(float)
        B = behavior_bins(day, c_idx + p_idx).astype(float)
        Xb, Yb = B[:, :len(c_idx)], B[:, len(c_idx):]
        for k_, j in enumerate(p_idx):
            y = A["counts"][j].astype(float)
            t2s = hc28.glm_cross(Xb, Yb[:, k_], Xs, y, rng_g); s2t = hc28.glm_cross(Xs, y, Xb, Yb[:, k_], rng_g)
            th.append(dict(modulated=c.loc[j, "category"] != "unmodulated", n_ca1=len(c_idx), perf_th2swr=t2s["perf"], perf_swr2th=s2t["perf"]))
        kinds = {"modulated": [j for j in p_idx if c.loc[j, "category"] != "unmodulated"],
                 "unmodulated": [j for j in p_idx if c.loc[j, "category"] == "unmodulated"],
                 "excited": [j for j in p_idx if c.loc[j, "category"] == "excited"],
                 "inhibited": [j for j in p_idx if c.loc[j, "category"] == "inhibited"]}
        for kind, idx in kinds.items():
            if not idx:
                continue
            X = np.array([A["counts"][j] for j in idx]).T.astype(float)
            if X.sum() == 0:
                continue
            for i in c_idx:
                cv = hc28.glm_cv(X, A["counts"][i].astype(float), rng_g, splits=glm_splits)
                if cv["converged"]:
                    rev_.append(dict(kind=kind, n_pfc=len(idx), perf=cv["perf"]))
        ci = [i for i in c_idx if A["pre_counts"].get(i) is not None]
        for j in kinds["modulated"]:
            if not ci or A["pre_counts"].get(j) is None or A["pre_counts"][j].sum() == 0:
                continue
            Xt = np.array([A["counts"][i] for i in ci]).T.astype(float); Xp = np.array([A["pre_counts"][i] for i in ci]).T.astype(float)
            yt, yp = A["counts"][j].astype(float), A["pre_counts"][j].astype(float)
            both = (Xt.sum(0) > 0) & (Xp.sum(0) > 0)
            g8_.append(dict(task_task=hc28.glm_cv(Xt, yt, rng_g, splits=glm_splits)["perf"], pre_pre=hc28.glm_cv(Xp, yp, rng_g, splits=glm_splits)["perf"],
                            task_pre=hc28.glm_cross(Xt[:, both], yt, Xp[:, both], yp, rng_g)["perf"],
                            pre_task=hc28.glm_cross(Xp[:, both], yp, Xt[:, both], yt, rng_g)["perf"]))
    gt = pd.DataFrame(th); gt = gt[np.isfinite(gt.perf_th2swr)].copy()
    gt["grp"] = size_groups(gt.n_ca1.values, "a")
    long = pd.concat([gt.assign(perf2=gt.perf_th2swr, mtype="theta_to_swr"), gt.assign(perf2=gt.perf_swr2th, mtype="swr_to_theta")])
    long = long[np.isfinite(long.perf2)]
    mt = gt[gt.modulated].perf_th2swr
    out["fig6e-theta-trained-glm"] = (f"movement-trained, modulated {mt.mean():.3f} (n = {len(mt)}, signed-rank vs 0 p = {stats.wilcoxon(mt).pvalue if len(mt) > 1 else np.nan:.2g}), "
                                      f"unmodulated {gt[~gt.modulated].perf_th2swr.mean():.3f}; two-way (tertiles) modulated p = "
                                      f"{anova_p('perf_th2swr ~ C(modulated) + C(grp)', gt, 'C(modulated)'):.2g}, group p = {anova_p('perf_th2swr ~ C(modulated) + C(grp)', gt, 'C(grp)'):.2g}; "
                                      f"model type x group p = {anova_p('perf2 ~ C(mtype) * C(grp)', long, 'C(mtype):C(grp)'):.2g} "
                                      f"(theta to SWR {gt.perf_th2swr.mean():.3f}, SWR to theta {gt.perf_swr2th.mean():.3f})")
    rv = pd.DataFrame(rev_); rv["grp"] = size_groups(rv.n_pfc.values, "c")
    mu = rv[rv.kind.isin(["modulated", "unmodulated"])]; ei = rv[rv.kind.isin(["excited", "inhibited"])]
    out["figs4c-pfc-predicts-ca1"] = (f"modulated {rv[rv.kind == 'modulated'].perf.mean():.3f}, unmodulated {rv[rv.kind == 'unmodulated'].perf.mean():.3f} "
                                      f"({len(rv)} converged models, {glm_splits} splits); two-way kind p = {anova_p('perf ~ C(kind) + C(grp)', mu, 'C(kind)'):.2g}, "
                                      f"size group p = {anova_p('perf ~ C(kind) + C(grp)', mu, 'C(grp)'):.2g}; excited vs inhibited p = "
                                      f"{anova_p('perf ~ C(kind) + C(grp)' if ei.grp.nunique() > 1 else 'perf ~ C(kind)', ei, 'C(kind)'):.2g}")
    g8v = pd.DataFrame(g8_)
    out["fig8d-glm-epoch-specific"] = (f"{len(g8v)} cells; task-task {g8v.task_task.mean():.3f}, task-pre {g8v.task_pre.mean():.3f} "
                                       f"(signed-rank vs 0 p = {stats.wilcoxon(g8v.task_pre.dropna()).pvalue if g8v.task_pre.notna().sum() > 1 else np.nan:.2g}), "
                                       f"pre-task {g8v.pre_task.mean():.3f}, pre-pre {g8v.pre_pre.mean():.3f}; task-pre vs task-task p = {ranksum(g8v.task_pre, g8v.task_task):.2g}, "
                                       f"pre-task vs task-task p = {ranksum(g8v.pre_task, g8v.task_task):.2g}, pre-pre vs task-pre p = {ranksum(g8v.pre_pre, g8v.task_pre):.2g}, "
                                       f"pre-pre vs pre-task p = {ranksum(g8v.pre_pre, g8v.pre_task):.2g}")
    return out


res2 = {k: battery_more(A) for k, A in alt.items()}
for claim, row in pd.DataFrame(res2).iterrows():
    print(f"{claim}:")
    for k, v in row.items():
        print(f"   {k}: {v}")
fig3-transient-responses:
   main (a, both runs): excited (n = 12) back at baseline from 480 ms (a), 330 ms (b); inhibited (n = 7) back at baseline from 480 ms (a), 480 ms (b) (expected within about 300 ms)
   b, mean envelope: excited (n = 17) back at baseline from 490 ms (a), 490 ms (b); inhibited (n = 3) back at baseline from 480 ms (a), 300 ms (b) (expected within about 300 ms)
   a, without wtr2: excited (n = 11) back at baseline from 470 ms (a), 450 ms (b); inhibited (n = 6) back at baseline from 490 ms (a), 430 ms (b) (expected within about 300 ms)
fig8bc-no-prerest-theta-spatial-relation:
   main (a, both runs): theta_peak excited r = -0.03 (p = 0.79, n = 120); theta_peak inhibited r = 0.15 (p = 0.22, n = 71); spatial excited r = -0.11 (p = 0.23, n = 120); spatial inhibited r = 0.18 (p = 0.14, n = 71)
   b, mean envelope: theta_peak excited r = -0.09 (p = 0.38, n = 92); theta_peak inhibited r = -0.42 (p = 0.12, n = 15); spatial excited r = -0.03 (p = 0.77, n = 92); spatial inhibited r = -0.40 (p = 0.14, n = 15)
   a, without wtr2: theta_peak excited r = -0.06 (p = 0.57, n = 104); theta_peak inhibited r = 0.20 (p = 0.13, n = 60); spatial excited r = -0.14 (p = 0.16, n = 104); spatial inhibited r = 0.18 (p = 0.17, n = 60)
fig7c-spatial-correlation:
   main (a, both runs): excited r = 0.20 (p = 0.022, n = 127); inhibited r = 0.40 (p = 0.00047, n = 71); inhibited stronger than excited, shuffle p = 0.062
   b, mean envelope: excited r = 0.17 (p = 0.059, n = 122); inhibited r = 0.13 (p = 0.66, n = 15); inhibited stronger than excited, shuffle p = 0.590
   a, without wtr2: excited r = 0.21 (p = 0.026, n = 111); inhibited r = 0.41 (p = 0.0011, n = 60); inhibited stronger than excited, shuffle p = 0.083
figs5-matched-selectivity:
   main (a, both runs): inhibited coverage IQR 0.341 to 0.678 (7 cells); excited r = 0.38 (p = 0.047, n = 28); inhibited r = 0.59 (p = 0.0013, n = 27); difference shuffle p (two-sided) = 0.347
   b, mean envelope: inhibited coverage IQR 0.191 to 0.487 (3 cells); excited r = 0.45 (p = 0.018, n = 27); inhibited r = -0.40 (p = 0.29, n = 9); difference shuffle p (two-sided) = 0.016
   a, without wtr2: inhibited coverage IQR 0.562 to 0.759 (6 cells); excited r = 0.48 (p = 0.049, n = 17); inhibited r = 0.26 (p = 0.47, n = 10); difference shuffle p (two-sided) = 0.503
figs6-replay-content:
   main (a, both runs): modulated -0.048 (n = 8), unmodulated 0.038 (n = 33); rank-sum p = 0.45 (two-sided), 0.78 (modulated greater)
   b, mean envelope: modulated 0.022 (n = 9), unmodulated 0.016 (n = 29); rank-sum p = 0.88 (two-sided), 0.56 (modulated greater)
   a, without wtr2: modulated -0.048 (n = 8), unmodulated 0.038 (n = 33); rank-sum p = 0.45 (two-sided), 0.78 (modulated greater)
fig6e-theta-trained-glm:
   main (a, both runs): movement-trained, modulated 0.038 (n = 19, signed-rank vs 0 p = 7.6e-06), unmodulated 0.021; two-way (tertiles) modulated p = 0.033, group p = 0.00078; model type x group p = 0.49 (theta to SWR 0.024, SWR to theta 0.016)
   b, mean envelope: movement-trained, modulated 0.022 (n = 20, signed-rank vs 0 p = 0.0049), unmodulated 0.020; two-way (tertiles) modulated p = 0.93, group p = 0.23; model type x group p = 0.72 (theta to SWR 0.021, SWR to theta 0.012)
   a, without wtr2: movement-trained, modulated 0.035 (n = 17, signed-rank vs 0 p = 0.00029), unmodulated 0.020; two-way (tertiles) modulated p = 0.21, group p = 7.6e-06; model type x group p = 0.67 (theta to SWR 0.021, SWR to theta 0.014)
figs4c-pfc-predicts-ca1:
   main (a, both runs): modulated 0.005, unmodulated 0.011 (797 converged models, 200 splits); two-way kind p = 0.97, size group p = 0.00019; excited vs inhibited p = 0.44
   b, mean envelope: modulated 0.005, unmodulated 0.010 (524 converged models, 200 splits); two-way kind p = 0.39, size group p = 0.012; excited vs inhibited p = 0.2
   a, without wtr2: modulated 0.005, unmodulated 0.011 (722 converged models, 200 splits); two-way kind p = 0.46, size group p = 0.00049; excited vs inhibited p = 0.67
fig8d-glm-epoch-specific:
   main (a, both runs): 19 cells; task-task 0.059, task-pre 0.003 (signed-rank vs 0 p = 0.56), pre-task 0.009, pre-pre 0.022; task-pre vs task-task p = 0.00034, pre-task vs task-task p = 0.0026, pre-pre vs task-pre p = 0.048, pre-pre vs pre-task p = 0.45
   b, mean envelope: 17 cells; task-task 0.037, task-pre -0.002 (signed-rank vs 0 p = 0.92), pre-task -0.001, pre-pre 0.019; task-pre vs task-task p = 0.023, pre-task vs task-task p = 0.059, pre-pre vs task-pre p = 0.11, pre-pre vs pre-task p = 0.096
   a, without wtr2: 17 cells; task-task 0.052, task-pre 0.004 (signed-rank vs 0 p = 0.28), pre-task 0.011, pre-pre 0.023; task-pre vs task-task p = 0.00033, pre-task vs task-task p = 0.0055, pre-pre vs task-pre p = 0.082, pre-pre vs pre-task p = 0.41

Result: Neither variant brings the classification near the paper's. Under the mean envelope 17 excited and 3 inhibited of 136 PFC cell-days remain after the spike criterion, and without the wtr2 runs 11 and 6 of 161. No downstream claim that fails under reading (a) meets its criterion under either variant, in the two batteries, which together repeat every claim from fig3-pfc-swr-modulation-fractions to fig8d (figs6 by regrouping the cells only). In particular the inhibited relation of fig7c is not stronger than the excited one (shuffle p = 0.590 under the mean envelope, 0.083 without wtr2), and no population returns to baseline by 330 ms in both groups under either reading of fig3-transient-responses. Two results that meet their criteria under reading (a) fail under a variant. figs5 fails under both: under the mean envelope the matched inhibited pairs show no positive relation (r = -0.40, p = 0.29, n = 9) and the shuffle finds a difference (p = 0.016), and without wtr2 the inhibited relation is not significant (r = 0.26, p = 0.47, n = 10). fig6e fails under the mean envelope, where modulated cells are not predicted above chance (p = 0.077). Several other results that hold under reading (a) weaken under the mean envelope, where only 3 inhibited cells remain: the inhibited pairs give 1 significant SWR correlation (fig6ab) and the theta cross-covariance does not predict the inhibited pairs' SWR correlation (r = 0.05, p = 0.85, fig6c). fig8bc holds under both variants (no relation at p < 0.05). Without the wtr2 runs, besides figs5, the movement-trained GLM no longer separates modulated from unmodulated cells (two-way p = 0.21, against 0.033 under reading a), a part of fig6e-theta-trained-glm, which fails on its interaction test under every reading (p = 0.49, 0.72 and 0.67).

SummaryΒΆ

Claim Outcome
wtrack-learning reproduced
ytrack-learning blocked, data missing
tables1-cell-counts partially reproduced
swr-detection-stats partially reproduced
figs2-swr-at-reward-wells reproduced
fig3-pfc-swr-modulation-fractions not reproduced
ca1-swr-modulated partially reproduced
fig3-transient-responses not reproduced
fig3de-ca1-precedes-pfc-peak not reproduced
fig3e-onset-later-in-pfc not reproduced
fig3f-swr-cross-covariance-lag not reproduced
fig4-theta-locked-fraction reproduced
fig4a-preferred-phases not reproduced
fig4-swr-modulated-more-theta-locked not reproduced
fig4b-kappa not reproduced
fig4c-theta-locked-more-swr-modulated partially reproduced
fig4-preferred-phase-concentration not reproduced
theta-lag-past reproduced
fig5b-mean-rates not reproduced
fig5c-spatial-coverage not reproduced
figs3-arm-and-direction-selectivity not reproduced
fig5e-speed-correlation not reproduced
fig5f-pre-swr-vs-movement not reproduced
figs3e-reward-modulation not reproduced
fig5g-ensemble-cofiring not reproduced
fig6-swr-correlated-pairs partially reproduced
fig6ab-both-signs reproduced
fig6c-theta-predicts-swr-correlation partially reproduced
figs4b-ca1-leads-in-theta partially reproduced
fig6e-glm-swr-prediction reproduced
fig6e-theta-trained-glm not reproduced
figs4c-pfc-predicts-ca1 not reproduced
fig7c-spatial-correlation not reproduced
figs5-matched-selectivity reproduced
figs6-replay-content not reproduced
fig8a-no-prerest-swr-correlation-relation reproduced
fig8bc-no-prerest-theta-spatial-relation reproduced
fig8d-glm-epoch-specific not reproduced
figs7-both-tracks blocked, data missing

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 three W-track rats are in the data set, so pooled values are compared with W-track data. The paper links no code; the SWR detector (filter, envelope smoothing, minimum duration, onset at the return to the mean, an event on any one ripple tetrode) follows the Frank-lab convention of the cited Karlsson and Frank (2009) as an assumption, and the readings the claims file names are shown. Units are cell-days; no identifier links units across days. Both W-track runs of each day are used, including the runs on a second W-track (wtr2) on days 6 to 8; rate maps give the two tracks bins of their own, and the replay analysis decodes the wtr1 runs only. Rate maps are 2 cm bins without smoothing. The reverse GLM uses 500 splits per model where the paper uses 5000, and the GLMs repeated under the other readings use 500 and 200.

The central difference is the SWR modulation of PFC cells: 19 of 167 PFC cell-days are SWR modulated here, against 56 of 165 in the paper's W-track data, and only 7 are inhibited against 26. Every animal has fewer modulated cells than in Table S2. The test itself flags 0.066 of the cells when the SWR onsets are shifted by 10 s. The classification stays far from the paper's under the mean-envelope SWRs and without the wtr2 runs, and no downstream claim that fails under the main reading meets its criterion under either (two batteries repeat every claim from fig3-pfc-swr-modulation-fractions to fig8d, figs6 by regrouping the cells only). Two claims that meet their criteria under the main reading fail under a variant: figs5-matched-selectivity under both, and fig6e-glm-swr-prediction under the mean envelope. Every claim that compares excited, inhibited and unmodulated PFC cells therefore rests on 12 excited and 7 inhibited cells, and most of those comparisons fail; these failures follow from the classification and its small groups more than they test the claims one by one. Pair-level findings that do not need many inhibited cells (SWR-correlated pairs, both signs, theta cross-covariance predicting SWR correlation, CA1 leading PFC, the absence of these relations in the pre-task rest) hold in direction under the main reading, with values that differ from the paper's; several of them weaken under the mean envelope, which leaves 3 inhibited cells.

SWR detection. Reading (a) matches the paper's count per day but not its duration or rate, and raises the CA1 population rate 0-200 ms after onset to 1.36 times the run mean (1.64 under the mean envelope, 0.90 at random low-speed times). The single-tetrode detections mostly do not coincide: the union over tetrodes holds 2.7 to 4.1 times the events of the busiest tetrode.

What was found about the data set. The cellinfo field spikewidth, described as peak-to-trough width in ms, holds 30 kHz samples (values 1 to 23). The position files of run epochs have 9 columns (with smoothed copies), where the description lists 7, and carry the pixel size as cmperpixel, where the description says cmperpix; the positions are in cm (centre arm 58 to 81 cm, consistent with the ~80 cm track). The second run of days 6 to 8 is on a second W-track named wtr2, which the description does not define (it mentions novel and familiar environments for "the final 3 days"). No identifier links a unit across days, so the paper's unique-unit counts cannot be checked. The streams share one clock: the CA1 rate after SWR onset is 1.36 times the run mean against 0.98 with onsets shifted by 10 s, and CA1 spatial information falls from 3.11 to 1.91 bits per spike when spikes are shifted by 30 s.